// screen-instructor.jsx
// Instructor dashboard: roster of all completions logged on this device.

const { useState: useStIns, useEffect: useEfIns } = React;

function InstructorScreen({ onBack }) {
  const [view, setView] = useStIns('roster'); // 'roster' | 'packets'
  const [data, setData] = useStIns(SylRosterStorage.loadRoster());
  const [packetsData, setPacketsData] = useStIns(
    (window.SylPacketsStorage && window.SylPacketsStorage.loadPackets()) || { packets: [] }
  );
  const [filter, setFilter] = useStIns('all');
  const [search, setSearch] = useStIns('');
  const [packetTypeFilter, setPacketTypeFilter] = useStIns('all'); // all|question|suggestion
  const [packetTagFilter, setPacketTagFilter] = useStIns('all');

  const records = data.records || [];
  const packets = (packetsData.packets || []).slice().sort((a, b) => b.submittedAt - a.submittedAt);
  const filteredPackets = packets
    .filter(p => packetTypeFilter === 'all' || p.type === packetTypeFilter)
    .filter(p => packetTagFilter === 'all' || p.tag === packetTagFilter)
    .filter(p => !search ||
      p.message.toLowerCase().includes(search.toLowerCase()) ||
      (p.studentName || '').toLowerCase().includes(search.toLowerCase()) ||
      (p.studentEmail || '').toLowerCase().includes(search.toLowerCase()));

  const filtered = records
    .filter(r => filter === 'all' || r.section === filter)
    .filter(r => !search || r.name.toLowerCase().includes(search.toLowerCase()) || r.email.toLowerCase().includes(search.toLowerCase()))
    .sort((a, b) => b.completedAt - a.completedAt);

  // Stats
  const total = records.length;
  const passed = records.filter(r => r.passed).length;
  const avgScore = total ? Math.round(records.reduce((s, r) => s + r.totalXp, 0) / total) : 0;
  const uniqueStudents = new Set(records.map(r => r.email)).size;

  const sections = ['all', ...Array.from(new Set(records.map(r => r.section))).sort()];

  function exportCsv() {
    const cols = ['Name', 'Email', 'Section', 'CompletedAt', 'Difficulty', 'TotalXP', 'Datastream', 'Heist', 'Policy', 'Grade', 'Passed', 'DurationSec'];
    const rows = records.map(r => [
      r.name, r.email, r.section,
      new Date(r.completedAt).toISOString(),
      r.difficulty, r.totalXp, r.scores.datastream || 0, r.scores.heist || 0, r.scores.policy || 0,
      r.grade, r.passed ? 'YES' : 'NO', r.durationSec || 0,
    ]);
    const csv = [cols, ...rows].map(row => row.map(v => `"${String(v).replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = `syllabus-override-roster-${Date.now()}.csv`;
    a.click(); URL.revokeObjectURL(url);
  }

  function clearAll() {
    if (!confirm('Clear all roster records? This cannot be undone.')) return;
    SylRosterStorage.clearRoster();
    setData({ records: [] });
  }

  function exportPacketsCsv() {
    const cols = ['SubmittedAt', 'Type', 'Tag', 'SrcPhase', 'Anonymous', 'Name', 'Email', 'Section', 'Squad', 'AwardedXP', 'Message'];
    const rows = packets.map(p => [
      new Date(p.submittedAt).toISOString(),
      p.type, p.tag, p.srcPhase,
      p.anonymous ? 'YES' : 'NO',
      p.studentName || '', p.studentEmail || '', p.studentSection || '',
      p.squadName || '', p.awardedXp || 0, p.message,
    ]);
    const csv = [cols, ...rows].map(row => row.map(v => `"${String(v).replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = `syllabus-override-packets-${Date.now()}.csv`;
    a.click(); URL.revokeObjectURL(url);
  }

  function clearAllPackets() {
    if (!confirm('Clear all submitted packets? This cannot be undone.')) return;
    window.SylPacketsStorage && window.SylPacketsStorage.clearPackets();
    setPacketsData({ packets: [] });
  }

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, padding: '24px 48px 32px' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <div className="chip chip-magenta" style={{ marginBottom: 10 }}>◆ INSTRUCTOR // CLEARANCE T1</div>
          <h2 className="t-display glow-magenta" style={{ fontSize: 32, letterSpacing: '0.04em', color: 'var(--neon-magenta)' }}>
            {view === 'roster' ? 'ROSTER OVERRIDE' : 'PACKET INTAKE'}
          </h2>
          <div style={{ color: 'var(--ink-60)', fontSize: 12, marginTop: 6 }}>
            {view === 'roster'
              ? '◇ All squad runs logged on this device. Export to CSV for the Canvas gradebook.'
              : '◇ Questions and suggestions transmitted from operatives. Sorted newest first.'}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          {view === 'roster' ? (
            <>
              <button className="btn btn-ghost" onClick={exportCsv} disabled={!total}>↓ EXPORT CSV</button>
              <button className="btn btn-ghost" onClick={clearAll} disabled={!total}
                style={{ borderColor: 'rgba(255,51,85,.4)', color: 'var(--neon-red)' }}>⌫ CLEAR</button>
            </>
          ) : (
            <>
              <button className="btn btn-ghost" onClick={exportPacketsCsv} disabled={!packets.length}>↓ EXPORT CSV</button>
              <button className="btn btn-ghost" onClick={clearAllPackets} disabled={!packets.length}
                style={{ borderColor: 'rgba(255,51,85,.4)', color: 'var(--neon-red)' }}>⌫ CLEAR</button>
            </>
          )}
          <button className="btn btn-primary" onClick={onBack}>◀ BACK</button>
        </div>
      </div>

      {/* Tab bar */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 14, borderBottom: '1px solid rgba(0,234,255,.15)' }}>
        {[
          { id: 'roster', label: `ROSTER (${total})` },
          { id: 'packets', label: `PACKETS (${packets.length})` },
        ].map(t => (
          <button key={t.id} onClick={() => setView(t.id)}
            aria-pressed={view === t.id}
            className="t-display"
            style={{
              padding: '10px 18px', cursor: 'pointer',
              background: view === t.id ? 'rgba(255,45,149,.14)' : 'transparent',
              border: 0,
              borderBottom: `2px solid ${view === t.id ? 'var(--neon-magenta)' : 'transparent'}`,
              color: view === t.id ? 'var(--neon-magenta)' : 'var(--ink-60)',
              fontSize: 12, letterSpacing: '0.14em',
              textShadow: view === t.id ? '0 0 8px rgba(255,45,149,.4)' : 'none',
              marginBottom: -1,
            }}>
            {t.label}
          </button>
        ))}
      </div>

      {view === 'roster' && (
      <>
      {/* Stat cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 16 }}>
        <StatCard label="TOTAL RUNS" value={total} accent="var(--neon-cyan)" />
        <StatCard label="UNIQUE STUDENTS" value={uniqueStudents} accent="var(--neon-magenta)" />
        <StatCard label="PASS RATE" value={total ? `${Math.round((passed / total) * 100)}%` : '—'} accent="var(--neon-lime)" />
        <StatCard label="AVG XP" value={avgScore.toLocaleString()} accent="var(--neon-yellow)" />
      </div>

      {/* Filters */}
      <div className="panel" style={{ padding: 14, marginBottom: 12, display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{ display: 'flex', gap: 6 }}>
          {sections.map(s => (
            <button key={s} onClick={() => setFilter(s)}
              style={{
                padding: '8px 14px', cursor: 'pointer',
                fontFamily: 'Orbitron, monospace', fontWeight: 700, fontSize: 11, letterSpacing: '0.12em',
                background: filter === s ? 'rgba(255,45,149,.18)' : 'transparent',
                border: `1px solid ${filter === s ? 'var(--neon-magenta)' : 'rgba(255,45,149,.25)'}`,
                color: filter === s ? 'var(--neon-magenta)' : 'var(--ink-60)',
              }}
            >{s === 'all' ? 'ALL SECTIONS' : `SEC-${s}`}</button>
          ))}
        </div>
        <input
          value={search} onChange={(e) => setSearch(e.target.value)}
          placeholder="Search by name or email…"
          style={{
            flex: 1, padding: '8px 12px',
            background: 'rgba(0,0,0,.4)', border: '1px solid rgba(0,234,255,.25)',
            color: 'var(--ink-100)', fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
            outline: 'none',
          }}
        />
        <div style={{ fontSize: 10, color: 'var(--ink-60)', letterSpacing: '0.14em' }}>
          {filtered.length} / {total} SHOWN
        </div>
      </div>

      {/* Roster table */}
      <div className="panel" style={{ flex: 1, padding: 0, display: 'flex', flexDirection: 'column', minHeight: 0, overflow: 'hidden' }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '1.5fr 1.8fr 60px 60px 80px 80px 80px 70px 90px',
          gap: 12, padding: '12px 20px',
          fontSize: 9, color: 'var(--ink-60)', letterSpacing: '0.16em', textTransform: 'uppercase',
          borderBottom: '1px solid rgba(0,234,255,.15)',
        }}>
          <div>Operative</div><div>Email</div><div>Sec</div><div>Diff</div>
          <div style={{ textAlign: 'right' }}>P01</div>
          <div style={{ textAlign: 'right' }}>P02</div>
          <div style={{ textAlign: 'right' }}>P03</div>
          <div style={{ textAlign: 'right' }}>Total</div>
          <div style={{ textAlign: 'right' }}>Grade</div>
        </div>

        <div style={{ flex: 1, overflowY: 'auto' }}>
          {filtered.length === 0 ? (
            <div style={{ padding: 48, textAlign: 'center', color: 'var(--ink-60)', fontSize: 13 }}>
              ◇ No runs logged{filter !== 'all' || search ? ' match the current filter.' : ' yet. Students will populate this list as they complete the game.'}
            </div>
          ) : filtered.map((r, i) => {
            const gradeColor = {
              S: 'var(--neon-yellow)', A: 'var(--neon-lime)', B: 'var(--neon-cyan)',
              C: 'var(--neon-magenta)', F: 'var(--neon-red)',
            }[r.grade];
            return (
              <div key={i} style={{
                display: 'grid', gridTemplateColumns: '1.5fr 1.8fr 60px 60px 80px 80px 80px 70px 90px',
                gap: 12, padding: '12px 20px', alignItems: 'center',
                fontSize: 12, fontFamily: 'JetBrains Mono, monospace',
                borderBottom: '1px solid rgba(0,234,255,.06)',
                background: i % 2 ? 'rgba(0,234,255,.02)' : 'transparent',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
                  <div style={{
                    width: 24, height: 24, background: 'rgba(0,234,255,.15)', border: '1px solid rgba(0,234,255,.5)',
                    color: 'var(--neon-cyan)', display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: 'Orbitron', fontWeight: 800, fontSize: 11,
                  }}>{r.name[0]?.toUpperCase()}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ color: 'var(--ink-100)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.name}</div>
                    <div style={{ fontSize: 9, color: 'var(--ink-60)', letterSpacing: '0.04em' }}>
                      {new Date(r.completedAt).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })}
                    </div>
                  </div>
                </div>
                <div style={{ color: 'var(--ink-80)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.email}</div>
                <div style={{ color: 'var(--neon-magenta)', fontSize: 11, letterSpacing: '0.06em' }}>SEC-{r.section}</div>
                <div style={{ color: 'var(--neon-yellow)', fontSize: 10, letterSpacing: '0.1em' }}>{r.difficulty.slice(0, 3).toUpperCase()}</div>
                <div style={{ textAlign: 'right', color: 'var(--neon-cyan)', fontVariantNumeric: 'tabular-nums' }}>{(r.scores.datastream || 0).toLocaleString()}</div>
                <div style={{ textAlign: 'right', color: 'var(--neon-magenta)', fontVariantNumeric: 'tabular-nums' }}>{(r.scores.heist || 0).toLocaleString()}</div>
                <div style={{ textAlign: 'right', color: 'var(--neon-yellow)', fontVariantNumeric: 'tabular-nums' }}>{(r.scores.policy || 0).toLocaleString()}</div>
                <div style={{ textAlign: 'right', color: 'var(--ink-100)', fontVariantNumeric: 'tabular-nums', fontWeight: 700 }}>{r.totalXp.toLocaleString()}</div>
                <div style={{ textAlign: 'right' }}>
                  <span className="t-display" style={{
                    display: 'inline-block', minWidth: 36, padding: '2px 0',
                    fontSize: 18, color: gradeColor,
                    textShadow: `0 0 8px ${gradeColor}66`,
                  }}>{r.grade}</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ marginTop: 12, fontSize: 10, color: 'var(--ink-60)', letterSpacing: '0.04em', lineHeight: 1.5 }}>
        ◇ <b style={{ color: 'var(--neon-lime)' }}>Live sync:</b> Each completion saves to this browser <i>and</i> POSTs to your <b>Syllabus Override · Completions</b> Google Form. Open the linked response Sheet in your Drive for the cross-device class roster.
      </div>
      </>
      )}

      {view === 'packets' && (
        <PacketsView
          packets={packets}
          filtered={filteredPackets}
          typeFilter={packetTypeFilter} setTypeFilter={setPacketTypeFilter}
          tagFilter={packetTagFilter} setTagFilter={setPacketTagFilter}
          search={search} setSearch={setSearch}
        />
      )}
    </div>
  );
}

const PACKET_TAG_LABELS = {
  policy: 'POLICY / RULES', deadline: 'DEADLINE', gai: 'AI / INTEGRITY',
  assignment: 'ASSIGNMENT', tech: 'TECH / TOOLING', other: 'OTHER',
};

function PacketsView({ packets, filtered, typeFilter, setTypeFilter, tagFilter, setTagFilter, search, setSearch }) {
  const total = packets.length;
  const questions = packets.filter(p => p.type === 'question').length;
  const suggestions = packets.filter(p => p.type === 'suggestion').length;
  const anonymous = packets.filter(p => p.anonymous).length;

  return (
    <>
      {/* Stat cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 16 }}>
        <StatCard label="TOTAL PACKETS" value={total} accent="var(--neon-magenta)" />
        <StatCard label="QUESTIONS" value={questions} accent="var(--neon-cyan)" />
        <StatCard label="SUGGESTIONS" value={suggestions} accent="var(--neon-yellow)" />
        <StatCard label="ANONYMOUS" value={anonymous} accent="var(--neon-lime)" />
      </div>

      {/* Filters */}
      <div className="panel" style={{ padding: 14, marginBottom: 12, display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 6 }}>
          {['all', 'question', 'suggestion'].map(t => (
            <button key={t} onClick={() => setTypeFilter(t)}
              className="t-mono"
              style={{
                padding: '8px 12px', cursor: 'pointer',
                background: typeFilter === t ? 'rgba(255,45,149,.18)' : 'transparent',
                border: `1px solid ${typeFilter === t ? 'var(--neon-magenta)' : 'rgba(255,45,149,.25)'}`,
                color: typeFilter === t ? 'var(--neon-magenta)' : 'var(--ink-60)',
                fontFamily: 'Orbitron, monospace', fontWeight: 700, fontSize: 10, letterSpacing: '0.14em',
                textTransform: 'uppercase',
              }}>
              {t === 'all' ? 'ALL TYPES' : t}
            </button>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {['all', ...Object.keys(PACKET_TAG_LABELS)].map(t => (
            <button key={t} onClick={() => setTagFilter(t)}
              className="t-mono"
              style={{
                padding: '6px 10px', cursor: 'pointer',
                background: tagFilter === t ? 'rgba(0,234,255,.14)' : 'transparent',
                border: `1px solid ${tagFilter === t ? 'var(--neon-cyan)' : 'rgba(0,234,255,.2)'}`,
                color: tagFilter === t ? 'var(--neon-cyan)' : 'var(--ink-60)',
                fontFamily: 'Orbitron, monospace', fontWeight: 700, fontSize: 9, letterSpacing: '0.12em',
              }}>
              {t === 'all' ? 'ALL TAGS' : (PACKET_TAG_LABELS[t] || t.toUpperCase())}
            </button>
          ))}
        </div>
        <input
          value={search} onChange={(e) => setSearch(e.target.value)}
          placeholder="Search message, name, email…"
          style={{
            flex: 1, minWidth: 200, padding: '8px 12px',
            background: 'rgba(0,0,0,.4)', border: '1px solid rgba(0,234,255,.25)',
            color: 'var(--ink-100)', fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
            outline: 'none',
          }}
        />
        <div style={{ fontSize: 10, color: 'var(--ink-60)', letterSpacing: '0.14em' }}>
          {filtered.length} / {total} SHOWN
        </div>
      </div>

      {/* Packets list */}
      <div className="panel" style={{ flex: 1, padding: 0, display: 'flex', flexDirection: 'column', minHeight: 0, overflow: 'hidden' }}>
        <div style={{ flex: 1, overflowY: 'auto' }}>
          {filtered.length === 0 ? (
            <div style={{ padding: 48, textAlign: 'center', color: 'var(--ink-60)', fontSize: 13 }}>
              ◇ No packets{packets.length === 0 ? ' transmitted yet. Students drop packets via the magenta button at the lower-left of the game.' : ' match the current filter.'}
            </div>
          ) : filtered.map((p, i) => {
            const isQ = p.type === 'question';
            const accent = isQ ? 'var(--neon-cyan)' : 'var(--neon-yellow)';
            return (
              <div key={p.id} style={{
                padding: '16px 20px',
                borderBottom: '1px solid rgba(0,234,255,.06)',
                background: i % 2 ? 'rgba(0,234,255,.02)' : 'transparent',
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginBottom: 8 }}>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                    <span className="t-display" style={{
                      display: 'inline-block', padding: '3px 9px',
                      background: isQ ? 'rgba(0,234,255,.14)' : 'rgba(251,191,36,.14)',
                      border: `1px solid ${accent}`, color: accent,
                      fontSize: 10, letterSpacing: '0.14em',
                    }}>{p.type.toUpperCase()}</span>
                    <span className="t-mono" style={{
                      padding: '3px 8px',
                      background: 'rgba(0,234,255,.06)', border: '1px solid rgba(0,234,255,.25)',
                      color: 'var(--ink-80)', fontSize: 9, letterSpacing: '0.12em',
                    }}>{PACKET_TAG_LABELS[p.tag] || p.tag.toUpperCase()}</span>
                    <span className="t-mono" style={{ fontSize: 9, color: 'var(--ink-60)', letterSpacing: '0.1em' }}>
                      SRC · {p.srcPhase ? p.srcPhase.toUpperCase() : '—'}
                    </span>
                    <span className="t-mono" style={{ fontSize: 9, color: 'var(--neon-yellow)', letterSpacing: '0.1em' }}>
                      +{p.awardedXp} XP
                    </span>
                  </div>
                  <div className="t-mono" style={{ fontSize: 10, color: 'var(--ink-60)', whiteSpace: 'nowrap', letterSpacing: '0.06em' }}>
                    {new Date(p.submittedAt).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })}
                  </div>
                </div>
                <div style={{ fontSize: 13, color: 'var(--ink-100)', lineHeight: 1.55, fontFamily: 'JetBrains Mono, monospace', whiteSpace: 'pre-wrap' }}>
                  {p.message}
                </div>
                <div style={{ marginTop: 8, fontSize: 10, color: 'var(--ink-60)', letterSpacing: '0.04em' }}>
                  {p.anonymous ? (
                    <span style={{ color: 'var(--neon-lime)' }}>◈ ANONYMOUS</span>
                  ) : (
                    <>
                      <span style={{ color: 'var(--ink-80)' }}>{p.studentName || 'Unknown operative'}</span>
                      {p.studentEmail && <span> · {p.studentEmail}</span>}
                      {p.studentSection && <span> · SEC-{p.studentSection}</span>}
                      {p.squadName && <span> · {p.squadName}</span>}
                    </>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
}

function StatCard({ label, value, accent }) {
  return (
    <div className="panel" style={{ padding: '14px 18px' }}>
      <div style={{ fontSize: 9, color: 'var(--ink-60)', letterSpacing: '0.18em' }}>{label}</div>
      <div className="t-display" style={{ fontSize: 28, color: accent, letterSpacing: '0.04em', marginTop: 4, textShadow: `0 0 12px ${accent}44` }}>
        {value}
      </div>
    </div>
  );
}

window.InstructorScreen = InstructorScreen;
