function Demo1() {
  const { provider, apiKey } = useAPI();
  const [idea, setIdea] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [result, setResult] = useState(null);
  const abortRef = useRef(null);

  const examples = [
    "A dashboard of NHS A&E waiting times by region",
    "Predicting which TfL stations will have delays tomorrow",
    "A churn model for a generic SaaS dataset from Kaggle",
    "Analysing UK supermarket own-brand price inflation 2022–2026",
  ];

  async function run() {
    if (!apiKey) { setError("No API key set. Scroll up to §5 to add one."); return; }
    if (!idea.trim()) { setError("Describe your project idea first — even one line."); return; }
    setLoading(true); setError(""); setResult(null);
    abortRef.current?.abort();
    abortRef.current = new AbortController();

    const system = `You are a senior UK data hiring manager giving a friend honest, warm feedback on a portfolio project idea. Score rigorously but kindly. Only return JSON.`;
    const user = `Project idea: """${idea.trim()}"""

Evaluate across 4 axes (each 0-10):
- uk_relevance: how UK-contextual is it?
- hiring_appeal: would a UK data hiring manager click through?
- ai_smell_risk: how much does it reek of generic AI-generated project? (0 = bespoke, 10 = pure slop)
- scope_realism: can a new grad actually ship this in 2-4 weeks?

Return ONLY this JSON (no markdown, no prose):
{
  "overall": <0-10>,
  "verdict": "<one sentence honest verdict, max 20 words>",
  "scores": {
    "uk_relevance": {"score": <0-10>, "note": "<1 sentence>"},
    "hiring_appeal": {"score": <0-10>, "note": "<1 sentence>"},
    "ai_smell_risk": {"score": <0-10>, "note": "<1 sentence, lower is better>"},
    "scope_realism": {"score": <0-10>, "note": "<1 sentence>"}
  },
  "strengths": ["<one strength>", "<another>"],
  "suggestions": ["<one concrete suggestion to strengthen>", "<another concrete suggestion>"]
}`;

    try {
      const raw = await callAI({ provider, apiKey, system, user, json: true, signal: abortRef.current.signal });
      const parsed = parseJSONLoose(raw);
      setResult(parsed);
    } catch (e) {
      if (e.name !== "AbortError") setError(e.message);
    } finally { setLoading(false); }
  }

  const axisColor = (k, v) => {
    if (k === "ai_smell_risk") return v <= 3 ? "teal" : v <= 6 ? "muted" : "ember";
    return v >= 7 ? "teal" : v >= 5 ? "muted" : "ember";
  };

  return (
    <section className="py-20 sm:py-28" id="demos">
      <div className="max-w-6xl mx-auto px-5 sm:px-8">
        <SectionHeader
          num="06"
          kicker="live demo · 1 of 3"
          title={<>"Rate my project idea".</>}
          lede="Paste any project you're considering. A real model, with your key, will evaluate it the way a UK hiring manager would. Try a weak idea to see it punished."
        />

        <div className="grid lg:grid-cols-12 gap-6">
          <div className="lg:col-span-7">
            <Card className="p-6">
              <LabelledInput label="your project idea" hint="one to three sentences is fine">
                <textarea rows={4} className="textarea" value={idea}
                  onChange={e => setIdea(e.target.value)}
                  placeholder="e.g. I want to build a dashboard showing how UK small business registrations changed by region after 2024."/>
              </LabelledInput>

              <div className="flex flex-wrap gap-2 mt-3">
                <span className="mono text-[11px] text-muted mr-1 self-center">try:</span>
                {examples.map((ex, i) => (
                  <button key={i} onClick={() => setIdea(ex)}
                    className="chip hover:bg-paper2 transition-colors text-left normal-case tracking-normal">{ex}</button>
                ))}
              </div>

              <div className="mt-5 flex items-center justify-between gap-3 flex-wrap">
                <button onClick={run} disabled={loading || !apiKey}
                  className="btn-teal px-5 py-2.5 rounded-lg text-sm inline-flex items-center gap-2">
                  {loading ? <><I.Loader size={14} className="animate-spin"/>Evaluating</> : <><I.Play size={14}/>Rate it</>}
                </button>
                {!apiKey && <NeedKeyNotice/>}
              </div>

              <ErrorBox onRetry={error ? run : null}>{error}</ErrorBox>
            </Card>
          </div>

          <div className="lg:col-span-5">
            <Card className="p-6 min-h-[320px]">
              {!result && !loading && (
                <div className="text-muted text-sm h-full flex flex-col justify-center items-center text-center py-10">
                  <I.Target size={24} className="mb-3 text-line"/>
                  <div>results will appear here</div>
                </div>
              )}
              {loading && (
                <div className="space-y-3 pt-2">
                  <Thinking label="the model is reading your idea"/>
                  {[...Array(4)].map((_, i) => (
                    <div key={i} className="h-6 shimmer rounded"/>
                  ))}
                </div>
              )}
              {result && (
                <div>
                  <div className="flex items-baseline gap-3 mb-3">
                    <div className="serif text-5xl text-ink">{result.overall}<span className="text-muted text-2xl">/10</span></div>
                    <Pill tone={result.overall >= 7 ? "teal" : result.overall >= 5 ? "default" : "ember"}>
                      {result.overall >= 7 ? "strong" : result.overall >= 5 ? "okay, fixable" : "rework it"}
                    </Pill>
                  </div>
                  <p className="serif text-[20px] text-ink leading-snug mb-4">"{result.verdict}"</p>
                  <div className="space-y-2 pt-3 border-t border-line">
                    {Object.entries(result.scores || {}).map(([k, v]) => {
                      const tone = axisColor(k, v.score);
                      return (
                        <div key={k}>
                          <div className="flex items-baseline justify-between">
                            <span className="mono text-[11px] uppercase tracking-widest text-ink2">{k.replace(/_/g, " ")}</span>
                            <span className={`mono text-xs ${tone === "teal" ? "text-teal" : tone === "ember" ? "text-ember" : "text-muted"}`}>{v.score}/10</span>
                          </div>
                          <div className="h-1 bg-paper2 rounded-full overflow-hidden mt-1">
                            <div className={`h-full ${tone === "teal" ? "bg-teal" : tone === "ember" ? "bg-ember" : "bg-muted"}`} style={{width:`${v.score*10}%`}}/>
                          </div>
                          <div className="text-[13px] text-muted mt-1">{v.note}</div>
                        </div>
                      );
                    })}
                  </div>
                  {result.strengths?.length > 0 && (
                    <div className="mt-4 pt-4 border-t border-line">
                      <div className="mono text-[11px] uppercase tracking-widest text-teal mb-1.5">strengths</div>
                      <ul className="tick-list space-y-1 text-[14px] text-ink2">
                        {result.strengths.map((s, i) => <li key={i}>{s}</li>)}
                      </ul>
                    </div>
                  )}
                  {result.suggestions?.length > 0 && (
                    <div className="mt-4 pt-4 border-t border-line">
                      <div className="mono text-[11px] uppercase tracking-widest text-ember mb-1.5">to strengthen</div>
                      <ul className="tick-list space-y-1 text-[14px] text-ink2">
                        {result.suggestions.map((s, i) => <li key={i}>{s}</li>)}
                      </ul>
                    </div>
                  )}
                </div>
              )}
            </Card>
          </div>
        </div>
      </div>
    </section>
  );
}
window.Demo1 = Demo1;
