// Modules, NotebookRevealSection, Audience, Authority

function ModulesSection() {
  const mods = [
    {
      id: "financeiro",
      pre: "Módulo 01",
      title: "Financeiro, boletos, Pix e cobranças sem perder o controle.",
      desc: "Automatize cobranças, acompanhe pagamentos, organize contratos e tenha uma visão clara da saúde financeira do condomínio.",
      bullets: ["Régua de cobrança automática", "Conciliação Pix em segundos", "Fluxo de caixa e DRE em tempo real"],
      img: "assets/financeiro.png",
      accent: "bg-brand-50",
    },
    {
      id: "portaria",
      pre: "Módulo 02",
      title: "Portaria, visitantes e acessos mais seguros.",
      desc: "Controle entradas, visitantes, QR Codes, autorizações, comunicados e ocorrências com mais rastreabilidade.",
      bullets: ["Pré-autorização por QR Code", "Encomendas com retirada digital", "Histórico de acessos auditável"],
      img: "assets/portaria.png",
      accent: "bg-paper-100",
      reverse: true,
    },
    {
      id: "rh",
      pre: "Módulo 03",
      title: "RH, folha, ponto e documentos em um fluxo organizado.",
      desc: "Gerencie colaboradores, férias, ponto, documentos e aprovações sem depender de processos espalhados.",
      bullets: ["Ponto digital com geolocalização", "Folha e provisões automáticas", "Documentos com assinatura eletrônica"],
      img: "assets/rh.png",
      accent: "bg-brand-50",
    },
    {
      id: "comunicacao",
      pre: "Módulo 04",
      title: "Comunicação clara entre condomínio, síndico e moradores.",
      desc: "Envie comunicados, registre ocorrências, acompanhe solicitações e reduza ruídos no dia a dia.",
      bullets: ["Comunicados segmentados por bloco", "Mural com confirmação de leitura", "Ocorrências com SLA e respostas"],
      img: "assets/sistem.png",
      accent: "bg-paper-100",
      reverse: true,
    },
  ];

  return (
    <Section id="modulos" label="05 Modules" className="py-24 md:py-32 bg-paper-50">
      <Container>
        <div className="max-w-[820px] mb-16">
          <FadeUp><Pill>Módulos principais</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">
              Do boleto à portaria,
              <span className="block text-mute-500 font-serif italic font-normal">tudo conectado em um só sistema.</span>
            </h2>
          </FadeUp>
        </div>

        <div className="flex flex-col gap-16 md:gap-24">
          {mods.map((m, idx) => (
            <div key={m.id} className="grid md:grid-cols-12 gap-8 md:gap-12 items-center">
              <FadeUp className={"md:col-span-6 " + (m.reverse ? "md:order-2" : "")}>
                <div className={"relative rounded-[28px] overflow-hidden " + m.accent + " p-8 md:p-10 aspect-[5/4] flex items-center justify-center"}>
                  <div className="absolute inset-0 halo opacity-50 pointer-events-none"></div>
                  <img src={m.img} alt="" className="relative w-full h-full max-w-[480px] object-contain drop-shadow-[0_30px_60px_rgba(8,8,8,0.18)]" loading="lazy" />
                  <div className="absolute top-4 left-4 text-[11px] uppercase tracking-[0.18em] text-ink-950/60 font-medium">{m.pre}</div>
                </div>
              </FadeUp>
              <FadeUp delay={0.05} className={"md:col-span-6 " + (m.reverse ? "md:order-1" : "")}>
                <h3 className="text-[28px] sm:text-[34px] lg:text-[40px] leading-[1.06] tracking-tightest font-semibold text-balance">
                  {m.title}
                </h3>
                <p className="mt-5 text-[16px] md:text-[17px] text-mute-500 leading-relaxed text-pretty max-w-[520px]">
                  {m.desc}
                </p>
                <ul className="mt-6 flex flex-col gap-3">
                  {m.bullets.map((b, i) => (
                    <li key={i} className="flex items-start gap-3 text-[15px]">
                      <span className="mt-1 w-5 h-5 rounded-full bg-brand-500/10 text-brand-500 inline-flex items-center justify-center shrink-0">
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12l5 5L20 6"/></svg>
                      </span>
                      <span className="text-ink-950/85">{b}</span>
                    </li>
                  ))}
                </ul>
                <div className="mt-7 flex flex-wrap gap-3">
                  <CTA href="#contato" variant="ghost">Ver demonstração</CTA>
                </div>
              </FadeUp>
            </div>
          ))}
        </div>
      </Container>
    </Section>
  );
}

