// ============================================================
//   LayoutHandoff — "Handoff overlay" (the smallest real move)
//   Keep the ATS stage list users already know. Don't make a
//   source taxonomy. Just draw the ONE line the calls keep
//   asking for: where the AI's territory ends and YOUR pipeline
//   begins.
//
//   • AI working = ambient zone at top, NOT a stage (pre-handoff)
//   • ═ Ready for you ═ = the handoff band, the loud treatment
//   • Then the real ATS stages you track: Reviewing → Interviewing
//   • Source = a quiet luggage tag on each row, never a lane
//   This is "make the handoff sign bigger," nothing more.
// ============================================================
const { color: HC } = window.FF;

function hf_bucket(c) {
  if (c.stage === 'sourcing') return 'ai';
  if (c.unread || c.justLanded || c.stage === 'new') return 'ready';
  const m = (c.lastMsg || '').toLowerCase();
  if (/scheduled|confirm|copilot|booked|interview/.test(m)) return 'interviewing';
  return 'reviewing';
}

const HF_MEMORY = {
  c19:'Also applied: CNC Setup', c20:'Former employee', c22:'Said no in March',
  c23:'2nd application', c16:'Do not hire', c10:'Applied 4×',
};

function LayoutHandoff({ candidates, selectedId, onSelect }) {
  const decorated = candidates.map(c => ({ ...c, _b: hf_bucket(c) }));
  const aiN = decorated.filter(c => c._b === 'ai').length;
  const ready = decorated.filter(c => c._b === 'ready');
  const reviewing = decorated.filter(c => c._b === 'reviewing');
  const interviewing = decorated.filter(c => c._b === 'interviewing');

  return (
    <div style={{ flex:1, overflow:'auto', minHeight:0 }}>
      {/* Pre-handoff: AI working, ambient, NOT a stage */}
      <div style={{ display:'flex', alignItems:'center', gap:9, padding:'12px 20px', background: HC.copilot[50], borderBottom:`1px solid ${HC.tint[80]}` }}>
        <span className="ai-dot" style={{ width:8, height:8, flex:'none' }}/>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontSize:13, fontWeight:700, color: HC.copilot[800] }}>AI is working {aiN}</div>
          <div style={{ fontSize:11.5, color: HC.copilot[700] }}>Sourcing · contacting · screening — nothing for you here yet</div>
        </div>
        <span style={{ fontSize:11, color: HC.copilot[700], fontWeight:600, flex:'none' }}>Peek ›</span>
      </div>

      {/* THE HANDOFF LINE */}
      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'14px 20px 6px' }}>
        <span style={{ height:1, flex:1, background: HC.primary[500] }}/>
        <span style={{ fontSize:10, fontWeight:800, letterSpacing:'.12em', textTransform:'uppercase', color: HC.primary[700] }}>You take over here</span>
        <span style={{ height:1, flex:1, background: HC.primary[500] }}/>
      </div>

      {/* Handoff band — the loud "ready for you" treatment */}
      <StageGroup label="Ready for you" hint="Just became yours — your first move" count={ready.length}
        accent={HC.primary[500]} band>
        {ready.map(c => <HandoffRow key={c.id} c={c} selected={c.id === selectedId} onSelect={onSelect} verb="Review" primary/>)}
      </StageGroup>

      {/* Real ATS stages — the tracking pipeline, kept intact */}
      <StageGroup label="Reviewing" hint="You're evaluating / in conversation" count={reviewing.length} accent={HC.caution[500]}>
        {reviewing.map(c => <HandoffRow key={c.id} c={c} selected={c.id === selectedId} onSelect={onSelect} verb="Open"/>)}
      </StageGroup>
      <StageGroup label="Interviewing" hint="Scheduled or in interview" count={interviewing.length} accent={HC.highlight[500]}>
        {interviewing.map(c => <HandoffRow key={c.id} c={c} selected={c.id === selectedId} onSelect={onSelect} verb="Open"/>)}
      </StageGroup>
    </div>
  );
}

