// screen-policy.jsx
// PROTOCOL 03 — POLICY FIREWALL
// Scenario cards. Pick the policy-correct action under time pressure.

const { useState: useSt3, useEffect: useEf3, useMemo: useMemo3 } = React;

function PolicyFirewallScreen({ run, difficulty, onComplete }) {
  const cfg = DIFF_CFG[difficulty];
  const scenarios = useMemo3(() => shuffle(POLICY_SCENARIOS), []);

  const [idx, setIdx] = useSt3(0);
  const [score, setScore] = useSt3(0);
  const [time, setTime] = useSt3(cfg.pfTime);
  const [picked, setPicked] = useSt3(null);
  const s = scenarios[idx];
  const done = idx >= scenarios.length;

  useEf3(() => {
    if (done || picked) return;
    setTime(cfg.pfTime);
  }, [idx]);

  useEf3(() => {
    if (done || picked) return;
    if (time <= 0) { resolve(null); return; }
    const t = setTimeout(() => setTime(time - 0.1), 100);
    return () => clearTimeout(t);
  }, [time, picked, done]);

  function resolve(optId) {
    if (picked) return;
    const opt = s.options.find(o => o.id === optId);
    const ok = opt?.correct;
    const gain = ok ? 200 + Math.round(time * 12) : 0;
    setPicked({ optId, ok, gain });
    setScore(score + gain);
    setTimeout(() => {
      if (idx + 1 >= scenarios.length) {
        onComplete({ protocol: 'policy', score: score + gain });
      } else {
        setIdx(idx + 1);
        setPicked(null);
      }
    }, 2400);
  }

  if (done) return null;

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
      <ProtocolHeader
        num="03" name="POLICY FIREWALL"
        progress={`${idx + 1}/${scenarios.length}`}
        score={score} combo={null} accent="var(--neon-yellow)"
      />

      <div style={{ position: 'relative', height: 4, background: 'rgba(251,191,36,.1)' }}>
        <div style={{
          position: 'absolute', left: 0, top: 0, bottom: 0,
          width: `${(time / cfg.pfTime) * 100}%`,
          background: time < 4 ? 'var(--neon-red)' : 'var(--neon-yellow)',
          boxShadow: `0 0 12px ${time < 4 ? 'var(--neon-red)' : 'var(--neon-yellow)'}`,
          transition: 'width .1s linear',
        }} />
      </div>

      <div style={{ flex: 1, padding: '32px 64px', display: 'flex', flexDirection: 'column', gap: 24, minHeight: 0, justifyContent: 'center', maxWidth: 1100, width: '100%', margin: '0 auto' }}>
        <div className="panel" style={{ padding: '28px 36px', position: 'relative' }}>
          <div className="chip chip-yellow" style={{ marginBottom: 16 }}>◇ INCOMING SCENARIO · {s.id.toUpperCase()}</div>
          <div className="t-mono" style={{ fontSize: 22, lineHeight: 1.5, color: 'var(--ink-100)' }}>
            {s.prompt}
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {s.options.map((o, i) => {
            const isPicked = picked?.optId === o.id;
            const reveal = !!picked;
            const isCorrect = o.correct;
            let border = 'rgba(251,191,36,.3)';
            let bg = 'rgba(251,191,36,.04)';
            if (reveal) {
              if (isCorrect) { border = 'var(--neon-lime)'; bg = 'rgba(170,255,0,.08)'; }
              else if (isPicked) { border = 'var(--neon-red)'; bg = 'rgba(255,51,85,.08)'; }
              else { border = 'rgba(0,0,0,.3)'; bg = 'rgba(0,0,0,.2)'; }
            }
            return (
              <button
                key={o.id}
                onClick={() => resolve(o.id)}
                disabled={!!picked}
                style={{
                  appearance: 'none', cursor: picked ? 'default' : 'pointer',
                  textAlign: 'left', padding: '18px 24px',
                  fontFamily: 'inherit', fontSize: 15, lineHeight: 1.5,
                  color: 'var(--ink-100)',
                  background: bg, border: `1px solid ${border}`,
                  display: 'flex', alignItems: 'center', gap: 16,
                  transition: 'all .15s',
                  boxShadow: reveal && isCorrect ? '0 0 24px rgba(170,255,0,.3)' : 'none',
                }}
                onMouseEnter={(e) => { if (!picked) e.currentTarget.style.background = 'rgba(251,191,36,.12)'; }}
                onMouseLeave={(e) => { if (!picked) e.currentTarget.style.background = bg; }}
              >
                <div className="t-display" style={{
                  fontSize: 14, color: reveal ? (isCorrect ? 'var(--neon-lime)' : isPicked ? 'var(--neon-red)' : 'var(--ink-40)') : 'var(--neon-yellow)',
                  letterSpacing: '0.1em', minWidth: 24,
                }}>
                  {o.id.toUpperCase()}
                </div>
                <div style={{ flex: 1 }}>{o.text}</div>
                {reveal && isCorrect && (
                  <div className="t-display" style={{ fontSize: 11, color: 'var(--neon-lime)', letterSpacing: '0.16em' }}>◉ CORRECT</div>
                )}
                {reveal && isPicked && !isCorrect && (
                  <div className="t-display" style={{ fontSize: 11, color: 'var(--neon-red)', letterSpacing: '0.16em' }}>◉ DENIED</div>
                )}
              </button>
            );
          })}
        </div>

        {picked && (
          <div className="panel" style={{
            padding: '14px 20px',
            borderColor: picked.ok ? 'var(--neon-lime)' : 'var(--neon-red)',
            animation: 'packet-in .3s',
          }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 6 }}>
              <span className="t-display" style={{ color: picked.ok ? 'var(--neon-lime)' : 'var(--neon-red)', letterSpacing: '0.12em', fontSize: 13 }}>
                {picked.ok ? `◉ FIREWALL CLEARED · +${picked.gain}` : '◉ POLICY VIOLATION'}
              </span>
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-80)', lineHeight: 1.5 }}>{s.why}</div>
          </div>
        )}
      </div>
    </div>
  );
}

window.PolicyFirewallScreen = PolicyFirewallScreen;
