// New sections: ShortcutBinder, FAQ, Languages
const { useState: useStateNS, useEffect: useEffectNS, useRef: useRefNS } = React;

// ShortcutBinder — rebind your trigger
function ShortcutBinder() {
  const [binding, setBinding] = useStateNS(["fn"]);
  const [listening, setListening] = useStateNS(false);
  const [pressedNow, setPressedNow] = useStateNS([]);
  const [savedFlash, setSavedFlash] = useStateNS(false);
  const [pressed, setPressed] = useStateNS(false);
  const heldRef = useRefNS(new Set());

  useEffectNS(() => {
    if (!listening) return;
    const held = heldRef.current; held.clear();
    const fmt = (e) => {
      const p = [];
      if (e.metaKey) p.push("⌘");
      if (e.ctrlKey) p.push("ctrl");
      if (e.altKey) p.push("opt");
      if (e.shiftKey) p.push("shift");
      const k = (e.key || "").toLowerCase();
      const named = { " ": "space", "escape": "esc", "tab": "tab", "capslock": "caps", "meta": "⌘", "control": "ctrl", "alt": "opt", "shift": "shift", "fn": "fn", "enter": "↵", "backspace": "⌫" };
      if (named[k]) { if (!p.includes(named[k])) p.push(named[k]); }
      else if (k.length === 1) p.push(k.toUpperCase());
      return p;
    };
    const onDown = (e) => { e.preventDefault(); const parts = fmt(e); window.__lastParts = parts; setPressedNow(parts); held.add(e.code); };
    const onUp = (e) => {
      held.delete(e.code);
      if (held.size === 0) {
        setBinding((curr) => (window.__lastParts && window.__lastParts.length) ? [...window.__lastParts] : curr);
        setListening(false); setSavedFlash(true);
        setTimeout(() => setSavedFlash(false), 1400);
      }
    };
    window.addEventListener("keydown", onDown);
    window.addEventListener("keyup", onUp);
    return () => { window.removeEventListener("keydown", onDown); window.removeEventListener("keyup", onUp); };
  }, [listening]);

  useEffectNS(() => {
    if (listening) return;
    const set = new Set();
    const onDown = (e) => {
      if (e.metaKey) set.add("⌘");
      if (e.ctrlKey) set.add("ctrl");
      if (e.altKey) set.add("opt");
      if (e.shiftKey) set.add("shift");
      const k = (e.key || "").toLowerCase();
      if (k.length === 1) set.add(k.toUpperCase());
      if (k === " ") set.add("space");
      if (binding.every(p => set.has(p)) && binding.length > 0) setPressed(true);
    };
    const clear = () => { set.clear(); setPressed(false); };
    window.addEventListener("keydown", onDown);
    window.addEventListener("keyup", clear);
    window.addEventListener("blur", clear);
    return () => { window.removeEventListener("keydown", onDown); window.removeEventListener("keyup", clear); window.removeEventListener("blur", clear); };
  }, [binding, listening]);

  const presets = [
    { label: "default", keys: ["fn"] },
    { label: "right opt", keys: ["opt"] },
    { label: "opt+space", keys: ["opt", "space"] },
    { label: "ctrl+space", keys: ["ctrl", "space"] },
    { label: "cmd+shift+space", keys: ["⌘", "shift", "space"] },
  ];
  const display = listening ? (pressedNow.length ? pressedNow : ["…"]) : binding;

  return (
    <section id="shortcut" className="section binder-section">
      <div className="section-head">
        <div className="section-eyebrow">結 · BIND</div>
        <h2 className="section-title">Rebind your trigger.</h2>
        <p className="section-sub">fn is a gentle default. If your muscle memory lives elsewhere, move it. This is the exact control you'll find in the app's Settings: hit Rebind, press something comfortable, done. Prefer tap-to-start over hold? There's a toggle mode too (tap right Option to start and stop).</p>
      </div>
      <div className="binder-stage">
        <div className={`binder-key ${listening ? "is-listening" : ""} ${pressed ? "is-pressed" : ""}`}>
          <div className="binder-key-inner">
            <div className="binder-key-caps">
              {display.map((p, i) => (
                <React.Fragment key={i}>
                  <span className="binder-cap">{p}</span>
                  {i < display.length - 1 ? <span className="binder-plus">+</span> : null}
                </React.Fragment>
              ))}
            </div>
            <div className="binder-key-hint">{listening ? "Press a key or chord…" : pressed ? "In the app, you'd be dictating right now." : "This key starts the mic in the app"}</div>
          </div>
        </div>
        <div className="binder-controls">
          <button className={`binder-record ${listening ? "is-live" : ""}`} onClick={() => { setListening(v => !v); setPressedNow([]); }}>
            <span className="binder-record-dot" />{listening ? "Cancel" : "Rebind"}
          </button>
          <div>
            <div className="binder-presets-label">The app's presets</div>
            <div className="binder-presets-list">
              {presets.map(p => {
                const same = p.keys.join("+") === binding.join("+");
                return (
                  <button key={p.label} className={`binder-preset ${same ? "is-active" : ""}`} onClick={() => { setBinding(p.keys); setSavedFlash(true); setTimeout(() => setSavedFlash(false), 1400); }}>
                    {p.keys.map((k, i) => (<React.Fragment key={i}><kbd>{k}</kbd>{i < p.keys.length - 1 ? <span className="plus">+</span> : null}</React.Fragment>))}
                    <span className="binder-preset-label">{p.label}</span>
                  </button>
                );
              })}
            </div>
          </div>
          <div className={`binder-saved ${savedFlash ? "is-shown" : ""}`}>✓ Saved, in spirit. The real binding lives in the app's Settings.</div>
        </div>
      </div>
    </section>
  );
}

