/* global React */
const { useState, useEffect, useRef } = React;

// ============================================================
// Helpers
// ============================================================
window.useT = function useT(lang) {
  return window.ONIL_CONTENT[lang];
};

window.TBDValue = function TBDValue({ variant = "pill", label = "TBD", w = 120 }) {
  if (variant === "blur") {
    return (
      <span className="tbd-blur">
        <span className="num">$ 0,000,000</span>
        <span className="lock">🔒 Disclosed</span>
      </span>
    );
  }
  if (variant === "shimmer") {
    return <span className="tbd-shimmer" style={{ width: w }} />;
  }
  if (variant === "asterisk") {
    return <span className="mono" style={{ color: "var(--gold)", fontSize: 13 }}>{label} *</span>;
  }
  return <span className="tbd tbd--lg">{label}</span>;
};

// ============================================================
// Nav
// ============================================================
window.Nav = function Nav({ lang, setLang, onApply, onSchedule }) {
  const t = window.useT(lang);
  return (
    <nav className="nav">
      <div className="container nav-inner">
        <a href="#" className="nav-logo">
          <img src="assets/logotipo-onil-x-2.webp" alt="OnilX" style={{ height: 22, width: "auto", display: "block" }} />
          <span style={{ color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.04em" }}>· $ONIL</span>
        </a>
        <div className="nav-links">
          {t.nav.links.map(l => <a key={l.href} href={l.href}>{l.label}</a>)}
        </div>
        <div className="nav-cta">
          <div className="lang-toggle" role="tablist" aria-label="Language">
            <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
            <button className={lang === "pt" ? "active" : ""} onClick={() => setLang("pt")}>PT</button>
          </div>
          <button className="btn btn--ghost btn--sm" onClick={onSchedule}>{t.nav.schedule}</button>
          <button className="btn btn--primary btn--sm" onClick={onApply}>
            {t.nav.apply}
            <span className="arrow">→</span>
          </button>
        </div>
      </div>
    </nav>
  );
};

// ============================================================
// Hero
// ============================================================
window.Hero = function Hero({ lang, variant = "quiet", tbdVariant, onApply, onSchedule }) {
  const t = window.useT(lang).hero;
  const [n, setN] = useState(0);
  const coinRef = useRef(null);
  // Animated KPI: years in production
  useEffect(() => {
    let raf, start = performance.now();
    const tick = (now) => {
      const p = Math.min(1, (now - start) / 1400);
      setN(Math.floor(p * 5));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [lang]);

  // Mount 3D hero coin
  useEffect(() => {
    if (coinRef.current && window.HeroCoinScene && !coinRef.current.dataset.mounted) {
      coinRef.current.dataset.mounted = "1";
      window.HeroCoinScene(coinRef.current);
    }
  }, []);

  return (
    <section className="hero" data-screen-label="Hero">
      <div className="container">
        <div className="hero-grid">
          <div data-reveal>
            <div className="eyebrow">{t.eyebrow}</div>
            <h1>
              {t.headline[0]}<br/>
              {t.headline[1]}<em>{t.headline[2]}</em>{t.headline[3]}
            </h1>
            <p className="hero-lede">{t.lede}</p>
            <div className="hero-cta">
              <button className="btn btn--primary" onClick={onApply}>
                {t.ctaPrimary} <span className="arrow">→</span>
              </button>
              <button className="btn btn--ghost" onClick={onSchedule}>{t.ctaSecondary}</button>
            </div>
          </div>
          <div data-reveal data-reveal-delay="1">
            <div className="hero-3d-wrap" ref={coinRef} aria-label="$ONIL coin"></div>
            <div className="hero-kpi">
              <span className="label">{t.kpiLabel}</span>
              <div className="value mono">{n}<span style={{ color: "var(--text-3)" }}>+</span></div>
              <span className="sub">{t.kpiSub}</span>
            </div>
          </div>
        </div>
        <div className="hero-meta">
          {t.meta.map((m, i) => (
            <div key={i}>
              <span className="k">{m.k}</span>
              <span className="v">{m.v}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ============================================================
// Trusted by
// ============================================================
window.Trusted = function Trusted({ lang }) {
  const t = window.useT(lang).trusted;
  return (
    <section className="trusted" data-screen-label="Trusted">
      <div className="container">
        <div className="trusted-label" data-reveal>{t.label}</div>
        <div className="partners-row" data-reveal data-reveal-delay="1">
          {t.partners.map((p, i) => (
            <div className="partner-logo" key={i}>
              <span className="dot" />{p}
            </div>
          ))}
        </div>
        <div className="chain-row" data-reveal data-reveal-delay="2">
          {t.chains.map(c => (
            <div className="chain-pill" key={c.name}>
              <span className={"chain-dot " + c.cls} />{c.name.toUpperCase()}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ============================================================
// How it works
// ============================================================
window.HowItWorks = function HowItWorks({ lang }) {
  const t = window.useT(lang).how;
  const flowKinds = ["payments", "custody", "caas", "otc"];
  return (
    <section className="section" id="how" data-screen-label="How it works">
      <div className="container">
        <div className="section-head" data-reveal>
          <div className="eyebrow">{t.eyebrow}</div>
          <h2>{t.title}</h2>
          <p>{t.lede}</p>
        </div>
        <div className="flows">
          {t.flows.map((f, i) => {
            const imgs = ["assets/frame-pagamentos.webp", "assets/frame-custodia.webp", "assets/frame-publico.png", "assets/frame-avo.webp"];
            return (
            <div className="flow" key={i} data-reveal data-reveal-delay={String(Math.min(i+1, 4))}>
              <div className="flow-3d" ref={el => {
                if (el && window.FlowIconScene && !el.dataset.mounted) {
                  el.dataset.mounted = "1";
                  window.FlowIconScene(el, flowKinds[i] || "payments");
                }
              }}></div>
              <div className="flow-head">
                <div>
                  <div className="flow-num">{f.n}</div>
                  <h3 className="flow-title" style={{ marginTop: 8 }}>{f.title}</h3>
                </div>
                <div className="flow-arrow">{f.arrow}</div>
              </div>
              <p className="flow-desc">{f.desc}</p>
              <div style={{ position: "relative", borderRadius: 10, overflow: "hidden", border: "1px solid var(--border)", aspectRatio: "16/7" }}>
                <img src={imgs[i]} alt="" style={{ display: "block", width: "100%", height: "100%", objectFit: "cover", filter: i === 2 ? "grayscale(0.3)" : "none" }} />
                <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(0,0,0,0) 30%, rgba(0,0,0,0.55))", pointerEvents: "none" }} />
              </div>
              <div className="flow-meta">
                {f.meta.map((m, j) => (
                  <div key={j} className="item">{m[0]} <b>{m[1]}</b></div>
                ))}
              </div>
            </div>
            );
          })}
        </div>
      </div>
    </section>
  );
};

// ============================================================
// Coverage map (custom dotted SVG world map)
// ============================================================
window.Coverage = function Coverage({ lang }) {
  const t = window.useT(lang).coverage;
  const [activeIdx, setActiveIdx] = useState(0);
  const active = t.rails[activeIdx];
  const globeRef = useRef(null);

  // Lat/Lng for each rail (mapped by index in t.rails order)
  const railCoords = [
    { lat: -23.5, lng: -46.6 },  // FI/IF — Brazil financial
    { lat: 40.7,  lng: -74.0 },  // FT — NY/global fintechs
    { lat: 51.5,  lng: -0.12 },  // EX — London/intl
    { lat: 1.35,  lng: 103.8 },  // AT — Singapore family offices
    { lat: -25.4, lng: -49.27 }, // BR HQ Curitiba
  ];

  useEffect(() => {
    if (globeRef.current && window.GlobeScene && !globeRef.current.dataset.mounted) {
      globeRef.current.dataset.mounted = "1";
      window.GlobeScene(globeRef.current, railCoords);
    }
  }, []);

  return (
    <section className="section" id="coverage" data-screen-label="Coverage">
      <div className="container">
        <div className="section-head" data-reveal>
          <div className="eyebrow">{t.eyebrow}</div>
          <h2>{t.title}</h2>
          <p>{t.lede}</p>
        </div>
        <div className="coverage-grid">
          <div className="globe-wrap" ref={globeRef} data-reveal></div>
          <div data-reveal data-reveal-delay="1">
            <div className="rail-list">
              {t.rails.map((r, i) => (
                <div key={i}
                  className={"rail-row " + (activeIdx === i ? "active" : "")}
                  onMouseEnter={() => setActiveIdx(i)}
                >
                  <div className="rail-flag">{r.flag}</div>
                  <div className="rail-name-row">
                    {r.name}
                    <span className="sub">{r.sub}</span>
                  </div>
                  <div className="rail-time">{r.time}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// ============================================================
// Tech Stack
// ============================================================
window.TechStack = function TechStack({ lang }) {
  const t = window.useT(lang).stack;
  return (
    <section className="section" data-screen-label="Tech stack">
      <div className="container">
        <div className="section-head" data-reveal>
          <div className="eyebrow">{t.eyebrow}</div>
          <h2>{t.title}</h2>
          <p>{t.lede}</p>
        </div>
        <div className="stack-grid">
          {t.groups.map((g, i) => (
            <div className="stack-card" key={i} data-reveal data-reveal-delay={String(Math.min(i+1, 4))}>
              <span className="label">{g.label}</span>
              <span className="name">{g.name}</span>
              <span className="desc">{g.desc}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};
