// Trust bar + Manifesto + Benefits + Gallery — editorial, no AI tone

const TrustBar = () => (
  <section className="trust-bar" aria-label="Provas institucionais">
    <div className="container trust-bar-inner">
      {CONTENT.trust.map((t, i) => (
        <span className="trust-item" key={i}>
          <span className="dot" aria-hidden="true"></span>
          <strong>{t.strong}</strong> <span className="trust-suffix">{t.suffix}</span>
        </span>
      ))}
    </div>
  </section>
);

const ManifestoSection = ({ intent = "" } = {}) => {
  const m = CONTENT.manifesto;
  return (
    <section
      className="section manifesto with-form"
      id="lead-form-manifesto"
      data-screen-label="02 Manifesto"
    >
      <div className="container">
        <div className="manifesto-text">
          <Reveal>
            <span className="eyebrow">{m.eyebrow}</span>
          </Reveal>
          <Reveal delay={120}>
            <h2 className="h-display manifesto-headline">
              {m.lineA}
              <br />
              <em>{m.lineB}</em>
            </h2>
          </Reveal>
          <Reveal delay={220}>
            <p className="manifesto-body">{m.body}</p>
          </Reveal>
        </div>

        <Reveal delay={200} className="manifesto-form-wrap">
          <div className="lead-form-card">
            <div className="lf-header">
              <h2 className="lf-title">Tabela completa, plantas e condições</h2>
              <p className="lf-sub">Receba o estudo personalizado.</p>
            </div>
            <LeadForm location="manifesto" defaultIntent={intent} />
          </div>
        </Reveal>
      </div>
    </section>
  );
};

const BenefitsSection = () => {
  const b = CONTENT.benefits;
  return (
    <section className="section" id="beneficios" data-screen-label="03 Diferenciais">
      <div className="container">
        <Reveal>
          <div className="bn-header">
            <div className="bn-header-text">
              <span className="eyebrow">{b.eyebrow}</span>
              <h2 className="h2 bn-headline">{b.headline}</h2>
            </div>
            <p className="lede bn-lede">{b.lede}</p>
          </div>
        </Reveal>

        <div className="bn-grid">
          {b.cards.map((c, i) => (
            <Reveal key={c.title} delay={i * 90}>
              <article className="bn-card">
                <span className="bn-num">0{i + 1}</span>
                <hr className="bn-rule" />
                <h3 className="h3 bn-card-title">{c.title}</h3>
                <p className="bn-card-body">{c.body}</p>
              </article>
            </Reveal>
          ))}
        </div>

        <Reveal delay={300}>
          <div className="bn-cta">
            <button
              type="button"
              className="link-arrow"
              onClick={() => {
                track("inline_cta_click", { location: "benefits" });
                scrollToId("lead-form-final");
              }}
            >
              Receber a tabela completa <Icon name="arrowR" size={14} />
            </button>
          </div>
        </Reveal>
      </div>
    </section>
  );
};

