// Header, Hero, Pain, AllInOne, Phone scroll story

function Header() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const links = [
    { href: "#plataforma", label: "Plataforma" },
    { href: "#modulos", label: "Módulos" },
    { href: "#experiencia", label: "Experiência" },
    { href: "#para-quem", label: "Para quem é" },
    { href: "#contato", label: "Contato" },
  ];
  return (
    <header
      className={
        "fixed left-0 right-0 z-50 transition-all duration-500 ease-[cubic-bezier(.2,.7,.1,1)] " +
        (scrolled ? "top-3 md:top-4" : "top-0")
      }
    >
      <div
        className={
          "mx-auto flex items-center justify-between gap-3 md:gap-6 transition-all duration-500 ease-[cubic-bezier(.2,.7,.1,1)] " +
          (scrolled
            ? "max-w-[1120px] h-[58px] md:h-[64px] rounded-full px-3 md:px-4 bg-white/80 backdrop-blur-xl border border-ink-950/[0.08] shadow-[0_18px_40px_-20px_rgba(8,8,8,0.18)]"
            : "max-w-[1240px] h-[64px] md:h-[72px] rounded-none px-5 sm:px-8 bg-transparent border border-transparent shadow-none")
        }
      >
        <div className={scrolled ? "pl-1" : ""}>
          <Logo />
        </div>
        <nav className="hidden lg:flex items-center gap-1">
          {links.map(l => (
            <a key={l.href} href={l.href} className="px-3 py-2 text-[14px] text-ink-950/70 hover:text-ink-950 transition rounded-full">
              {l.label}
            </a>
          ))}
        </nav>
        <div className="hidden md:flex items-center">
          <CTA href="#contato" className={"text-[14px] transition-all " + (scrolled ? "h-10 px-5" : "h-10 px-5")}>
            Solicitar avaliação
          </CTA>
        </div>
        <button
          aria-label="Abrir menu"
          className="md:hidden inline-flex items-center justify-center rounded-full border border-ink-950/10 bg-white/70 w-10 h-10"
          onClick={() => setOpen(true)}
        >
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg>
        </button>
      </div>

      {/* Mobile drawer */}
      <div className={"fixed inset-0 z-[60] md:hidden transition " + (open ? "pointer-events-auto" : "pointer-events-none")}>
        <div className={"absolute inset-0 bg-ink-950/40 transition-opacity " + (open ? "opacity-100" : "opacity-0")} onClick={() => setOpen(false)} />
        <div className={"absolute top-0 right-0 h-full w-[86%] max-w-[380px] bg-paper-50 shadow-2xl transition-transform duration-300 " + (open ? "translate-x-0" : "translate-x-full")}>
          <div className="flex items-center justify-between h-[64px] px-5 border-b border-ink-950/[0.06]">
            <Logo />
            <button aria-label="Fechar" onClick={() => setOpen(false)} className="w-10 h-10 rounded-full border border-ink-950/10 inline-flex items-center justify-center">
              <I name="x" />
            </button>
          </div>
          <div className="p-5 flex flex-col gap-1">
            {links.map(l => (
              <a key={l.href} href={l.href} onClick={() => setOpen(false)} className="py-3 text-[18px] font-medium border-b border-ink-950/[0.06]">
                {l.label}
              </a>
            ))}
            <div className="mt-5 flex flex-col gap-3">
              <CTA href="#contato" onClick={() => setOpen(false)}>Solicitar avaliação</CTA>
              <CTA href="#plataforma" variant="ghost" onClick={() => setOpen(false)} icon={false}>Ver como funciona</CTA>
            </div>
          </div>
        </div>
      </div>
    </header>
  );
}