/* ────────────────────────────────────────────────────────────
   NotebookRevealSection — GSAP ScrollTrigger
   ──────────────────────────────────────────────────────────── */
function NotebookRevealSection() {
  const sectionRef = useRef(null);
  const stageRef = useRef(null);
  const notebookRef = useRef(null);
  const screenRef = useRef(null);
  const reduced = usePrefersReducedMotion();

  useLayoutEffect(() => {
    if (!window.gsap || !window.ScrollTrigger) return;
    const ctx = gsap.context(() => {
      // Notebook stays still — only the screen overlay fades on scroll
      gsap.set(notebookRef.current, { clearProps: "all" });
      gsap.set(screenRef.current, { opacity: 1 });

      if (reduced) {
        gsap.set(screenRef.current, { opacity: 0 });
        return;
      }

      const tl = gsap.timeline({
        scrollTrigger: {
          trigger: sectionRef.current,
          start: "top top",
          end: "+=160%",
          pin: stageRef.current,
          pinSpacing: true,
          scrub: 0.6,
          anticipatePin: 1,
        }
      });
      // Pure opacity exit on the boot screen
      tl.to(screenRef.current, { opacity: 0, ease: "power1.inOut" }, 0);

      // Fade in indicator cards via stagger
      const cards = sectionRef.current.querySelectorAll("[data-card]");
      gsap.set(cards, { opacity: 0, y: 30, scale: 0.92 });
      tl.to(cards, { opacity: 1, y: 0, scale: 1, stagger: 0.08, ease: "power2.out" }, 0.4);
    }, sectionRef);
    return () => ctx.revert();
  }, [reduced]);

  const cards = [
    { t: "Inadimplência", v: "6,3%", trend: "-0,8 p.p.", pos: "top-[6%] left-[2%]", icon: "chart" },
    { t: "Boletos em aberto", v: "R$ 142.380", trend: "↓ 4,2%", pos: "top-[8%] right-[2%]", icon: "doc" },
    { t: "Ocorrências pendentes", v: "5", trend: "2 críticas", pos: "top-1/2 left-[1%]", icon: "spark" },
    { t: "Reservas da semana", v: "14", trend: "↑ 3", pos: "top-1/2 right-[1%]", icon: "calendar" },
    { t: "Comunicados", v: "12 enviados", trend: "97% leitura", pos: "bottom-[8%] left-[6%]", icon: "msg" },
    { t: "Portaria · hoje", v: "148 eventos", trend: "3 bloqueios", pos: "bottom-[6%] right-[6%]", icon: "shield" },
  ];

  return (
    <Section id="dashboard" label="06 Notebook reveal" className="bg-paper-100 relative">
      <div ref={sectionRef} className="relative">
        <div ref={stageRef} className="relative h-screen w-full overflow-hidden">
          <div className="absolute inset-0 halo opacity-50 pointer-events-none"></div>

          <Container className="relative h-full grid grid-rows-[auto_1fr] py-10 md:py-16">
            <div className="text-center max-w-[820px] mx-auto">
              <FadeUp><Pill>Painel de gestão</Pill></FadeUp>
              <FadeUp delay={0.05}>
                <h2 className="mt-4 text-[30px] sm:text-[40px] lg:text-[52px] leading-[1.02] tracking-tightest font-semibold text-balance">
                  Uma visão completa
                  <span className="block text-mute-500 font-serif italic font-normal">para decidir melhor.</span>
                </h2>
              </FadeUp>
              <FadeUp delay={0.1}>
                <p className="mt-5 text-[15px] md:text-[16px] text-mute-500 max-w-[640px] mx-auto text-pretty">
                  O painel centraliza indicadores, pendências, alertas, financeiro, chamados e movimentações importantes, para a gestão atuar antes do problema crescer.
                </p>
              </FadeUp>
            </div>

            <div className="relative w-full h-full flex items-center justify-center overflow-visible pb-6 md:pb-10">
              <div
                className="relative w-full mx-auto"
                style={{ aspectRatio: '1 / 1', maxWidth: '1080px', maxHeight: 'min(68vh, 760px)' }}
              >
                {/* Notebook base (real dashboard) */}
                <div ref={notebookRef} className="absolute inset-0 will-change-transform">
                  <img src="assets/notebook.png" alt="CondoClin dashboard no notebook" className="w-full h-full object-contain drop-shadow-[0_40px_70px_rgba(8,8,8,0.25)]" />
                </div>

                {/* Boot overlay: the original tela-notebook image, faded by scroll */}
                <div ref={screenRef} className="absolute inset-0 will-change-[opacity] pointer-events-none">
                  <img src="assets/tela-notebook.png" alt="" className="w-full h-full object-contain" />
                </div>

                {/* Floating indicator cards */}
                {cards.map((c, i) => (
                  <div
                    key={i}
                    data-card
                    className={"absolute " + c.pos + " hidden md:block z-10"}
                  >
                    <div className="glass rounded-2xl p-3 pr-4 flex items-center gap-3 min-w-[180px] lift">
                      <div className="w-9 h-9 rounded-lg bg-brand-50 text-brand-500 inline-flex items-center justify-center">
                        <I name={c.icon} size={16}/>
                      </div>
                      <div>
                        <div className="text-[10px] uppercase tracking-[0.16em] text-mute-500">{c.t}</div>
                        <div className="text-[14px] font-semibold tracking-tight">{c.v}</div>
                        <div className="text-[11px] text-ok-500">{c.trend}</div>
                      </div>
                    </div>
                  </div>
                ))}

                {/* Mobile fallback chip strip */}
                <div className="md:hidden absolute -bottom-2 left-0 right-0 flex gap-2 overflow-x-auto no-scrollbar pb-2 z-10">
                  {cards.slice(0,4).map((c,i)=>(
                    <div key={i} data-card className="glass rounded-2xl p-3 flex items-center gap-2 shrink-0">
                      <div className="w-7 h-7 rounded-md bg-brand-50 text-brand-500 inline-flex items-center justify-center"><I name={c.icon} size={14}/></div>
                      <div>
                        <div className="text-[9px] uppercase tracking-[0.14em] text-mute-500">{c.t}</div>
                        <div className="text-[12px] font-semibold tracking-tight">{c.v}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </Container>
        </div>
      </div>
    </Section>
  );
}

function AudienceSection() {
  const cards = [
    { t: "Administradoras", d: "Mais controle para gerenciar múltiplos condomínios com processos padronizados.", icon: "building" },
    { t: "Síndicos", d: "Menos sobrecarga operacional e mais clareza para tomar decisões.", icon: "shield" },
    { t: "Moradores", d: "Uma experiência simples para acessar boletos, comunicados, reservas e solicitações.", icon: "home" },
    { t: "Equipes internas", d: "Portaria, financeiro, RH e manutenção trabalhando no mesmo fluxo.", icon: "cog" },
  ];
  return (
    <Section id="para-quem" label="07 Audience" className="py-24 md:py-32 bg-ink-950 text-paper-50 relative overflow-hidden">
      <div className="absolute inset-0 halo-dark opacity-80 pointer-events-none"></div>
      <Container className="relative">
        <div className="max-w-[760px]">
          <FadeUp><Pill dark>Para quem é</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">
              Feito para quem administra, opera
              <span className="block text-white/55 font-serif italic font-normal">e vive o condomínio.</span>
            </h2>
          </FadeUp>
        </div>

        <div className="mt-12 grid sm:grid-cols-2 lg:grid-cols-4 gap-3 md:gap-4">
          {cards.map((c, i) => (
            <FadeUp key={i} delay={i * 0.05}>
              <div className="group h-full rounded-2xl border border-white/[0.08] bg-white/[0.04] p-6 hover:bg-white/[0.07] transition lift">
                <div className="w-11 h-11 rounded-xl bg-brand-500/15 text-brand-300 inline-flex items-center justify-center">
                  <I name={c.icon} size={18}/>
                </div>
                <div className="mt-5 text-[18px] font-semibold tracking-tight">{c.t}</div>
                <div className="mt-2 text-[13.5px] text-white/65 leading-relaxed text-pretty">{c.d}</div>
                <div className="mt-6 inline-flex items-center gap-2 text-[12px] text-brand-300 opacity-80 group-hover:opacity-100 transition">
                  <span>Ver papel</span>
                  <I name="arrow" size={14}/>
                </div>
              </div>
            </FadeUp>
          ))}
        </div>

        {/* Authority sub-block */}
        <div className="mt-20 grid lg:grid-cols-12 gap-10 items-center">
          <div className="lg:col-span-7">
            <FadeUp>
              <h3 className="text-[28px] sm:text-[34px] lg:text-[42px] leading-[1.04] tracking-tightest font-semibold text-balance">
                Tecnologia para transformar a rotina condominial em gestão inteligente.
              </h3>
            </FadeUp>
            <FadeUp delay={0.06}>
              <p className="mt-5 text-[16px] text-white/65 max-w-[560px] text-pretty">
                O CondoClin foi pensado para reduzir ruídos, centralizar informações e criar uma experiência mais organizada para todos os envolvidos na vida condominial.
              </p>
            </FadeUp>
            <div className="mt-8 grid sm:grid-cols-2 gap-3">
              {[
                "Plataforma completa",
                "Experiência mobile-first",
                "Gestão centralizada",
                "Comunicação integrada",
                "Dados para decisão",
                "Processos mais seguros",
              ].map((t, i) => (
                <FadeUp key={i} delay={i * 0.04}>
                  <div className="flex items-center gap-3 rounded-xl border border-white/10 bg-white/[0.03] px-4 py-3">
                    <span className="w-2 h-2 rounded-full bg-brand-500"></span>
                    <span className="text-[14px] text-white/85">{t}</span>
                  </div>
                </FadeUp>
              ))}
            </div>
          </div>
          <div className="lg:col-span-5">
            <FadeUp delay={0.1}>
              <div className="relative">
                <div className="absolute inset-0 rounded-[32px] bg-gradient-to-br from-brand-500/30 to-transparent blur-2xl"></div>
                <div className="relative rounded-[28px] glass-dark p-6">
                  <div className="flex items-center gap-3">
                    <img src="assets/cond-ai.png" alt="" className="w-14 h-14 rounded-full object-cover bg-white/5" />
                    <div>
                      <div className="text-[13px] text-white/60">Atendimento CondoClin</div>
                      <div className="text-[15px] font-semibold tracking-tight">Marina · especialista</div>
                    </div>
                  </div>
                  <div className="mt-5 rounded-2xl bg-white/[0.04] border border-white/[0.06] p-4 text-[14px] text-white/80 leading-relaxed">
                    "A gestão condominial que antes era fragmentada, agora cabe em uma única experiência."
                  </div>
                  <div className="mt-4 flex gap-2">
                    <CTA href="#contato" variant="primary" className="h-10 px-4 text-[13px]">Falar agora</CTA>
                    <CTA href="#faq" variant="ghost-dark" className="h-10 px-4 text-[13px]" icon={false}>Dúvidas frequentes</CTA>
                  </div>
                </div>
              </div>
            </FadeUp>
          </div>
        </div>
      </Container>
    </Section>
  );
}

Object.assign(window, { ModulesSection, NotebookRevealSection, AudienceSection });
