// ============================================================
//   LayoutDecision — "Decision Mode"
//   The violent move: throw out the list. Throw out the tabs.
//   Throw out the detail panel. One candidate, one screen,
//   three buttons. Keyboard-driven. Brutalist.
//
//   The argument: if the verb is "next action," then the UI
//   should BE the next action. Recruiters shouldn't be managing
//   a list — they should be making a decision.
// ============================================================
const { color: DEC } = window.FF;

function LayoutDecision({ candidates, onExit }) {
  // Queue = anything where a human needs to decide.
  const queue = React.useMemo(() => candidates.filter(c =>
    (c.unread || c.justLanded) || c.stage === 'review'
      || (c.stage === 'engaged' && /awaiting reply|i'm still interested|interested|what shift|2nd shift|22\+|confirmed availability/i.test(c.lastMsg || ''))
  ), [candidates]);

  const [idx, setIdx] = React.useState(0);
  const [log, setLog] = React.useState([]); // {id, action}
  const total = queue.length;
  const remaining = total - idx;
  const c = queue[idx];

  const advance = (action) => {
    if (!c) return;
    setLog(l => [{ id: c.id, name: c.name, action }, ...l].slice(0, 8));
    setIdx(i => Math.min(i + 1, total));
  };
  const undo = () => {
    if (!log.length) return;
    setLog(l => l.slice(1));
    setIdx(i => Math.max(0, i - 1));
  };

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === '1' || e.key === 'r' || e.key === 'R') advance('rejected');
      else if (e.key === '2' || e.key === 's' || e.key === 'S') advance('skipped');
      else if (e.key === '3' || e.key === 'a' || e.key === 'A') advance('advanced');
      else if (e.key === 'z' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); undo(); }
      else if (e.key === 'Escape') onExit?.();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  });

  return (
    <div data-screen-label="Decision Mode" style={{
      position: 'fixed', inset: 0, zIndex: 50,
      background: DEC.shade[880], color: '#fff',
      fontFamily: "'Inter',system-ui,sans-serif",
      display: 'flex', flexDirection: 'column',
    }}>
      <DecisionTopBar idx={idx} total={total} log={log} onExit={onExit} onUndo={undo}/>
      <div style={{
        flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '0 32px', position: 'relative', minHeight: 0,
      }}>
        {!c ? <DoneScreen log={log} onExit={onExit}/> : (
          <React.Fragment>
            <DecisionStack remaining={remaining}/>
            <DecisionCard c={c} idx={idx}/>
          </React.Fragment>
        )}
      </div>
      {c && <DecisionActions onAction={advance}/>}
      <DecisionLog log={log}/>
    </div>
  );
}

/* ---------- Top bar ---------- */
function DecisionTopBar({ idx, total, log, onExit, onUndo }) {
  return (
    <div style={{
      padding: '20px 28px', display: 'flex', alignItems: 'center', gap: 20,
      borderBottom: `1px solid ${DEC.shade[860]}`,
    }}>
      <div style={{
        fontSize: 11, fontWeight: 700, letterSpacing: '.14em',
        textTransform: 'uppercase', color: DEC.copilot[300],
      }}>Decision Mode</div>
      <div style={{ flex: 1, display: 'flex', alignItems: 'baseline', gap: 14 }}>
        <span style={{
          fontFamily: 'ui-monospace,SFMono-Regular,monospace', fontSize: 22,
          fontWeight: 700, color: '#fff', fontVariantNumeric: 'tabular-nums', letterSpacing: '-.02em',
        }}>
          {String(Math.min(idx + 1, total)).padStart(2, '0')}<span style={{ opacity: .35 }}> / {String(total).padStart(2, '0')}</span>
        </span>
        <span style={{ fontSize: 12, color: 'rgba(255,255,255,.55)' }}>
          Ready for you · Machine Operator I
        </span>
      </div>
      <ProgressDots idx={idx} total={total} log={log}/>
      <button onClick={onUndo} disabled={!log.length} style={{
        padding: '6px 10px', background: 'transparent',
        border: `1px solid ${DEC.shade[820]}`, borderRadius: 6,
        color: log.length ? '#fff' : 'rgba(255,255,255,.3)',
        fontSize: 11, fontWeight: 600, cursor: log.length ? 'pointer' : 'not-allowed',
        letterSpacing: '.04em', textTransform: 'uppercase',
      }}>↶ Undo</button>
      <button onClick={onExit} style={{
        padding: '6px 12px', background: 'transparent',
        border: `1px solid ${DEC.shade[820]}`, borderRadius: 6, color: '#fff',
        fontSize: 11, fontWeight: 600, cursor: 'pointer',
        letterSpacing: '.04em', textTransform: 'uppercase',
      }}>Esc · Exit</button>
    </div>
  );
}