const GallerySection = () => {
  const [open, setOpen] = lfUseState(null);
  const [active, setActive] = lfUseState(0);
  const gs = CONTENT.gallerySection;
  const images = CONTENT.gallery.map((g) => ({
    ...g,
    url: CONTENT.images[g.img] || CONTENT.images.lobby,
  }));
  const blockRefs = lfUseRef([]);

  // Sticky scroll-sync: IntersectionObserver pra detectar bloco ativo
  lfUseEffect(() => {
    if (typeof window === "undefined") return;
    if (window.matchMedia("(max-width: 768px)").matches) return;
    const nodes = blockRefs.current.filter(Boolean);
    if (!nodes.length) return;
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting && e.intersectionRatio > 0.5) {
            const idx = Number(e.target.getAttribute("data-idx"));
            if (!Number.isNaN(idx)) setActive(idx);
          }
        });
      },
      { threshold: [0.5, 0.75], rootMargin: "-20% 0px -20% 0px" }
    );
    nodes.forEach((n) => obs.observe(n));
    return () => obs.disconnect();
  }, [images.length]);

  lfUseEffect(() => {
    if (open === null) return;
    const onKey = (e) => {
      if (e.key === "Escape") setOpen(null);
      if (e.key === "ArrowLeft") setOpen(o => Math.max(0, o - 1));
      if (e.key === "ArrowRight") setOpen(o => Math.min(images.length - 1, o + 1));
    };
    document.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [open, images.length]);

  const scrollToBlock = (i) => {
    const node = blockRefs.current[i];
    if (node && typeof node.scrollIntoView === "function") {
      node.scrollIntoView({ behavior: "smooth", block: "center" });
    }
    setActive(i);
  };

  return (
    <section className="section section-tight" id="galeria" data-screen-label="04 Galeria">
      <div className="container">
        <Reveal>
          <div className="g-header">
            <div className="g-header-text">
              <span className="eyebrow">{gs.eyebrow}</span>
              <h2 className="h2 g-headline">{gs.headline}</h2>
            </div>
            <p className="lede g-lede">{gs.lede}</p>
          </div>
        </Reveal>

        {/* Sticky scroll-sync — desktop */}
        <div className="gallery-sticky-wrap hidden-mobile">
          <div className="gallery-sticky-image">
            {images.map((img, i) => (
              <img
                key={i}
                src={img.url}
                alt={img.label}
                loading={i === 0 ? "eager" : "lazy"}
                decoding="async"
                className={`gallery-sticky-img ${active === i ? "is-active" : ""}`}
                onClick={() => { setOpen(active); track("gallery_open", { image_index: active }); }}
              />
            ))}
            <button
              type="button"
              className="g-expand-sticky"
              onClick={() => { setOpen(active); track("gallery_open", { image_index: active }); }}
              aria-label="Ampliar imagem"
            >
              <Icon name="expand" size={16} />
            </button>
          </div>

          <div className="gallery-scroll-list">
            {images.map((img, i) => (
              <div
                key={i}
                ref={(el) => { if (blockRefs.current) blockRefs.current[i] = el; }}
                data-idx={i}
                className={`gallery-scroll-block ${active === i ? "is-active" : ""}`}
              >
                <span className="g-block-num">{String(i + 1).padStart(2, "0")}</span>
                <h3 className="g-block-title">{img.label}</h3>
                {img.caption && <p className="g-block-caption">{img.caption}</p>}
              </div>
            ))}
          </div>
        </div>

        {/* Thumbs strip — desktop */}
        <div className="gallery-thumbs-strip hidden-mobile">
          {images.map((img, i) => (
            <button
              key={i}
              type="button"
              className={`g-thumb ${active === i ? "is-active" : ""}`}
              onClick={() => scrollToBlock(i)}
              aria-label={`Ir para ${img.label}`}
            >
              <img src={img.url} alt={img.label} loading="lazy" decoding="async" />
            </button>
          ))}
        </div>

        {/* Mobile snap row */}
        <div className="gallery-mobile only-mobile">
          {images.map((img, i) => (
            <button
              key={i}
              className="g-item-m"
              onClick={() => { setOpen(i); track("gallery_open", { image_index: i }); }}
              aria-label={`Abrir foto: ${img.label}`}
            >
              <img src={img.url} alt={img.label} loading="lazy" decoding="async" />
            </button>
          ))}
        </div>
      </div>

      {open !== null && (
        <div
          className="dialog-overlay"
          onClick={() => setOpen(null)}
          role="dialog"
          aria-modal="true"
          aria-label="Galeria ampliada"
        >
          <button className="dialog-close" onClick={() => setOpen(null)} aria-label="Fechar">
            <Icon name="close" size={20} />
          </button>
          {open > 0 && (
            <button
              className="dialog-nav prev"
              onClick={(e) => { e.stopPropagation(); setOpen(o => o - 1); }}
              aria-label="Anterior"
            >
              <Icon name="chevronL" size={22} />
            </button>
          )}
          {open < images.length - 1 && (
            <button
              className="dialog-nav next"
              onClick={(e) => { e.stopPropagation(); setOpen(o => o + 1); }}
              aria-label="Próxima"
            >
              <Icon name="chevronR" size={22} />
            </button>
          )}
          <div
            className="dialog-content"
            onClick={(e) => e.stopPropagation()}
          >
            <img src={images[open].url} alt={images[open].label} />
            <div className="dialog-caption">
              <span>{String(open + 1).padStart(2, "0")} / {String(images.length).padStart(2, "0")}</span>
              <span>{images[open].label}</span>
            </div>
          </div>
        </div>
      )}
    </section>
  );
};

