/* global React */
const { useState: useState2, useEffect: useEffect2 } = React;

// ============================================================
// Token Section (tokenomics + vesting)
// ============================================================
window.TokenSection = function TokenSection({ lang, tbdVariant }) {
  const t = window.useT(lang).token;
  const [hover, setHover] = useState2(null);
  const tokenCoinRef = React.useRef(null);
  const allocBarRef = React.useRef(null);
  const vestingRef = React.useRef(null);

  useEffect2(() => {
    if (tokenCoinRef.current && window.TokenCoinScene && !tokenCoinRef.current.dataset.mounted) {
      tokenCoinRef.current.dataset.mounted = "1";
      window.TokenCoinScene(tokenCoinRef.current);
    }
    // observers for bar + vesting
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add("in-view"); });
    }, { threshold: 0.2 });
    if (allocBarRef.current) io.observe(allocBarRef.current);
    if (vestingRef.current) io.observe(vestingRef.current);
    return () => io.disconnect();
  }, []);

  return (
    <section className="token-section section" id="token" data-screen-label="Token">
      <div className="container">
        <div className="token-hero">
          <div data-reveal>
            <div className="eyebrow">{t.eyebrow}</div>
            <span className="token-symbol mono"><span className="dollar">$</span>ONIL</span>
            <div ref={tokenCoinRef} style={{ width: "100%", maxWidth: 380, aspectRatio: "1/1", marginTop: 24 }}></div>
          </div>
          <div data-reveal data-reveal-delay="1">
            <p className="token-tagline">{t.tagline}</p>
            <p style={{ color: "var(--text-2)", fontSize: 14, lineHeight: 1.6, maxWidth: "52ch", margin: "0 0 32px" }}>{t.lede}</p>
            <ol className="token-rights">
              {t.rights.map((r, i) => (
                <li key={i}>
                  <span className="num">{r.num}.</span>
                  <span><b>{r.title}.</b> <span style={{ color: "var(--text-3)" }}>{r.body}</span></span>
                </li>
              ))}
            </ol>
          </div>
        </div>

        {/* Tokenomics bar */}
        <div className="alloc-block" data-reveal>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 16 }}>
            <h3 style={{ fontSize: 18, fontWeight: 500, margin: 0, letterSpacing: "-0.01em" }}>{t.allocLabel}</h3>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-3)", letterSpacing: "0.06em" }}>
              TOTAL SUPPLY: <window.TBDValue variant={tbdVariant} label="TBD" w={80} />
            </span>
          </div>
          <div className="alloc-bar" ref={allocBarRef}>
            {t.allocBuckets.map((b, i) => (
              <div key={i} className="alloc-seg"
                style={{ flex: b.pct, background: b.color, color: i < 2 ? "#0A0700" : "rgba(255,255,255,0.7)" }}
                onMouseEnter={() => setHover(i)}
                onMouseLeave={() => setHover(null)}
                title={`${b.name} · ${b.pct}%`}
              >
                {b.pct >= 8 ? `${b.pct}%` : ""}
              </div>
            ))}
          </div>
          <div className="alloc-legend">
            {t.allocBuckets.map((b, i) => (
              <div key={i} className="alloc-legend-item"
                style={{ opacity: hover === null || hover === i ? 1 : 0.4, transition: "opacity .2s" }}
              >
                <span className="alloc-swatch" style={{ background: b.color }} />
                <span className="alloc-name">{b.name}</span>
                <span className="alloc-pct">{b.pct}%</span>
              </div>
            ))}
          </div>
          <p style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-4)", marginTop: 16, letterSpacing: "0.04em" }}>
            * {t.allocFootnote}
          </p>
        </div>

        {/* Vesting */}
        <div className="vesting" ref={vestingRef}>
          <div className="vesting-head">
            <h3>{t.vesting.title}</h3>
            <div className="legend">
              <span><i style={{ background: "repeating-linear-gradient(45deg, var(--gold) 0 3px, var(--gold-deep) 3px 6px)" }} />Cliff</span>
              <span><i style={{ background: "linear-gradient(90deg, var(--gold), var(--gold-soft))" }} />Linear unlock</span>
            </div>
          </div>
          {t.vesting.rows.map((r, i) => {
            const cliffW = (r.cliffPct);
            const linearW = (r.linearPct);
            return (
              <div className="vest-row" key={i}>
                <div className="vest-label">
                  {r.name}
                  <span className="sub">{r.sub}</span>
                </div>
                <div className="vest-track">
                  {cliffW > 0 && <div className="vest-cliff" style={{ left: 0, width: cliffW + "%" }} />}
                  {linearW > 0 && <div className="vest-linear" style={{ left: cliffW + "%", width: linearW + "%" }} />}
                </div>
                <div className="vest-pct">{r.total}</div>
              </div>
            );
          })}
          <div className="vest-axis">
            <div />
            <div className="scale">
              <span>TGE</span><span>+6m</span><span>+12m</span><span>+24m</span><span>+36m</span><span>+48m</span>
            </div>
            <div />
          </div>
        </div>
      </div>
    </section>
  );
};

