// ============================================================
//   LayoutSpine — "Stage Spine / In Play" 🔥  (developed)
//   The funnel runs as a horizontal spine across the top; the
//   live "in play" middle IS the whole screen; pre-engaged and
//   review+ collapse to dim slivers you can peek into.
//
//   Developed into a real surface: no detail panel — clicking a
//   card expands it in place with the why-here receipt, memory,
//   and real actions. Edge segments open a peek drawer.
// ============================================================
const { color: SPC, font: SPF } = window.FF;

function sp_owner(c) {
  if (c.unread || c.justLanded) return { label:'Ready for you', tint: SPC.primary[50], fg: SPC.primary[800], dot: SPC.primary[500], next:'Review reply', primary:true };
  const m = (c.lastMsg || '').toLowerCase();
  if (/awaiting|reminder|screening questions/.test(m)) return { label:'Waiting', tint: SPC.caution[50], fg: SPC.caution[700], dot: SPC.caution[500], next:'Nudge or move on', primary:false };
  if (/scheduled|copilot|confirm/.test(m)) return { label:'In progress', tint: SPC.inform[50], fg: SPC.inform[700], dot: SPC.inform[500], next:'Confirm interview', primary:true };
  return { label:'In progress', tint: SPC.inform[50], fg: SPC.inform[700], dot: SPC.inform[500], next:'Continue', primary:false };
}

const SP_MEMORY = {
  c19:'Also applied to CNC Setup at Honda', c20:'Former employee · 2021',
  c22:'Said no in March — shift conflict', c23:'2nd application, this job',
  c27:'Interviewed Feb · QA role',
};

function sp_why(c) {
  const h = c.id.split('').reduce((a, ch) => a + ch.charCodeAt(0), 0);
  const attempts = (h % 3) + 1;
  if (c.source === 'applied') return `Applied on their own, cleared screening, scored ${c.score}.`;
  return `AI-sourced, contacted ${attempts}×, replied — interested. Hasn't formally applied.`;
}

function LayoutSpine({ candidates, onExit }) {
  const [sel, setSel] = React.useState(null);
  const [peek, setPeek] = React.useState(null); // 'pre' | 'post' | null

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') { peek ? setPeek(null) : onExit?.(); } };
    window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey);
  });

  const pre = candidates.filter(c => c.stage === 'sourcing' || c.stage === 'new');
  const inPlay = candidates.filter(c => c.stage === 'engaged');
  const postCount = 18;

  return (
    <div data-screen-label="Stage Spine" style={{ position:'fixed', inset:0, zIndex:50, background: SPC.tint[20], fontFamily: SPF.sans, color: SPC.shade[880], display:'flex', flexDirection:'column' }}>
      <div style={{ padding:'14px 24px', display:'flex', alignItems:'center', gap:12, borderBottom:`1px solid ${SPC.tint[80]}`, background:'#fff' }}>
        <span style={{ fontSize:15, fontWeight:800, letterSpacing:'-.01em' }}>In Play</span>
        <span style={{ fontSize:12, color: SPC.shade[700] }}>Machine Operator I · O'Neal Manufacturing</span>
        <div style={{ flex:1 }}/>
        <span style={{ fontSize:10, fontWeight:700, letterSpacing:'.14em', textTransform:'uppercase', color: SPC.shade[600], padding:'3px 9px', border:`1px solid ${SPC.tint[100]}`, borderRadius:9999 }}>Stage Spine</span>
        <button onClick={onExit} style={{ padding:'6px 12px', background:'transparent', border:`1px solid ${SPC.tint[100]}`, borderRadius:6, color: SPC.shade[820], fontSize:11, fontWeight:600, cursor:'pointer', letterSpacing:'.04em', textTransform:'uppercase' }}>Esc · Exit</button>
      </div>

      <div style={{ flex:1, display:'flex', minHeight:0 }}>
        <div style={{ width:208, flex:'none', background:'#fff', borderRight:`1px solid ${SPC.tint[80]}`, padding:'14px 12px', overflow:'auto' }}>
          <div style={{ fontSize:10, fontWeight:700, letterSpacing:'.1em', textTransform:'uppercase', color: SPC.shade[600], padding:'0 6px 8px' }}>Saved jobs</div>
          {[{ t:'Machine Operator I', n:12, on:true }, { t:'Maintenance Tech II', n:6, on:false }].map(j => (
            <div key={j.t} style={{ padding:'10px 10px', borderRadius:8, marginBottom:4, background: j.on ? SPC.highlight[50] : 'transparent', cursor:'pointer' }}>
              <div style={{ fontSize:13, fontWeight: j.on ? 700 : 500, color: SPC.shade[880], lineHeight:1.25 }}>{j.t}</div>
              <div style={{ fontSize:11, color: SPC.shade[700], marginTop:2 }}>{j.n} in play</div>
            </div>
          ))}
        </div>

        <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0, position:'relative' }}>
          <StageSpineBar preN={pre.length} inN={inPlay.length} postN={postCount} onPeek={setPeek}/>
          <div style={{ flex:1, overflow:'auto', padding:'18px 22px 40px' }}>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(320px,1fr))', gap:12, alignItems:'start' }}>
              {inPlay.map(c => <InPlayCard key={c.id} c={c} expanded={c.id === sel} onToggle={() => setSel(sel === c.id ? null : c.id)}/>)}
            </div>
          </div>

          {peek && <PeekDrawer kind={peek} pre={pre} onClose={() => setPeek(null)}/>}
        </div>
      </div>
    </div>
  );
}

