/* Shared "live interview" demo, drives a timeline of transcript chunks,
   block-fill percentages, asked-question highlights, and next-question
   suggestions. Returns a state object that variations can render however
   they like. */

const DEMO_SCRIPT = [
  // t (ms), type, payload
  { t: 0,     kind: "status",       value: "listening" },
  { t: 600,   kind: "status",       value: "recording" },
  { t: 1200,  kind: "transcript",   speaker: "interviewer", text: "So, last time you tried to find an apartment, walk me through it." },
  { t: 1800,  kind: "asked",        id: "q1" },
  { t: 2200,  kind: "transcript",   speaker: "guest", text: "Yeah, it was about two months ago, I had to relocate pretty fast for work." },
  { t: 3000,  kind: "block",        id: "context", value: 35 },
  { t: 3400,  kind: "block",        id: "story",   value: 20 },
  { t: 3800,  kind: "suggestion",   value: "What was the hardest part of it?", priority: "deepen" },
  { t: 4400,  kind: "transcript",   speaker: "guest", text: "The hardest thing was the listings, half of them were already gone or just fake photos." },
  { t: 5200,  kind: "block",        id: "problem", value: 55 },
  { t: 5600,  kind: "block",        id: "story",   value: 45 },
  { t: 6000,  kind: "transcript",   speaker: "guest", text: "Honestly by day four I almost gave up, it was just frustrating." },
  { t: 6600,  kind: "block",        id: "emotion", value: 50 },
  { t: 6900,  kind: "suggestion",   value: "Ask what they tried as a workaround", priority: "next" },
  { t: 7400,  kind: "transcript",   speaker: "interviewer", text: "What did you do to get around that?" },
  { t: 7800,  kind: "asked",        id: "q2" },
  { t: 8200,  kind: "transcript",   speaker: "guest", text: "I started messaging agents directly on Telegram, that worked better." },
  { t: 9000,  kind: "block",        id: "solution", value: 40 },
  { t: 9400,  kind: "block",        id: "context",  value: 65 },
  { t: 9800,  kind: "suggestion",   value: "Probe: how did you decide which agent to trust?", priority: "criteria" },
  { t: 10400, kind: "transcript",   speaker: "guest", text: "I picked the ones with the most listings and recent activity, felt safer." },
  { t: 11200, kind: "block",        id: "criteria", value: 60 },
  { t: 11600, kind: "block",        id: "solution", value: 70 },
  { t: 12000, kind: "transcript",   speaker: "interviewer", text: "Got it, and how did that compare to using the big aggregator sites?" },
  { t: 12400, kind: "asked",        id: "q3" },
  { t: 13000, kind: "transcript",   speaker: "guest", text: "Aggregators were way slower. Telegram was almost real-time." },
  { t: 13800, kind: "block",        id: "criteria", value: 80 },
  { t: 14200, kind: "block",        id: "problem",  value: 78 },
  { t: 14600, kind: "suggestion",   value: "Now ask about emotion, did they feel relief?", priority: "emotion" },
  { t: 15400, kind: "transcript",   speaker: "guest", text: "When I finally signed, I literally cried, relief mostly. It was three weeks of hell." },
  { t: 16200, kind: "block",        id: "emotion", value: 90 },
  { t: 16600, kind: "block",        id: "story",   value: 85 },
];

const DEMO_LOOP = 18000;

const GUIDE_QUESTIONS = [
  { id: "q1", text: "Tell me about the last time you looked for an apartment.", group: "Story" },
  { id: "q2", text: "What was hardest about it, what did you do?", group: "Problem" },
  { id: "q3", text: "How did your workaround compare to existing tools?", group: "Solution" },
  { id: "q4", text: "What would you change about how this works today?", group: "Criteria" },
  { id: "q5", text: "How did that whole experience feel, looking back?", group: "Emotion" },
];

const BLOCKS = [
  { id: "context",  label: "Context",  color: "#8891AA", hint: "Who · when · where" },
  { id: "problem",  label: "Problem",  color: "#C35323", hint: "What's broken today" },
  { id: "solution", label: "Solution", color: "#0E7C3A", hint: "What they tried" },
  { id: "criteria", label: "Criteria", color: "#006DFA", hint: "How they pick" },
  { id: "emotion",  label: "Emotion",  color: "#8A38F5", hint: "How it felt" },
  { id: "story",    label: "Story",    color: "#C8AFF0", hint: "Concrete moments" },
];

function useDemoState({ speed: speedProp, autoStart = true } = {}) {
  const tweak = (window.useTweak && window.useTweak()) || {};
  const speed = speedProp != null ? speedProp : (tweak.demoSpeed || 1);
  const [tick, setTick] = React.useState(0);
  const [running, setRunning] = React.useState(autoStart);
  const startRef = React.useRef(performance.now());

  React.useEffect(() => {
    if (!running) return;
    let raf;
    let lastBucket = -1;
    const BUCKET = 120; // ms, throttle to ~8 ticks/sec to avoid jank
    const loop = () => {
      const elapsed = (performance.now() - startRef.current) * speed;
      const t = elapsed % DEMO_LOOP;
      const bucket = Math.floor(t / BUCKET);
      if (bucket !== lastBucket) {
        lastBucket = bucket;
        setTick(bucket * BUCKET);
      }
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [running, speed]);

  // Evaluate state at current tick
  const state = React.useMemo(() => {
    const transcript = [];
    const askedIds = new Set();
    let suggestion = null;
    let status = "idle";
    const blocks = Object.fromEntries(BLOCKS.map(b => [b.id, 0]));

    for (const ev of DEMO_SCRIPT) {
      if (ev.t > tick) break;
      if (ev.kind === "transcript") transcript.push({ ...ev, age: tick - ev.t });
      else if (ev.kind === "asked") askedIds.add(ev.id);
      else if (ev.kind === "suggestion") suggestion = { ...ev, age: tick - ev.t };
      else if (ev.kind === "status") status = ev.value;
      else if (ev.kind === "block") blocks[ev.id] = ev.value;
    }

    // Keep transcript trim to last N
    const lastTranscript = transcript.slice(-5);
    return { tick, transcript: lastTranscript, askedIds, suggestion, status, blocks };
  }, [tick]);

  return { state, running, setRunning, restart: () => { startRef.current = performance.now(); } };
}

window.DEMO_SCRIPT = DEMO_SCRIPT;
window.DEMO_LOOP = DEMO_LOOP;
window.GUIDE_QUESTIONS = GUIDE_QUESTIONS;
window.BLOCKS = BLOCKS;
window.useDemoState = useDemoState;