function StageGroup({ label, hint, count, accent, band, children }) {
  return (
    <div style={{ background: band ? HC.primary[50] + '55' : '#fff' }}>
      <div style={{ display:'flex', alignItems:'center', gap:8, padding:'9px 20px 7px' }}>
        <span style={{ width:8, height:8, borderRadius:'50%', background: accent, flex:'none' }}/>
        <span style={{ fontSize:12.5, fontWeight:800, color: HC.shade[880], letterSpacing: band ? '0' : 0 }}>{label}</span>
        <span style={{ fontSize:11.5, fontWeight:700, color: HC.shade[600], fontVariantNumeric:'tabular-nums' }}>{count}</span>
        <span style={{ fontSize:11, color: HC.shade[600], marginLeft:2 }}>· {hint}</span>
      </div>
      {children}
      {!React.Children.count(children) && (
        <div style={{ padding:'4px 20px 12px 38px', fontSize:11.5, color: HC.shade[600], fontStyle:'italic' }}>Empty</div>
      )}
    </div>
  );
}

function HandoffRow({ c, selected, onSelect, verb, primary }) {
  const [hover, setHover] = React.useState(false);
  const mem = HF_MEMORY[c.id];
  const dnh = mem === 'Do not hire';
  const sourced = c.source === 'sourced';
  return (
    <div
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      onClick={() => onSelect?.(c.id)}
      style={{
        position:'relative', display:'flex', alignItems:'center', gap:10,
        padding:'9px 20px', cursor:'pointer', borderTop:`1px solid ${HC.tint[60]}`,
        background: selected ? HC.highlight[50] + '88' : hover ? HC.tint[20] : 'transparent',
      }}>
      {selected && <div style={{ position:'absolute', left:0, top:0, bottom:0, width:3, background: HC.highlight[500] }}/>}

      <span style={{ width:14, flex:'none', display:'flex', justifyContent:'center' }}>
        {hover
          ? <input type="checkbox" onClick={e => e.stopPropagation()} style={{ width:13, height:13, accentColor: HC.highlight[500] }}/>
          : <span style={{ width:7, height:7, borderRadius:'50%', background: primary ? HC.primary[500] : HC.tint[200] }}/>
        }
      </span>

      <div style={{ flex:1, minWidth:0, display:'flex', alignItems:'baseline', gap:7 }}>
        <span style={{ fontSize:13.5, fontWeight:600, color: HC.shade[880], flex:'none' }}>{c.name}</span>
        {/* source = luggage tag, quiet */}
        <span title={sourced ? 'AI-sourced' : 'Applied directly'} style={{ fontSize:10, color: sourced ? HC.copilot[600] : HC.shade[600], flex:'none', fontWeight:600 }}>
          {sourced ? '⚡' : '↳'}
        </span>
        <span style={{ fontSize:12, color: HC.shade[700], whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', minWidth:0 }}>
          {c.lastMsg || `${c.role}`}
        </span>
      </div>

      <div style={{ display:'flex', alignItems:'center', gap:9, flex:'none' }}>
        {mem && (
          <span style={{
            fontSize:10, fontWeight:600, padding:'2px 7px', borderRadius:9999,
            background: dnh ? HC.critical[50] : HC.tint[40], color: dnh ? HC.critical[700] : HC.shade[700],
            border: dnh ? `1px solid ${HC.critical[300]}` : 'none',
            textTransform: dnh ? 'uppercase' : 'none', letterSpacing: dnh ? '.03em' : 0,
          }}>{mem}</span>
        )}
        <span style={{ fontSize:11, fontWeight:700, color: HC.primary[700], width:28, textAlign:'right' }}>★{c.score}</span>
        {hover
          ? <button onClick={e => e.stopPropagation()} style={{ padding:'4px 11px', background: HC.shade[880], color:'#fff', border:0, borderRadius:6, fontSize:12, fontWeight:600, cursor:'pointer', width:66, textAlign:'center' }}>{verb}</button>
          : <span style={{ width:66 }}/>
        }
      </div>
    </div>
  );
}

Object.assign(window, { LayoutHandoff });
