// a11y.jsx — Shared accessibility helpers for Phase 2 fixes.
// - Live region announcer (window.sylAnnounce)
// - Global pause hook (extends the Drop Packet pause to a manual button)
// - Result icons (dual-encoded correct/incorrect: glyph + text + color)

(function () {
  // ── Live-region announcer ─────────────────────────────────────────
  // Mounted once at app root. Other code calls window.sylAnnounce("text")
  // to push a message into a polite or assertive aria-live region.

  function A11yAnnouncer() {
    const [polite, setPolite] = React.useState('');
    const [assertive, setAssertive] = React.useState('');

    React.useEffect(() => {
      function onMsg(e) {
        const { text, urgent } = e.detail || {};
        if (!text) return;
        // Toggle to force re-announce identical strings
        if (urgent) {
          setAssertive('');
          setTimeout(() => setAssertive(text), 30);
        } else {
          setPolite('');
          setTimeout(() => setPolite(text), 30);
        }
      }
      window.addEventListener('syl-announce', onMsg);
      window.sylAnnounce = (text, urgent = false) => {
        window.dispatchEvent(new CustomEvent('syl-announce', { detail: { text, urgent } }));
      };
      return () => window.removeEventListener('syl-announce', onMsg);
    }, []);

    return (
      <>
        <div className="sr-only" role="status" aria-live="polite" aria-atomic="true">
          {polite}
        </div>
        <div className="sr-only" role="alert" aria-live="assertive" aria-atomic="true">
          {assertive}
        </div>
      </>
    );
  }

  // ── Global pause button (HUD) ─────────────────────────────────────
  // Distinct from Drop Packet pause: a deliberate "I need a break" toggle.
  // Uses the same pause channel so all timers freeze.

  function PauseButton({ phase }) {
    const [paused, setPaused] = React.useState(false);

    // Don't show on screens with no timers / pre-game screens
    const showOn = ['datastream', 'triage', 'hexsweep', 'heist', 'board'];
    const visible = showOn.includes(phase);

    React.useEffect(() => {
      // Sync local state with global pause channel (Drop Packet may also pause)
      function onPause(e) {
        // Only react if we're not the source — avoid loops
        if (e.detail._fromPauseBtn) return;
        // Drop Packet open should not flip this button's state since it auto-resumes
      }
      window.addEventListener('syl-pause', onPause);
      return () => window.removeEventListener('syl-pause', onPause);
    }, []);

    function toggle() {
      const next = !paused;
      setPaused(next);
      window.__sylPaused = next;
      window.dispatchEvent(new CustomEvent('syl-pause', {
        detail: { paused: next, _fromPauseBtn: true }
      }));
      window.sylAnnounce && window.sylAnnounce(next ? 'Mission paused' : 'Mission resumed');
    }

    // Keyboard shortcut: P
    React.useEffect(() => {
      function onKey(e) {
        if (e.key === 'p' || e.key === 'P') {
          // Ignore when typing in inputs
          const t = e.target;
          if (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable) return;
          if (!showOn.includes(phase)) return;
          e.preventDefault();
          toggle();
        }
      }
      window.addEventListener('keydown', onKey);
      return () => window.removeEventListener('keydown', onKey);
      // eslint-disable-next-line
    }, [paused, phase]);

    if (!visible) return null;

    return (
      <>
        <button onClick={toggle}
          aria-label={paused ? 'Resume mission timers (shortcut: P)' : 'Pause mission timers (shortcut: P)'}
          aria-pressed={paused}
          className="t-mono"
          style={{
            padding: '6px 12px', fontSize: 10, letterSpacing: '0.16em',
            background: paused ? 'rgba(251,191,36,.18)' : 'rgba(0,234,255,.06)',
            color: paused ? 'var(--neon-yellow)' : 'var(--ink-80)',
            border: `1px solid ${paused ? 'var(--neon-yellow)' : 'rgba(0,234,255,.3)'}`,
            cursor: 'pointer', textTransform: 'uppercase', fontFamily: 'inherit',
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
          <span aria-hidden="true">{paused ? '▶' : '❚❚'}</span>
          {paused ? 'RESUME' : 'PAUSE'}
        </button>

        {/* Full-screen overlay when paused via this button */}
        {paused && (
          <div role="dialog" aria-modal="true" aria-labelledby="pause-title"
            style={{
              position: 'fixed', inset: 0, zIndex: 85,
              background: 'rgba(2,4,16,.85)', backdropFilter: 'blur(8px)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexDirection: 'column', gap: 20, padding: 24,
            }}>
            <div className="chip" style={{ borderColor: 'var(--neon-yellow)',
              color: 'var(--neon-yellow)' }}>◢ MISSION PAUSED</div>
            <h2 id="pause-title" style={{
              fontFamily: 'Orbitron', fontWeight: 800, fontSize: 36,
              letterSpacing: '0.04em', color: 'var(--ink-100)', margin: 0,
              textAlign: 'center',
            }}>
              TIMERS FROZEN
            </h2>
            <p style={{ fontSize: 13, color: 'var(--ink-80)',
              maxWidth: 420, textAlign: 'center', lineHeight: 1.5, margin: 0 }}>
              Take your time. All clocks, packets, and queues are held until you resume.
            </p>
            <button onClick={toggle} className="btn btn-primary"
              style={{ marginTop: 8 }} autoFocus>
              <span aria-hidden="true">▶</span> RESUME MISSION
            </button>
            <p className="t-mono" style={{ fontSize: 10, letterSpacing: '0.18em',
              color: 'var(--ink-60)', margin: 0 }}>
              press P to toggle
            </p>
          </div>
        )}
      </>
    );
  }

  // ── Result icon — dual-encoded correct/incorrect ──────────────────
  // Use everywhere correct/incorrect is communicated. Color alone fails 1.4.1.

  function ResultIcon({ correct, size = 14 }) {
    return (
      <span aria-hidden="true" style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: size, height: size, borderRadius: '50%',
        background: correct ? 'var(--neon-lime)' : 'var(--neon-red)',
        color: '#000', fontSize: size * 0.7, fontWeight: 900,
        lineHeight: 1, fontFamily: 'system-ui, sans-serif',
      }}>
        {correct ? '✓' : '✕'}
      </span>
    );
  }

  window.A11yAnnouncer = A11yAnnouncer;
  window.PauseButton = PauseButton;
  window.ResultIcon = ResultIcon;
})();
