import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { SiteShell } from "@/components/site/SiteShell";
import manifestoHero from "@/assets/manifesto-hero.jpg";
import manifestoHumano from "@/assets/manifesto-humano.jpg";
import manifestoVida from "@/assets/manifesto-vida.jpg";

export const Route = createFileRoute("/manifesto")({
  head: () => ({
    meta: [
      { title: "Manifesto — Instituto Vida Segura" },
      {
        name: "description",
        content:
          "Uma declaração pública daquilo em que acreditamos. Toda cultura de segurança começa pelas pessoas.",
      },
      { property: "og:title", content: "Manifesto — Instituto Vida Segura" },
      {
        property: "og:description",
        content:
          "Transformamos conhecimento em cuidado, comportamento em cultura e pessoas em protagonistas de ambientes mais seguros, saudáveis e humanos.",
      },
      { property: "og:image", content: "https://institutovidasegura.lovable.app/og-manifesto.jpg" },
    ],
  }),
  component: ManifestoPage,
});

/* -------------------------------------------------------------------------- */
/*  Reveal wrapper — fade + slide on scroll                                   */
/* -------------------------------------------------------------------------- */

function Reveal({
  children,
  delay = 0,
  as = "div",
  className = "",
}: {
  children: ReactNode;
  delay?: number;
  as?: "div" | "p" | "h1" | "h2" | "h3" | "span" | "blockquote";
  className?: string;
}) {
  const ref = useRef<HTMLElement | null>(null);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (typeof IntersectionObserver === "undefined") {
      setVisible(true);
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setVisible(true);
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.2, rootMargin: "0px 0px -10% 0px" }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const cls = `${className} transition-all duration-[1100ms] ease-out will-change-transform ${
    visible ? "translate-y-0 opacity-100" : "translate-y-6 opacity-0"
  }`;
  const style = { transitionDelay: `${delay}ms` };
  const setRef = (el: HTMLElement | null) => {
    ref.current = el;
  };

  switch (as) {
    case "p":
      return <p ref={setRef} className={cls} style={style}>{children}</p>;
    case "h1":
      return <h1 ref={setRef} className={cls} style={style}>{children}</h1>;
    case "h2":
      return <h2 ref={setRef} className={cls} style={style}>{children}</h2>;
    case "h3":
      return <h3 ref={setRef} className={cls} style={style}>{children}</h3>;
    case "span":
      return <span ref={setRef} className={cls} style={style}>{children}</span>;
    case "blockquote":
      return <blockquote ref={setRef} className={cls} style={style}>{children}</blockquote>;
    default:
      return <div ref={setRef} className={cls} style={style}>{children}</div>;
  }
}

/* -------------------------------------------------------------------------- */
/*  Section shells                                                            */
/* -------------------------------------------------------------------------- */

const SECTION =
  "relative flex min-h-screen w-full items-center justify-center px-6 py-24 sm:py-32";

function TextSection({
  eyebrow,
  children,
  tone = "light",
  maxW = "max-w-3xl",
  align = "left",
}: {
  eyebrow?: string;
  children: ReactNode;
  tone?: "light" | "dark" | "soft";
  maxW?: string;
  align?: "left" | "center";
}) {
  const bg =
    tone === "dark"
      ? "bg-[color:var(--safe)] text-white"
      : tone === "soft"
      ? "bg-[color:oklch(0.98_0.005_180)] text-foreground"
      : "bg-background text-foreground";

  return (
    <section className={`${SECTION} ${bg}`}>
      <div
        className={`mx-auto w-full ${maxW} ${
          align === "center" ? "text-center" : "text-left"
        }`}
      >
        {eyebrow && (
          <Reveal
            as="p"
            className="mb-10 text-[11px] font-medium uppercase tracking-[0.32em] opacity-70"
          >
            {eyebrow}
          </Reveal>
        )}
        {children}
      </div>
    </section>
  );
}

/* -------------------------------------------------------------------------- */
/*  Page                                                                      */
/* -------------------------------------------------------------------------- */

const LINE =
  "font-display font-light leading-[1.15] tracking-tight text-4xl sm:text-5xl lg:text-6xl";
