// screen-drop-packet.jsx — Floating button + modal for student question submission.
// Persists questions to localStorage so the instructor inbox can read them.

const { useState: useStDp, useEffect: useEfDp } = React;

const DROP_PACKET_KEY = 'syl_drop_packets_v1';

const SylPacketStorage = {
  load() {
    try { return JSON.parse(localStorage.getItem(DROP_PACKET_KEY) || '[]'); }
    catch { return []; }
  },
  save(packet) {
    const all = SylPacketStorage.load();
    all.push(packet);
    localStorage.setItem(DROP_PACKET_KEY, JSON.stringify(all));
  },
  clear() { localStorage.removeItem(DROP_PACKET_KEY); },
  markResolved(id, resolved) {
    const all = SylPacketStorage.load().map(p =>
      p.id === id ? { ...p, resolved } : p);
    localStorage.setItem(DROP_PACKET_KEY, JSON.stringify(all));
  },
};

const PACKET_TAGS = [
  { id: 'policy',     label: 'Policy / Rules',    accent: '#22d3ee' },
  { id: 'deadline',   label: 'Deadline',          accent: '#fbbf24' },
  { id: 'gai',        label: 'AI / Integrity',    accent: '#a78bfa' },
  { id: 'assignment', label: 'Assignment Detail', accent: '#aaff00' },
  { id: 'tech',       label: 'Tech / Tooling',    accent: '#ff2d95' },
  { id: 'other',      label: 'Other',             accent: '#94a3b8' },
];

const PACKET_KINDS = [
  { id: 'question',   label: 'QUESTION',   xp: 50,  glyph: '?',
    helper: 'Stuck on a policy, deadline, or rule. Ask the instructor.' },
  { id: 'suggestion', label: 'SUGGESTION', xp: 75,  glyph: '+',
    helper: 'Improvement for the course or this game. Constructive ideas earn more XP.' },
];

// XP awarded on top of base
const XP_BONUS_DETAIL    = 25;  // 80+ chars, demonstrates effort
const XP_BONUS_FIRST_DAY = 25;  // First packet of the day
const XP_BONUS_RESOLVED  = 50;  // Awarded retroactively when instructor resolves

function dailyKey() { return new Date().toISOString().slice(0, 10); }