const BeachConceptSection = () => {
  const bc = CONTENT.beachConcept || {};
  const imgLarge = CONTENT.images[bc.imgLarge] || CONTENT.images.heroBg;
  const imgSmall = CONTENT.images[bc.imgSmall] || CONTENT.images.lobby;
  return (
    <section className="section beach-concept" data-screen-label="05 Beach Concept">
      <div className="container beach-concept-grid">
        <Reveal className="bc-col bc-col-large">
          <figure className="bc-figure bc-figure-large">
            <img
              src={imgLarge}
              alt={bc.headline || "Conceito Rove"}
              loading="lazy"
              decoding="async"
            />
          </figure>
        </Reveal>

        <div className="bc-col bc-col-stacked">
          <Reveal delay={120}>
            <figure className="bc-figure bc-figure-small">
              <img
                src={imgSmall}
                alt={`${bc.headline || "Rove"} — detalhe`}
                loading="lazy"
                decoding="async"
              />
            </figure>
          </Reveal>
          <Reveal delay={220}>
            <div className="bc-text">
              {bc.eyebrow && <span className="eyebrow">{bc.eyebrow}</span>}
              {bc.headline && <h2 className="h2 bc-headline">{bc.headline}</h2>}
              {bc.sub && <p className="bc-sub">{bc.sub}</p>}
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
};

// D14/D15 · Áreas comuns + Galeria fundidas — 2-col desktop · 1-col mobile
// D18 · Galeria à ESQUERDA (62% · maior · esticada) · cards à DIREITA (38%)
// D21 · Scroll-PIN no desktop: section sticky, cada step (vh) de scroll troca a foto · libera após última
//        Mobile mantém scroll-sync simples (sem pin).
const AmenitiesGallerySection = () => {
  const a = CONTENT.amenities;
  const images = CONTENT.gallery.map((g) => ({
    ...g,
    url: CONTENT.images[g.img] || CONTENT.images.lobby,
  }));
  const [idx, setIdx] = lfUseState(0);
  const sectionRef = lfUseRef(null);
  const manualOverrideRef = lfUseRef(0);

  // Preload silencioso das próximas imagens (não-crítico)
  lfUseEffect(() => {
    if (typeof Image === "undefined") return;
    images.forEach((im) => {
      const i = new Image();
      i.src = im.url;
    });
  }, []);

  // D21 · scroll-driver: PIN no desktop (≥980px), scroll-sync simples no mobile
  lfUseEffect(() => {
    if (typeof window === "undefined") return;
    if (!images.length) return;
    let raf = null;
    const mql =
      typeof window.matchMedia === "function"
        ? window.matchMedia("(min-width: 980px)")
        : null;
    const tick = () => {
      raf = null;
      if (Date.now() < manualOverrideRef.current) return;
      const node = sectionRef.current;
      if (!node) return;
      const rect = node.getBoundingClientRect();
      const vh = window.innerHeight || document.documentElement.clientHeight;
      const pinned = mql ? mql.matches : false;
      let targetIdx;
      if (pinned) {
        // pin: cada vh de scroll dentro da section = 1 step
        const scrolled = -rect.top;
        const step = scrolled / Math.max(vh, 1);
        targetIdx = Math.min(images.length - 1, Math.max(0, Math.floor(step)));
      } else {
        // mobile / fallback original: imagem troca conforme section passa pelo viewport
        const visible = rect.top < vh && rect.bottom > 0;
        if (!visible) return;
        const denom = rect.height + vh;
        if (denom <= 0) return;
        const progress = Math.max(0, Math.min(1, (vh - rect.top) / denom));
        targetIdx = Math.min(images.length - 1, Math.floor(progress * images.length));
      }
      setIdx((curr) => (targetIdx !== curr ? targetIdx : curr));
    };
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll, { passive: true });
    onScroll();
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [images.length]);

  const safeIdx = Math.min(Math.max(idx, 0), Math.max(images.length - 1, 0));
  const current = images[safeIdx];

  const handleThumbClick = (i, label) => {
    manualOverrideRef.current = Date.now() + 3000;
    setIdx(i);
    track("gallery_thumb_click", { i, label });
  };

  return (
    <section
      ref={sectionRef}
      className="section amenities-gallery"
      id="amenities-gallery"
      data-screen-label="04 Áreas + Galeria"
      style={{ "--ag-steps": images.length }}
    >
      <div className="ag-pin-wrap">
      <div className="container ag-container">
        {/* D18 · galeria PRIMEIRO no DOM → coluna esquerda do grid */}
        <div className="ag-gallery">
          <Reveal>
            <div className="ag-stage">
              {images.map((im, i) => (
                <img
                  key={i}
                  src={im.url}
                  alt={im.label}
                  loading={i === 0 ? "eager" : "lazy"}
                  decoding="async"
                  className={`ag-stage-img ${i === safeIdx ? "is-active" : ""}`}
                />
              ))}
              {current && <span className="ag-caption">{current.label}</span>}
            </div>
          </Reveal>

          <div className="ag-thumbs" role="tablist" aria-label="Galeria de imagens">
            {images.map((im, i) => (
              <button
                key={i}
                type="button"
                role="tab"
                aria-selected={i === safeIdx}
                className={`ag-thumb ${i === safeIdx ? "is-active" : ""}`}
                onClick={() => handleThumbClick(i, im.label)}
                aria-label={`Ver ${im.label}`}
              >
                <img src={im.url} alt="" loading="lazy" decoding="async" />
              </button>
            ))}
          </div>
        </div>

        {/* D18 · cards de áreas comuns → coluna direita */}
        <div className="ag-amenities">
          <Reveal>
            <div className="ag-amenities-header">
              <span className="eyebrow">Áreas comuns + Imagens</span>
              <h2 className="h2 am-headline">{a.headline}</h2>
              <p className="lede am-lede">{a.lede}</p>
            </div>
          </Reveal>

          <div className="ag-amenities-grid">
            {a.items.map((item, i) => (
              <Reveal key={item.title} delay={i * 60}>
                <article className="am-card am-card-compact">
                  <div className="am-photo">
                    <img
                      src={CONTENT.images[item.img]}
                      alt={`${item.title} · ${item.subtitle}`}
                      loading="lazy"
                      decoding="async"
                    />
                  </div>
                  <div className="am-body">
                    <span className="am-num mono">{String(i + 1).padStart(2, "0")}</span>
                    <h3 className="am-title">{item.title}</h3>
                    <p className="am-sub">{item.subtitle}</p>
                  </div>
                </article>
              </Reveal>
            ))}
          </div>
        </div>
      </div>
      </div>
    </section>
  );
};

Object.assign(window, { TrustBar, ManifestoSection, BenefitsSection, GallerySection, BeachConceptSection, AmenitiesGallerySection });
