// Smart Contexts — LLM polishing adapts to what you're doing
const { useState: useStateSC, useEffect: useEffectSC, useRef: useRefSC } = React;

const CONTEXTS = [
  {
    id: "filler",
    label: "Filler removal",
    emoji: "🧹",
    app: "Mail · reply to Sam",
    tone: "Your sentence, minus the debris",
    raw: "ok so um can you like check whats up with the contract thing the one we uh talked about last week i think theres an issue with clause four",
    polished: "Can you check what's up with the contract we talked about last week? I think there's an issue with clause four.",
    changes: ["um: gone", "like: gone", "meaning: intact"],
  },
  {
    id: "corrections",
    label: "Self-corrections",
    emoji: "↩️",
    app: "Slack · #standup",
    tone: "Keeps where you landed, not the detour",
    raw: "lets meet on monday no wait tuesday at like 3 uh actually 3:30 to go over the uh launch plan",
    polished: "Let's meet on Tuesday at 3:30 to go over the launch plan.",
    changes: ["monday: overruled", "3:00: overruled", "final answer kept"],
  },
  {
    id: "appAware",
    label: "App-aware",
    emoji: "💬",
    app: "Messages · to Alex",
    tone: "Casual for chat, complete sentences for email",
    raw: "hey um running like ten minutes late the uh train stopped for no reason",
    polished: "Hey, running ten minutes late. The train stopped for no reason.",
    changes: ["stays casual in chat", "no forced formality", "same words"],
  },
  {
    id: "dictionary",
    label: "Custom words",
    emoji: "📖",
    app: "VS Code · commit message",
    tone: "Your jargon, spelled your way",
    raw: "um bump the qwen model and redeploy the uh kubernetes cluster before niels wakes up",
    polished: "Bump the Qwen model and redeploy the Kubernetes cluster before Niels wakes up.",
    changes: ["Qwen: from your dictionary", "Niels: not \"kneels\"", "casing exact"],
  },
];

function SmartContexts() {
  const [selected, setSelected] = useStateSC("filler");
  const [typed, setTyped] = useStateSC("");
  const [polishing, setPolishing] = useStateSC(false);
  const prevSelected = useRefSC(selected);

  const ctx = CONTEXTS.find(c => c.id === selected);

  // Animated typewriter for polished output
  useEffectSC(() => {
    if (prevSelected.current === selected && typed === ctx.polished) return;
    prevSelected.current = selected;
    setPolishing(true);
    setTyped("");
    const target = ctx.polished;
    let i = 0;
    const id = setInterval(() => {
      i += Math.max(1, Math.round(target.length / 80));
      if (i >= target.length) {
        setTyped(target);
        setPolishing(false);
        clearInterval(id);
      } else {
        setTyped(target.slice(0, i));
      }
    }, 18);
    return () => clearInterval(id);
  }, [selected]);

  return (
    <section className="section smart-contexts">
      <div className="section-head">
        <div className="section-eyebrow">Light-touch cleanup</div>
        <h2 className="section-title">Your words. <span className="sc-accent">Minus the mess.</span></h2>
        <p className="section-sub">Ninja Typer doesn't rewrite you. It sweeps up the um's, resolves your mid-sentence U-turns, fixes punctuation, and leaves everything else exactly as you said it. An editor with a katana, not a ghostwriter.</p>
      </div>

      <div className="sc-wrap">
        {/* Context picker */}
        <div className="sc-tabs" role="tablist">
          {CONTEXTS.map(c => (
            <button
              key={c.id}
              role="tab"
              aria-selected={selected === c.id}
              className={`sc-tab ${selected === c.id ? "sc-tab-active" : ""}`}
              onClick={() => setSelected(c.id)}
            >
              <span className="sc-tab-emoji" aria-hidden>{c.emoji}</span>
              <span className="sc-tab-label">{c.label}</span>
            </button>
          ))}
        </div>

        {/* Split: raw speech -> polished output */}
        <div className="sc-split">
          <div className="sc-panel sc-raw">
            <div className="sc-panel-head">
              <div className="sc-panel-eyebrow">
                <span className="sc-dot sc-dot-red" />
                you said
              </div>
              <div className="sc-panel-meta">raw transcript · straight off the mic</div>
            </div>
            <div className="sc-raw-text">"{ctx.raw}"</div>
            <div className="sc-waveform" aria-hidden>
              {Array.from({ length: 42 }).map((_, i) => (
                <span key={i} className="sc-wave-bar" style={{
                  height: `${20 + Math.abs(Math.sin(i * 0.7) * 60) + Math.abs(Math.cos(i * 1.3) * 20)}%`,
                  animationDelay: `${(i * 40) % 1200}ms`,
                }} />
              ))}
            </div>
          </div>

          <div className="sc-arrow">
            <svg width="48" height="48" viewBox="0 0 48 48" aria-hidden>
              <circle cx="24" cy="24" r="22" fill="var(--accent)" stroke="var(--ink)" strokeWidth="2" />
              <path d="M16 24h14M24 18l6 6-6 6" stroke="var(--ink)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" fill="none" />
            </svg>
            <div className="sc-arrow-label">clean,<br/>don't rewrite</div>
          </div>

          <div className="sc-panel sc-polished">
            <div className="sc-panel-head">
              <div className="sc-panel-eyebrow">
                <span className="sc-dot sc-dot-green" />
                ninja wrote
              </div>
              <div className="sc-panel-meta">{ctx.app}</div>
            </div>
            <div className="sc-polished-text">
              {typed}
              {polishing && <span className="sc-caret" />}
            </div>
            <div className="sc-meta-row">
              <div className="sc-tone">
                <span className="sc-meta-label">tone</span>
                <span className="sc-meta-value">{ctx.tone}</span>
              </div>
              <div className="sc-changes">
                {ctx.changes.map((c, i) => (
                  <span key={i} className="sc-chip">{c}</span>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Bottom: how it detects context */}
        <div className="sc-footer">
          <div className="sc-footer-item">
            <div className="sc-footer-num">01</div>
            <div className="sc-footer-body">
              <strong>Sees the app.</strong> A commit message shouldn't read like an email, and an iMessage shouldn't read like a memo.
            </div>
          </div>
          <div className="sc-footer-item">
            <div className="sc-footer-num">02</div>
            <div className="sc-footer-body">
              <strong>Peeks at the field.</strong> The text already in the box guides punctuation and casing, so your sentence lands matching its surroundings.
            </div>
          </div>
          <div className="sc-footer-item">
            <div className="sc-footer-num">03</div>
            <div className="sc-footer-body">
              <strong>Touches nothing else.</strong> No added facts, no invented sentences, no answering your text like a chatbot. Already clean? It passes through untouched.
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { SmartContexts });
