/* global React, Tag, Confidence */
const { useState: _useState, useRef: _useRef, useEffect: _useEffect, useCallback: _useCallback } = React;

// ============================================================
// INTERACTIVE DEMO BLOCK — toggles between three live demos
// ============================================================

function InteractiveDemo() {
  const [tab, setTab] = React.useState("url"); // url | question | video
  return (
    <div className="demo">
      <div className="demo__head">
        <div className="demo__head-dots">
          <i /><i /><i />
        </div>
        <span>nv-evidence-engine // live</span>
        <div className="demo__tab-row">
          <button className={`demo__tab ${tab === "url" ? "demo__tab--active" : ""}`} onClick={() => setTab("url")}>UX audit</button>
          <button className={`demo__tab ${tab === "question" ? "demo__tab--active" : ""}`} onClick={() => setTab("question")}>Research question</button>
          <button className={`demo__tab ${tab === "video" ? "demo__tab--active" : ""}`} onClick={() => setTab("video")}>Concept to insight</button>
        </div>
      </div>
      <div className="demo__body">
        {tab === "url" && <DemoURLAudit />}
        {tab === "question" && <DemoQuestionGenerator />}
        {tab === "video" && <DemoVideoToInsight />}
      </div>
    </div>
  );
}

// ============================================================
// DEMO 1 — URL UX audit
// ============================================================