function DropPacketButton({ phase, run, student }) {
  const [open, setOpen] = useStDp(false);
  const [text, setText] = useStDp('');
  const [tag, setTag] = useStDp('policy');
  const [kind, setKind] = useStDp('question');
  const [anon, setAnon] = useStDp(false);
  const [sent, setSent] = useStDp(null); // null | {xp, breakdown}
  const [xpTotal, setXpTotal] = useStDp(() => {
    const all = SylPacketStorage.load();
    return all.reduce((s, p) => s + (p.xp || 0), 0);
  });

  // Broadcast pause state so timed protocols can freeze their timers
  useEfDp(() => {
    window.__sylPaused = open;
    window.dispatchEvent(new CustomEvent('syl-pause', { detail: { paused: open } }));
    return () => {
      window.__sylPaused = false;
      window.dispatchEvent(new CustomEvent('syl-pause', { detail: { paused: false } }));
    };
  }, [open]);

  // Hide on instructor screens
  if (phase === 'instructor' || phase === 'signin') return null;

  function submit() {
    if (!text.trim()) return;
    const k = PACKET_KINDS.find((x) => x.id === kind);

    // Calculate XP
    const breakdown = [{ label: `${k.label} BASE`, xp: k.xp }];
    if (text.trim().length >= 80) breakdown.push({ label: 'DETAILED PACKET', xp: XP_BONUS_DETAIL });
    const all = SylPacketStorage.load();
    const today = dailyKey();
    const firstToday = !all.some((p) => new Date(p.sentAt).toISOString().slice(0, 10) === today);
    if (firstToday) breakdown.push({ label: 'FIRST DROP TODAY', xp: XP_BONUS_FIRST_DAY });
    const xp = breakdown.reduce((s, b) => s + b.xp, 0);

    const packet = {
      id: 'pkt_' + Date.now() + '_' + Math.random().toString(36).slice(2, 7),
      text: text.trim(),
      kind,
      tag,
      anon,
      phase,
      student: anon ? null : (student ? { name: student.name, email: student.email, section: student.section } : null),
      role: run?.role?.name || null,
      sentAt: Date.now(),
      resolved: false,
      xp,
    };
    SylPacketStorage.save(packet);

    // Cross-device sync to the Google Form, if wired
    if (window.SylFormsSync && window.SylFormsSync.postPacket) {
      window.SylFormsSync.postPacket(packet);
    }

    setXpTotal((t) => t + xp);
    setSent({ xp, breakdown });
    setTimeout(() => {
      setOpen(false); setSent(null); setText(''); setTag('policy'); setKind('question'); setAnon(false);
    }, 2400);
  }

  return (
    <>
      {/* Floating launcher */}
      {!open && (
        <button onClick={() => setOpen(true)} className="t-mono"
          aria-label={`Drop a packet — ask the instructor a question or send a suggestion${xpTotal > 0 ? `. You have earned ${xpTotal} XP from packets.` : ''}`}
          style={{
            position: 'fixed', right: 18, bottom: 18, zIndex: 80,
            padding: '10px 14px', fontSize: 11, letterSpacing: '0.18em',
            background: 'linear-gradient(180deg, rgba(255,45,149,.2), rgba(15,19,48,.95))',
            color: 'var(--neon-magenta)',
            border: '1px solid var(--neon-magenta)',
            cursor: 'pointer', textTransform: 'uppercase',
            boxShadow: '0 0 18px rgba(255,45,149,.35)',
            display: 'flex', alignItems: 'center', gap: 10, fontFamily: 'inherit',
          }}>
          <span aria-hidden="true" style={{ fontSize: 14 }}>◢</span> DROP_PACKET
          {xpTotal > 0 && (
            <span aria-hidden="true" style={{
              padding: '2px 7px', fontSize: 9, letterSpacing: '0.14em',
              background: 'var(--neon-yellow)', color: '#1a1200',
              fontWeight: 700, borderRadius: 1,
            }}>+{xpTotal} XP</span>
          )}
        </button>
      )}

      {/* Modal */}
      {open && (
        <div role="dialog" aria-modal="true" aria-labelledby="droppacket-title"
          style={{
            position: 'fixed', inset: 0, zIndex: 90,
            background: 'rgba(2,4,16,.78)', backdropFilter: 'blur(6px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
          }}
          onClick={() => !sent && setOpen(false)}
          onKeyDown={(e) => { if (e.key === 'Escape' && !sent) setOpen(false); }}>
          <div className="panel panel-magenta" onClick={(e) => e.stopPropagation()}
            style={{ width: 'min(560px, 100%)', padding: 24, position: 'relative',
              maxHeight: '90vh', overflowY: 'auto' }}>

            {/* Header */}
            <div style={{ display: 'flex', justifyContent: 'space-between',
              alignItems: 'flex-start', marginBottom: 14 }}>
              <div>
                <div className="chip chip-magenta" style={{ marginBottom: 8 }}>
                  ◢ ENCRYPTED CHANNEL / INSTRUCTOR
                </div>
                <h2 id="droppacket-title" style={{ fontFamily: 'Orbitron', fontWeight: 800, fontSize: 22,
                  letterSpacing: '0.04em', color: 'var(--ink-100)', margin: 0 }}>
                  DROP A PACKET
                </h2>
                <div style={{ fontSize: 11, color: 'var(--ink-60)', marginTop: 4, lineHeight: 1.5 }}>
                  Questions and suggestions both earn XP. Detailed packets earn bonus.
                </div>
                <div className="t-mono" style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  marginTop: 10, padding: '3px 8px',
                  fontSize: 9, letterSpacing: '0.18em',
                  color: 'var(--neon-yellow)',
                  background: 'rgba(251,191,36,.1)',
                  border: '1px solid rgba(251,191,36,.4)',
                }}>
                  <span className="pulse-dot" style={{
                    width: 6, height: 6, borderRadius: '50%',
                    background: 'var(--neon-yellow)',
                  }} />
                  MISSION PAUSED
                </div>
              </div>
              {!sent && (
                <button onClick={() => setOpen(false)} className="t-mono"
                  aria-label="Close packet drop and resume mission"
                  style={{
                    background: 'transparent', border: '1px solid transparent', color: 'var(--ink-80)',
                    fontSize: 18, cursor: 'pointer', padding: 4, lineHeight: 1,
                  }}><span aria-hidden="true">✕</span></button>
              )}
            </div>

            {sent ? (
              <div className="t-mono" role="status" aria-live="polite" style={{
                padding: 24, textAlign: 'center',
                color: 'var(--neon-lime)', fontSize: 13, letterSpacing: '0.12em',
                border: '1px solid var(--neon-lime)',
                background: 'rgba(170,255,0,.08)',
              }}>
                <div style={{ fontSize: 14, marginBottom: 12 }}>✓ PACKET TRANSMITTED</div>
                <div style={{
                  display: 'inline-block', padding: '14px 24px',
                  background: 'rgba(251,191,36,.12)',
                  border: '1px solid var(--neon-yellow)',
                  margin: '8px 0 14px',
                }}>
                  <div style={{ fontSize: 9, color: 'var(--ink-60)',
                    letterSpacing: '0.16em', marginBottom: 4 }}>// XP AWARDED</div>
                  <div style={{ fontFamily: 'Orbitron', fontWeight: 800, fontSize: 28,
                    color: 'var(--neon-yellow)', letterSpacing: '0.04em' }}>
                    +{sent.xp}
                  </div>
                </div>
                <div style={{ fontSize: 10, letterSpacing: '0.12em',
                  color: 'var(--ink-80)', display: 'flex', flexDirection: 'column', gap: 3 }}>
                  {sent.breakdown.map((b, i) => (
                    <div key={i} style={{ display: 'flex', justifyContent: 'space-between',
                      maxWidth: 280, margin: '0 auto', width: '100%' }}>
                      <span>{b.label}</span>
                      <span style={{ color: 'var(--neon-yellow)' }}>+{b.xp}</span>
                    </div>
                  ))}
                </div>
                <div style={{ color: 'var(--ink-60)', fontSize: 9, letterSpacing: '0.14em', marginTop: 12 }}>
                  +50 BONUS WHEN INSTRUCTOR RESOLVES
                </div>
              </div>
            ) : (
              <>
                {/* Kind picker — Question vs Suggestion */}
                <div className="t-mono" style={{ fontSize: 9, color: 'var(--ink-60)',
                  letterSpacing: '0.18em', marginBottom: 6 }}>// TYPE</div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14 }}>
                  {PACKET_KINDS.map((k) => {
                    const active = kind === k.id;
                    return (
                      <button key={k.id} onClick={() => setKind(k.id)}
                        role="radio" aria-checked={active}
                        aria-label={`${k.label}, worth ${k.xp} XP. ${k.helper}`}
                        style={{
                          padding: '12px 14px', textAlign: 'left', cursor: 'pointer',
                          background: active ? 'rgba(255,45,149,.15)' : 'rgba(0,0,0,.3)',
                          border: `1px solid ${active ? 'var(--neon-magenta)' : 'rgba(255,45,149,.2)'}`,
                          fontFamily: 'inherit',
                          boxShadow: active ? '0 0 14px rgba(255,45,149,.3)' : 'none',
                          transition: 'all .15s',
                        }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between',
                          alignItems: 'center', marginBottom: 4 }}>
                          <span className="t-mono" style={{ fontSize: 12,
                            color: active ? 'var(--neon-magenta)' : 'var(--ink-80)',
                            letterSpacing: '0.14em', fontWeight: 700 }}>
                            <span aria-hidden="true">{active ? '◉' : '◇'} </span>{k.label}
                          </span>
                          <span className="t-mono" style={{ fontSize: 10,
                            color: 'var(--neon-yellow)', letterSpacing: '0.1em' }}>
                            +{k.xp} XP
                          </span>
                        </div>
                        <div style={{ fontSize: 10, color: 'var(--ink-80)', lineHeight: 1.4 }}>
                          {k.helper}
                        </div>
                      </button>
                    );
                  })}
                </div>

                {/* Tag picker */}
                <div className="t-mono" style={{ fontSize: 9, color: 'var(--ink-60)',
                  letterSpacing: '0.18em', marginBottom: 6 }}>// TAG</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14 }}>
                  {PACKET_TAGS.map((t) => (
                    <button key={t.id} onClick={() => setTag(t.id)}
                      className="t-mono"
                      style={{
                        padding: '5px 10px', fontSize: 10, letterSpacing: '0.12em',
                        background: tag === t.id ? `${t.accent}22` : 'rgba(0,234,255,.04)',
                        color: tag === t.id ? t.accent : 'var(--ink-60)',
                        border: `1px solid ${tag === t.id ? t.accent : 'rgba(0,234,255,.2)'}`,
                        cursor: 'pointer', textTransform: 'uppercase',
                        fontFamily: 'inherit',
                      }}>{t.label}</button>
                  ))}
                </div>

                {/* Textarea */}
                <div className="t-mono" style={{ fontSize: 9, color: 'var(--ink-60)',
                  letterSpacing: '0.18em', marginBottom: 6 }}>// MESSAGE</div>
                <textarea
                  value={text}
                  onChange={(e) => setText(e.target.value.slice(0, 600))}
                  rows={5}
                  autoFocus
                  aria-label="Your question or suggestion. Maximum 600 characters."
                  placeholder="What's the question, op? Be specific — what packet, which week, what doesn't add up..."
                  style={{
                    width: '100%', padding: '10px 12px', fontSize: 13, lineHeight: 1.5,
                    background: 'rgba(0,0,0,.4)', color: 'var(--ink-100)',
                    border: '1px solid rgba(255,45,149,.3)', outline: 'none',
                    fontFamily: 'JetBrains Mono, monospace',
                    resize: 'vertical',
                  }}
                />
                <div className="t-mono" style={{ fontSize: 9, color: 'var(--ink-40)',
                  letterSpacing: '0.12em', marginTop: 4, textAlign: 'right' }}>
                  {text.length} / 600
                </div>

                {/* Anon toggle + context preview */}
                <div style={{ display: 'flex', justifyContent: 'space-between',
                  alignItems: 'center', marginTop: 10, gap: 12 }}>
                  <label className="t-mono" style={{
                    display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer',
                    fontSize: 11, color: anon ? 'var(--neon-magenta)' : 'var(--ink-60)',
                    letterSpacing: '0.12em', textTransform: 'uppercase',
                  }}>
                    <input type="checkbox" checked={anon}
                      onChange={(e) => setAnon(e.target.checked)}
                      style={{ accentColor: '#ff2d95' }} />
                    Send anonymously
                  </label>
                  <div className="t-mono" style={{ fontSize: 9, color: 'var(--ink-40)',
                    letterSpacing: '0.14em' }}>
                    SRC · {phase.toUpperCase()}{run?.role ? ` · ${run.role.name}` : ''}
                  </div>
                </div>

                {/* Submit */}
                <button onClick={submit} disabled={!text.trim()}
                  className="btn btn-primary"
                  style={{
                    marginTop: 16, width: '100%',
                    background: 'linear-gradient(180deg, var(--neon-magenta), #b80055)',
                    opacity: text.trim() ? 1 : 0.4,
                    cursor: text.trim() ? 'pointer' : 'not-allowed',
                  }}>
                  ◢ TRANSMIT
                </button>
              </>
            )}
          </div>
        </div>
      )}
    </>
  );
}