// ============================================================
// Participate
// ============================================================
window.Participate = function Participate({ lang, onApply, tbdVariant }) {
  const t = window.useT(lang).participate;
  return (
    <section className="section" id="participate" data-screen-label="Participate">
      <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="steps">
          {t.steps.map((s, i) => (
            <div className="step" key={i} data-reveal data-reveal-delay={String(Math.min(i+1, 4))}>
              <span className="step-num">{s.n}</span>
              <h3>{s.title}</h3>
              <p>{s.body}</p>
              <div className="step-meta">
                <span>{s.meta[0]}{i === 2 ? <window.TBDValue variant={tbdVariant} label="TBD" w={60} /> : null}</span>
                {i !== 2 && <span>{s.meta[1]}</span>}
              </div>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "center", marginTop: 40 }}>
          <button className="btn btn--primary" onClick={onApply}>
            {window.useT(lang).nav.apply} <span className="arrow">→</span>
          </button>
        </div>
      </div>
    </section>
  );
};

// ============================================================
// Roadmap
// ============================================================
window.Roadmap = function Roadmap({ lang }) {
  const t = window.useT(lang).roadmap;
  const [tab, setTab] = useState2(0);
  const phase = t.phases[tab];
  return (
    <section className="section" data-screen-label="Roadmap">
      <div className="container">
        <div className="section-head" data-reveal>
          <div className="eyebrow">{t.eyebrow}</div>
          <h2>{t.title}</h2>
        </div>
        <div className="roadmap-tabs" data-reveal data-reveal-delay="1">
          {t.phases.map((p, i) => (
            <button key={i} className={tab === i ? "active" : ""} onClick={() => setTab(i)}>
              {p.tab}
            </button>
          ))}
        </div>
        <div className="roadmap-panel">
          <div className="roadmap-summary">
            <div className="phase">{phase.date}</div>
            <h3>{phase.title}</h3>
            <p>{phase.desc}</p>
          </div>
          <div className="roadmap-list">
            {phase.items.map((it, i) => (
              <div key={i} className={"item " + (it.done ? "done" : "")}>
                <span className="check">{it.done ? "[ ✓ ]" : "[   ]"}</span>
                <div className="text">{it.text}<span className="sub">{it.sub}</span></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

// ============================================================
// Team
// ============================================================
window.Team = function Team({ lang }) {
  const t = window.useT(lang).team;
  return (
    <section className="section" data-screen-label="Team">
      <div className="container">
        <div className="section-head">
          <div className="eyebrow">{t.eyebrow}</div>
          <h2>{t.title}</h2>
          <p>{t.lede}</p>
        </div>
        <div className="team-grid">
          {t.members.map((m, i) => (
            <div className="team-card" key={i} data-reveal data-reveal-delay={String(Math.min(i+1, 4))}>
              <div className="team-photo">
                <span className="ph">FOUNDER PHOTO</span>
              </div>
              <div className="team-info">
                <div className="role" style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--gold)" }}>{m.role}</div>
                <div className="name" style={{ marginTop: 8 }}><window.TBDValue variant="pill" label={m.name} /></div>
                <div className="meta">{m.meta}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ============================================================
// FAQ
// ============================================================
window.FAQ = function FAQ({ lang }) {
  const t = window.useT(lang).faq;
  const [open, setOpen] = useState2(0);
  return (
    <section className="section" id="faq" data-screen-label="FAQ">
      <div className="container">
        <div className="section-head" data-reveal>
          <div className="eyebrow">{t.eyebrow}</div>
          <h2>{t.title}</h2>
        </div>
        <div className="faq-grid">
          {t.items.map((it, i) => (
            <div key={i} className={"faq-item " + (open === i ? "open" : "")} data-reveal data-reveal-delay={String(Math.min((i % 5)+1, 4))}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{it.q}</span>
                <span className="icon">+</span>
              </button>
              <div className="faq-a"><div>{it.a}</div></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ============================================================
// Compliance
// ============================================================
window.Compliance = function Compliance({ lang }) {
  const t = window.useT(lang).compliance;
  return (
    <section className="section" data-screen-label="Compliance">
      <div className="container">
        <div className="section-head" data-reveal>
          <div className="eyebrow">{t.eyebrow}</div>
          <h2>{t.title}</h2>
        </div>
        <div className="compliance-grid">
          {t.cards.map((c, i) => (
            <div className="compliance-card" key={i} data-reveal data-reveal-delay={String(Math.min(i+1, 4))}>
              <span className="badge">{c.badge}</span>
              <span className="title">{c.title}</span>
              <span className="desc">{c.desc}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ============================================================
// Final CTA
// ============================================================
window.FinalCTA = function FinalCTA({ lang, onApply, onSchedule }) {
  const t = window.useT(lang).finalCta;
  const particlesRef = React.useRef(null);
  useEffect2(() => {
    if (particlesRef.current && window.CtaParticleScene && !particlesRef.current.dataset.mounted) {
      particlesRef.current.dataset.mounted = "1";
      window.CtaParticleScene(particlesRef.current);
    }
  }, []);
  return (
    <section className="final-cta" data-screen-label="Final CTA">
      <div className="cta-particles" ref={particlesRef}></div>
      <h2 data-reveal>{t.headline[0]}<em>{t.headline[1]}</em>{t.headline[2]}</h2>
      <p data-reveal data-reveal-delay="1">{t.lede}</p>
      <div className="cta-row" data-reveal data-reveal-delay="2">
        <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>
    </section>
  );
};

// ============================================================
// Footer
// ============================================================
window.Footer = function Footer({ lang }) {
  const t = window.useT(lang).footer;
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="nav-logo" style={{ marginBottom: 16, gap: 12 }}>
              <img src="assets/logotipo-onil-x-2.webp" alt="OnilX" style={{ height: 24, width: "auto", display: "block" }} />
              <span style={{ color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.04em" }}>· $ONIL</span>
            </div>
            <p style={{ color: "var(--text-3)", fontSize: 13, maxWidth: "36ch", margin: 0 }}>{t.tagline}</p>
          </div>
          {t.cols.map((c, i) => (
            <div key={i}>
              <h5>{c.title}</h5>
              <ul>{c.links.map((l, j) => <li key={j}><a href="#">{l}</a></li>)}</ul>
            </div>
          ))}
        </div>
        <div className="footer-disclaimer">
          <p>{t.legal}</p>
          <p style={{ flex: "1 1 100%" }}>{t.disclaimer}</p>
        </div>
      </div>
    </footer>
  );
};

// ============================================================
// Apply Modal
// ============================================================
window.ApplyModal = function ApplyModal({ lang, onClose }) {
  const t = window.useT(lang).apply;
  const [step, setStep] = useState2(0);
  const [done, setDone] = useState2(false);
  const [data, setData] = useState2({ ticket: "", jurisdiction: "", qualified: false, name: "", email: "", org: "", notes: "", agree: false });
  const upd = (k, v) => setData({ ...data, [k]: v });

  if (done) {
    return (
      <div className="modal-backdrop" onClick={onClose}>
        <div className="modal" onClick={e => e.stopPropagation()}>
          <button className="modal-close" onClick={onClose} aria-label="Close">×</button>
          <div className="modal-success">
            <div className="check">✓</div>
            <h3 style={{ textAlign: "center" }}>{t.success}</h3>
            <p style={{ color: "var(--text-2)", fontSize: 14, textAlign: "center", maxWidth: "44ch", margin: "12px auto 0" }}>{t.successBody}</p>
            <div style={{ display: "flex", justifyContent: "center", marginTop: 28 }}>
              <button className="btn btn--ghost btn--sm" onClick={onClose}>{t.close}</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const canNext = step === 0 ? (data.ticket && data.jurisdiction && data.qualified)
                : step === 1 ? (data.name && data.email)
                : data.agree;

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">×</button>
        <div className="eyebrow" style={{ marginBottom: 12 }}>{t.steps[step]} · {step + 1}/3</div>
        <h3>{t.title}</h3>
        <p className="lede">{t.lede}</p>
        <div className="modal-steps">
          {[0,1,2].map(i => <div key={i} className={"dot " + (i <= step ? "active" : "")} />)}
        </div>

        {step === 0 && (
          <div>
            <div className="form-row">
              <label>{t.step1.ticket}</label>
              <select value={data.ticket} onChange={e => upd("ticket", e.target.value)}>
                <option value="">—</option>
                {t.step1.ticketOptions.map(o => <option key={o} value={o}>{o}</option>)}
              </select>
            </div>
            <div className="form-row">
              <label>{t.step1.jurisdiction}</label>
              <input type="text" placeholder={t.step1.jurisdictionPlaceholder} value={data.jurisdiction} onChange={e => upd("jurisdiction", e.target.value)} />
            </div>
            <label className="checkbox-row">
              <input type="checkbox" checked={data.qualified} onChange={e => upd("qualified", e.target.checked)} />
              <span>{t.step1.qualified}</span>
            </label>
          </div>
        )}

        {step === 1 && (
          <div>
            <div className="form-row">
              <label>{t.step2.name}</label>
              <input type="text" value={data.name} onChange={e => upd("name", e.target.value)} />
            </div>
            <div className="form-row">
              <label>{t.step2.email}</label>
              <input type="email" value={data.email} onChange={e => upd("email", e.target.value)} />
            </div>
            <div className="form-row">
              <label>{t.step2.org}</label>
              <input type="text" value={data.org} onChange={e => upd("org", e.target.value)} />
            </div>
            <div className="form-row">
              <label>{t.step2.notes}</label>
              <textarea rows="3" value={data.notes} onChange={e => upd("notes", e.target.value)} />
            </div>
          </div>
        )}

        {step === 2 && (
          <div>
            <div style={{ background: "rgba(255,255,255,0.02)", border: "1px solid var(--border)", borderRadius: 10, padding: 18, marginBottom: 18 }}>
              <h4 style={{ margin: 0, fontSize: 13, fontFamily: "var(--font-mono)", letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--text-3)", fontWeight: 500, marginBottom: 12 }}>{t.step3.review}</h4>
              <div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: "8px 16px", fontSize: 13 }}>
                <span style={{ color: "var(--text-3)" }}>{t.step1.ticket}</span><span>{data.ticket || "—"}</span>
                <span style={{ color: "var(--text-3)" }}>{t.step1.jurisdiction}</span><span>{data.jurisdiction || "—"}</span>
                <span style={{ color: "var(--text-3)" }}>{t.step2.name}</span><span>{data.name || "—"}</span>
                <span style={{ color: "var(--text-3)" }}>{t.step2.email}</span><span>{data.email || "—"}</span>
                <span style={{ color: "var(--text-3)" }}>{t.step2.org}</span><span>{data.org || "—"}</span>
              </div>
            </div>
            <label className="checkbox-row">
              <input type="checkbox" checked={data.agree} onChange={e => upd("agree", e.target.checked)} />
              <span>{t.step3.agree}</span>
            </label>
          </div>
        )}

        <div className="modal-actions">
          <button className="btn btn--ghost btn--sm" onClick={() => step > 0 ? setStep(step - 1) : onClose()}>
            {step === 0 ? t.close : t.back}
          </button>
          {step < 2 ? (
            <button className="btn btn--primary btn--sm" disabled={!canNext} style={{ opacity: canNext ? 1 : 0.4 }}
              onClick={() => canNext && setStep(step + 1)}>{t.next} →</button>
          ) : (
            <button className="btn btn--primary btn--sm" disabled={!canNext} style={{ opacity: canNext ? 1 : 0.4 }}
              onClick={() => canNext && setDone(true)}>{t.submit} →</button>
          )}
        </div>
      </div>
    </div>
  );
};

// ============================================================
// Schedule Modal
// ============================================================
window.ScheduleModal = function ScheduleModal({ lang, onClose }) {
  const t = window.useT(lang).schedule;
  const [done, setDone] = useState2(false);
  const [data, setData] = useState2({ name: "", email: "" });
  if (done) {
    return (
      <div className="modal-backdrop" onClick={onClose}>
        <div className="modal" onClick={e => e.stopPropagation()}>
          <button className="modal-close" onClick={onClose}>×</button>
          <div className="modal-success">
            <div className="check">✓</div>
            <h3 style={{ textAlign: "center" }}>{t.success}</h3>
            <p style={{ color: "var(--text-2)", fontSize: 14, textAlign: "center", maxWidth: "44ch", margin: "12px auto 0" }}>{t.successBody}</p>
          </div>
        </div>
      </div>
    );
  }
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}>×</button>
        <div className="eyebrow" style={{ marginBottom: 12 }}>IR · 30 min</div>
        <h3>{t.title}</h3>
        <p className="lede">{t.lede}</p>
        <div style={{ background: "rgba(255,173,0,0.04)", border: "1px dashed color-mix(in oklch, var(--gold) 40%, transparent)", borderRadius: 12, padding: 28, textAlign: "center", marginBottom: 24 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.16em", color: "var(--gold)", textTransform: "uppercase", marginBottom: 8 }}>📅 {t.placeholder}</div>
          <div style={{ fontSize: 13, color: "var(--text-3)", maxWidth: "44ch", margin: "0 auto" }}>{t.placeholderSub}</div>
        </div>
        <div className="form-row">
          <label>{t.name}</label>
          <input type="text" value={data.name} onChange={e => setData({ ...data, name: e.target.value })} />
        </div>
        <div className="form-row">
          <label>{t.email}</label>
          <input type="email" value={data.email} onChange={e => setData({ ...data, email: e.target.value })} />
        </div>
        <div className="modal-actions">
          <button className="btn btn--ghost btn--sm" onClick={onClose}>Close</button>
          <button className="btn btn--primary btn--sm" disabled={!(data.name && data.email)}
            style={{ opacity: data.name && data.email ? 1 : 0.4 }}
            onClick={() => data.name && data.email && setDone(true)}>{t.submit} →</button>
        </div>
      </div>
    </div>
  );
};