function Hero() {
  return (
    <Section id="top" label="01 Hero" className="hero-gradient pt-[96px] md:pt-[120px] pb-16 md:pb-24 overflow-hidden">
      <Container>
        <div className="grid lg:grid-cols-12 gap-10 lg:gap-6 items-center">
          <div className="lg:col-span-7">
            <FadeUp>
              <Pill>Plataforma única para condomínios</Pill>
            </FadeUp>
            <FadeUp delay={0.05}>
              <h1 className="mt-5 text-[44px] sm:text-[58px] lg:text-[76px] leading-[0.98] tracking-tightest font-semibold text-balance">
                Gestão condominial completa.
                <span className="block text-mute-500 font-normal italic font-serif text-[42px] sm:text-[54px] lg:text-[68px] leading-[1.02] mt-2">
                  Em uma experiência simples, rápida e conectada.
                </span>
              </h1>
            </FadeUp>
            <FadeUp delay={0.12}>
              <p className="mt-7 max-w-[600px] text-[17px] md:text-[18px] leading-[1.55] text-mute-500 text-pretty">
                Boletos, Pix, cobranças, portaria, RH, financeiro, documentos, assinaturas, reservas e comunicação. Em uma única plataforma para síndicos, administradoras e moradores.
              </p>
            </FadeUp>
            <FadeUp delay={0.18}>
              <div className="mt-8 flex flex-wrap items-center gap-3">
                <CTA href="#contato">Solicitar avaliação</CTA>
                <CTA href="#plataforma" variant="ghost" icon={false}>
                  <span className="inline-flex items-center justify-center w-5 h-5 rounded-full bg-ink-950 text-paper-50 mr-1">
                    <svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7L8 5Z"/></svg>
                  </span>
                  Ver como funciona
                </CTA>
              </div>
              <p className="mt-4 text-[13px] text-mute-500 max-w-[480px]">
                Uma avaliação rápida para entender a realidade do seu condomínio.
              </p>
            </FadeUp>

            {/* Trust row */}
            <FadeUp delay={0.26}>
              <div className="mt-10 flex flex-wrap items-center gap-x-6 gap-y-3 text-mute-500">
                <div className="flex items-center gap-2 text-[13px]"><span className="w-1.5 h-1.5 rounded-full bg-ok-500"></span> LGPD by design</div>
                <div className="flex items-center gap-2 text-[13px]"><span className="w-1.5 h-1.5 rounded-full bg-ok-500"></span> Pix nativo</div>
                <div className="flex items-center gap-2 text-[13px]"><span className="w-1.5 h-1.5 rounded-full bg-ok-500"></span> Assinatura eletrônica</div>
                <div className="flex items-center gap-2 text-[13px]"><span className="w-1.5 h-1.5 rounded-full bg-ok-500"></span> App iOS & Android</div>
              </div>
            </FadeUp>
          </div>

          <div className="lg:col-span-5 relative">
            <FadeUp delay={0.1}>
              <div className="relative">
                {/* Floating cards behind */}
                <div className="absolute -top-6 -left-6 z-10 hidden sm:block">
                  <MiniStat label="Inadimplência" value="6,3%" sub="↓ 0,8 p.p. vs. mês ant." />
                </div>
                <div className="absolute -bottom-6 -right-2 z-10 hidden sm:block">
                  <MiniStat label="Boletos pagos hoje" value="R$ 142.380" sub="↑ 4,2% em 24h" />
                </div>
                <div className="absolute top-1/2 -right-8 -translate-y-1/2 z-10 hidden md:block">
                  <div className="glass rounded-2xl p-3 flex items-center gap-3 lift">
                    <div className="w-9 h-9 rounded-xl bg-brand-50 text-brand-500 inline-flex items-center justify-center"><I name="pix" size={18}/></div>
                    <div>
                      <div className="text-[12px] text-mute-500">Pix recebido</div>
                      <div className="text-[14px] font-semibold tracking-tight">R$ 824,50 · Bl. A 1204</div>
                    </div>
                  </div>
                </div>
                <div className="relative aspect-square">
                  <img src="assets/tudo-em-um.png" alt="Plataforma centralizada CondoClin" className="w-full h-full object-contain drop-shadow-[0_30px_60px_rgba(8,8,8,0.18)]" />
                </div>
              </div>
            </FadeUp>
          </div>
        </div>

        {/* Logo marquee placeholder */}
        <div className="mt-16 md:mt-24 border-t border-ink-950/[0.06] pt-8">
          <div className="text-[12px] uppercase tracking-[0.18em] text-mute-500 mb-5 text-center">Construído para administradoras, síndicos e moradores</div>
          <div className="overflow-hidden relative">
            <div className="flex gap-12 marquee-track w-max items-center">
              {[
                "ADM Acácias", "Grupo Vila Nova", "Síndico Pro", "Residencial Aurora",
                "Bosque Prime", "Conexa Imóveis", "Riviera Adm.", "Núcleo Living",
                "ADM Acácias", "Grupo Vila Nova", "Síndico Pro", "Residencial Aurora",
                "Bosque Prime", "Conexa Imóveis", "Riviera Adm.", "Núcleo Living",
              ].map((n, i) => (
                <div key={i} className="text-mute-500/70 text-[18px] font-medium tracking-tight whitespace-nowrap">{n}</div>
              ))}
            </div>
          </div>
        </div>
      </Container>
    </Section>
  );
}