function ProgressDots({ idx, total, log }) {
  // Tiny strip of dots, colored by decision so far.
  const COLOR = { rejected: DEC.critical[500], skipped: '#fff', advanced: DEC.primary[500] };
  return (
    <div style={{ display: 'flex', gap: 3, alignItems: 'center' }}>
      {Array.from({ length: total }).map((_, i) => {
        const decision = log.find(l => l.id && i < idx && i === idx - 1 - log.findIndex(x => x.id === l.id)) ? null : null;
        // simpler: walk log in reverse to map back to dots
        const decisionForDot = i < idx ? (log[idx - 1 - i]?.action) : null;
        const isNext = i === idx;
        return (
          <span key={i} style={{
            width: isNext ? 18 : 8, height: 4, borderRadius: 2,
            background: decisionForDot ? COLOR[decisionForDot] : isNext ? '#fff' : 'rgba(255,255,255,.18)',
            transition: 'width .15s ease',
          }}/>
        );
      })}
    </div>
  );
}

/* ---------- The card ---------- */
function DecisionCard({ c, idx }) {
  const lastMsg = c.lastMsg || `${c.role} at ${c.company}`;
  const isQuote = lastMsg.startsWith('"') || lastMsg.startsWith('\u201C');
  return (
    <div key={c.id} style={{
      width: 'min(720px, 100%)', background: '#fff', color: DEC.shade[880],
      borderRadius: 16, padding: '40px 44px 36px',
      boxShadow: '0 30px 60px rgba(0,0,0,.45), 0 0 0 1px rgba(255,255,255,.05)',
      position: 'relative', zIndex: 2,
      animation: 'dm-card-in .3s cubic-bezier(.2,.8,.2,1)',
    }}>
      <style>{`
        @keyframes dm-card-in {
          from { transform: translateY(8px) scale(.98); opacity: 0; }
          to   { transform: translateY(0) scale(1); opacity: 1; }
        }
      `}</style>

      {/* Eyebrow — the match */}
      <div style={{
        fontSize: 11, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase',
        color: DEC.shade[700], marginBottom: 14,
      }}>
        Match · for Machine Operator I · Greensboro, NC
      </div>

      {/* Name — huge */}
      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 16, flexWrap: 'wrap', marginBottom: 14,
      }}>
        <h1 style={{
          margin: 0, fontFamily: "'Museo','Museo Sans',Georgia,serif", fontWeight: 900,
          fontSize: 56, letterSpacing: '-.02em', lineHeight: 1, color: DEC.shade[880],
        }}>{c.name}</h1>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 4, padding: '4px 10px 4px 8px',
          background: DEC.primary[500], color: '#fff',
          fontSize: 18, fontWeight: 800, borderRadius: 6,
        }}>★ {c.score}</span>
      </div>

      {/* Current role */}
      <div style={{ fontSize: 15, color: DEC.shade[820], marginBottom: 22 }}>
        Currently {c.role} at <span style={{ fontWeight: 700, color: DEC.shade[880] }}>{c.company}</span>
      </div>

      <div style={{ height: 1, background: DEC.tint[80], marginBottom: 22 }}/>

      {/* Why this came to you */}
      <div style={{ marginBottom: 22 }}>
        <div style={{
          fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase',
          color: DEC.copilot[700], marginBottom: 8,
        }}>{c.source === 'applied' ? 'They applied' : 'AI sourced them'} · {c.time}</div>
        <div style={{ fontSize: 22, lineHeight: 1.35, color: DEC.shade[880], fontWeight: isQuote ? 500 : 400, fontStyle: isQuote ? 'italic' : 'normal' }}>
          {isQuote ? lastMsg : `"${lastMsg.replace(/^["\u201C]|["\u201D]$/g, '')}"`}
        </div>
      </div>

      {/* Memory layer */}
      <DecisionMemory id={c.id}/>
    </div>
  );
}

function DecisionMemory({ id }) {
  const m = (window.__MEMORY_FOR_DECISION__ || {})[id] || inferMemory(id);
  if (!m) return null;
  const isDNH = m.kind === 'dnh';
  return (
    <div style={{
      padding: '12px 14px', background: isDNH ? DEC.critical[50] : DEC.tint[40],
      border: `1px solid ${isDNH ? DEC.critical[300] : DEC.tint[80]}`,
      borderRadius: 8, display: 'flex', alignItems: 'center', gap: 10,
    }}>
      <span style={{
        fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase',
        color: isDNH ? DEC.critical[700] : DEC.shade[700],
      }}>Memory</span>
      <span style={{
        fontSize: 13, fontWeight: isDNH ? 700 : 500,
        color: isDNH ? DEC.critical[700] : DEC.shade[820],
      }}>{m.text}</span>
    </div>
  );
}
function inferMemory(id) {
  const M = {
    c18:{ kind:'fresh',   text:'First conversation' },
    c19:{ kind:'repeat',  text:'Also applied to CNC Setup' },
    c23:{ kind:'repeat',  text:'2nd application, this job' },
    c22:{ kind:'saidno',  text:'Said no in March — shift conflict' },
    c20:{ kind:'former',  text:'Former employee · 2021' },
    c27:{ kind:'former',  text:'Interviewed Feb · QA role' },
    c10:{ kind:'repeat',  text:'Applied 4× in 90 days' },
    c11:{ kind:'former',  text:'Former employee · 2019–2022' },
    c16:{ kind:'dnh',     text:'Do not hire' },
  };
  return M[id];
}

