// screen-deadline-heist.jsx
// PROTOCOL 02 — DEADLINE HEIST
// Calendar grid with WK slots. Click a node, click a slot. Lock it in.

const { useState: useSt2, useEffect: useEf2, useMemo: useMemo2 } = React;

function DeadlineHeistScreen({ run, difficulty, onComplete }) {
  const cfg = DIFF_CFG[difficulty];
  const allNodes = useMemo2(() => shuffle(DEADLINE_NODES).slice(0, cfg.dlNodes), []);
  const targetWeeks = useMemo2(() => {
    const used = new Set(allNodes.map(n => n.week));
    return WEEK_SLOTS.filter(w => used.has(w.id));
  }, [allNodes]);

  const [pool, setPool] = useSt2(allNodes);
  const [placed, setPlaced] = useSt2({}); // weekId -> { node, correct }
  const [picked, setPicked] = useSt2(null);
  const [score, setScore] = useSt2(0);
  const [time, setTime] = useSt2(cfg.dlTime);
  const [done, setDone] = useSt2(false);
  const [floats, setFloats] = useSt2([]);

  useEf2(() => {
    if (done) return;
    if (time <= 0 || pool.length === 0) {
      setDone(true);
      setTimeout(() => onComplete({ protocol: 'heist', score }), 1500);
      return;
    }
    const t = setTimeout(() => setTime(time - 0.1), 100);
    return () => clearTimeout(t);
  }, [time, pool.length, done]);

  function placeIntoSlot(weekId) {
    if (!picked || placed[weekId]) return;
    const correct = picked.week === weekId;
    setPlaced({ ...placed, [weekId]: { node: picked, correct } });
    setPool(pool.filter(n => n.id !== picked.id));
    setPicked(null);
    const gain = correct ? 250 : -100;
    setScore((s) => Math.max(0, s + gain));
    const fId = Math.random();
    setFloats((f) => [...f, { id: fId, gain, weekId }]);
    setTimeout(() => setFloats((f) => f.filter(x => x.id !== fId)), 1000);
  }

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
      <ProtocolHeader
        num="02" name="DEADLINE HEIST"
        progress={`${Object.keys(placed).length}/${allNodes.length}`}
        score={score} combo={null} accent="var(--neon-magenta)"
      />

      {/* Timer */}
      <div style={{ position: 'relative', height: 4, background: 'rgba(255,45,149,.1)' }}>
        <div style={{
          position: 'absolute', left: 0, top: 0, bottom: 0,
          width: `${(time / cfg.dlTime) * 100}%`,
          background: time < 8 ? 'var(--neon-red)' : 'var(--neon-magenta)',
          boxShadow: `0 0 12px ${time < 8 ? 'var(--neon-red)' : 'var(--neon-magenta)'}`,
          transition: 'width .1s linear',
        }} />
      </div>

      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '320px 1fr', gap: 24, padding: '24px 48px 32px', minHeight: 0 }}>
        {/* Node pool */}
        <div className="panel" style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 10, minHeight: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div className="chip chip-magenta">◇ NODE BUFFER</div>
            <div style={{ fontSize: 10, color: 'var(--ink-60)' }}>
              {pool.length} REMAINING · ⏱{time.toFixed(1)}s
            </div>
          </div>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8, overflowY: 'auto', paddingRight: 4 }}>
            {pool.map((node) => {
              const active = picked?.id === node.id;
              return (
                <button
                  key={node.id}
                  onClick={() => setPicked(active ? null : node)}
                  style={{
                    appearance: 'none', textAlign: 'left', cursor: 'pointer',
                    padding: '10px 12px', fontFamily: 'inherit',
                    background: active ? 'rgba(255,45,149,.18)' : 'rgba(255,45,149,.06)',
                    border: `1px solid ${active ? 'var(--neon-magenta)' : 'rgba(255,45,149,.3)'}`,
                    color: 'var(--ink-100)', fontSize: 12,
                    boxShadow: active ? '0 0 16px rgba(255,45,149,.4)' : 'none',
                    transition: 'all .15s',
                    clipPath: 'polygon(8px 0, 100% 0, calc(100% - 8px) 100%, 0 100%)',
                  }}
                >
                  <div style={{ fontSize: 9, color: 'var(--neon-magenta)', letterSpacing: '0.14em', marginBottom: 4 }}>
                    ◇ DUE {node.date.toUpperCase()}
                  </div>
                  <div style={{ lineHeight: 1.35 }}>{node.label}</div>
                </button>
              );
            })}
            {pool.length === 0 && (
              <div style={{ color: 'var(--neon-lime)', fontSize: 12, padding: 20, textAlign: 'center' }}>
                ◉ BUFFER FLUSHED
              </div>
            )}
          </div>
          <div style={{ fontSize: 10, color: 'var(--ink-60)', lineHeight: 1.5, paddingTop: 8, borderTop: '1px solid rgba(255,45,149,.15)' }}>
            ◇ Select a node, then drop into the matching week. <b style={{ color: 'var(--neon-lime)' }}>+250</b> on hit, <b style={{ color: 'var(--neon-red)' }}>−100</b> on miss.
          </div>
        </div>

        {/* Calendar grid */}
        <div className="panel panel-magenta" style={{ padding: 24, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <div className="chip chip-magenta">◇ TIMELINE GRID // SPRING 2026</div>
            <div style={{ fontSize: 10, color: 'var(--ink-60)' }}>SECTOR 03/12</div>
          </div>
          <div style={{ flex: 1, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, minHeight: 0 }}>
            {targetWeeks.map((wk) => {
              const slot = placed[wk.id];
              const isFloat = floats.find(f => f.weekId === wk.id);
              return (
                <button
                  key={wk.id}
                  onClick={() => placeIntoSlot(wk.id)}
                  disabled={!!slot}
                  style={{
                    appearance: 'none', textAlign: 'left', position: 'relative',
                    padding: '14px 16px', fontFamily: 'inherit',
                    background: slot
                      ? (slot.correct ? 'rgba(170,255,0,.08)' : 'rgba(255,51,85,.08)')
                      : 'rgba(0,0,0,.3)',
                    border: `1px solid ${slot ? (slot.correct ? 'var(--neon-lime)' : 'var(--neon-red)') : (picked ? 'var(--neon-magenta)' : 'rgba(255,45,149,.3)')}`,
                    color: 'var(--ink-100)', cursor: slot ? 'default' : (picked ? 'pointer' : 'default'),
                    transition: 'all .2s', minHeight: 110,
                    boxShadow: !slot && picked ? '0 0 16px rgba(255,45,149,.3)' : 'none',
                  }}
                >
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 6 }}>
                    <div className="t-display" style={{ fontSize: 16, color: slot ? (slot.correct ? 'var(--neon-lime)' : 'var(--neon-red)') : 'var(--neon-magenta)', letterSpacing: '0.06em' }}>
                      {wk.label}
                    </div>
                    <div style={{ fontSize: 10, color: 'var(--ink-60)', letterSpacing: '0.1em' }}>{wk.range}</div>
                  </div>
                  {slot ? (
                    <div>
                      <div style={{ fontSize: 12, color: 'var(--ink-100)', lineHeight: 1.4, marginBottom: 4 }}>{slot.node.label}</div>
                      <div style={{ fontSize: 10, color: slot.correct ? 'var(--neon-lime)' : 'var(--neon-red)', letterSpacing: '0.14em' }}>
                        {slot.correct ? '◉ LOCKED' : '◉ MISALIGNED'}
                      </div>
                    </div>
                  ) : (
                    <div style={{ fontSize: 11, color: 'var(--ink-40)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
                      ░ EMPTY SLOT ░
                    </div>
                  )}
                  {isFloat && (
                    <div style={{
                      position: 'absolute', top: 8, right: 12,
                      fontFamily: 'Orbitron', fontWeight: 800, fontSize: 22,
                      color: isFloat.gain > 0 ? 'var(--neon-lime)' : 'var(--neon-red)',
                      animation: 'float-up 1s ease-out forwards', pointerEvents: 'none',
                    }}>
                      {isFloat.gain > 0 ? '+' : ''}{isFloat.gain}
                    </div>
                  )}
                </button>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

window.DeadlineHeistScreen = DeadlineHeistScreen;