function PainSection() {
  const items = [
    { icon: "chart", t: "Cobranças espalhadas", d: "Boletos manuais e planilhas paralelas." },
    { icon: "msg", t: "Comunicação confusa", d: "Grupos perdidos e avisos que se diluem." },
    { icon: "doc", t: "Documentos perdidos", d: "Atas, contratos e ofícios em pastas dispersas." },
    { icon: "cog", t: "Processos manuais", d: "Aprovações lentas e retrabalho diário." },
    { icon: "cam", t: "Portaria sem integração", d: "Acessos e visitantes sem rastreabilidade." },
    { icon: "user", t: "Moradores sem clareza", d: "Ligações repetidas e dúvidas básicas." },
    { icon: "bolt", t: "Síndico sobrecarregado", d: "Mil pequenas decisões sem indicadores." },
    { icon: "lock", t: "Falta de controle", d: "Sem visão financeira em tempo real." },
  ];
  return (
    <Section id="dor" label="02 Pain" className="py-24 md:py-32 bg-paper-50">
      <Container>
        <div className="max-w-[860px]">
          <FadeUp><Pill>O problema</Pill></FadeUp>
          <FadeUp delay={0.05}>
            <h2 className="mt-5 text-[34px] sm:text-[44px] lg:text-[54px] leading-[1.02] tracking-tightest font-semibold text-balance">
              Administrar um condomínio não deveria depender de planilhas, grupos perdidos e sistemas desconectados.
            </h2>
          </FadeUp>
          <FadeUp delay={0.1}>
            <p className="mt-6 text-[17px] text-mute-500 text-pretty max-w-[640px]">
              Quando cada área funciona em uma ferramenta diferente, a gestão perde tempo, controle e previsibilidade. O <span className="text-ink-950 font-medium">CondoClin</span> organiza tudo em um só fluxo.
            </p>
          </FadeUp>
        </div>

        <div className="mt-12 md:mt-16 grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4">
          {items.map((it, i) => (
            <FadeUp key={i} delay={i * 0.04}>
              <div className="group rounded-2xl border border-ink-950/[0.07] bg-white/70 p-5 h-full lift">
                <div className="w-10 h-10 rounded-xl bg-paper-100 text-ink-950 inline-flex items-center justify-center group-hover:bg-brand-50 group-hover:text-brand-500 transition">
                  <I name={it.icon} size={18}/>
                </div>
                <div className="mt-4 text-[15px] font-semibold tracking-tight">{it.t}</div>
                <div className="mt-1 text-[13px] text-mute-500 leading-relaxed">{it.d}</div>
              </div>
            </FadeUp>
          ))}
        </div>
      </Container>
    </Section>
  );
}

