/* SpeakMind — feature deep-dives, stats, pricing, testimonials, footer */

/* hook: rotate an index on an interval */
function useRotate(n, ms) {
  const [i, setI] = useState(0);
  useEffect(() => { const t = setInterval(() => setI((x) => (x + 1) % n), ms); return () => clearInterval(t); }, [n, ms]);
  return i;
}

/* ---- Context Aware visual: cards light up in sequence ---- */
function ContextVisual({ apps }) {
  const t = window.SM.t;
  const active = useRotate(apps.length, 1500);
  return (
    <div className="ctx-grid">
      {apps.map((id, idx) => {
        const c = window.SM.ctx[id];
        return (
          <div key={id} className={"ctx-card" + (idx === active ? " active" : "")}>
            <span className="g" style={{ background: c.color }}>{c.glyph}</span>
            <span className="nm">{c.name}</span>
            <span className="hint">{t(c.hint)}</span>
            <span className="lang">→ {t(c.register)}</span>
          </div>
        );
      })}
    </div>
  );
}

/* ---- Memory Dictionary visual: rows, one pops ---- */
function MemoryVisual() {
  const terms = window.SM.dict;
  const pop = useRotate(terms.length, 1300);
  return (
    <div className="dict-vis">
      {terms.map((t, i) => (
        <div key={t.term} className={"dict-row" + (i === pop ? " pop" : "")}>
          <span className="term">{t.term}</span>
          <span className="kind">{t.kind}</span>
          <span className="count">{t.count}× used</span>
        </div>
      ))}
    </div>
  );
}

/* ---- Modes visual: pills, one expands ---- */
function ModesVisual() {
  const t = window.SM.t;
  const modes = window.SM.modes;
  const on = useRotate(modes.length, 1400);
  return (
    <div className="modes-vis">
      {modes.map((m, i) => (
        <div key={m.id} className={"mode-pill" + (i === on ? " on" : "")}>
          <span className="mi">{m.icon}</span>{m.name}
          <span className="md">{t(m.desc)}</span>
        </div>
      ))}
    </div>
  );
}

const FEAT_VIS = { context: (f) => <ContextVisual apps={f.apps} />, memory: () => <MemoryVisual />, modes: () => <ModesVisual /> };

function Feature({ f, flip }) {
  const t = window.SM.t;
  return (
    <div className={"feat" + (flip ? " flip" : "")}>
      <div className="feat-copy reveal">
        <div className="eyebrow">{t(f.eyebrow)}</div>
        <h3>{t(f.title)}</h3>
        <p>{t(f.body)}</p>
        <div className="feat-tag">{t(f.tag)}</div>
      </div>
      <div className="feat-vis reveal" data-d="2">{FEAT_VIS[f.id](f)}</div>
    </div>
  );
}

function Features() {
  const t = window.SM.t;
  return (
    <section id="features">
      <div className="wrap">
        <div className="section-head reveal" style={{ paddingTop: "90px" }}>
          <div className="eyebrow" data-no="03">{t("Why it feels like magic")}</div>
          <h2>{t("Not just dictation. It understands what you mean.")}</h2>
          <p>{t("Three things make SpeakMind feel less like a microphone and more like a writing partner that already knows your world.")}</p>
        </div>
        {window.SM.features.map((f, i) => <Feature key={f.id} f={f} flip={i % 2 === 1} />)}
      </div>
    </section>
  );
}

/* ---- Stats ---- */
function Sparkline() {
  const ref = useRef(null);
  const [show, setShow] = useState(false);
  const vals = [12, 18, 15, 24, 30, 28, 41, 38, 52, 47, 63, 58, 74, 92];
  const peak = Math.max(...vals);
  useEffect(() => {
    const o = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setShow(true); o.disconnect(); } }, { threshold: .3 });
    if (ref.current) o.observe(ref.current);
    return () => o.disconnect();
  }, []);
  return (
    <div className="spark" ref={ref}>
      {vals.map((v, i) => <i key={i} className={i === vals.length - 1 ? "peak" : ""} style={{ height: show ? `${(v / peak) * 100}%` : "4px" }} />)}
    </div>
  );
}