const LINE_SM =
  "font-display font-light leading-[1.25] tracking-tight text-2xl sm:text-3xl lg:text-[2.25rem]";

function ManifestoPage() {
  return (
    <SiteShell>
      {/* ---------- HERO ---------- */}
      <section className="relative flex min-h-screen w-full items-center justify-center overflow-hidden">
        <img
          src={manifestoHero}
          alt="Pessoas colaborando em ambiente corporativo"
          width={1920}
          height={1280}
          className="absolute inset-0 h-full w-full object-cover"
        />
        <div className="absolute inset-0 bg-gradient-to-b from-[color:var(--safe)]/85 via-[color:var(--safe)]/70 to-[color:var(--safe)]/90" />
        <div className="relative z-10 mx-auto max-w-4xl px-6 text-center text-white">
          <Reveal
            as="p"
            className="mb-8 text-[11px] font-medium uppercase tracking-[0.4em] text-white/70"
          >
            Instituto Vida Segura
          </Reveal>
          <Reveal
            as="h1"
            delay={150}
            className="font-display text-6xl font-light leading-[1] tracking-tight sm:text-7xl lg:text-[9rem]"
          >
            Manifesto
          </Reveal>
          <Reveal
            as="p"
            delay={500}
            className="mx-auto mt-10 max-w-2xl text-lg font-light leading-relaxed text-white/85 sm:text-xl"
          >
            Acreditamos que toda cultura de segurança
            <br className="hidden sm:block" /> começa pelas pessoas.
          </Reveal>
          <Reveal delay={900} className="mt-16 flex justify-center">
            <span className="inline-block h-16 w-px bg-white/50" />
          </Reveal>
        </div>
      </section>

      {/* ---------- BLOCO 1 ---------- */}
      <TextSection eyebrow="I">
        <div className="space-y-8">
          <Reveal as="p" className={LINE}>
            Durante muito tempo aprendemos que segurança era{" "}
            <span className="italic text-muted-foreground">cumprir normas</span>.
          </Reveal>
          <Reveal as="p" delay={200} className={LINE}>
            Que produtividade era{" "}
            <span className="italic text-muted-foreground">entregar resultados</span>.
          </Reveal>
          <Reveal as="p" delay={400} className={LINE}>
            Que liderança era{" "}
            <span className="italic text-muted-foreground">controlar pessoas</span>.
          </Reveal>
          <Reveal
            as="p"
            delay={700}
            className="mt-16 font-display text-3xl font-medium text-[color:var(--life)] sm:text-4xl"
          >
            Mas descobrimos algo muito maior.
          </Reveal>
        </div>
      </TextSection>

      {/* ---------- BLOCO 2 ---------- */}
      <TextSection tone="soft" eyebrow="II">
        <div className="space-y-6">
          <Reveal as="p" className={LINE_SM}>
            Descobrimos que por trás de cada indicador existe uma{" "}
            <span className="text-[color:var(--safe)]">história</span>.
          </Reveal>
          <Reveal as="p" delay={200} className={LINE_SM}>
            Por trás de cada acidente existe uma{" "}
            <span className="text-[color:var(--safe)]">decisão</span>.
          </Reveal>
          <Reveal as="p" delay={400} className={LINE_SM}>
            Por trás de cada decisão existe uma{" "}
            <span className="text-[color:var(--safe)]">emoção</span>.
          </Reveal>
          <Reveal
            as="p"
            delay={800}
            className="mt-14 font-display text-4xl font-medium leading-tight tracking-tight text-[color:var(--safe)] sm:text-6xl lg:text-7xl"
          >
            E por trás de cada emoção
            <br />
            existe uma{" "}
            <span className="italic text-gradient-life">pessoa</span>.
          </Reveal>
        </div>
      </TextSection>

      {/* ---------- BLOCO 3 (with image) ---------- */}
      <section className="relative flex min-h-screen w-full items-stretch">
        <div className="grid w-full grid-cols-1 lg:grid-cols-2">
          <div className="relative min-h-[50vh] overflow-hidden lg:min-h-screen">
            <img
              src={manifestoHumano}
              alt="Mentor acolhendo colega em ambiente de trabalho"
              width={1920}
              height={1280}
              loading="lazy"
              className="absolute inset-0 h-full w-full object-cover"
            />
          </div>
          <div className="flex items-center bg-background px-6 py-24 sm:px-16 sm:py-32">
            <div className="max-w-xl space-y-8">
              <Reveal
                as="p"
                className="text-[11px] font-medium uppercase tracking-[0.32em] text-[color:var(--life)]"
              >
                III · Nossa origem
              </Reveal>
              <Reveal as="p" delay={150} className={LINE}>
                Foi por isso que o{" "}
                <span className="italic">Instituto Vida Segura</span> nasceu.
              </Reveal>
              <Reveal
                as="p"
                delay={450}
                className="text-xl font-light leading-relaxed text-muted-foreground sm:text-2xl"
              >
                Não para ensinar empresas a{" "}
                <span className="text-foreground">cumprir normas</span>.
              </Reveal>
              <Reveal
                as="p"
                delay={650}
                className="text-xl font-light leading-relaxed text-muted-foreground sm:text-2xl"
              >
                Mas para ajudá-las a{" "}
                <span className="font-medium text-[color:var(--safe)]">
                  compreender pessoas
                </span>
                .
              </Reveal>
            </div>
          </div>
        </div>
      </section>

      {/* ---------- BLOCO 4 ---------- */}
      <TextSection tone="dark" align="center" maxW="max-w-4xl" eyebrow="IV">
        <Reveal
          as="h2"
          className="font-display text-4xl font-light leading-[1.1] tracking-tight sm:text-6xl lg:text-7xl"
        >
          Não acreditamos que o comportamento humano
          <br />
          seja o <span className="italic text-[color:var(--safe-gold)]">problema</span>.
        </Reveal>
        <Reveal
          as="p"
          delay={400}
          className="mx-auto mt-12 max-w-2xl text-lg font-light leading-relaxed text-white/75 sm:text-xl"
        >
          Acreditamos que ele revela aquilo que ainda precisa ser
          compreendido.
        </Reveal>
      </TextSection>

      {/* ---------- BLOCO 5 ---------- */}
      <TextSection eyebrow="V">
        <Reveal as="p" className={LINE}>
          Não acreditamos que saúde mental
          <br />
          seja apenas um{" "}
          <span className="italic text-muted-foreground">benefício</span>.
        </Reveal>
        <Reveal
          as="p"
          delay={350}
          className="mt-10 max-w-2xl text-xl font-light leading-relaxed text-muted-foreground sm:text-2xl"
        >
          Ela é a base para equipes fortes, líderes conscientes e
          organizações sustentáveis.
        </Reveal>
      </TextSection>

      {/* ---------- BLOCO 6 ---------- */}
      <TextSection tone="soft" eyebrow="VI">
        <div className="grid gap-12 lg:grid-cols-[1.2fr_1fr] lg:items-center">
          <div className="space-y-8">
            <Reveal as="p" className={LINE_SM}>
              Não acreditamos que tecnologia{" "}
              <span className="italic text-muted-foreground">substitua</span>{" "}
              pessoas.
            </Reveal>
            <Reveal
              as="p"
              delay={300}
              className="font-display text-3xl font-medium leading-tight tracking-tight text-[color:var(--safe)] sm:text-4xl lg:text-5xl"
            >
              Criamos tecnologia para{" "}
              <span className="italic text-gradient-life">aproximar</span>{" "}
              pessoas.
            </Reveal>
          </div>
          <Reveal delay={500} className="flex justify-center">
            <ConnectingDots />
          </Reveal>
        </div>
      </TextSection>

      {/* ---------- BLOCO 7 ---------- */}
      <TextSection eyebrow="VII" align="center" maxW="max-w-3xl">
        <Reveal as="p" className={LINE}>
          Não acreditamos em treinamentos
          <br />
          que terminam quando as luzes da sala se apagam.
        </Reveal>
        <Reveal
          as="p"
          delay={450}
          className="mt-12 font-display text-2xl font-medium italic text-[color:var(--life)] sm:text-3xl"
        >
          Acreditamos em transformação contínua.
        </Reveal>
      </TextSection>

      {/* ---------- BLOCO 8 (emotional) ---------- */}
      <section className="relative flex min-h-screen w-full items-center overflow-hidden">
        <img
          src={manifestoVida}
          alt="Silhueta ao entardecer olhando para o horizonte"
          width={1920}
          height={1280}
          loading="lazy"
          className="absolute inset-0 h-full w-full object-cover"
        />
        <div className="absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-transparent" />
        <div className="relative z-10 mx-auto w-full max-w-6xl px-6 sm:px-12">
          <div className="max-w-2xl space-y-8 text-white">
            <Reveal
              as="p"
              className="text-[11px] font-medium uppercase tracking-[0.32em] text-white/60"
            >
              VIII
            </Reveal>
            <Reveal as="p" delay={150} className={LINE_SM}>
              Não acreditamos que prevenir seja apenas evitar acidentes.
            </Reveal>
            <div className="space-y-4 pt-6">
              <Reveal
                as="p"
                delay={450}
                className="font-display text-4xl font-light leading-tight tracking-tight sm:text-5xl lg:text-6xl"
              >
                Prevenir é <span className="italic text-[color:var(--safe-gold)]">proteger sonhos</span>.
              </Reveal>
              <Reveal
                as="p"
                delay={700}
                className="font-display text-4xl font-light leading-tight tracking-tight sm:text-5xl lg:text-6xl"
              >
                É <span className="italic text-[color:var(--safe-gold)]">preservar famílias</span>.
              </Reveal>
              <Reveal
                as="p"
                delay={950}
                className="font-display text-4xl font-light leading-tight tracking-tight sm:text-5xl lg:text-6xl"
              >
                É <span className="italic text-[color:var(--safe-gold)]">cuidar da vida</span>.
              </Reveal>
            </div>
          </div>
        </div>
      </section>

      {/* ---------- BLOCO 9 ---------- */}
      <TextSection eyebrow="IX" align="center" maxW="max-w-5xl">
        <Reveal
          as="p"
          className="font-display text-2xl font-light leading-snug text-muted-foreground sm:text-3xl"
        >
          Acreditamos que empresas extraordinárias
          <br />
          não são construídas por processos.
        </Reveal>
        <Reveal
          as="p"
          delay={500}
          className="mt-14 font-display text-5xl font-medium leading-[1.05] tracking-tight text-[color:var(--safe)] sm:text-7xl lg:text-[7rem]"
        >
          São construídas por{" "}
          <span className="italic text-gradient-life">pessoas</span>.
        </Reveal>
      </TextSection>

      {/* ---------- ASSINATURA ---------- */}
      <section
        className={`${SECTION} bg-gradient-to-br from-[color:var(--safe)] via-[color:oklch(0.28_0.05_250)] to-[color:oklch(0.22_0.04_250)] text-white`}
      >
        <div className="mx-auto max-w-4xl text-center">
          <Reveal
            as="p"
            className="mb-12 text-[11px] font-medium uppercase tracking-[0.4em] text-white/60"
          >
            A assinatura do Instituto
          </Reveal>
          <Reveal delay={200} className="mb-14 flex justify-center">
            <span className="block h-px w-24 bg-[color:var(--safe-gold)]" />
          </Reveal>
          <Reveal
            as="blockquote"
            delay={350}
            className="font-display text-2xl font-light leading-[1.35] tracking-tight sm:text-3xl lg:text-4xl"
          >
            Transformamos{" "}
            <span className="italic text-[color:var(--safe-gold)]">conhecimento</span>{" "}
            em cuidado,{" "}
            <span className="italic text-[color:var(--safe-gold)]">comportamento</span>{" "}
            em cultura e{" "}
            <span className="italic text-[color:var(--safe-gold)]">pessoas</span>{" "}
            em protagonistas de ambientes mais seguros, saudáveis e humanos.
          </Reveal>
          <Reveal delay={900} className="mt-14 flex justify-center">
            <span className="block h-px w-24 bg-[color:var(--safe-gold)]" />
          </Reveal>
        </div>
      </section>

      {/* ---------- ENCERRAMENTO ---------- */}
      <TextSection align="center" maxW="max-w-3xl">
        <Reveal
          as="h2"
          className="font-display text-4xl font-light leading-[1.15] tracking-tight sm:text-5xl lg:text-6xl"
        >
          Nosso compromisso
          <br />
          com o <span className="italic text-gradient-life">futuro</span>.
        </Reveal>

        <div className="mx-auto mt-14 max-w-2xl space-y-6 text-lg leading-relaxed text-muted-foreground sm:text-xl">
          <Reveal as="p" delay={200}>
            Que um dia nenhuma empresa cuide da saúde mental apenas para
            cumprir uma norma.
          </Reveal>
          <Reveal as="p" delay={400}>
            Que cuide porque compreendeu que{" "}
            <span className="text-foreground">
              pessoas saudáveis constroem empresas extraordinárias
            </span>
            .
          </Reveal>
          <Reveal
            as="p"
            delay={700}
            className="pt-6 font-display text-2xl italic text-[color:var(--safe)] sm:text-3xl"
          >
            Até esse dia chegar…
          </Reveal>
          <Reveal
            as="p"
            delay={950}
            className="font-display text-2xl italic text-[color:var(--life)] sm:text-3xl"
          >
            continuaremos trabalhando.
          </Reveal>
        </div>
      </TextSection>

      {/* ---------- FECHAMENTO / ASSINATURA VISUAL ---------- */}
      <section className="flex min-h-[70vh] w-full items-center justify-center bg-[color:var(--safe)] px-6 py-24 text-center text-white">
        <div className="max-w-2xl">
          <Reveal delay={100} className="mb-8 flex justify-center">
            <span className="block h-px w-16 bg-white/40" />
          </Reveal>
          <Reveal
            as="p"
            delay={250}
            className="font-display text-3xl font-medium tracking-tight sm:text-4xl"
          >
            Instituto Vida Segura
          </Reveal>
          <Reveal
            as="p"
            delay={500}
            className="mt-6 font-display text-lg italic text-white/75 sm:text-xl"
          >
            &ldquo;Transformando vidas para transformar organizações.&rdquo;
          </Reveal>
          <Reveal delay={800} className="mt-10 flex justify-center">
            <span className="block h-px w-16 bg-white/40" />
          </Reveal>
        </div>
      </section>
    </SiteShell>
  );
}

