/* SpeakMind — extra sections: app marquee, languages, talk-vs-type speed race,
   plus count-up + in-view hooks. */

function useInView(threshold = 0.3) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const o = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setSeen(true); o.disconnect(); } }, { threshold });
    o.observe(ref.current);
    return () => o.disconnect();
  }, []);
  return [ref, seen];
}

function CountNum({ to, dur = 1400, prefix = "", suffix = "", deci = 0 }) {
  const [ref, seen] = useInView(0.5);
  const [n, setN] = useState(0);
  useEffect(() => {
    if (!seen) return;
    let raf, start;
    const step = (t) => {
      if (!start) start = t;
      const p = Math.min((t - start) / dur, 1);
      const e = 1 - Math.pow(1 - p, 3);
      setN(to * e);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [seen, to]);
  return <span ref={ref}>{prefix}{n.toFixed(deci)}{suffix}</span>;
}

/* ---- app marquee: works everywhere you type ---- */
function AppMarquee() {
  const known = ["chatgpt", "cursor", "gmail", "notion", "safari", "slack"].map((id) => window.SM.ctx[id]);
  const extra = [
    { name: "VS Code", glyph: "⌖", color: "#2c7ad6" }, { name: "Figma", glyph: "✦", color: "#a259ff" },
    { name: "Linear", glyph: "▰", color: "#5e6ad2" }, { name: "Slack", glyph: "◗", color: "#611f69" },
    { name: "Obsidian", glyph: "◆", color: "#7c3aed" }, { name: "Discord", glyph: "◎", color: "#5865f2" },
    { name: "Word", glyph: "W", color: "#2b579a" }, { name: "Things", glyph: "✓", color: "#1f7fdc" },
    { name: "Arc", glyph: "◐", color: "#fc6c5c" }, { name: "Telegram", glyph: "✈", color: "#2aabee" },
  ];
  const all = [...known, ...extra];
  const loop = [...all, ...all];
  return (
    <section className="marq-sec">
      <div className="wrap">
        <p className="marq-cap reveal">{window.SM.t("Dictates straight into 100+ apps — anywhere you can type.")}</p>
      </div>
      <div className="marq reveal" data-d="1">
        <div className="marq-row">
          {loop.map((a, i) => (
            <span className="app-chip" key={i}>
              <span className="g" style={{ background: a.color }}>{a.glyph}</span>{a.name}
            </span>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---- hero speed strip: talk vs type, quantified up front ---- */
function HeroStats() {
  const t = window.SM.t;
  return (
    <section id="speed" className="hstats">
      <div className="wrap">
        <div className="hstats-grid reveal">
          <div className="hstat dim">
            <div className="hs-lab">{t("You, typing")}</div>
            <div className="hs-big"><CountNum to={51} /><span className="u">wpm</span></div>
          </div>
          <div className="hstat hot">
            <div className="hs-lab">{t("You, with SpeakMind")}</div>
            <div className="hs-big"><CountNum to={211} /><span className="u">wpm</span></div>
          </div>
          <div className="hstat">
            <div className="hs-lab">{t("Time you get back")}</div>
            <div className="hs-big">1<span className="u">{t("day / week")}</span></div>
          </div>
        </div>
        <p className="hstats-foot mono reveal">{t("You speak ~4× faster than you type — SpeakMind keeps up and drops clean text the moment you let go.")}</p>
      </div>
    </section>
  );
}

/* ---- big chapter divider (groups the feature story, typeless-style) ---- */
function Chapter({ word, sub }) {
  return (
    <div className="chapter reveal">
      <div className="wrap">
        <h2 className="chapter-word">{word}</h2>
        {sub && <p className="chapter-sub">{sub}</p>}
      </div>
    </div>
  );
}

/* ---- languages strip: spoken → translated, target language rotates ---- */
function Languages() {
  const t = window.SM.t;
  const L = window.SM.languages;
  const [ri, setRi] = useState(0);
  useEffect(() => {
    const n = L.rotate.length;
    const t = setInterval(() => setRi((x) => (x + 1) % n), 3000);
    return () => clearInterval(t);
  }, [L]);
  const r = L.rotate[ri % L.rotate.length];
  return (
    <section id="languages" className="lang-sec">
      <div className="wrap">
        <div className="lang-grid">
          <div className="lang-copy reveal">
            <div className="eyebrow" data-no="04">{t(L.eyebrow)}</div>
            <h2>{t(L.headA)} <span className="ink-accent">{t(L.headB)}</span></h2>
            <p>{t(L.body)}</p>
            <div className="lang-chips reveal" data-d="1">
              {L.chips.map((l) => (
                <span className={"lang-chip" + (l.live ? " live" : "")} key={l.code}>
                  {l.code}{l.live ? <span className="ld" /> : <span className="soon">soon</span>}
                </span>
              ))}
            </div>
          </div>
          <div className="lang-demo reveal" data-d="2">
            <div className="lang-card">
              <div className="lc-row src"><span className="lc-tag mono">{r.srcTag}</span><p>{r.src}</p></div>
              <div className="lc-arrow"><span>{t(L.arrowLabel || "⇄ Translate")}</span></div>
              <div className="lc-row dst" key={ri}><span className="lc-tag mono">{r.dstTag}</span><p>{r.dst}</p></div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.SMx = { useInView, CountNum, AppMarquee, HeroStats, Chapter, Languages };