function AllInOneSection() {
  const cards = [
    { t: "Financeiro", d: "Receitas, despesas e contratos.", i: "chart" },
    { t: "Boletos & Pix", d: "Emissão, conciliação e baixa automática.", i: "pix" },
    { t: "Cobranças", d: "Régua, lembretes e acordos.", i: "bell" },
    { t: "Portaria", d: "Acessos, encomendas e ronda.", i: "shield" },
    { t: "Visitantes", d: "Pré-autorização e QR Code.", i: "qrcode" },
    { t: "RH", d: "Ponto, folha, férias e documentos.", i: "user" },
    { t: "Almoxarifado", d: "Estoque, requisições e validade.", i: "box" },
    { t: "Documentos", d: "Pastas, versão e busca.", i: "doc" },
    { t: "Assinatura eletrônica", d: "Contratos com validade jurídica.", i: "sign" },
    { t: "Reservas", d: "Salão, churrasqueira e quadras.", i: "calendar" },
    { t: "Ocorrências", d: "Abertura, triagem e SLA.", i: "spark" },
    { t: "Comunicação", d: "Comunicados, enquetes e mural.", i: "msg" },
    { t: "Relatórios", d: "Indicadores para decidir antes.", i: "grid" },
  ];
  return (
    <Section id="plataforma" label="03 All-in-one" className="py-24 md:py-32 bg-paper-100 relative overflow-hidden">
      <div className="absolute inset-0 halo opacity-60 pointer-events-none" />
      <Container className="relative">
        <div className="grid lg:grid-cols-12 gap-12 items-start">
          <div className="lg:col-span-5 lg:sticky lg:top-32">
            <FadeUp><Pill>Tudo em um</Pill></FadeUp>
            <FadeUp delay={0.05}>
              <h2 className="mt-5 text-[36px] sm:text-[46px] lg:text-[56px] leading-[1.02] tracking-tightest font-semibold text-balance">
                Tudo o que o condomínio precisa.
                <span className="block text-mute-500 font-normal italic font-serif">Um só lugar para administrar.</span>
              </h2>
            </FadeUp>
            <FadeUp delay={0.1}>
              <p className="mt-6 text-[16px] text-mute-500 max-w-[480px] text-pretty">
                Treze módulos integrados, dados que conversam e uma única interface para a administradora, o síndico e o morador.
              </p>
            </FadeUp>
            <FadeUp delay={0.16}>
              <div className="mt-6 flex flex-wrap gap-3">
                <CTA href="#modulos">Conhecer a plataforma</CTA>
              </div>
            </FadeUp>

            <FadeUp delay={0.22}>
              <div className="mt-10 relative aspect-square max-w-[420px]">
                <img src="assets/sistem.png" alt="Ecossistema CondoClin" className="w-full h-full object-contain drop-shadow-[0_30px_60px_rgba(8,8,8,0.18)]" />
              </div>
            </FadeUp>
          </div>

          <div className="lg:col-span-7">
            <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
              {cards.map((c, i) => (
                <FadeUp key={i} delay={(i % 6) * 0.03}>
                  <div className="rounded-2xl border border-ink-950/[0.07] bg-white p-4 sm:p-5 h-full lift">
                    <div className="flex items-center justify-between">
                      <div className="w-9 h-9 rounded-lg bg-brand-50 text-brand-500 inline-flex items-center justify-center">
                        <I name={c.i} size={16}/>
                      </div>
                      <span className="text-[10px] uppercase tracking-[0.18em] text-mute-500">{String(i+1).padStart(2,"0")}</span>
                    </div>
                    <div className="mt-4 text-[15px] font-semibold tracking-tight">{c.t}</div>
                    <div className="mt-1 text-[12.5px] text-mute-500 leading-relaxed">{c.d}</div>
                  </div>
                </FadeUp>
              ))}
              {/* Decorative tile */}
              <FadeUp delay={0.2}>
                <div className="rounded-2xl bg-ink-950 text-paper-50 p-5 h-full relative overflow-hidden">
                  <div className="absolute inset-0 halo-dark opacity-90 pointer-events-none"/>
                  <div className="relative">
                    <div className="text-[11px] uppercase tracking-[0.18em] text-white/60">Em um só fluxo</div>
                    <div className="mt-4 text-[18px] font-semibold tracking-tight leading-snug">
                      Menos planilhas, menos retrabalho.<br/>Mais controle.
                    </div>
                    <div className="mt-6 flex items-center gap-2">
                      <span className="inline-block w-1.5 h-1.5 rounded-full bg-brand-500"></span>
                      <span className="text-[12px] text-white/70">Live · CondoClin Cloud</span>
                    </div>
                  </div>
                </div>
              </FadeUp>
            </div>
          </div>
        </div>
      </Container>
    </Section>
  );
}