/* ---------- Stack visual — the queue behind the current card ---------- */
function DecisionStack({ remaining }) {
  // Three card outlines visible behind the main card.
  if (remaining <= 1) return null;
  return (
    <React.Fragment>
      {[1, 2, 3].slice(0, Math.min(3, remaining - 1)).map(i => (
        <div key={i} style={{
          position: 'absolute',
          width: 'min(720px, 100%)', height: '60%',
          background: '#fff', borderRadius: 16,
          transform: `translateY(${10 + i * 8}px) scale(${1 - i * 0.018})`,
          opacity: 0.12 - i * 0.025,
          zIndex: 1,
          boxShadow: '0 30px 60px rgba(0,0,0,.3)',
        }}/>
      ))}
    </React.Fragment>
  );
}

/* ---------- Three big buttons ---------- */
function DecisionActions({ onAction }) {
  const btn = (label, kbd, bg, fg, onClick) => (
    <button onClick={onClick} style={{
      flex: 1, padding: '18px 20px', background: bg, color: fg,
      border: 0, borderRadius: 10, cursor: 'pointer',
      fontSize: 16, fontWeight: 700, letterSpacing: '.01em',
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12,
      transition: 'transform .08s ease',
    }} onMouseDown={e => e.currentTarget.style.transform = 'scale(.985)'}
       onMouseUp={e => e.currentTarget.style.transform = ''}
       onMouseLeave={e => e.currentTarget.style.transform = ''}>
      <span style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: 22, height: 22, borderRadius: 4,
        background: 'rgba(0,0,0,.15)', fontSize: 11, fontFamily: 'ui-monospace,monospace',
        fontWeight: 700, letterSpacing: 0,
      }}>{kbd}</span>
      {label}
    </button>
  );
  return (
    <div style={{
      padding: '14px 28px 28px', display: 'flex', gap: 12,
      borderTop: `1px solid ${DEC.shade[860]}`,
    }}>
      {btn('Reject',  '1', DEC.critical[500], '#fff', () => onAction('rejected'))}
      {btn('Skip',    '2', '#fff',            DEC.shade[880], () => onAction('skipped'))}
      {btn('Advance', '3', DEC.primary[500],  '#fff', () => onAction('advanced'))}
    </div>
  );
}

/* ---------- Running decision log ---------- */
function DecisionLog({ log }) {
  const ICON = { rejected: '✗', skipped: '↷', advanced: '✓' };
  const COLOR = {
    rejected: DEC.critical[500], skipped: 'rgba(255,255,255,.5)', advanced: DEC.primary[500],
  };
  return (
    <div style={{
      position: 'absolute', left: 28, bottom: 110, width: 220,
      pointerEvents: 'none', opacity: log.length ? 1 : 0, transition: 'opacity .2s ease',
    }}>
      <div style={{
        fontSize: 10, fontWeight: 700, letterSpacing: '.14em',
        textTransform: 'uppercase', color: 'rgba(255,255,255,.45)', marginBottom: 8,
      }}>Just decided</div>
      {log.slice(0, 5).map((l, i) => (
        <div key={i} style={{
          fontSize: 12, color: 'rgba(255,255,255,.7)',
          padding: '3px 0', display: 'flex', alignItems: 'center', gap: 8,
          opacity: 1 - i * 0.18,
        }}>
          <span style={{ color: COLOR[l.action], fontWeight: 700, width: 14, textAlign: 'center' }}>{ICON[l.action]}</span>
          <span style={{ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{l.name}</span>
        </div>
      ))}
    </div>
  );
}

/* ---------- End screen ---------- */
function DoneScreen({ log, onExit }) {
  const c = { advanced: 0, rejected: 0, skipped: 0 };
  log.forEach(l => { c[l.action] = (c[l.action] || 0) + 1; });
  return (
    <div style={{ textAlign: 'center' }}>
      <div style={{
        fontFamily: "'Museo','Museo Sans',Georgia,serif", fontWeight: 900,
        fontSize: 84, color: '#fff', letterSpacing: '-.03em', lineHeight: 1, marginBottom: 16,
      }}>Cleared.</div>
      <div style={{ fontSize: 16, color: 'rgba(255,255,255,.6)', marginBottom: 28 }}>
        {log.length} decisions made — {c.advanced} advanced, {c.rejected} rejected, {c.skipped} skipped.
      </div>
      <button onClick={onExit} style={{
        padding: '12px 22px', background: '#fff', color: DEC.shade[880],
        border: 0, borderRadius: 8, fontSize: 14, fontWeight: 700, cursor: 'pointer',
      }}>Back to workspace</button>
    </div>
  );
}

Object.assign(window, { LayoutDecision });