// FAQ
function FAQ() {
  const items = [
    { q: "How much does it cost?", a: "Nothing right now. During early access the app is free: you plug in your own Groq API key (free tier available) and dictation runs on your account, or you skip keys entirely with local mode. Paid plans will come eventually, and early users will hear it from us first." },
    { q: "Does it work offline?", a: "Yes, in local mode. Download a Whisper model (1.6 to 3GB) plus a local LLM and dictation runs entirely on your Mac. You sign in once when you set up; after that, offline is offline." },
    { q: "Is my voice sent to a server?", a: "By default, audio goes to Groq for transcription using your own API key, and it isn't stored by the app. Want zero network? Local mode. Want zero AI touching your words? Privacy Mode gives you the raw transcript, unedited." },
    { q: "Will it rewrite what I say?", a: "No. The cleanup is deliberately light-touch: fillers out, self-corrections resolved, punctuation fixed. Your words and your sentence structure stay. The ninja edits, it does not ghostwrite." },
    { q: "Does it work in Cursor / VS Code / terminal?", a: "Yes. Anywhere there's a text cursor. Cursor, VS Code, iTerm, Notion, Slack, Gmail, Obsidian, Linear. If you can type there, you can dictate there." },
    { q: "Does it handle accents and weird words?", a: "It runs on Whisper, which speaks 57 languages and has heard every accent on Earth. For your project names and inside jokes, add them to the custom dictionary and they'll come out spelled right." },
    { q: "Can I whisper to it?", a: "Yes. Whisper mode normalizes your microphone gain automatically, so speaking at library volume transcribes as accurately as full voice. Built for open offices, red-eye flights, and 2 a.m. ideas next to a sleeping human." },
    { q: "What if I stop mid-sentence?", a: "It waits. You haven't released the key, so you haven't finished thinking. Sip your coffee. It'll be here." },
    { q: "Does it replace my keyboard?", a: "No. Your keyboard is still the best tool for short edits, passwords, and punctuation. fn is for when your thoughts outrun your fingers." },
    { q: "Windows and Linux?", a: "macOS 14+ only, for now. The ninja trained on one mountain and refuses to leave it until the craft is perfect." },
  ];
  const [open, setOpen] = useStateNS(0);
  return (
    <section id="faq" className="section faq-section">
      <div className="section-head">
        <div className="section-eyebrow">問 · ASK</div>
        <h2 className="section-title">Everything you wanted to know.</h2>
        <p className="section-sub">The real questions people send us. Answered honestly, without marketing fog.</p>
      </div>
      <div className="faq-list">
        {items.map((it, i) => {
          const isOpen = open === i;
          return (
            <div key={i} className={`faq-item ${isOpen ? "is-open" : ""}`}>
              <button className="faq-q" onClick={() => setOpen(isOpen ? -1 : i)} aria-expanded={isOpen}>
                <span className="faq-q-text">{it.q}</span>
                <span className="faq-toggle" aria-hidden>
                  <svg viewBox="0 0 24 24" width="20" height="20"><path d="M6 9 L12 15 L18 9" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" /></svg>
                </span>
              </button>
              <div className="faq-a-wrap"><div className="faq-a">{it.a}</div></div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// Languages
function Languages() {
  const langs = ["English","Spanish","French","German","Italian","Portuguese","Dutch","Russian","Japanese","Chinese","Korean","Arabic","Hindi","Turkish","Polish","Czech","Danish","Finnish","Greek","Hebrew","Hungarian","Indonesian","Malay","Norwegian","Romanian","Slovak","Swedish","Thai","Ukrainian","Vietnamese","Bulgarian","Catalan","Croatian","Estonian","Latvian","Lithuanian","Serbian","Slovenian","Filipino","Swahili","Urdu","Bengali","Tamil","Telugu","Marathi","Gujarati","Kannada","Malayalam","Persian","Afrikaans","Welsh","Icelandic","Galician","Basque","Belarusian","Azerbaijani","Kazakh","Nepali"];
  const [hover, setHover] = useStateNS(null);
  return (
    <section id="languages" className="section langs-section">
      <div className="section-head">
        <div className="section-eyebrow">言 · TONGUE</div>
        <h2 className="section-title">Fifty-seven languages.<br/><span className="section-title-muted">One fn.</span></h2>
        <p className="section-sub">Pick one, or let auto-detect figure out what you're speaking today.</p>
        <div className="langs-hearing" aria-live="polite">
          {hover ? <>Currently hearing <strong>{hover}</strong></> : " "}
        </div>
      </div>
      <div className="langs-cluster">
        {langs.map((l, i) => (
          <button key={l} className="lang-chip" style={{ animationDelay: `${(i % 12) * 0.05}s` }} onMouseEnter={() => setHover(l)} onMouseLeave={() => setHover(h => h === l ? null : h)}>{l}</button>
        ))}
      </div>

    </section>
  );
}

Object.assign(window, { ShortcutBinder, FAQ, Languages });