function StageSpineBar({ preN, inN, postN, onPeek }) {
  const dim = (label, n, sub, onClick) => (
    <button onClick={onClick} style={{ flex:'0 0 auto', minWidth:90, padding:'12px 14px', opacity:.55, borderRight:`1px solid ${SPC.tint[80]}`, background:'transparent', textAlign:'left', cursor:'pointer' }}>
      <div style={{ fontSize:10, fontWeight:700, letterSpacing:'.06em', textTransform:'uppercase', color: SPC.shade[700] }}>{label}</div>
      <div style={{ fontSize:16, fontWeight:800, color: SPC.shade[820], fontVariantNumeric:'tabular-nums' }}>{n}</div>
      <div style={{ fontSize:10, color: SPC.shade[600] }}>{sub} ›</div>
    </button>
  );
  return (
    <div style={{ display:'flex', alignItems:'stretch', background:'#fff', borderBottom:`1px solid ${SPC.tint[80]}` }}>
      {dim('Sourcing', 9, 'AI working', () => onPeek('pre'))}
      {dim('New', Math.max(0, preN - 9), 'peek', () => onPeek('pre'))}
      <div style={{ flex:1, padding:'12px 18px', background: SPC.primary[50] + '88', borderLeft:`2px solid ${SPC.primary[500]}`, borderRight:`2px solid ${SPC.primary[500]}` }}>
        <div style={{ fontSize:10.5, fontWeight:800, letterSpacing:'.08em', textTransform:'uppercase', color: SPC.primary[800] }}>● In play — engaged</div>
        <div style={{ fontSize:24, fontWeight:900, color: SPC.shade[880], letterSpacing:'-.02em', lineHeight:1.1 }}>{inN} candidates</div>
        <div style={{ fontSize:11.5, color: SPC.shade[700] }}>Live conversations. This is everything below.</div>
      </div>
      {dim('Review +', postN, 'tracked', () => onPeek('post'))}
    </div>
  );
}

function InPlayCard({ c, expanded, onToggle }) {
  const O = sp_owner(c);
  const quote = c.lastMsg && (c.lastMsg.startsWith('"') || c.lastMsg.startsWith('\u201C'));
  const mem = SP_MEMORY[c.id];
  return (
    <div onClick={onToggle} style={{
      background:'#fff', borderRadius:12, padding:'14px 16px', cursor:'pointer',
      border:`1px solid ${expanded ? SPC.highlight[500] : SPC.tint[80]}`,
      boxShadow: expanded ? '0 6px 18px rgba(13,10,44,.10)' : 'none',
    }}>
      <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:7 }}>
        <h3 style={{ margin:0, fontSize:15, fontWeight:700, color: SPC.shade[880], whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{c.name}</h3>
        <span style={{ display:'inline-flex', alignItems:'center', gap:3, padding:'1px 6px 1px 4px', background: SPC.primary[500], color:'#fff', fontSize:11, fontWeight:700, borderRadius:4, flex:'none' }}><span style={{ fontSize:9 }}>★</span>{c.score}</span>
        <div style={{ flex:1 }}/>
        <span style={{ display:'inline-flex', alignItems:'center', gap:5, padding:'2px 8px 2px 7px', borderRadius:9999, fontSize:11, fontWeight:700, background: O.tint, color: O.fg, flex:'none' }}>
          <span style={{ width:6, height:6, borderRadius:'50%', background: O.dot }}/>{O.label}
        </span>
      </div>
      <div style={{ fontSize:13, color: SPC.shade[820], marginBottom:8, lineHeight:1.45, fontStyle: quote ? 'italic' : 'normal' }}>{c.lastMsg || c.role}</div>

      {!expanded && (
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <span style={{ fontSize:11.5, color: SPC.shade[700] }}>{c.role} · {c.loc.split(',')[0]}</span>
          {mem && <span style={{ fontSize:10.5, color: SPC.highlight[700], background: SPC.highlight[50], padding:'1px 7px', borderRadius:9999, flex:'none' }}>◇ {mem.split(' ').slice(0,2).join(' ')}…</span>}
          <div style={{ flex:1 }}/>
          <span style={{ fontSize:11, color: SPC.shade[600] }}>{expanded ? '▲' : '▾'}</span>
        </div>
      )}

      {expanded && (
        <div style={{ marginTop:10, paddingTop:12, borderTop:`1px solid ${SPC.tint[80]}` }} onClick={e => e.stopPropagation()}>
          <div style={{ fontSize:10.5, fontWeight:700, letterSpacing:'.08em', textTransform:'uppercase', color: SPC.shade[600], marginBottom:5 }}>Why they're here</div>
          <div style={{ fontSize:13, color: SPC.shade[820], lineHeight:1.5, marginBottom:10 }}>{sp_why(c)}</div>
          {mem && (
            <div style={{ marginBottom:12 }}>
              <span style={{ fontSize:11.5, color: SPC.highlight[700], background: SPC.highlight[50], padding:'3px 9px', borderRadius:9999, fontWeight:600 }}>◇ {mem}</span>
            </div>
          )}
          <div style={{ fontSize:12.5, color: SPC.shade[700], marginBottom:12 }}>{c.role} · {c.loc} · ✉ 336-276-4475</div>
          <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
            <button style={{ padding:'8px 14px', background: SPC.shade[880], color:'#fff', border:0, borderRadius:7, fontSize:13, fontWeight:600, cursor:'pointer' }}>📅 Schedule interview</button>
            <button style={{ padding:'8px 14px', background:'#fff', color: SPC.shade[820], border:`1px solid ${SPC.tint[100]}`, borderRadius:7, fontSize:13, fontWeight:600, cursor:'pointer' }}>💬 Message</button>
            <button style={{ padding:'8px 14px', background:'#fff', color: SPC.shade[820], border:`1px solid ${SPC.tint[100]}`, borderRadius:7, fontSize:13, fontWeight:600, cursor:'pointer' }}>View resume</button>
            <div style={{ flex:1 }}/>
            <button style={{ padding:'8px 14px', background:'#fff', color: SPC.critical[700], border:`1px solid ${SPC.critical[50]}`, borderRadius:7, fontSize:13, fontWeight:600, cursor:'pointer' }}>Pass</button>
          </div>
        </div>
      )}
    </div>
  );
}

