// screen-preflight.jsx — Pre-Flight Briefing
// Mandatory stop between the title-screen briefing and squad assembly.
// Three tabs: DIRECTIVES (how to play), SYLLABUS (review course doc), CONFIRM (acknowledge).
// Players cannot Initiate until they (a) open the syllabus and (b) tick the acknowledgment.

const { useState: useStPf, useEffect: useEfPf } = React;

const PF_DIRECTIVES = [
  { num: '01', title: 'Run 3 Protocols', body: 'Datastream · Heist · Firewall.' },
  { num: '02', title: 'Survive 2 Interludes', body: 'Triage and Hex Sweep between rounds.' },
  { num: '03', title: 'Score 1500 XP', body: 'Combos multiply. Wrong answers reset them.' },
  { num: '04', title: 'Pause Anytime', body: 'Press P or open DROP_PACKET.' },
  { num: '05', title: 'Solo or Squad', body: 'Pick on the next screen.' },
  { num: '06', title: 'Accessibility', body: 'Tweaks panel — top right.' },
];

function PreflightScreen({ onLaunch, onBack, onResources }) {
  const [tab, setTab] = useStPf('directives');
  const [acked, setAcked] = useStPf(false);
  const [syllabusOpened, setSyllabusOpened] = useStPf(false);

  const canLaunch = acked && syllabusOpened;

  function pickTab(id) {
    if (id === 'syllabus') setSyllabusOpened(true);
    setTab(id);
  }

  return (
    <div style={{ width: '100%', height: '100%', padding: '24px 40px',
      display: 'flex', flexDirection: 'column', gap: 16, overflow: 'hidden' }}>

      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
        borderBottom: '1px solid rgba(0,234,255,.18)', paddingBottom: 12 }}>
        <div>
          <div className="t-mono" style={{ fontSize: 11, color: 'var(--neon-cyan)',
            letterSpacing: '0.18em', marginBottom: 6 }}>◢ NODE/INFO-I-399 // PRE-FLIGHT</div>
          <h1 style={{ fontFamily: 'Orbitron', fontWeight: 800, fontSize: 36, margin: 0,
            letterSpacing: '0.04em', color: 'var(--ink-100)' }}>
            MISSION BRIEFING
          </h1>
          <div style={{ fontSize: 12, color: 'var(--ink-60)', marginTop: 6, maxWidth: 720 }}>
            Three steps. Read. Review. Acknowledge.
          </div>
        </div>
        <button className="btn btn-ghost" onClick={onBack} style={{ minWidth: 120 }} aria-label="Return to title screen">◂ BACK</button>
      </div>

      {/* Tabs */}
      <div role="tablist" aria-label="Pre-flight sections" style={{ display: 'flex', gap: 4 }}>
        <PfTab id="directives" tab={tab} onClick={pickTab} label="◇ DIRECTIVES" />
        <PfTab id="syllabus" tab={tab} onClick={pickTab} label="◇ SYLLABUS"
          badge={syllabusOpened ? '✓' : '!'} badgeColor={syllabusOpened ? 'var(--neon-lime)' : 'var(--neon-yellow)'} />
        <PfTab id="confirm" tab={tab} onClick={pickTab} label="◇ ACKNOWLEDGE"
          badge={acked ? '✓' : null} badgeColor="var(--neon-lime)" />
      </div>

      {/* Body */}
      <div style={{ flex: 1, overflowY: 'auto', paddingRight: 8 }}
        role="tabpanel" aria-label={`${tab} panel`}>

        {tab === 'directives' && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 14, maxWidth: 1100, margin: '0 auto' }}>
            {PF_DIRECTIVES.map((d) => (
              <div key={d.num} className="panel" style={{ padding: '20px 22px', display: 'flex', gap: 16, alignItems: 'center' }}>
                <div style={{ fontFamily: 'Orbitron', fontWeight: 800, fontSize: 32, color: 'var(--neon-cyan)', lineHeight: 1, minWidth: 48 }}>{d.num}</div>
                <div>
                  <div className="t-display" style={{ fontSize: 14, color: 'var(--ink-100)', letterSpacing: '0.06em', marginBottom: 4 }}>{d.title}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-80)', lineHeight: 1.5 }}>{d.body}</div>
                </div>
              </div>
            ))}
          </div>
        )}

        {tab === 'syllabus' && (
          <SyllabusReview />
        )}

        {tab === 'confirm' && (
          <div style={{ maxWidth: 720, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 18 }}>
            <div className="panel" style={{ padding: 24 }}>
              <div className="chip chip-yellow" style={{ marginBottom: 14 }}>◇ ACKNOWLEDGMENT</div>
              <div style={{ fontSize: 13, color: 'var(--ink-80)', lineHeight: 1.7, marginBottom: 18 }}>
                Before deploying you must confirm you have read the course syllabus and understand the policies covered in this mission. Your acknowledgment is logged with your sign-in and reported to the instructor.
              </div>
              <label style={{ display: 'flex', alignItems: 'flex-start', gap: 12, cursor: 'pointer', padding: 12,
                background: acked ? 'rgba(170,255,0,.08)' : 'rgba(0,234,255,.04)',
                border: `1px solid ${acked ? 'var(--neon-lime)' : 'rgba(0,234,255,.2)'}`,
                transition: 'background .15s' }}>
                <input type="checkbox" checked={acked} onChange={(e) => setAcked(e.target.checked)}
                  style={{ marginTop: 3, width: 18, height: 18, accentColor: 'var(--neon-lime)' }}
                  aria-describedby="ack-text" />
                <span id="ack-text" style={{ fontSize: 13, color: 'var(--ink-100)', lineHeight: 1.5 }}>
                  I confirm I have <b>read the INFO-I 399 syllabus</b> and reviewed the late-work policy, attendance policy, and GAI use policy. I understand my responses in this game will be recorded.
                </span>
              </label>
              {!syllabusOpened && (
                <div role="alert" className="t-mono" style={{ marginTop: 14, fontSize: 11, color: 'var(--neon-yellow)', letterSpacing: '0.12em' }}>
                  ◢ OPEN THE SYLLABUS TAB FIRST TO UNLOCK DEPLOYMENT
                </div>
              )}
            </div>

            <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end' }}>
              {onResources && (
                <button onClick={onResources} className="t-mono"
                  style={{ background: 'transparent', border: '1px solid rgba(255,45,149,.4)',
                    color: 'var(--neon-magenta)', padding: '10px 18px', fontSize: 11,
                    letterSpacing: '0.16em', cursor: 'pointer', textTransform: 'uppercase' }}>
                  ◢ SUPPORT_NET
                </button>
              )}
              <button className="btn btn-primary" onClick={onLaunch} disabled={!canLaunch}
                aria-label={canLaunch ? 'Initiate run — proceed to squad assembly' : 'Acknowledge syllabus and tick checkbox to proceed'}>
                ► INITIATE RUN
              </button>
            </div>
            {!canLaunch && (
              <div className="t-mono" style={{ textAlign: 'right', fontSize: 10, color: 'var(--ink-60)', letterSpacing: '0.14em' }}>
                {!syllabusOpened && '// REVIEW SYLLABUS '}
                {!acked && '// CHECK ACKNOWLEDGMENT'}
              </div>
            )}
          </div>
        )}
      </div>

      {/* Footer status */}
      <div className="t-mono" style={{ fontSize: 10, color: 'var(--ink-40)',
        letterSpacing: '0.14em', borderTop: '1px solid rgba(0,234,255,.1)',
        paddingTop: 10, display: 'flex', justifyContent: 'space-between' }}>
        <span>// SYLLABUS_REVIEW: {syllabusOpened ? '✓ COMPLETE' : '— PENDING'}</span>
        <span>// ACK: {acked ? '✓ SIGNED' : '— UNSIGNED'}</span>
      </div>
    </div>
  );
}