/* ────────────────────────────────────────────────────────────
   PhoneScrollStory — GSAP ScrollTrigger
   ──────────────────────────────────────────────────────────── */
function PhoneScrollStory() {
  const sectionRef = useRef(null);
  const stageRef = useRef(null);
  const phoneRef = useRef(null);
  const fundoRef = useRef(null);
  const frenteRef = useRef(null);
  const shadowRef = useRef(null);
  const text1Ref = useRef(null);
  const text2Ref = useRef(null);
  const text3Ref = useRef(null);
  const progressRef = useRef(null);
  const reduced = usePrefersReducedMotion();

  useLayoutEffect(() => {
    if (!window.gsap || !window.ScrollTrigger) return;
    const ctx = gsap.context(() => {
      // Initial poses — both faces always opaque, backface-visibility handles the swap
      gsap.set(phoneRef.current, { rotationY: 0, scale: 0.96, transformPerspective: 1800, transformOrigin: "50% 50%" });
      gsap.set(fundoRef.current, { rotationY: 0 });          // shows when parent rotation ~ 0
      gsap.set(frenteRef.current, { rotationY: 180 });       // shows when parent rotation ~ 180
      gsap.set(text2Ref.current, { opacity: 0, y: 24 });
      gsap.set(text3Ref.current, { opacity: 0, y: 24 });

      if (reduced) {
        gsap.set(phoneRef.current, { rotationY: 180, scale: 1 });
        return;
      }

      const tl = gsap.timeline({
        scrollTrigger: {
          trigger: sectionRef.current,
          start: "top top",
          end: "+=200%",
          pin: stageRef.current,
          pinSpacing: true,
          scrub: 0.6,
          anticipatePin: 1,
          onUpdate: (st) => { if (progressRef.current) progressRef.current.style.transform = `scaleX(${st.progress})`; }
        }
      });

      // Rotation 0 → 180 across the whole timeline
      tl.to(phoneRef.current, { rotationY: 180, ease: "none" }, 0);
      // Scale beat: in then out
      tl.fromTo(phoneRef.current, { scale: 0.96 }, { scale: 1.06, ease: "none" }, 0)
        .to(phoneRef.current, { scale: 1, ease: "none" }, 0.5);

      // Soft floor shadow reacts to rotation
      tl.fromTo(shadowRef.current,
        { scaleX: 1, opacity: 0.7 },
        { scaleX: 0.55, opacity: 0.95, ease: "none" }, 0)
        .to(shadowRef.current, { scaleX: 1, opacity: 0.7, ease: "none" }, 0.5);

      // Text steps — three discrete narrative beats
      tl.to(text1Ref.current, { opacity: 0, y: -20, ease: "power2.out" }, 0.32);
      tl.fromTo(text2Ref.current, { opacity: 0, y: 24 }, { opacity: 1, y: 0, ease: "power2.out" }, 0.36);
      tl.to(text2Ref.current, { opacity: 0, y: -20, ease: "power2.out" }, 0.68);
      tl.fromTo(text3Ref.current, { opacity: 0, y: 24 }, { opacity: 1, y: 0, ease: "power2.out" }, 0.72);
    }, sectionRef);
    return () => ctx.revert();
  }, [reduced]);

  return (
    <Section id="experiencia" label="04 Phone story" className="section-dark text-paper-50 relative">
      <div ref={sectionRef} className="relative">
        <div ref={stageRef} className="relative h-screen w-full overflow-hidden">
          {/* Background glow */}
          <div className="absolute inset-0 pointer-events-none">
            <div className="absolute inset-0 halo-dark opacity-80"></div>
          </div>

          <Container className="relative h-full grid grid-rows-[auto_1fr_auto] py-10 md:py-16">
            <div className="flex items-center justify-between">
              <Pill dark>Experiência mobile</Pill>
              <div className="hidden md:flex items-center gap-2 text-white/60 text-[12px] tracking-[0.16em] uppercase">
                <span>Scroll</span>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M12 5v14M6 13l6 6 6-6"/></svg>
              </div>
            </div>

            <div className="grid lg:grid-cols-12 gap-10 lg:gap-6 items-center mt-6 lg:mt-0">
              <div className="lg:col-span-5 order-2 lg:order-1 relative min-h-[120px]">
                {/* Heading is constant */}
                <h2 className="text-[30px] sm:text-[40px] lg:text-[52px] leading-[1.02] tracking-tightest font-semibold text-balance">
                  Do painel do síndico
                  <span className="block text-white/55 italic font-serif font-normal">à palma da mão do morador.</span>
                </h2>

                {/* Stacked text steps */}
                <div className="relative mt-7 h-[140px]">
                  <p ref={text1Ref} className="absolute inset-0 text-[16px] md:text-[17px] text-white/75 max-w-[440px] leading-relaxed">
                    O morador acompanha boletos, comunicados, reservas, acessos e documentos pelo app.
                  </p>
                  <p ref={text2Ref} className="absolute inset-0 text-[16px] md:text-[17px] text-white/75 max-w-[440px] leading-relaxed">
                    O síndico visualiza pendências, aprova solicitações e acompanha a rotina do condomínio com clareza.
                  </p>
                  <p ref={text3Ref} className="absolute inset-0 text-[16px] md:text-[17px] text-white/75 max-w-[440px] leading-relaxed">
                    A administradora centraliza operação, financeiro e comunicação em uma experiência digital única.
                  </p>
                </div>

                <div className="mt-6 hidden md:flex items-center gap-3">
                  <CTA href="#modulos" variant="ghost-dark">Conhecer módulos</CTA>
                </div>
              </div>

              <div className="lg:col-span-7 order-1 lg:order-2">
                <div className="phone-stage relative mx-auto w-[78vw] max-w-[420px] aspect-[1/1.05]">
                  <div ref={phoneRef} className="phone-3d absolute inset-0">
                    <div ref={fundoRef} className="phone-face">
                      <img src="assets/celular-fundo.png" alt="" />
                    </div>
                    <div ref={frenteRef} className="phone-face">
                      <img src="assets/celular-frente.png" alt="CondoClin app, tela inicial" />
                    </div>
                  </div>
                  <div ref={shadowRef} className="floor-shadow"></div>
                </div>
              </div>
            </div>

            {/* Progress bar */}
            <div className="mt-8">
              <div className="h-[2px] w-full bg-white/10 rounded-full overflow-hidden">
                <div ref={progressRef} className="h-full w-full bg-brand-500 origin-left scale-x-0"></div>
              </div>
              <div className="mt-3 flex items-center justify-between text-[11px] uppercase tracking-[0.18em] text-white/50">
                <span>01 · Morador</span>
                <span>02 · Síndico</span>
                <span>03 · Administradora</span>
              </div>
            </div>
          </Container>
        </div>
      </div>
    </Section>
  );
}

Object.assign(window, { Header, Hero, PainSection, AllInOneSection, PhoneScrollStory });
