// StruggleReelScreen.jsx
// Tutor drills into one student. 30-60s auto-compiled reel + score timeline + misconception summary.
// Source: roadmap.json (struggle-reel), design_brief.html ("90 seconds, exact misconception").

function StruggleReelScreen({ studentId, onBack }) {
  const [t, setT] = React.useState(24); // seconds into reel, 0..64
  const [playing, setPlaying] = React.useState(true);
  const duration = 64;

  // Auto-advance
  React.useEffect(() => {
    if (!playing) return;
    const h = setInterval(() => setT(prev => {
      if (prev >= duration) { setPlaying(false); return duration; }
      return prev + 1;
    }), 1000);
    return () => clearInterval(h);
  }, [playing]);

  // Reel segments — each is a frame from the session with score dip + what happened.
  const segments = [
    { start: 0,  end: 12, score: 0.82, kind: "ok",   title: "Set up dH correctly",
      note: "Applied d(PV) expansion without hesitation.",
      frame: "enthalpy" },
    { start: 12, end: 26, score: 0.48, kind: "dip",  title: "Stalled · 9 seconds on d(PV)",
      note: "Long pause after writing dU. Eraser marks on P dV + V dP.",
      frame: "stall" },
    { start: 26, end: 40, score: 0.31, kind: "low",  title: "Wrote dU = T dS − P dV as identity, hedged on 'why'",
      note: "In self-explanation: \"basically it just is\". Classified blurry.",
      frame: "hedge" },
    { start: 40, end: 52, score: 0.35, kind: "low",  title: "Probe: what's an inexact differential?",
      note: "Could not distinguish dU from δW. Probe flagged.",
      frame: "probe" },
    { start: 52, end: 64, score: 0.66, kind: "rec",  title: "Recovered via product rule reminder",
      note: "Re-derived on second attempt. Clean.",
      frame: "recover" },
  ];

  const cur = segments.find(s => t >= s.start && t < s.end) || segments[segments.length - 1];

  const fmt = (s) => `${Math.floor(s/60)}:${String(s%60).padStart(2,"0")}`;

  // Misconception summary (derived)
  const misconceptions = [
    { severity: "high",   kind: "blurry",  tag: "exact vs inexact differentials",
      evidence: "3 hedges, 1 probe flagged. Connected product rule only after prompt." },
    { severity: "medium", kind: "blank",   tag: "δW vs dU distinction",
      evidence: "Could not answer probe. Has not been taught explicitly." },
    { severity: "watch",  kind: "decay",   tag: "Legendre transforms (seen 14d ago)",
      evidence: "Will need before Maxwell relations next week." },
  ];

  // Frame illustration (fake video still) — swapped by segment.
  const Frame = ({ kind }) => {
    if (kind === "enthalpy") {
      return (
        <g>
          <text x="60" y="100" fontFamily="Caveat, cursive" fontSize="30" fill="#1a1a1a">H = U + PV</text>
          <text x="60" y="160" fontFamily="Caveat, cursive" fontSize="28" fill="#1a1a1a">dH = dU + d(PV)</text>
          <text x="60" y="220" fontFamily="Caveat, cursive" fontSize="28" fill="#1a1a1a">dH = dU + P dV + V dP</text>
        </g>
      );
    }
    if (kind === "stall") {
      return (
        <g>
          <text x="60" y="100" fontFamily="Caveat, cursive" fontSize="26" fill="#1a1a1a">dH = dU + d(PV)</text>
          <text x="60" y="160" fontFamily="Caveat, cursive" fontSize="26" fill="#a9361e" opacity="0.5">
            dH = dU + P dV <tspan textDecoration="line-through">+ V dV</tspan>
          </text>
          <text x="60" y="200" fontFamily="Caveat, cursive" fontSize="22" fill="#a9361e" opacity="0.7">↑ erased</text>
          <rect x="55" y="220" width="200" height="40" fill="none" stroke="#a9361e" strokeWidth="1" strokeDasharray="4 3" rx="4"/>
          <text x="65" y="246" fontFamily="var(--font-mono)" fontSize="12" fill="#a9361e">· 9.2s pause</text>
        </g>
      );
    }
    if (kind === "hedge") {
      return (
        <g>
          <text x="60" y="100" fontFamily="Caveat, cursive" fontSize="26" fill="#1a1a1a">dU = T dS − P dV</text>
          <rect x="50" y="140" width="340" height="130" fill="#9747FF" fillOpacity="0.08" stroke="#9747FF" strokeOpacity="0.3" strokeWidth="1" strokeDasharray="4 3" rx="6"/>
          <text x="66" y="164" fontFamily="var(--font-mono)" fontSize="11" fill="#9747FF">AUDIO · self-explanation</text>
          <text x="66" y="194" fontFamily="var(--font-serif)" fontStyle="italic" fontSize="16" fill="#1a1a1a">"it's just, basically, the</text>
          <text x="66" y="218" fontFamily="var(--font-serif)" fontStyle="italic" fontSize="16" fill="#1a1a1a">first law, so dU is kind of</text>
          <text x="66" y="242" fontFamily="var(--font-serif)" fontStyle="italic" fontSize="16" fill="#1a1a1a">always that expression…"</text>
        </g>
      );
    }
    if (kind === "probe") {
      return (
        <g>
          <rect x="40" y="70" width="360" height="60" fill="#fff" stroke="#9747FF" strokeWidth="1.2" rx="8"/>
          <text x="56" y="94" fontFamily="var(--font-sans)" fontSize="11" fill="#9747FF" fontWeight="700">PROBE</text>
          <text x="56" y="118" fontFamily="var(--font-serif)" fontSize="18" fill="#1a1a1a">What makes dU exact and δW inexact?</text>
          <text x="60" y="176" fontFamily="Caveat, cursive" fontSize="26" fill="#8a836c">…</text>
          <text x="60" y="214" fontFamily="var(--font-mono)" fontSize="11" fill="#a9361e">· no response · 14s</text>
        </g>
      );
    }
    // recover
    return (
      <g>
        <text x="60" y="100" fontFamily="Caveat, cursive" fontSize="24" fill="#1a1a1a">d(fg) = f dg + g df</text>
        <text x="60" y="140" fontFamily="Caveat, cursive" fontSize="22" fill="#8a836c">f = P, g = V</text>
        <text x="60" y="200" fontFamily="Caveat, cursive" fontSize="26" fill="#1a1a1a">dH = T dS + V dP ✓</text>
        <text x="280" y="200" fontFamily="var(--font-sans)" fontSize="12" fill="#619F4A" fontWeight="700">CRISP</text>
      </g>
    );
  };

  return (
    <section className="reel">
      <div className="reel-top">
        <button className="back-btn" onClick={onBack}>
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M15 6l-6 6 6 6"/></svg>
          All students
        </button>
        <div className="reel-top-id">
          <div className="tutor-avatar tutor-avatar-lg">CJ</div>
          <div>
            <div className="reel-name">Cooper Jenkins</div>
            <div className="reel-meta">ME 80 · Session 14 · May 10</div>
          </div>
        </div>
        <div className="reel-top-actions">
          <button className="btn-ghost">Full session</button>
          <button className="btn-primary">Send note to Cooper</button>
        </div>
      </div>

      <div className="reel-body">
        <div className="reel-stage">
          <div className="reel-viewport">
            <svg viewBox="0 0 440 300" width="100%" height="100%" className="reel-frame">
              <defs>
                <pattern id="reel-grid" width="24" height="24" patternUnits="userSpaceOnUse">
                  <path d="M24 0H0V24" fill="none" stroke="rgba(173,89,5,0.1)" strokeWidth="0.5"/>
                </pattern>
              </defs>
              <rect width="440" height="300" fill="#fefaf3"/>
              <rect width="440" height="300" fill="url(#reel-grid)"/>
              <Frame kind={cur.frame}/>
            </svg>
            <div className="reel-overlay">
              <div className="reel-overlay-tl">
                <span className={"reel-tag reel-tag-" + cur.kind}>{cur.kind === "dip" ? "Stall" : cur.kind === "low" ? "Low score" : cur.kind === "rec" ? "Recovered" : "OK"}</span>
                <span className="reel-overlay-score">score {Math.round(cur.score * 100)}</span>
              </div>
              <div className="reel-overlay-br">{fmt(t)} / {fmt(duration)}</div>
            </div>
          </div>

          <div className="reel-caption">
            <div className="reel-caption-title">{cur.title}</div>
            <div className="reel-caption-body">{cur.note}</div>
          </div>

          <div className="reel-transport">
            <button className="reel-play" onClick={() => setPlaying(p => !p)} aria-label={playing ? "pause" : "play"}>
              {playing
                ? <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><rect x="6" y="5" width="4" height="14"/><rect x="14" y="5" width="4" height="14"/></svg>
                : <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>}
            </button>
            <div className="reel-scrub">
              {/* background score line */}
              <svg viewBox="0 0 640 40" preserveAspectRatio="none" className="reel-scrub-svg">
                {/* score area */}
                <defs>
                  <linearGradient id="scoreGrad" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor="#619F4A" stopOpacity="0.4"/>
                    <stop offset="100%" stopColor="#619F4A" stopOpacity="0"/>
                  </linearGradient>
                </defs>
                <path d="M0 20 Q 40 8, 80 10 T 160 24 Q 200 32, 240 30 T 320 32 Q 360 34, 400 30 Q 440 26, 480 22 Q 520 18, 560 14 Q 600 10, 640 8 L 640 40 L 0 40 Z"
                      fill="url(#scoreGrad)"/>
                <path d="M0 20 Q 40 8, 80 10 T 160 24 Q 200 32, 240 30 T 320 32 Q 360 34, 400 30 Q 440 26, 480 22 Q 520 18, 560 14 Q 600 10, 640 8"
                      fill="none" stroke="#1a1a1a" strokeWidth="1.2"/>
                {/* segment markers */}
                {segments.map(s => (
                  <g key={s.start}>
                    <line x1={(s.start/duration)*640} y1="0" x2={(s.start/duration)*640} y2="40"
                          stroke="#d4c9bc" strokeWidth="0.5"/>
                  </g>
                ))}
                {/* playhead */}
                <line x1={(t/duration)*640} y1="0" x2={(t/duration)*640} y2="40" stroke="#ad5905" strokeWidth="1.5"/>
                <circle cx={(t/duration)*640} cy="6" r="4" fill="#ad5905"/>
              </svg>
              <div className="reel-segments">
                {segments.map(s => {
                  const w = ((s.end - s.start) / duration) * 100;
                  const left = (s.start / duration) * 100;
                  return (
                    <button key={s.start}
                      className={"reel-seg reel-seg-" + s.kind + (t >= s.start && t < s.end ? " reel-seg-active" : "")}
                      style={{left: left + "%", width: w + "%"}}
                      onClick={() => { setT(s.start); setPlaying(false); }}
                      title={s.title}
                    />
                  );
                })}
              </div>
            </div>
            <div className="reel-time">{fmt(t)} / {fmt(duration)}</div>
          </div>
        </div>

        <aside className="reel-side">
          <div className="reel-card">
            <div className="eyebrow-sm">Why this reel was cut</div>
            <div className="reel-card-body">
              Five moments where Cooper's score dropped below 0.5 or paused 5s+. Auto-selected from a 47-minute session.
            </div>
          </div>

          <div className="reel-card">
            <div className="eyebrow-sm">Detected misconceptions</div>
            <div className="reel-misc-list">
              {misconceptions.map((m, i) => (
                <div key={i} className={"reel-misc reel-misc-" + m.severity}>
                  <div className="reel-misc-head">
                    <span className={"chip chip-" + (m.kind === "decay" ? "decay" : m.kind === "blank" ? "blank" : "blurry")}>
                      {m.kind}
                    </span>
                    <span className="reel-misc-sev">{m.severity}</span>
                  </div>
                  <div className="reel-misc-tag">{m.tag}</div>
                  <div className="reel-misc-ev">{m.evidence}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="reel-card reel-card-suggest">
            <div className="eyebrow-sm">Suggested action · 3 min</div>
            <div className="reel-suggest-body">
              Walk Cooper through one exact-vs-inexact example on the board. Then have him re-derive dH.
            </div>
            <div className="reel-suggest-actions">
              <button className="btn-ghost">Not useful</button>
              <button className="btn-primary">Save to notes</button>
            </div>
          </div>
        </aside>
      </div>
    </section>
  );
}

Object.assign(window, { StruggleReelScreen });
