// ============================================================
//   Two cross-job takes on Action needed.
//
//   Both exist because of one finding in the call corpus: the attention
//   problem often isn't *inside* the panel — it's that the recruiter isn't in
//   the panel at all. Steris, unprompted:
//
//     "We'll have it open as one of the tabs, and we're going back and forth…
//      we have our ATS, we have Indeed… it just keeps me lost. [A candidate]
//      will reply back to me and I get the email — but if I don't look, it
//      might be two hours."
//
//   Reorganising one job's candidate list does nothing for that. Both layouts
//   below attack the cross-job version of the problem instead.
//
//     LayoutAllJobs  (#all-jobs)  — one queue spanning every job
//     LayoutActivity (#activity)  — today's activity feed, made robust
//
//   Both reuse atTrigger() so the ladder stays single-sourced.
// ============================================================
const { color: XJ } = window.FF;

const xjJob    = (id) => (window.__JOBS__ || []).find(j => j.id === id) || { title:'—' };
const xjShort  = (t) => (t.length > 26 ? t.slice(0, 25) + '…' : t);
const xjInit   = (n) => n.split(' ').map(s => s[0]).slice(0, 2).join('');
const xjSorted = (list) => list
  .map(c => ({ c, t: atTrigger(c) })).filter(x => x.t)
  .sort((a, b) => a.t.rank - b.t.rank || a.t.sort - b.t.sort || (b.c.score || 0) - (a.c.score || 0));

/* ============================================================
   ALL JOBS — a full-width takeover, NOT a candidates-panel layout.

   The candidates panel is scoped to whatever job is selected in the rail, so
   a cross-job list can't live there without contradicting the shell: you'd be
   looking at another req's candidates under this req's header. Production
   already has the right precedent — Candidate Archive is a nav-level view
   where "candidates aren't scoped to a specific job".

   So this replaces panels 2+3 entirely. Entered from the aggregate row at the
   top of the jobs rail, exited back to where you were.

   Distinct from #activity on purpose: the feed is an inbox you check and
   leave, this is a working surface you sit and grind through — job is a
   column, rows are wider, wait-age is explicit.
   ============================================================ */