function DemoURLAudit() {
  const [url, setUrl] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [progress, setProgress] = React.useState(0);
  const [findings, setFindings] = React.useState(null);
  const [error, setError] = React.useState(null);

  const examples = ["stripe.com", "linear.app", "notion.so", "airbnb.com"];

  const run = async () => {
    if (!url || loading) return;
    setLoading(true);
    setFindings(null);
    setError(null);
    setProgress(0);

    // simulated UX-agent progress
    const stages = [12, 28, 52, 74, 90];
    let stage = 0;
    const tick = setInterval(() => {
      if (stage < stages.length) {
        setProgress(stages[stage++]);
      }
    }, 380);

    try {
      const prompt = `You are a UX-research agent simulating a first impression of a SaaS marketing site. The user's site is "${url}".
Return ONLY valid JSON, no prose, with this exact shape:
{"firstImpression":"…(one sentence, plain language, in voice of a real visitor)…",
 "findings":[
   {"title":"…short specific issue title…","severity":"high|med|low","detail":"…1 sentence specific UX critique referencing the type of site…","evidence":"…one short imagined participant quote with a timestamp prefix, e.g. '02:14 — \\"…\\"'…"},
   ... 3 to 4 findings total
 ],
 "confidence": 0.62 to 0.92
}
Be specific to the kind of company "${url}" appears to be — invent plausible critique like a senior product researcher would. No markdown. No \`\`\`.`;

      const txt = await window.claude.complete(prompt);
      let parsed;
      try {
        // strip code fences just in case
        const clean = txt.trim().replace(/^```(?:json)?\s*/i, "").replace(/```\s*$/, "");
        parsed = JSON.parse(clean);
      } catch (e) {
        throw new Error("Couldn't parse the audit. Try again.");
      }
      setProgress(100);
      setFindings(parsed);
    } catch (e) {
      setError(e.message || "Something went wrong.");
    } finally {
      clearInterval(tick);
      setLoading(false);
    }
  };

  return (
    <>
      <div>
        <div className="card__label">
          <span className="card__label-dot" /> INPUT · WEBSITE URL
        </div>
        <div className="demo__input-wrap">
          <span className="demo__input-prefix">https://</span>
          <input
            className="demo__input"
            placeholder="your-product.com"
            value={url}
            onChange={(e) => setUrl(e.target.value.replace(/^https?:\/\//, ""))}
            onKeyDown={(e) => e.key === "Enter" && run()}
          />
          <button className="btn btn--primary" onClick={run} disabled={loading}>
            {loading ? "Auditing…" : "Run UX agent →"}
          </button>
        </div>
        <div className="demo__examples">
          <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--fg-dim)", marginRight: 4 }}>TRY:</span>
          {examples.map((e) => (
            <span key={e} className="demo__example" onClick={() => setUrl(e)}>{e}</span>
          ))}
        </div>
        <div style={{ marginTop: 22 }}>
          <div className="card__label"><span className="card__label-dot" /> METHOD</div>
          <p style={{ fontSize: 13, color: "var(--fg-muted)", lineHeight: 1.55, marginTop: 8 }}>
            An AI agent simulates a first-time visitor task, then surfaces friction points with imagined source quotes. In the full platform, agents test live sites and back every finding with real participant evidence.
          </p>
        </div>
      </div>

      <div className="demo__output">
        {loading && (
          <>
            <div className="demo__progress"><i style={{ width: `${progress}%` }} /></div>
            <div className="demo__output-empty" style={{ height: 200 }}>
              UX AGENT NAVIGATING · {progress}%
            </div>
          </>
        )}
        {!loading && error && (
          <div className="demo__output-empty" style={{ color: "var(--accent)" }}>{error}</div>
        )}
        {!loading && !findings && !error && (
          <div className="demo__output-empty">
            ▢ &nbsp; OUTPUT WILL APPEAR HERE
          </div>
        )}
        {!loading && findings && (
          <div>
            <div className="card__label">
              <span className="card__label-dot" /> FIRST IMPRESSION
            </div>
            <div style={{ fontSize: 15, lineHeight: 1.45, margin: "4px 0 18px", color: "var(--fg)" }}>
              "{findings.firstImpression}"
            </div>
            <div className="card__label">
              <span className="card__label-dot" /> FRICTION FINDINGS · {findings.findings.length}
            </div>
            <div style={{ marginTop: 4 }}>
              {findings.findings.map((f, i) => (
                <div className="demo__finding" key={i}>
                  <div className="demo__finding-head">
                    <div className="demo__finding-title">{f.title}</div>
                    <Tag accent={f.severity === "high"}>{(f.severity || "med").toUpperCase()}</Tag>
                  </div>
                  <div className="demo__finding-body">{f.detail}</div>
                  {f.evidence && (
                    <div style={{ marginTop: 8, paddingLeft: 10, borderLeft: "2px solid var(--accent)", fontFamily: "var(--mono)", fontSize: 11, color: "var(--fg-muted)", lineHeight: 1.5 }}>
                      {f.evidence}
                    </div>
                  )}
                </div>
              ))}
            </div>
            {findings.confidence !== undefined && (
              <div style={{ marginTop: 18 }}>
                <Confidence pct={Number(findings.confidence)} />
              </div>
            )}
          </div>
        )}
      </div>
    </>
  );
}

// ============================================================
// DEMO 2 — Research question → study plan
// ============================================================

function DemoQuestionGenerator() {
  const [q, setQ] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [plan, setPlan] = React.useState(null);
  const [error, setError] = React.useState(null);

  const examples = [
    "Why are users abandoning checkout?",
    "Which onboarding screen confuses new users most?",
    "How do shoppers react to our new packaging?",
    "Does our pricing message land with mid-market buyers?",
  ];

  const run = async () => {
    if (!q || loading) return;
    setLoading(true);
    setPlan(null);
    setError(null);
    try {
      const prompt = `You are an AI research planner. The user's research question is: "${q}".
Return ONLY valid JSON (no prose, no markdown, no code fences) with this exact shape:
{
  "studyType": "one of: AI-Moderated Interviews | Agentic UX Test | Concept & Video Test | Synthetic Focus Group",
  "audience": "1-line description of the recommended participant audience",
  "n": "recommended sample size as a string, e.g. '40 participants'",
  "timeline": "estimated time, e.g. '5 days'",
  "guide": ["5 short interview / task questions worded like a senior researcher would ask"],
  "outputs": ["3-4 concrete deliverables, e.g. Executive PDF, Clip reel, Pattern clusters, ..."]
}`;
      const txt = await window.claude.complete(prompt);
      const clean = txt.trim().replace(/^```(?:json)?\s*/i, "").replace(/```\s*$/, "");
      const parsed = JSON.parse(clean);
      setPlan(parsed);
    } catch (e) {
      setError("Couldn't generate a plan. Try a more specific question.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <div>
        <div className="card__label"><span className="card__label-dot" /> ASK A RESEARCH QUESTION</div>
        <textarea
          className="demo__textarea"
          placeholder="What do you want to learn about your customers?"
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 12 }}>
          <div className="demo__examples" style={{ margin: 0 }}>
            {examples.map((e) => (
              <span key={e} className="demo__example" onClick={() => setQ(e)}>{e}</span>
            ))}
          </div>
          <button className="btn btn--primary" onClick={run} disabled={loading}>
            {loading ? "Planning…" : "Generate study plan →"}
          </button>
        </div>
        <div style={{ marginTop: 22 }}>
          <div className="card__label"><span className="card__label-dot" /> METHOD</div>
          <p style={{ fontSize: 13, color: "var(--fg-muted)", lineHeight: 1.55, marginTop: 8 }}>
            NeroView selects the right research mode, recommends an audience and sample, and drafts the interview guide. Editable end-to-end before you ship the study.
          </p>
        </div>
      </div>

      <div className="demo__output">
        {loading && <div className="demo__output-empty">DRAFTING STUDY PLAN…</div>}
        {!loading && error && <div className="demo__output-empty" style={{ color: "var(--accent)" }}>{error}</div>}
        {!loading && !plan && !error && (
          <div className="demo__output-empty">
            ▢ &nbsp; STUDY PLAN WILL APPEAR HERE
          </div>
        )}
        {!loading && plan && (
          <div>
            <div className="card__label"><span className="card__label-dot" /> RECOMMENDED METHOD</div>
            <div style={{ fontSize: 17, fontWeight: 500, letterSpacing: "-0.01em", margin: "4px 0 14px" }}>
              {plan.studyType}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12, marginBottom: 18, paddingBottom: 16, borderBottom: "1px dashed var(--border)" }}>
              <div>
                <div style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--fg-dim)", letterSpacing: "0.1em" }}>AUDIENCE</div>
                <div style={{ fontSize: 13, marginTop: 4 }}>{plan.audience}</div>
              </div>
              <div>
                <div style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--fg-dim)", letterSpacing: "0.1em" }}>SAMPLE</div>
                <div style={{ fontSize: 13, marginTop: 4 }}>{plan.n}</div>
              </div>
              <div>
                <div style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--fg-dim)", letterSpacing: "0.1em" }}>TIMELINE</div>
                <div style={{ fontSize: 13, marginTop: 4 }}>{plan.timeline}</div>
              </div>
            </div>
            <div className="card__label"><span className="card__label-dot" /> INTERVIEW GUIDE</div>
            <ol style={{ margin: "8px 0 18px", padding: "0 0 0 20px", fontSize: 13, color: "var(--fg)", lineHeight: 1.55 }}>
              {(plan.guide || []).map((g, i) => <li key={i} style={{ marginBottom: 6 }}>{g}</li>)}
            </ol>
            <div className="card__label"><span className="card__label-dot" /> DELIVERABLES</div>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 8 }}>
              {(plan.outputs || []).map((o, i) => <Tag key={i} dot accent={i === 0}>{o}</Tag>)}
            </div>
          </div>
        )}
      </div>
    </>
  );
}

