// ============================================================
//   LayoutDesk — "The Desk" 🔥
//   Same instinct as Stage Spine, opposite move: dissolve JOBS.
//   No saved-jobs rail, no per-job page. One wall of every
//   "in play" candidate across ALL your reqs, each tagged with
//   its job, worked by priority instead of one-job-at-a-time.
//   Pre-engaged (AI's) and tracked (review+) sit as two muted
//   counters in the corners — present, never front and center.
//
//   Tests the last sacred cow of Manage Jobs: do recruiters want
//   to work a JOB, or work their DESK?
// ============================================================
const { color: DKC, font: DKF } = window.FF;

const DK_JOBS = {
  mo:   'Machine Operator I',
  mt:   'Maintenance Tech II',
};

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

function LayoutDesk({ candidates, onExit }) {
  const [job, setJob] = React.useState('all');
  // In play across the whole desk = engaged everywhere. Tag each with a job.
  const inPlay = candidates
    .filter(c => c.stage === 'engaged')
    .map((c, i) => ({ ...c, _job: i % 3 === 0 ? 'mt' : 'mo' }));
  const shown = job === 'all' ? inPlay : inPlay.filter(c => c._job === job);
  // priority sort: ready first
  shown.sort((a, b) => (dk_owner(b).primary - dk_owner(a).primary) || b.score - a.score);

  const preCount = candidates.filter(c => c.stage === 'sourcing' || c.stage === 'new').length;

  return (
    <div data-screen-label="The Desk" style={{ position:'fixed', inset:0, zIndex:50, background: DKC.tint[20], fontFamily: DKF.sans, color: DKC.shade[880], display:'flex', flexDirection:'column' }}>
      {/* top bar */}
      <div style={{ padding:'14px 24px', display:'flex', alignItems:'center', gap:12, borderBottom:`1px solid ${DKC.tint[80]}`, background:'#fff' }}>
        <span style={{ fontSize:15, fontWeight:800, letterSpacing:'-.01em' }}>Your desk</span>
        <span style={{ fontSize:12, color: DKC.shade[700] }}>{inPlay.length} in play across all jobs</span>
        <div style={{ flex:1 }}/>
        <span style={{ fontSize:10, fontWeight:700, letterSpacing:'.14em', textTransform:'uppercase', color: DKC.shade[600], padding:'3px 9px', border:`1px solid ${DKC.tint[100]}`, borderRadius:9999 }}>The Desk</span>
        <button onClick={onExit} style={{ padding:'6px 12px', background:'transparent', border:`1px solid ${DKC.tint[100]}`, borderRadius:6, color: DKC.shade[820], fontSize:11, fontWeight:600, cursor:'pointer', letterSpacing:'.04em', textTransform:'uppercase' }}>Esc · Exit</button>
      </div>

      {/* filter + corner counters: jobs demoted to chips, pre/post muted */}
      <div style={{ padding:'12px 24px', display:'flex', alignItems:'center', gap:8, borderBottom:`1px solid ${DKC.tint[80]}`, background:'#fff', flexWrap:'wrap' }}>
        <span style={{ fontSize:11, fontWeight:700, letterSpacing:'.06em', textTransform:'uppercase', color: DKC.shade[600], marginRight:2 }}>Jobs</span>
        {[{ k:'all', t:'All' }, { k:'mo', t:'Machine Operator I' }, { k:'mt', t:'Maintenance Tech II' }].map(j => {
          const on = job === j.k;
          return (
            <button key={j.k} onClick={() => setJob(j.k)} style={{
              padding:'5px 12px', borderRadius:9999, cursor:'pointer', fontSize:12.5, fontWeight: on ? 700 : 500,
              background: on ? DKC.shade[880] : '#fff', color: on ? '#fff' : DKC.shade[820],
              border:`1px solid ${on ? DKC.shade[880] : DKC.tint[100]}`,
            }}>{j.t}</button>
          );
        })}
        <div style={{ flex:1 }}/>
        <span style={{ fontSize:11.5, color: DKC.copilot[700], display:'inline-flex', alignItems:'center', gap:5 }}>
          <span className="ai-dot" style={{ width:7, height:7 }}/> AI working {preCount}
        </span>
        <span style={{ fontSize:11.5, color: DKC.shade[600] }}>· Tracked 18</span>
      </div>

      {/* the wall */}
      <div style={{ flex:1, overflow:'auto', padding:'18px 24px 40px' }}>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(280px,1fr))', gap:12 }}>
          {shown.map(c => <DeskCard key={c.id} c={c}/>)}
        </div>
      </div>
    </div>
  );
}

function DeskCard({ c }) {
  const O = dk_owner(c);
  const quote = c.lastMsg && (c.lastMsg.startsWith('"') || c.lastMsg.startsWith('\u201C'));
  return (
    <div style={{ background:'#fff', borderRadius:12, padding:'13px 15px', border:`1px solid ${DKC.tint[80]}` }}>
      {/* job tag — the only thing reminding you which req this is */}
      <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:8 }}>
        <span style={{ fontSize:10, fontWeight:700, letterSpacing:'.04em', textTransform:'uppercase', color: DKC.highlight[600], background: DKC.highlight[50], padding:'2px 7px', borderRadius:5 }}>{DK_JOBS[c._job]}</span>
        <div style={{ flex:1 }}/>
        <span style={{ display:'inline-flex', alignItems:'center', gap:5, padding:'2px 8px 2px 7px', borderRadius:9999, fontSize:10.5, fontWeight:700, background: O.tint, color: O.fg }}>
          <span style={{ width:6, height:6, borderRadius:'50%', background: O.dot }}/>{O.label}
        </span>
      </div>
      <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:6 }}>
        <h3 style={{ margin:0, fontSize:15, fontWeight:700, color: DKC.shade[880], whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{c.name}</h3>
        <span style={{ fontSize:11, color: DKC.primary[700], fontWeight:700, flex:'none' }}>★{c.score}</span>
      </div>
      <div style={{ fontSize:12.5, color: DKC.shade[820], marginBottom:10, lineHeight:1.45, fontStyle: quote ? 'italic' : 'normal', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
        {c.lastMsg || c.role}
      </div>
      <div style={{ display:'flex', alignItems:'center', gap:8 }}>
        <span style={{ fontSize:11, color: DKC.shade[700] }}>{c.loc.split(',')[0]}</span>
        <div style={{ flex:1 }}/>
        {O.primary
          ? <button style={{ padding:'5px 11px', background: DKC.shade[880], color:'#fff', border:0, borderRadius:6, fontSize:12, fontWeight:600, cursor:'pointer' }}>{O.next} →</button>
          : <span style={{ fontSize:11.5, color: DKC.shade[700] }}>{O.next}</span>
        }
      </div>
    </div>
  );
}

Object.assign(window, { LayoutDesk });