/* Peek drawer — the de-emphasized zones are present, never front and center */
function PeekDrawer({ kind, pre, onClose }) {
  const isPre = kind === 'pre';
  const items = isPre
    ? pre
    : [ // fabricated tracked archive (review+)
        { id:'p1', name:'Brittney Cole', role:'Material Handler', stage:'Hired' },
        { id:'p2', name:'Tara Singleton', role:'Production Lead', stage:'Offer' },
        { id:'p3', name:'Rachel Vu', role:'CNC Operator', stage:'Reviewed' },
        { id:'p4', name:'Donnell Pierce', role:'Machine Operator', stage:'Passed' },
      ];
  return (
    <div onClick={onClose} style={{ position:'absolute', inset:0, zIndex:10, background:'rgba(15,23,42,.32)', display:'flex', justifyContent: isPre ? 'flex-start' : 'flex-end' }}>
      <div onClick={e => e.stopPropagation()} style={{ width:'min(380px,80%)', height:'100%', background:'#fff', boxShadow:'0 0 40px rgba(0,0,0,.2)', display:'flex', flexDirection:'column' }}>
        <div style={{ padding:'16px 18px', borderBottom:`1px solid ${SPC.tint[80]}`, display:'flex', alignItems:'center', gap:8 }}>
          <div>
            <div style={{ fontSize:14, fontWeight:800 }}>{isPre ? 'AI is working' : 'Tracked'}</div>
            <div style={{ fontSize:11.5, color: SPC.shade[700] }}>{isPre ? "You don't need these yet — peek only" : 'Already filed — out of your way'}</div>
          </div>
          <div style={{ flex:1 }}/>
          <button onClick={onClose} style={{ width:30, height:30, borderRadius:7, border:`1px solid ${SPC.tint[100]}`, background:'#fff', cursor:'pointer', fontSize:14 }}>✕</button>
        </div>
        <div style={{ flex:1, overflow:'auto' }}>
          {items.map(c => (
            <div key={c.id} style={{ padding:'11px 18px', borderBottom:`1px solid ${SPC.tint[80]}`, display:'flex', alignItems:'center', gap:10, opacity:.85 }}>
              <span style={{ width:28, height:28, borderRadius:'50%', background: SPC.tint[60], color: SPC.shade[820], display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700, flex:'none' }}>{c.name.split(' ').map(s => s[0]).slice(0, 2).join('')}</span>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:13, fontWeight:600, color: SPC.shade[880] }}>{c.name}</div>
                <div style={{ fontSize:11.5, color: SPC.shade[700] }}>{c.role}</div>
              </div>
              <span style={{ fontSize:10.5, fontWeight:600, color: SPC.shade[700], background: SPC.tint[40], padding:'2px 8px', borderRadius:9999 }}>{isPre ? (c.stage === 'sourcing' ? 'Sourcing' : 'New') : c.stage}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LayoutSpine });
