/* global React, window */
// Sections for the Dolado lean premium homepage.
// All sections take `t` (translated copy block) and `theme`.
// Components export to window.DoladoSections for app.jsx to consume.

const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* ============================================================
   Hook — IntersectionObserver reveal
   ============================================================ */
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12 }
    );
    el.querySelectorAll(".reveal").forEach((n) => io.observe(n));
    return () => io.disconnect();
  }, []);
  return ref;
}

/* ============================================================
   LogoMarquee — infinite-scroll logo carousel
   Duplicates the list and translates -50% so the loop is seamless.
   Pauses on hover. Theme-aware monochrome via CSS.
   ============================================================ */
function LogoMarquee({ items, speed = 40, itemWidth = 220, dense = false }) {
  // Duplicate for seamless loop. Three copies keeps it smooth even
  // when the list is short (8 funds × 3 = 24 cells visible at any time).
  const looped = [...items, ...items, ...items];
  // Resolve logo path through window.__resources for standalone HTML bundles
  // (the bundler maps each declared resource id to a blob URL at runtime).
  const resolveSrc = (p) =>
    (typeof window !== "undefined" && window.__resources && window.__resources[p]) || p;
  return (
    <div className={`logo-marquee ${dense ? "is-dense" : ""}`}>
      <div
        className="logo-marquee-track"
        style={{
          animationDuration: `${speed}s`,
          "--marquee-item-w": `${itemWidth}px`,
        }}
      >
        {looped.map((it, i) => (
          <div key={i} className="logo-marquee-item" title={it.name}>
            <img src={resolveSrc(it.logo)} alt={it.name} loading="lazy" />
          </div>
        ))}
      </div>
    </div>
  );
}

/* ============================================================
   Hook — count-up
   ============================================================ */
function useCountUp(target, { duration = 1200, decimals = 0 } = {}) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(eased * target);
            if (t < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [target, duration]);
  return [val, ref];
}

/* ============================================================
   NAV
   ============================================================ */
function Nav({ t, lang, setLang, theme, openModal }) {
  return (
    <nav className="dl-nav">
      <a className="dl-nav-brand" href="#top" onClick={(e) => e.preventDefault()}>
        <img src="assets/dolado-logo-white.png" alt="dolado" className="dl-nav-brand-logo" />
      </a>
      <div className="dl-nav-meta">
        <span>{theme === "dark" ? "Operating layer / live" : "Operating layer · live"}</span>
      </div>
      <ul className="dl-nav-links">
        {t.nav.links.map((l) => (
          <li key={l.id}><a href={`#${l.id}`}>{l.label}</a></li>
        ))}
      </ul>
      <div className="dl-nav-right">
        <div className="dl-lang" role="group" aria-label="Language">
          <button
            className={lang === "en" ? "active" : ""}
            onClick={() => setLang("en")}
            aria-pressed={lang === "en"}
          >EN</button>
          <button
            className={lang === "pt" ? "active" : ""}
            onClick={() => setLang("pt")}
            aria-pressed={lang === "pt"}
          >PT</button>
        </div>
        <a className="dl-btn dl-btn-primary" href="https://form.typeform.com/to/uNagcvzT?utm_source=google_search" target="_blank" rel="noopener noreferrer">
          {t.nav.cta} <span className="dl-btn-arrow" aria-hidden="true"></span>
        </a>
      </div>
    </nav>
  );
}

/* ============================================================
   HERO
   ============================================================ */