// ============================================================
// DEMO 3 — Concept → insight scrubber (animated)
// ============================================================

function DemoVideoToInsight() {
  const [t, setT] = React.useState(0); // 0..100
  const [playing, setPlaying] = React.useState(false);
  const rafRef = React.useRef(0);

  React.useEffect(() => {
    if (!playing) return;
    let last = performance.now();
    const tick = (now) => {
      const dt = now - last;
      last = now;
      setT((prev) => {
        const next = prev + dt * 0.018; // ~5.5s to traverse
        if (next >= 100) { setPlaying(false); return 100; }
        return next;
      });
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [playing]);

  const moments = [
    { at: 18, label: "Hesitation", text: "“Wait, what does 'team plan' include?”" },
    { at: 42, label: "Confusion", text: "“I'm not sure where to click.”" },
    { at: 67, label: "Positive", text: "“Oh, this is actually clear.”" },
    { at: 88, label: "Decision", text: "“Yeah, I'd try this.”" },
  ];
  const activeIdx = moments.findIndex((m, i) => t < m.at + 6 && t >= m.at - 2);

  return (
    <>
      <div>
        <div className="card__label"><span className="card__label-dot" /> CONCEPT VIDEO · PARTICIPANT REACTION</div>
        <div style={{ position: "relative", aspectRatio: "16/10", borderRadius: "var(--radius-md)", overflow: "hidden", background: "var(--bg-elev-2)", border: "1px solid var(--border)" }}>
          {/* background mock concept frame */}
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(135deg, color-mix(in oklab, var(--accent) 12%, var(--bg-elev-2)), var(--bg-elev-2))" }} />
          <div style={{ position: "absolute", left: 16, top: 16, fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em", color: "var(--fg-muted)" }}>
            CONCEPT_V3.mp4
          </div>
          {/* face PIP */}
          <div style={{ position: "absolute", bottom: 12, right: 12, width: 80, height: 60, background: "var(--bg-elev)", border: "1px solid var(--border)", borderRadius: 6, overflow: "hidden" }}>
            <div style={{ position: "absolute", bottom: 0, left: "50%", transform: "translateX(-50%)", width: "60%", aspectRatio: "1/1.1", background: "color-mix(in oklab, var(--fg) 28%, transparent)", borderRadius: "50% 50% 8% 8% / 60% 60% 8% 8%" }} />
          </div>
          {/* scrubbing playhead overlay */}
          <div style={{ position: "absolute", left: `${t}%`, top: 0, bottom: 0, width: 2, background: "var(--accent)", boxShadow: "0 0 12px var(--accent)" }} />

          {/* active moment caption */}
          {activeIdx >= 0 && (
            <div style={{ position: "absolute", left: 16, bottom: 16, maxWidth: "60%", padding: "10px 12px", background: "color-mix(in oklab, var(--bg) 80%, transparent)", border: "1px solid var(--border)", borderRadius: 8, backdropFilter: "blur(8px)" }}>
              <div style={{ fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: "0.12em", color: "var(--accent)", marginBottom: 4 }}>
                {moments[activeIdx].label.toUpperCase()} · {Math.round(moments[activeIdx].at * 0.05 * 60)}s
              </div>
              <div style={{ fontSize: 13, color: "var(--fg)" }}>{moments[activeIdx].text}</div>
            </div>
          )}
        </div>

        {/* scrubber */}
        <div style={{ marginTop: 14, position: "relative", height: 32 }}>
          <div style={{ position: "absolute", left: 0, right: 0, top: 14, height: 4, background: "var(--bg-elev-2)", borderRadius: 2 }} />
          <div style={{ position: "absolute", left: 0, top: 14, height: 4, width: `${t}%`, background: "var(--accent)", borderRadius: 2 }} />
          {moments.map((m, i) => (
            <div key={i} style={{ position: "absolute", left: `${m.at}%`, top: 9, width: 2, height: 14, background: t >= m.at ? "var(--accent)" : "var(--fg-dim)" }} />
          ))}
          <input
            type="range" min="0" max="100" step="0.5" value={t}
            onChange={(e) => { setPlaying(false); setT(parseFloat(e.target.value)); }}
            style={{ position: "absolute", inset: 0, opacity: 0, width: "100%", height: "100%", cursor: "pointer" }}
          />
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
          <button className="btn btn--ghost" onClick={() => { setPlaying(true); if (t >= 100) setT(0); }}>
            {playing ? "❚❚ Pause" : "▶  Play participant"}
          </button>
          <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--fg-muted)" }}>
            00:{String(Math.round(t * 0.6)).padStart(2, "0")} / 01:00
          </span>
        </div>
      </div>

      <div className="demo__output">
        <div className="card__label"><span className="card__label-dot" /> LIVE EVIDENCE STREAM</div>
        <div style={{ marginTop: 8 }}>
          {moments.map((m, i) => {
            const captured = t >= m.at;
            const isActive = i === activeIdx;
            return (
              <div key={i} className="demo__finding" style={{ opacity: captured ? 1 : 0.35, transition: "opacity 240ms" }}>
                <div className="demo__finding-head">
                  <div className="demo__finding-title">{m.label} · {Math.round(m.at * 0.6)}s</div>
                  {captured && <Tag dot accent={isActive}>{captured ? "CAPTURED" : "PENDING"}</Tag>}
                </div>
                <div className="demo__finding-body" style={{ fontStyle: "italic" }}>
                  {captured ? m.text : "—"}
                </div>
              </div>
            );
          })}
        </div>
        {t >= 100 && (
          <div className="card card--accent" style={{ marginTop: 16, padding: 14 }}>
            <div className="card__label"><span className="card__label-dot" /> CLUSTERED INSIGHT</div>
            <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: "-0.005em", margin: "4px 0 10px" }}>
              Confusion peaks mid-video, but the final CTA recovers — concept is salvageable with a tighter middle.
            </div>
            <Confidence pct={0.78} />
          </div>
        )}
      </div>
    </>
  );
}

Object.assign(window, { InteractiveDemo, DemoURLAudit, DemoQuestionGenerator, DemoVideoToInsight });