function Stats() {
  const t = window.SM.t;
  return (
    <section id="stats">
      <div className="wrap" style={{ padding: "60px 28px 30px" }}>
        <div className="section-head reveal">
          <div className="eyebrow" data-no="06">{t("By the numbers")}</div>
          <h2>{t("Fast is just the start.")}</h2>
          <p>{t("Speed is only half of it. SpeakMind also stays accurate, lands text in under a second, and quietly tracks every word saved across your day.")}</p>
        </div>
        <div className="stats-grid reveal" data-d="1" style={{ marginTop: "44px" }}>
          {window.SM.stats.map((s, i) => {
            const numeric = /^\d+$/.test(s.big);
            return (
            <div className="stat" key={i}>
              <div className="num">{numeric ? <window.SMx.CountNum to={parseInt(s.big, 10)} /> : s.big}<span className="u">{s.unit}</span></div>
              <div className="lbl">{t(s.label)}</div>
              <div className="note">{t(s.note)}</div>
            </div>
          ); })}
        </div>
        <div className="reveal" data-d="2" style={{ marginTop: "20px", padding: "26px 24px", background: "var(--surface)", border: "1px solid var(--border2)", borderRadius: "var(--r-lg)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: "8px" }}>
            <strong style={{ fontSize: "15px" }}>{t("Daily spoken words · last 14 days")}</strong>
            <span className="mono" style={{ fontSize: "12px", color: "var(--text-faint)" }}>{t("+612% since you started")}</span>
          </div>
          <Sparkline />
        </div>
      </div>
    </section>
  );
}

/* ---- Pricing ---- */
function Pricing() {
  const [annual, setAnnual] = useState(true);
  const t = window.SM.t;
  return (
    <section id="pricing">
      <div className="wrap" style={{ padding: "90px 28px 40px" }}>
        <div className="section-head reveal" style={{ margin: "0 auto", textAlign: "center" }}>
          <div className="eyebrow" data-no="07">{t("Pricing")}</div>
          <h2>{t("Start free. Upgrade when talking becomes a habit.")}</h2>
        </div>
        <div className="price-grid reveal" data-d="1" style={{ marginTop: "48px" }}>
          {window.SM.pricing.map((p, i) => {
            const cyc = p.cycles ? (annual ? p.cycles.annual : p.cycles.monthly) : p;
            const ext = !!cyc.href && cyc.href.startsWith("http");
            // For the annual cycle, lead with the per-month equivalent and note
            // the yearly billing — makes the savings obvious.
            let amt = cyc.price, per = cyc.per, note = null;
            if (p.cycles) {
              if (annual) {
                const yr = parseFloat(p.cycles.annual.price.replace(/[^0-9.]/g, ""));
                amt = "$" + (yr / 12).toFixed(0);
                per = "/ month";
                note = t("Billed annually") + " — " + p.cycles.annual.price + "/yr · " + t("save 33%");
              } else {
                note = t("Billed monthly — go annual to save 33%");
              }
            }
            return (
            <div key={p.name} className={"price-card" + (p.featured ? " featured" : "")}>
              {p.featured ? <span className="price-badge">{t("Most popular")}</span> : (p.badge ? <span className="price-badge">{t(p.badge)}</span> : null)}
              <div className="price-name">{p.name}</div>
              <div className="price-amt">{amt}<span className="per">{t(per)}</span></div>
              {note && <div className="price-note">{note}</div>}
              {p.cycles && (
                <div className="cycle-toggle">
                  <button className={!annual ? "on" : ""} onClick={() => setAnnual(false)}>{t("Monthly")}</button>
                  <button className={annual ? "on" : ""} onClick={() => setAnnual(true)}>{t("Annual")}<span className="save">−33%</span></button>
                </div>
              )}
              <div className="price-tag">{t(p.tagline)}</div>
              <ul className="price-feats">{p.feats.map((f) => <li key={f}>{t(f)}</li>)}</ul>
              <a className={"price-btn" + (p.featured ? "" : (i === 0 ? " go" : ""))}
                 href={cyc.href || "#"}
                 target={ext ? "_blank" : undefined}
                 rel={ext ? "noopener noreferrer" : undefined}>{t(p.cta)}</a>
              {p.featured && <div className="price-reassure">{t("No charge today · free for 14 days · cancel anytime")}</div>}
            </div>
          ); })}
        </div>
      </div>
    </section>
  );
}

/* ---- Testimonials ---- */
function TCard({ t: item }) {
  const tr = window.SM.t;
  const c = window.SM.ctx[item.app];
  return (
    <div className="tcard">
      <div className="q">"{tr(item.quote)}"</div>
      <div className="who">
        <span className="av" style={{ background: c.color }}>{item.name[0]}</span>
        <div><div className="nm">{item.name}</div><div className="ro">{tr(item.role)}</div></div>
      </div>
    </div>
  );
}

function Testimonials() {
  const t = window.SM.t;
  const list = window.SM.testimonials;
  const rowA = [...list.slice(0, 3), ...list.slice(0, 3)];
  const rowB = [...list.slice(3), ...list.slice(3)];
  return (
    <section id="loved">
      <div className="wrap">
        <div className="section-head reveal" style={{ paddingTop: "90px", margin: "0 auto", textAlign: "center" }}>
          <div className="eyebrow" data-no="08">{t("Loved out loud")}</div>
          <h2>{t("People stopped typing and never looked back.")}</h2>
        </div>
      </div>
      <div className="tmarquee reveal" data-d="1" style={{ marginTop: "44px" }}>
        <div className="trow a">{rowA.map((t, i) => <TCard key={i} t={t} />)}</div>
        <div className="trow b">{rowB.map((t, i) => <TCard key={i} t={t} />)}</div>
      </div>
    </section>
  );
}

/* ---- CTA + Footer ---- */
function FooterCTA() {
  const t = window.SM.t;
  return (
    <section id="download">
      <div className="wrap">
        <div className="cta">
          <div className="cta-mark reveal" />
          <h2 className="reveal" data-d="1">{t("Talk. It's already written.")}</h2>
          <p className="sub reveal" data-d="2">{t("Free to download. All seven modes, Context Aware, and 8 languages from day one. More coming soon.")}</p>
          <div className="hero-ctas reveal" data-d="3" style={{ justifyContent: "center" }}>
            <a className="btn btn-primary" href="#"><span className="apple"></span> {t("Download for Mac — Free")}</a>
            <a className="btn btn-ghost" href="#pricing">{t("See plans")}</a>
          </div>
          <div className="hero-meta reveal" data-d="4" style={{ justifyContent: "center" }}>
            <span><span className="ok">✓</span> macOS 15 Sequoia+</span>
            <span><span className="ok">✓</span> {t("Apple Silicon & Intel")}</span>
            <span><span className="ok">✓</span> {t("No card required")}</span>
          </div>
        </div>
        <footer>
          <div className="footer-grid">
            <div className="foot-col">
              <div className="brand" style={{ marginBottom: "14px" }}><span className="mark" /> SpeakMind</div>
              <p style={{ fontSize: "13.5px", color: "var(--text-dim)", maxWidth: "30ch" }}>{t("Voice-to-text that understands what you mean. Built for Mac.")}</p>
            </div>
            <div className="foot-col"><h5>{t("Product")}</h5><a href="#features">{t("Features")}</a><a href="#pricing">{t("Pricing")}</a><a href="#stats">{t("Insights")}</a><a href="#download">{t("Download")}</a></div>
            <div className="foot-col"><h5>{t("Company")}</h5><a href="#">{t("About")}</a><a href="#">{t("Blog")}</a><a href="#">{t("Careers")}</a><a href="#">{t("Contact")}</a></div>
            <div className="foot-col"><h5>{t("Legal")}</h5><a href="privacy.html">{t("Privacy")}</a><a href="terms.html">{t("Terms")}</a><a href="privacy.html#security">{t("Security")}</a></div>
          </div>
          <div className="foot-bottom">
            <span>{t("© 2026 SpeakMind. Made for people who think faster than they type.")}</span>
            <span>⌥Space · Multilingual · macOS</span>
          </div>
        </footer>
      </div>
    </section>
  );
}

window.SMSections = { Features, Stats, Pricing, Testimonials, FooterCTA };