function HeroSparkline() {
  // Simple SVG sparkline tracking GMV-style data.
  const points = [4, 7, 5, 9, 8, 11, 10, 14, 13, 17, 16, 20, 19, 23];
  const max = Math.max(...points);
  const w = 320, h = 28;
  const step = w / (points.length - 1);
  const path = points
    .map((p, i) => `${i === 0 ? "M" : "L"} ${i * step} ${h - (p / max) * (h - 4) - 2}`)
    .join(" ");
  return (
    <svg className="slab-spark" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <path d={path} fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function Hero({ t, openModal, currentHeadlineIdx }) {
  const headline = t.hero.headlines[currentHeadlineIdx % t.hero.headlines.length];

  // Animate the headline word-by-word? No — system says headlines arrive once, fade + slide. Use a simple cross-fade keyed by headline.
  return (
    <section className="hero" id="top">
      <div className="grid-bg" aria-hidden="true"></div>

      <div className="hero-status" aria-hidden="true">
        <span className="hero-status-pill">{t.hero.status.label} · {t.hero.status.value}</span>
        <span className="hero-status-meta">{t.hero.status.meta}</span>
      </div>

      <div className="container hero-inner">
        <div className="hero-eyebrow">{t.hero.eyebrow}</div>

        <h1 className="hero-title" key={headline}>
          {(() => {
            const parts = headline.split(/(Agentic Commerce|Agentic|agentes|agents|Agentic Era|comércio guiado por IA|AI-driven commerce|próxima interface|next commerce interface)/);
            return parts.map((p, i) =>
              /Agentic|agents|agentes|AI-driven|guiado|interface/.test(p) ? (
                <span className="h-accent" key={i}>{p}</span>
              ) : (
                <React.Fragment key={i}>{p}</React.Fragment>
              )
            );
          })()}
        </h1>

        <p className="hero-sub">{t.hero.sub}</p>

        <div className="hero-actions">
          <a className="dl-btn dl-btn-primary dl-btn-lg" href="https://form.typeform.com/to/uNagcvzT?utm_source=google_search" target="_blank" rel="noopener noreferrer">
            {t.hero.cta} <span className="dl-btn-arrow" aria-hidden="true"></span>
          </a>
          <a className="dl-btn dl-btn-lg" href="#readiness">
            {t.hero.ctaSecondary}
          </a>
        </div>

        <div className="hero-trust">
          {t.hero.trust.map((x, i) => <span key={i}>{x}</span>)}
        </div>
      </div>

      <div className="hero-clients">
        <div className="container hero-clients-head">
          <span className="hero-clients-label">{t.proof.clients.label}</span>
          <span className="hero-clients-sub">{t.proof.clients.more}</span>
        </div>
        <div className="hero-clients-marquee">
          <LogoMarquee items={t.proof.clients.list} speed={68} itemWidth={280} />
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   POSITIONING
   ============================================================ */
function Positioning({ t }) {
  const ref = useReveal();
  return (
    <section className="section" id="positioning" ref={ref}>
      <div className="container">
        <div className="section-num reveal">{t.positioning.eyebrow}</div>
        <h2 className="dl-h2 reveal" style={{ maxWidth: 980 }}>{t.positioning.title}</h2>

        <div className="arc reveal">
          {t.positioning.arc.map((step, i) => (
            <div key={i} className={`arc-step ${i === 1 ? "is-now" : i === 2 ? "is-future" : ""}`}>
              <div className="arc-phase">{step.phase}</div>
              <div className="arc-verb">{step.verb}.</div>
              <div className="arc-body">{step.body}</div>
              {i < 2 && <div className="arc-arrow" aria-hidden="true">→</div>}
            </div>
          ))}
        </div>

        <p className="kicker reveal">{t.positioning.kicker}</p>
      </div>
    </section>
  );
}

/* ============================================================
   CORE BUSINESS
   ============================================================ */
function CoreBusiness({ t }) {
  const ref = useReveal();
  const [active, setActive] = useState(0);
  const pillars = t.core.pillars;
  const current = pillars[active];

  return (
    <section className="section" id="operation" ref={ref}>
      <div className="container">
        <div className="section-num reveal">{t.core.eyebrow}</div>
        <h2 className="dl-h2 reveal" style={{ maxWidth: 900 }}>{t.core.title}</h2>
        <p className="lede reveal">{t.core.lede}</p>

        <div className="core-stack reveal">
          {/* Tab rail */}
          <div className="core-tabs" role="tablist" aria-label="Operating disciplines">
            {pillars.map((p, i) => (
              <button
                key={i}
                role="tab"
                aria-selected={i === active}
                className={`core-tab ${i === active ? "active" : ""}`}
                onClick={() => setActive(i)}
              >
                <span className="core-tab-marker" aria-hidden="true"></span>
                <span className="core-tab-n">{p.n}</span>
                <span className="core-tab-name">{p.name}</span>
                <span className="core-tab-arrow" aria-hidden="true">›</span>
              </button>
            ))}
          </div>

          {/* Active detail */}
          <div className="core-detail" key={active} role="tabpanel">
            <div className="core-detail-head">
              <div className="core-detail-eyebrow">
                <span className="core-detail-n">{current.n}</span>
                <span className="core-detail-divider"></span>
                <h3 className="core-detail-name">{current.name}</h3>
              </div>
              <span className="core-detail-status">
                <span className="core-detail-dot" aria-hidden="true"></span>
                {t.core.statusLabel}
              </span>
            </div>

            <p className="core-detail-claim">{current.claim}</p>

            <div className="core-detail-grid">
              <div className="core-detail-owns">
                <div className="core-detail-section-label">
                  <span className="core-detail-section-tag">DLDO</span>
                  {t.core.ownsLabel}
                </div>
                <ul className="core-detail-list">
                  {current.owns.map((o, i) => (
                    <li key={i} style={{ animationDelay: `${i * 60}ms` }}>{o}</li>
                  ))}
                </ul>
              </div>

              <div className="core-detail-side">
                <div className="core-detail-replaces">
                  <div className="core-detail-section-label core-detail-section-label-mute">{t.core.replacesLabel}</div>
                  <div className="core-detail-replaces-value">{current.replaces}</div>
                </div>
                <div className="core-detail-metric">
                  <div className="core-detail-section-label core-detail-section-label-mute">{current.metric.label}</div>
                  <div className="core-detail-metric-value">{current.metric.value}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="authority-mfst reveal">
          <div className="authority-mfst-label">{t.core.authority.label}</div>
          <div className="authority-mfst-body">
            {t.core.authority.lead}{" "}
            <span className="authority-mfst-punch">{t.core.authority.punch}</span>
          </div>
        </div>

        <div className="reveal">
          <window.DoladoDashboards.OpsAnatomy data={t.core.anatomy} />
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   AGENTIC COMMERCE — with live prompt mockup
   ============================================================ */
function PromptMockup({ data }) {
  const [active, setActive] = useState(0);
  const [typed, setTyped] = useState("");
  const [phase, setPhase] = useState("typing"); // typing | done

  const current = data.prompts[active];

  // Typewriter effect for the query, then reveal answer.
  useEffect(() => {
    setPhase("typing");
    setTyped("");
    const q = current.q;
    let i = 0;
    let cancelled = false;
    const tick = () => {
      if (cancelled) return;
      if (i <= q.length) {
        setTyped(q.slice(0, i));
        i += 1;
        const jitter = 14 + Math.random() * 24;
        setTimeout(tick, jitter);
      } else {
        setPhase("done");
      }
    };
    tick();
    return () => { cancelled = true; };
  }, [active, current.q]);

  return (
    <div className="prompt" role="figure" aria-label="Live agent simulation">
      <div className="prompt-head">
        <span>{data.label}</span>
        <span className="prompt-head-dots" aria-hidden="true">
          <span></span><span></span><span></span>
        </span>
      </div>

      <div className="prompt-tabs" role="tablist">
        {data.prompts.map((p, i) => (
          <button
            key={i}
            role="tab"
            aria-selected={i === active}
            className={`prompt-tab ${i === active ? "active" : ""}`}
            onClick={() => setActive(i)}
          >{p.category}</button>
        ))}
      </div>

      <div className="prompt-body">
        <div className="prompt-query">
          <div className="prompt-query-label">user_q</div>
          <div className="prompt-query-text">
            {typed}
            {phase === "typing" && <span className="caret" aria-hidden="true"></span>}
          </div>
        </div>

        {phase === "done" && (
          <div className="prompt-answer" key={active}>
            <div className="prompt-answer-label">agent · recommends</div>
            {current.answer.map((rec, i) => (
              <div key={i} className={`prompt-rec ${rec.operated ? "operated" : ""}`}>
                <div className="prompt-rec-num">{String(i + 1).padStart(2, "0")}</div>
                <div className="prompt-rec-main">
                  <div className="prompt-rec-brand" data-tag={rec.operated ? data.operatedTag : ""}>
                    {rec.brand}
                  </div>
                  <div className="prompt-rec-line">{rec.line}</div>
                  <div className="prompt-rec-reason">{rec.reason}</div>
                </div>
                <div className="prompt-rec-price">{rec.price}</div>
              </div>
            ))}
          </div>
        )}
      </div>

      <div className="prompt-caption">{data.caption}</div>
    </div>
  );
}

function AgenticCommerce({ t }) {
  const ref = useReveal();
  return (
    <section className="section" id="agentic" ref={ref}>
      <div className="container">
        <div className="section-num reveal">{t.agentic.eyebrow}</div>
        <h2 className="dl-h2 reveal" style={{ maxWidth: 1000 }}>
          {t.agentic.title}<br />
          <span className="accent-text">{t.agentic.title2}</span>
        </h2>

        <div className="agentic-grid">
          <div className="reveal">
            <p className="lede" style={{ marginTop: 0, marginBottom: 24 }}>{t.agentic.lede}</p>
            <div className="pillars-vert">
              {t.agentic.pillars.map((p, i) => (
                <div key={i} className="pillar-vert">
                  <div className="pillar-vert-tag">{p.tag}</div>
                  <div className="pillar-vert-body">{p.body}</div>
                </div>
              ))}
            </div>
            <p className="kicker" style={{ marginTop: 32, fontSize: 16 }}>{t.agentic.kicker}</p>
          </div>

          <div className="reveal">
            <PromptMockup data={t.agentic.promptDemo} />
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   READINESS — sample report card
   ============================================================ */
function ReportCard({ sample }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          setVisible(true);
          io.disconnect();
        }
      });
    }, { threshold: 0.3 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  return (
    <div className="report" ref={ref}>
      <div className="report-head">
        <span>{sample.title}</span>
        <span className="report-head-tag">live</span>
      </div>

      <div className="report-score">
        <div className="report-score-value">
          {sample.score}<sup>/100</sup>
        </div>
        <div className="report-score-label">{sample.scoreLabel}</div>

        <div className="report-bands" style={{ position: "relative", marginTop: 24 }}>
          <div className="report-band at-risk"></div>
          <div className="report-band operating"></div>
          <div className="report-band excellent"></div>
          <div className="report-bands-marker" style={{ left: `calc(${sample.score}% - 1px)` }}></div>
        </div>
        <div className="report-bands-labels">
          {sample.bands.slice().reverse().map((b, i) => <span key={i}>{b.label}</span>)}
        </div>
      </div>

      <div className="report-breakdown">
        {sample.breakdown.map((d, i) => (
          <div className="report-row" key={i}>
            <div className="report-row-name">{d.dim}</div>
            <div className="report-row-bar">
              <div
                className={`report-row-bar-fill ${d.state}`}
                style={{ width: visible ? `${d.val}%` : "0%" }}
              ></div>
            </div>
            <div className="report-row-val">{d.val}</div>
          </div>
        ))}
      </div>

      <div className="report-foot">
        <span>Dolado · Readiness Index™</span>
        <span>v2.4</span>
      </div>
    </div>
  );
}

function Readiness({ t, openModal }) {
  const ref = useReveal();
  return (
    <section className="section" id="readiness" ref={ref}>
      <div className="container">
        <div className="section-num reveal">{t.readiness.eyebrow}</div>
        <div className="readiness-product reveal">{t.readiness.product}</div>
        <h2 className="dl-h2 reveal" style={{ maxWidth: 880 }}>{t.readiness.title}</h2>

        <div className="readiness-grid">
          <div className="reveal">
            <ul className="analyzes">
              {t.readiness.analyzes.map((x, i) => <li key={i}>{x}</li>)}
            </ul>
            <a className="dl-btn dl-btn-primary dl-btn-lg" href="https://form.typeform.com/to/uNagcvzT?utm_source=google_search" target="_blank" rel="noopener noreferrer" style={{ marginTop: 32 }}>
              {t.readiness.cta} <span className="dl-btn-arrow" aria-hidden="true"></span>
            </a>
          </div>
          <div className="reveal">
            <ReportCard sample={t.readiness.sample} />
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   WHY
   ============================================================ */
function Why({ t }) {
  const ref = useReveal();
  return (
    <section className="section" id="why" ref={ref}>
      <div className="container">
        <div className="section-num reveal">{t.why.eyebrow}</div>
        <h2 className="dl-h2 reveal" style={{ maxWidth: 1000 }}>{t.why.title}</h2>

        <div className="why-grid">
          <div className="why-body reveal">
            <p>{t.why.lede}</p>
            <p>{t.why.body}</p>
          </div>
          <div className="why-stamp reveal">
            <span className="why-stamp-mark">stamp</span>
            {t.why.stamp}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   PROOF — stats + marketplaces + cases
   ============================================================ */
function AnimatedKpi({ kpi, prefix, suffix }) {
  // Parse numeric portion; preserve thousand separators ("5,000" or "5.000").
  const parsed = parseFloat(String(kpi).replace(/[,\.]/g, ""));
  const isNumeric = !isNaN(parsed) && parsed > 0;
  const [val, ref] = useCountUp(isNumeric ? parsed : 0);

  const formatted = useMemo(() => {
    if (!isNumeric) return kpi;
    // Match formatting of source string
    const v = Math.round(val);
    if (/[,]/.test(String(kpi))) {
      return v.toLocaleString("en-US");
    }
    if (/[\.]/.test(String(kpi))) {
      return v.toLocaleString("de-DE");
    }
    return String(v);
  }, [val, kpi, isNumeric]);

  return (
    <div className="stat-kpi" ref={ref}>
      {prefix && <span className="stat-kpi-prefix">{prefix}</span>}
      <span>{formatted}</span>
      {suffix && <span className="stat-kpi-suffix">{suffix}</span>}
    </div>
  );
}

function Proof({ t }) {
  const ref = useReveal();
  return (
    <section className="section" id="proof" ref={ref}>
      <div className="container">
        <div className="section-num reveal">{t.proof.eyebrow}</div>
        <h2 className="dl-h2 reveal" style={{ maxWidth: 880 }}>{t.proof.title}</h2>

        <div className="stats-band reveal">
          {t.proof.stats.map((s, i) => (
            <div key={i} className="stat">
              <AnimatedKpi kpi={s.kpi} prefix={s.prefix} suffix={s.suffix} />
              <div className="stat-label">{s.label}</div>
            </div>
          ))}
        </div>

        <div className="marketplaces-strip reveal">
          <div className="marketplaces-strip-label">Operated marketplaces</div>
          <div className="marketplaces-strip-items">
            {t.proof.marketplaces.map((m, i) => <span key={i}>{m}</span>)}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   SOCIAL PROOF — clients + press band right under the hero
   ============================================================ */
function SocialProof({ t }) {
  const ref = useReveal();
  return (
    <section className="social-proof" ref={ref}>
      <div className="container">
        <div className="press-block reveal">
          <div className="press-head">
            <span className="press-eyebrow">{t.proof.press.eyebrow}</span>
            <h3 className="press-title">{t.proof.press.title}</h3>
          </div>
          <div className="press-grid">
            {t.proof.press.items.map((p, i) => (
              <a
                key={i}
                href={p.url}
                target="_blank"
                rel="noopener noreferrer"
                className={`press-card press-card-${p.id}`}
              >
                <div className="press-card-top">
                  <span className="press-card-n">{String(i + 1).padStart(2, "0")}</span>
                  <span className="press-card-arrow" aria-hidden="true">↗</span>
                </div>
                <div className="press-mark-wrap">
                  <span className={`press-mark press-mark-${p.id}`}>{p.publication}</span>
                </div>
                <div className="press-card-meta">
                  <span>{p.section}</span>
                  <span className="press-card-sep">·</span>
                  <span>{p.date}</span>
                </div>
                <blockquote className="press-card-headline">{p.headline}</blockquote>
                <div className="press-card-foot">
                  <span>{t.proof.press.ctaRead} {p.publication}</span>
                  <span className="press-card-arrow-2" aria-hidden="true">→</span>
                </div>
              </a>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   BACKERS — investor showcase
   ============================================================ */
function Backers({ t }) {
  const ref = useReveal();
  return (
    <section className="section" id="backers" ref={ref}>
      <div className="container">
        <div className="section-num reveal">{t.backers.eyebrow}</div>
        <h2 className="dl-h2 reveal" style={{ maxWidth: 980 }}>{t.backers.title}</h2>
        <p className="lede reveal">{t.backers.sub}</p>

        <div className="reveal backers-marquee-wrap">
          <LogoMarquee items={t.backers.funds} speed={50} itemWidth={300} />
        </div>

        <ul className="backers-directory reveal">
          {t.backers.funds.map((f, i) => (
            <li key={i} className="backers-dir-item">
              <span className="backers-dir-n">{String(i + 1).padStart(2, "0")}</span>
              <span className="backers-dir-name">{f.name}</span>
              <span className="backers-dir-thesis">{f.thesis}</span>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}

/* ============================================================
   LAB
   ============================================================ */
function Lab({ t, openModal }) {
  const ref = useReveal();
  return (
    <section className="section" id="lab" ref={ref}>
      <div className="container">
        <div className="section-num reveal">{t.lab.eyebrow}</div>
        <h2 className="dl-h2 reveal" style={{ maxWidth: 900 }}>{t.lab.product}</h2>

        <div className="lab-block reveal">
          <div className="lab-left">
            <div className="lab-product">{t.lab.product}</div>
            <div className="lab-title">{t.lab.title}</div>
            <div className="lab-positioning">{t.lab.positioning}</div>

            <dl className="lab-facts">
              <div className="lab-facts-head">{t.lab.facts.label}</div>
              {t.lab.facts.items.map((f, i) => (
                <div key={i} className="lab-fact-row">
                  <dt>{f.label}</dt>
                  <dd>{f.value}</dd>
                </div>
              ))}
            </dl>

            <div className="lab-personas">
              <div className="lab-personas-label">{t.lab.personasLabel}</div>
              <div className="lab-personas-list">
                {t.lab.personas.map((p, i) => (
                  <div key={i} className="lab-persona">
                    <div className="lab-persona-role">{p.role}</div>
                    <div className="lab-persona-line">{p.line}</div>
                  </div>
                ))}
              </div>
            </div>

            <div className="lab-cta-wrap">
              <a className="dl-btn dl-btn-primary dl-btn-lg" href="https://form.typeform.com/to/uNagcvzT?utm_source=google_search" target="_blank" rel="noopener noreferrer">
                {t.lab.cta} <span className="dl-btn-arrow" aria-hidden="true"></span>
              </a>
              <div className="lab-cta-meta">{t.lab.ctaMeta}</div>
            </div>
          </div>

          <div className="lab-right">
            <div className="lab-right-eyebrow">Included</div>
            <ul className="lab-includes">
              {t.lab.includes.map((x, i) => <li key={i}>{x}</li>)}
            </ul>
          </div>
        </div>

        <div className="lab-outcomes reveal">
          <div className="lab-outcomes-head">
            <span className="lab-outcomes-eyebrow">{t.lab.outcomes.eyebrow}</span>
            <h3 className="lab-outcomes-title">{t.lab.outcomes.label}</h3>
          </div>
          <div className="lab-outcomes-grid">
            {t.lab.outcomes.items.map((o, i) => (
              <article key={i} className="lab-outcome">
                <div className="lab-outcome-top">
                  <span className="lab-outcome-n">{o.n}</span>
                  <span className="lab-outcome-meta">{o.meta}</span>
                </div>
                <h4 className="lab-outcome-name">{o.name}</h4>
                <p className="lab-outcome-body">{o.body}</p>
              </article>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}
// We don't truly have a `lang` here for the cohort dt labels — the cohort dl uses static-ish labels.
// Simple helper: returns the first (we'll always pass EN for these short labels).
function lang_safe(en, pt) { return en; }

/* ============================================================
   FINAL CTA
   ============================================================ */
function FinalCta({ t, openModal }) {
  const ref = useReveal();
  return (
    <section className="final" id="final" ref={ref}>
      <div className="container">
        <div className="section-num reveal" style={{ justifyContent: "center", display: "inline-flex" }}>
          {t.finalCta.eyebrow}
        </div>
        <h2 className="final-title reveal">{t.finalCta.title}</h2>
        <p className="final-body reveal">{t.finalCta.body}</p>
        <a className="dl-btn dl-btn-primary dl-btn-lg reveal" href="https://form.typeform.com/to/uNagcvzT?utm_source=google_search" target="_blank" rel="noopener noreferrer">
          {t.finalCta.cta} <span className="dl-btn-arrow" aria-hidden="true"></span>
        </a>
      </div>
    </section>
  );
}

/* ============================================================
   FOOTER
   ============================================================ */
function Footer({ t }) {
  return (
    <footer className="dl-footer">
      <div className="container">
        <div className="dl-footer-top">
          <div>
            <div className="dl-footer-brand">
              <span className="dl-footer-brand-dot" aria-hidden="true"></span>
              <span>dolado</span>
            </div>
            <p className="dl-footer-tagline">{t.footer.tagline}</p>
          </div>
          <div className="dl-footer-cols">
            {t.footer.cols.map((c, i) => (
              <div key={i} className="dl-footer-col">
                <div className="dl-footer-col-title">{c.title}</div>
                <ul>
                  {c.links.map((l, j) => <li key={j}><a href="#" onClick={(e) => e.preventDefault()}>{l}</a></li>)}
                </ul>
              </div>
            ))}
          </div>
        </div>
        <div className="dl-footer-legal">
          <span>{t.footer.legal}</span>
          <span>v2026.01</span>
        </div>
      </div>
    </footer>
  );
}

/* ============================================================
   MODAL — Executive Diagnosis lead form
   ============================================================ */
function Modal({ t, open, onClose }) {
  const [form, setForm] = useState({ name: "", email: "", role: "", brand: "", gmv: "", notes: "" });
  const [submitted, setSubmitted] = useState(false);
  const closeBtnRef = useRef(null);

  useEffect(() => {
    if (open && closeBtnRef.current) closeBtnRef.current.focus();
    const onKey = (e) => { if (e.key === "Escape" && open) onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  // Reset when re-opening after submit
  useEffect(() => {
    if (open) {
      setTimeout(() => setSubmitted(false), 0);
    }
  }, [open]);

  if (!open) return null;

  const handleSubmit = (e) => {
    e.preventDefault();
    setSubmitted(true);
  };

  const update = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  return (
    <div className="modal-overlay" onClick={onClose} role="dialog" aria-modal="true" aria-labelledby="modal-title">
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button ref={closeBtnRef} className="modal-close" onClick={onClose} aria-label={t.modal.closeLabel}>×</button>

        {submitted ? (
          <div className="modal-success">
            <div className="modal-success-mark" aria-hidden="true">✓</div>
            <div className="modal-success-title">{t.modal.success}</div>
          </div>
        ) : (
          <>
            <div className="modal-head">
              <div className="modal-eyebrow">Executive · by invitation</div>
              <h3 className="modal-title" id="modal-title">{t.modal.title}</h3>
              <p className="modal-sub">{t.modal.sub}</p>
            </div>
            <form onSubmit={handleSubmit}>
              <div className="modal-body">
                <div className="modal-grid">
                  <div className="field">
                    <label htmlFor="m-name">{t.modal.fields.name}</label>
                    <input id="m-name" required value={form.name} onChange={update("name")} autoComplete="name" />
                  </div>
                  <div className="field">
                    <label htmlFor="m-email">{t.modal.fields.email}</label>
                    <input id="m-email" type="email" required value={form.email} onChange={update("email")} autoComplete="email" />
                  </div>
                  <div className="field">
                    <label htmlFor="m-role">{t.modal.fields.role}</label>
                    <input id="m-role" value={form.role} onChange={update("role")} placeholder="CMO, Head of E-commerce…" />
                  </div>
                  <div className="field">
                    <label htmlFor="m-brand">{t.modal.fields.brand}</label>
                    <input id="m-brand" required value={form.brand} onChange={update("brand")} />
                  </div>
                  <div className="field field-full">
                    <label htmlFor="m-gmv">{t.modal.fields.gmv}</label>
                    <select id="m-gmv" required value={form.gmv} onChange={update("gmv")}>
                      <option value="">—</option>
                      {t.modal.gmvOptions.map((g, i) => <option key={i} value={g}>{g}</option>)}
                    </select>
                  </div>
                  <div className="field field-full">
                    <label htmlFor="m-notes">{t.modal.fields.notes}</label>
                    <textarea id="m-notes" value={form.notes} onChange={update("notes")} rows="2" />
                  </div>
                </div>
              </div>
              <div className="modal-foot">
                <span className="modal-foot-note">1-business-day SLA · São Paulo</span>
                <button type="submit" className="dl-btn dl-btn-primary">
                  {t.modal.submit} <span className="dl-btn-arrow" aria-hidden="true"></span>
                </button>
              </div>
            </form>
          </>
        )}
      </div>
    </div>
  );
}

/* ============================================================
   Export
   ============================================================ */
Object.assign(window, {
  DoladoSections: {
    Nav, Hero, SocialProof, Positioning, CoreBusiness, AgenticCommerce, Readiness, Why, Proof, Backers, Lab, FinalCta, Footer, Modal,
  },
});