function PfTab({ id, tab, onClick, label, badge, badgeColor }) {
  const active = tab === id;
  return (
    <button role="tab" aria-selected={active} onClick={() => onClick(id)} className="t-mono"
      style={{
        padding: '10px 18px', fontSize: 11, letterSpacing: '0.16em', cursor: 'pointer',
        background: active ? 'rgba(0,234,255,.12)' : 'rgba(0,234,255,.03)',
        color: active ? 'var(--neon-cyan)' : 'var(--ink-60)',
        border: `1px solid ${active ? 'var(--neon-cyan)' : 'rgba(0,234,255,.18)'}`,
        borderBottom: active ? '1px solid var(--bg-deep)' : '1px solid rgba(0,234,255,.18)',
        textTransform: 'uppercase', position: 'relative', display: 'inline-flex', gap: 8, alignItems: 'center',
      }}>
      {label}
      {badge && (
        <span aria-hidden="true" style={{ color: badgeColor, fontSize: 11 }}>{badge}</span>
      )}
    </button>
  );
}

// ─── Embedded syllabus review ─────────────────────────────────────────────
function SyllabusReview() {
  const sections = [
    { id: 'overview', title: 'Course Overview',
      body: 'INFO-I 399 (Spring) — a research-skills course with three major deliverables: a Hackathon Project (20%), a Research Poster (30%), and Bi-weekly Reports + In-class Participation (15%). Remaining 35% is split across the 3 Minute Thesis, Group Resume, and Course Policies Quiz.' },
    { id: 'deadlines', title: 'Deadlines & Late Work',
      body: 'All assignments are due at 5:00 PM (deadline chosen to protect student sleep and family time). A 3-day grace period applies to bi-weekly reports — no explanation required. After grace, 1% per day for up to 7 days. After day 10, late work is not accepted. Major deliverables (Hackathon, Poster) cannot be submitted late.' },
    { id: 'attendance', title: 'Attendance Policy',
      body: 'Attendance is required. Each unexcused absence reduces your final course grade by 3%. Top Hat is used for in-class quizzing and attendance — physical presence required. Arriving more than 15 minutes late may count as an absence. University-sanctioned absences are excused with documentation; you self-report illness. Missing the Hackathon may result in failing the course.' },
    { id: 'gai', title: 'Generative AI Use',
      body: 'GAI is permitted with acknowledgment, citation, and prompt disclosure. You must include the actual prompts you used. Spell/grammar checks (e.g. Grammarly) are exempt; translation is NOT exempt. Using AI to generate code without disclosure is a violation. Plagiarism reports go to the Office of Student Conduct.' },
    { id: 'email', title: 'Email Etiquette',
      body: 'Include "INFO-I 399" in the subject line. Allow at least 24 hours for a reply before following up. Instructors do not respond on weekends; for weekend emails allow 1 day after the weekend. Slack is not an official channel.' },
    { id: 'events', title: 'Required In-Person Events',
      body: 'Research Data Hackathon (mid-semester), 3 Minute Thesis (final), and the Research Poster Symposium (late April). The 3MT is graded — not extra credit. The Hackathon is in-person; remote/Zoom attendance is not permitted.' },
    { id: 'accommodations', title: 'Accommodations & Inclusion',
      body: 'Disability accommodations through AES are confidential — disclosure to classmates is never required. Religious accommodation forms must be submitted at least 2 weeks before the absence. Pronouns and chosen names are respected by all course participants.' },
    { id: 'group', title: 'Group Work',
      body: 'Hackathon teams are assigned by the instructional staff. Team evaluations are anonymous and influence individual scores. The Group Resume is the first major team deliverable.' },
    { id: 'wellness', title: 'Wellness & Support',
      body: 'CAPS counseling is free for enrolled students. The Resource Vault in this game lists 22+ campus services — review them. If overwhelmed, contact the team early; grades are not negotiated, but support pathways exist.' },
  ];
  return (
    <div className="panel" style={{ padding: '24px 28px', maxHeight: '100%', overflow: 'auto' }}>
      <div className="chip" style={{ marginBottom: 16 }}>◇ INFO-I 399 // SPRING SYLLABUS — DIGEST</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        {sections.map((s) => (
          <div key={s.id}>
            <h2 style={{ fontFamily: 'Orbitron', fontWeight: 700, fontSize: 14,
              letterSpacing: '0.06em', color: 'var(--neon-cyan)', margin: '0 0 6px',
              textTransform: 'uppercase' }}>
              ▸ {s.title}
            </h2>
            <div style={{ fontSize: 12.5, color: 'var(--ink-80)', lineHeight: 1.65 }}>
              {s.body}
            </div>
          </div>
        ))}
      </div>
      <div className="t-mono" style={{ marginTop: 24, fontSize: 10, color: 'var(--ink-40)',
        letterSpacing: '0.14em', borderTop: '1px solid rgba(0,234,255,.1)', paddingTop: 12 }}>
        // FULL SYLLABUS PDF AVAILABLE ON CANVAS — THIS IS A DIGEST FOR REVIEW
      </div>
    </div>
  );
}

window.PreflightScreen = PreflightScreen;