window.DropPacketButton = DropPacketButton;
window.SylPacketStorage = SylPacketStorage;
window.PACKET_TAGS = PACKET_TAGS;
window.PACKET_KINDS = PACKET_KINDS;
window.XP_BONUS_RESOLVED = XP_BONUS_RESOLVED;

// Compat shim — older Instructor Dashboard expects the legacy SylPacketsStorage
// (plural, with loadPackets/savePacket/clearPackets and a flatter field shape).
// This adapter maps to/from the bundle's canonical shape so the dashboard keeps
// working without changes. Both APIs read/write the same localStorage bucket.
function _adaptPacketOut(p) {
  return {
    id: p.id,
    type: p.kind,
    tag: p.tag,
    message: p.text,
    anonymous: !!p.anon,
    srcPhase: p.phase,
    studentName:    p.student ? p.student.name    : null,
    studentEmail:   p.student ? p.student.email   : null,
    studentSection: p.student ? p.student.section : null,
    squadName: null,
    awardedXp: p.xp,
    submittedAt: p.sentAt,
    resolved: !!p.resolved,
  };
}
window.SylPacketsStorage = {
  PACKETS_KEY: DROP_PACKET_KEY,
  loadPackets() { return { packets: SylPacketStorage.load().map(_adaptPacketOut) }; },
  savePacket(compat) {
    SylPacketStorage.save({
      id: compat.id || ('pkt_' + Date.now() + '_' + Math.random().toString(36).slice(2, 7)),
      text: compat.message,
      kind: compat.type,
      tag: compat.tag,
      anon: !!compat.anonymous,
      phase: compat.srcPhase,
      student: compat.studentName ? { name: compat.studentName, email: compat.studentEmail, section: compat.studentSection } : null,
      role: null,
      sentAt: compat.submittedAt || Date.now(),
      resolved: !!compat.resolved,
      xp: compat.awardedXp || 0,
    });
  },
  clearPackets() { SylPacketStorage.clear(); },
};

// Hook for timed screens — returns true when DROP_PACKET modal is open
window.useSylPaused = function useSylPaused() {
  const [paused, setPaused] = React.useState(!!window.__sylPaused);
  React.useEffect(() => {
    function onPause(e) { setPaused(!!e.detail.paused); }
    window.addEventListener('syl-pause', onPause);
    return () => window.removeEventListener('syl-pause', onPause);
  }, []);
  return paused;
};