/* -------------------------------------------------------------------------- */
/*  Small decorative SVG for Bloco 6                                          */
/* -------------------------------------------------------------------------- */

function ConnectingDots() {
  return (
    <svg
      viewBox="0 0 220 220"
      className="h-56 w-56 sm:h-72 sm:w-72"
      fill="none"
      aria-hidden="true"
    >
      <defs>
        <linearGradient id="dotLine" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="var(--life)" stopOpacity="0.9" />
          <stop offset="100%" stopColor="var(--safe)" stopOpacity="0.6" />
        </linearGradient>
      </defs>
      <line x1="40" y1="40" x2="180" y2="110" stroke="url(#dotLine)" strokeWidth="1" />
      <line x1="180" y1="110" x2="60" y2="180" stroke="url(#dotLine)" strokeWidth="1" />
      <line x1="60" y1="180" x2="40" y2="40" stroke="url(#dotLine)" strokeWidth="1" />
      <line x1="40" y1="40" x2="110" y2="110" stroke="url(#dotLine)" strokeWidth="1" />
      <line x1="180" y1="110" x2="110" y2="110" stroke="url(#dotLine)" strokeWidth="1" />
      <line x1="60" y1="180" x2="110" y2="110" stroke="url(#dotLine)" strokeWidth="1" />
      <circle cx="40" cy="40" r="7" fill="var(--safe)" />
      <circle cx="180" cy="110" r="7" fill="var(--safe)" />
      <circle cx="60" cy="180" r="7" fill="var(--safe)" />
      <circle cx="110" cy="110" r="9" fill="var(--life)" />
    </svg>
  );
}