function LayoutAllJobsTakeover({ candidates, onExit }) {
  const [jobFilter, setJobFilter] = React.useState('all');
  const [done, setDone]           = React.useState({});
  const all   = xjSorted(candidates).filter(x => !done[x.c.id]);
  const items = jobFilter === 'all' ? all : all.filter(x => x.c.jobId === jobFilter);
  const byJob = {};
  all.forEach(x => { byJob[x.c.jobId] = (byJob[x.c.jobId] || 0) + 1; });
  const age = (t) => {
    const h = Math.abs(Math.round(t.sort));
    return t.rank === 4 ? `${h}d` : h ? `${h}h` : 'now';
  };

  return (
    <div style={{ position:'fixed', inset:0, zIndex:60, background:'#fff', display:'flex', flexDirection:'column' }}>
      {/* Header */}
      <div style={{ padding:'18px 28px', borderBottom:`1px solid ${XJ.tint[80]}`, display:'flex', alignItems:'center', gap:14 }}>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ display:'flex', alignItems:'baseline', gap:9 }}>
            <h1 style={{ margin:0, fontSize:21, fontWeight:800, color: XJ.shade[880], letterSpacing:'-.01em' }}>Needs you</h1>
            <span style={{ fontSize:12, fontWeight:800, color:'#fff', background: XJ.primary[600], borderRadius:9999, padding:'2px 9px' }}>{all.length}</span>
          </div>
          <div style={{ fontSize:12.5, color: XJ.shade[600], marginTop:2 }}>
            Every job, most urgent first. Work top to bottom — this is the whole list.
          </div>
        </div>
        <button onClick={onExit} style={{
          flex:'none', display:'inline-flex', alignItems:'center', gap:6, padding:'8px 14px',
          background:'#fff', border:`1px solid ${XJ.tint[100]}`, borderRadius:8,
          fontSize:13, fontWeight:600, color: XJ.shade[820], cursor:'pointer',
        }}>← Back to jobs</button>
      </div>

      {/* Job scope */}
      <div style={{ padding:'12px 28px', borderBottom:`1px solid ${XJ.tint[60]}`, display:'flex', gap:7, flexWrap:'wrap', background: XJ.tint[20] }}>
        {[{ id:'all', label:'All jobs', n: all.length },
          ...(window.__JOBS__ || []).map(j => ({ id:j.id, label:j.title, n: byJob[j.id] || 0 }))
        ].map(f => {
          const on = jobFilter === f.id;
          return (
            <button key={f.id} onClick={() => setJobFilter(f.id)} style={{
              display:'inline-flex', alignItems:'center', gap:6, padding:'6px 13px',
              background: on ? XJ.shade[880] : '#fff', color: on ? '#fff' : XJ.shade[820],
              border:`1px solid ${on ? XJ.shade[880] : XJ.tint[100]}`,
              borderRadius:9999, fontSize:12.5, fontWeight:600, cursor:'pointer', whiteSpace:'nowrap',
            }}>{xjShort(f.label)}<span style={{ fontWeight:800 }}>{f.n}</span></button>
          );
        })}
      </div>

      {/* Column headers — this is a working surface, so it reads as a table */}
      <div style={{
        display:'flex', gap:16, padding:'9px 28px', borderBottom:`1px solid ${XJ.tint[80]}`,
        fontSize:9.5, fontWeight:800, letterSpacing:'.05em', textTransform:'uppercase', color: XJ.shade[600],
      }}>
        <span style={{ flex:'0 0 250px' }}>Candidate</span>
        <span style={{ flex:'0 0 210px' }}>Job</span>
        <span style={{ flex:1 }}>Why it needs you</span>
        <span style={{ flex:'0 0 52px', textAlign:'right' }}>Waiting</span>
        <span style={{ flex:'0 0 150px' }}/>
      </div>

      <div style={{ flex:1, overflow:'auto' }}>
        {items.map(({ c, t }) => (
          <div key={c.id} style={{
            display:'flex', gap:16, alignItems:'center', padding:'11px 28px',
            borderBottom:`1px solid ${XJ.tint[60]}`,
          }}>
            <div style={{ flex:'0 0 250px', display:'flex', alignItems:'center', gap:10, minWidth:0 }}>
              <span style={{ width:30, height:30, borderRadius:'50%', flex:'none', background: XJ.tint[60], color: XJ.shade[820], display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700 }}>{xjInit(c.name)}</span>
              <div style={{ minWidth:0 }}>
                <div style={{ fontSize:13.5, fontWeight:700, color: XJ.shade[880], whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{c.name}</div>
                <div style={{ fontSize:11, color: XJ.shade[600] }}>★{c.score} · {c.source === 'applied' ? 'Applied' : 'Sourced'}</div>
              </div>
            </div>
            <div style={{ flex:'0 0 210px', fontSize:12, color: XJ.shade[820], whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
              {xjShort(xjJob(c.jobId).title)}
            </div>
            <div style={{ flex:1, display:'flex', alignItems:'center', gap:8, minWidth:0 }}>
              <span style={{ flex:'none', fontSize:9.5, fontWeight:800, letterSpacing:'.04em', textTransform:'uppercase', color: AT_CAT[t.cat] || XJ.shade[600] }}>{t.cat}</span>
              <span style={{ fontSize:12.5, color: XJ.shade[820], whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{t.reason}</span>
            </div>
            <div style={{ flex:'0 0 52px', textAlign:'right', fontSize:12, fontWeight:600, color: t.rank === 1 ? XJ.critical[600] : XJ.shade[700], fontVariantNumeric:'tabular-nums' }}>
              {age(t)}
            </div>
            <div style={{ flex:'0 0 150px', display:'flex', justifyContent:'flex-end', gap:7 }}>
              <button style={{ padding:'6px 12px', background: XJ.shade[880], color:'#fff', border:0, borderRadius:7, fontSize:12, fontWeight:600, cursor:'pointer' }}>{t.action}</button>
              <button onClick={() => setDone(d => ({ ...d, [c.id]: true }))} style={{
                padding:'6px 10px', background:'#fff', border:`1px solid ${XJ.tint[100]}`, borderRadius:7,
                fontSize:12, fontWeight:600, color: XJ.shade[700], cursor:'pointer',
              }}>Dismiss</button>
            </div>
          </div>
        ))}
        {!items.length && (
          <div style={{ padding:'64px 28px', textAlign:'center', color: XJ.shade[600] }}>
            <div style={{ fontSize:30, marginBottom:8 }}>✓</div>
            <div style={{ fontSize:15, fontWeight:800, color: XJ.shade[880] }}>Nothing left. You're clear across every job.</div>
          </div>
        )}
      </div>
    </div>
  );
}

/* ============================================================
   ACTIVITY — today's feed, made robust.

   Today it's one row per unread candidate conversation, newest first.
   That only ever surfaces ONE trigger type (a candidate messaged you) and
   only clears by reading. Two consequences: the scheduling failure, the
   finished screening and the going-stale candidate never appear at all; and
   "read" is not the same as "handled", so the badge lies.

   This version keeps the shape recruiters already know — bell, count, panel,
   Mark all as read — and widens the contract from "unread messages" to
   "unhandled work", bucketed by what's being asked of you.
   ============================================================ */
const XJ_BUCKETS = [
  { cats:['Waiting on us'],                      label:'Replies waiting on you' },
  { cats:['Needs your help','Decision needed'],  label:'Needs a decision or a hand' },
  { cats:['New application','Screened'],         label:'Ready for review' },
  { cats:['Stale'],                              label:'Going cold' },
];

function LayoutActivity({ candidates, selectedId, onSelect }) {
  const [read, setRead] = React.useState({});
  const all  = xjSorted(candidates).filter(x => !read[x.c.id]);
  const open = XJ_BUCKETS.map(b => ({ ...b, items: all.filter(x => b.cats.includes(x.t.cat)) })).filter(b => b.items.length);

  return (
    <React.Fragment>
      <div style={{ padding:'16px 16px 13px', borderBottom:`1px solid ${XJ.tint[80]}`, display:'flex', alignItems:'center', gap:8 }}>
        <h3 style={{ margin:0, fontSize:16, fontWeight:800, color: XJ.shade[880] }}>Activity</h3>
        <span style={{ fontSize:11.5, fontWeight:800, color:'#fff', background: XJ.critical[600], borderRadius:9999, padding:'1px 8px' }}>{all.length}</span>
        <span style={{ flex:1 }}/>
        <button onClick={() => setRead(Object.fromEntries(candidates.map(c => [c.id, true])))} style={{
          border:0, background:'transparent', cursor:'pointer', fontSize:11.5, fontWeight:600, color: XJ.highlight[700],
        }}>Mark all as read</button>
      </div>

      <div style={{ flex:1, overflow:'auto' }}>
        {open.map(b => (
          <div key={b.label}>
            <div style={{
              padding:'9px 16px', background: XJ.tint[20], borderBottom:`1px solid ${XJ.tint[60]}`,
              fontSize:10, fontWeight:800, letterSpacing:'.05em', textTransform:'uppercase', color: XJ.shade[600],
            }}>{b.label} <span style={{ color: XJ.shade[700] }}>{b.items.length}</span></div>
            {b.items.map(({ c, t }) => {
              const on = c.id === selectedId;
              return (
                <div key={c.id} onClick={() => onSelect?.(c.id)} style={{
                  position:'relative', padding:'11px 16px', borderBottom:`1px solid ${XJ.tint[80]}`, cursor:'pointer',
                  background: on ? XJ.highlight[50] + '66' : '#fff', display:'flex', gap:11,
                }}>
                  {on && <div style={{ position:'absolute', left:0, top:0, bottom:0, width:3, background: XJ.highlight[500] }}/>}
                  <span style={{ width:30, height:30, borderRadius:'50%', flex:'none', background: XJ.tint[60], color: XJ.shade[820], display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700 }}>{xjInit(c.name)}</span>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ display:'flex', alignItems:'baseline', gap:6 }}>
                      <span style={{ fontSize:13, fontWeight:700, color: XJ.shade[880], whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{c.name}</span>
                      <span style={{ flex:'none', fontSize:11, color: XJ.shade[600] }}>{c.time}</span>
                    </div>
                    <div style={{ fontSize:11, color: XJ.shade[600], margin:'1px 0 3px', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
                      {xjShort(xjJob(c.jobId).title)}
                    </div>
                    <div style={{ fontSize:12, color: XJ.shade[820], lineHeight:1.35 }}>{c.lastMsg || t.reason}</div>
                  </div>
                  {/* Read ≠ handled, so the dismissal is explicit rather than a
                      side effect of opening the row. */}
                  <button onClick={e => { e.stopPropagation(); setRead(r => ({ ...r, [c.id]: true })); }}
                    title="Dismiss — a new event will bring them back"
                    style={{ flex:'none', alignSelf:'center', border:`1px solid ${XJ.tint[100]}`, background:'#fff', borderRadius:6, padding:'3px 8px', fontSize:11, fontWeight:600, color: XJ.shade[700], cursor:'pointer' }}>
                    Dismiss
                  </button>
                </div>
              );
            })}
          </div>
        ))}
        {!open.length && (
          <div style={{ padding:'48px 24px', textAlign:'center', color: XJ.shade[600] }}>
            <div style={{ fontSize:26, marginBottom:6 }}>✓</div>
            <div style={{ fontSize:14, fontWeight:700, color: XJ.shade[880] }}>All caught up!</div>
          </div>
        )}
      </div>
    </React.Fragment>
  );
}

Object.assign(window, { LayoutAllJobsTakeover, LayoutActivity });
