// ============================================================
//   LayoutStacked — no queue. Just the stages, with whatever needs a human
//   floated to the top of its own stage.
//
//   The missing cell in the comparison. The other layouts only ask "tabs or
//   no tabs"; this asks the better question:
//
//     #action-needed  attention is EXTRACTED into a queue (and mirrored back
//                     into the funnel as a lens, so people appear twice)
//     #stacked        attention is ORDERED IN PLACE — single presence
//     #focus          ordered in place, but trapped behind tabs
//
//   What it wins: no tabs, so no hunting and no "which tab should I be in";
//   Sourcing stops being a peer competing for a click; and nobody is listed
//   twice, which retires the lens-vs-decomposition question entirely.
//
//   What it costs, and this is the thing to watch: precedence goes
//   stage-local. The ladder can rank within Engaged but not across the whole
//   board, so a 30h post-interview decision sits below a 3h reply purely
//   because of scroll order. Each stage header therefore carries its own
//   "N need you" so the distribution is at least legible.
//
//   Reuses atTrigger() / AT_CAT so the ladder stays single-sourced.
// ============================================================
const { color: SK } = window.FF;

// Human-owned stages in funnel order, then the two "not yours" families last
// so they don't read as step one of the workflow.
const SK_SECTIONS = [
  { key:'new',       label:'New applications', stages:['new'] },
  { key:'engaged',   label:'Engaged',          stages:['engaged'] },
  { key:'review',    label:'Reviewed',         stages:['review'] },
  { key:'interview', label:'Interviewing',     stages:['interview'] },
  { key:'offer',     label:'Offer',            stages:['offer'] },
  { key:'hired',     label:'Hired',            stages:['hired'] },
];
const SK_QUIET = [
  { key:'ai',     label:'AI working', stages:['sourcing'], note:'not yours yet',  accent:'copilot' },
  { key:'closed', label:'Closed',     stages:['closed'],   note:null,             accent:'shade' },
];

function LayoutStacked({ candidates, selectedId, onSelect, vocab }) {
  const f = useFilterBar();
  // Human stages open, the not-yours families collapsed.
  const [open, setOpen] = React.useState(() => new Set(SK_SECTIONS.map(s => s.key)));
  const toggle = (k) => setOpen(s => { const n = new Set(s); n.has(k) ? n.delete(k) : n.add(k); return n; });

  const pool = candidates.filter(c => f.matchSource(c) && f.matchSecondary(c));
  const build = (sec) => {
    const all   = pool.filter(c => sec.stages.includes(c.stage));
    const needs = all.filter(atTrigger).sort((a, b) => {
      const ta = atTrigger(a), tb = atTrigger(b);
      return ta.rank - tb.rank || ta.sort - tb.sort || (b.score || 0) - (a.score || 0);
    });
    return { ...sec, needs, rest: all.filter(c => !atTrigger(c)).slice().sort(f.sortFn), total: all.length };
  };

  const sections = SK_SECTIONS.map(build);
  const quiet    = SK_QUIET.map(build);

  return (
    <React.Fragment>
      <FilterBar f={f}/>
      <div style={{ flex:1, overflow:'auto', borderTop:`1px solid ${SK.tint[80]}` }}>
        {sections.map(s => (
          <StackSection key={s.key} s={s} open={open.has(s.key)} onToggle={() => toggle(s.key)}
            selectedId={selectedId} onSelect={onSelect} vocab={vocab}/>
        ))}
        <div style={{ borderTop:`6px solid ${SK.tint[20]}` }}>
          {quiet.map(s => (
            <StackSection key={s.key} s={s} open={open.has(s.key)} onToggle={() => toggle(s.key)}
              selectedId={selectedId} onSelect={onSelect} vocab={vocab} quiet/>
          ))}
        </div>
      </div>
    </React.Fragment>
  );
}

function StackSection({ s, open, onToggle, selectedId, onSelect, vocab, quiet }) {
  if (!s.total) return null;
  const accent = quiet ? (s.accent === 'copilot' ? SK.copilot[800] : SK.shade[800]) : SK.shade[880];
  return (
    <div>
      <button onClick={onToggle} aria-expanded={open} className="ff-stagehd" style={{
        width:'100%', textAlign:'left', display:'flex', alignItems:'center', gap:9,
        padding:'11px 16px', background:'transparent', border:0,
        borderBottom:`1px solid ${SK.tint[60]}`, cursor:'pointer', transition:'background .12s',
      }}>
        <span style={{
          width:16, height:16, flex:'none', display:'inline-flex', alignItems:'center', justifyContent:'center',
          borderRadius:4, background: quiet && s.accent === 'copilot' ? SK.copilot[50] : SK.tint[40],
          color: quiet && s.accent === 'copilot' ? SK.copilot[700] : SK.shade[800],
          fontSize:12, fontWeight:700, transition:'transform .15s', transform: open ? 'rotate(90deg)' : 'none',
        }}>›</span>
        <span style={{ fontSize:11.5, fontWeight:800, letterSpacing:'.04em', textTransform:'uppercase', color: accent }}>{s.label}</span>
        <span style={{ fontSize:11, fontWeight:700, color: SK.shade[800], fontVariantNumeric:'tabular-nums' }}>{s.total}</span>
        {/* Per-stage attention count — with no global queue, this is the only
            thing telling you where the work actually is. */}
        {s.needs.length > 0 && (
          <span style={{
            display:'inline-flex', alignItems:'center', gap:5, padding:'1px 8px 1px 6px', borderRadius:9999,
            background: SK.primary[50], color: SK.primary[700], fontSize:10.5, fontWeight:800,
          }}>
            <span style={{ width:5, height:5, borderRadius:'50%', background: SK.primary[500] }}/>
            {s.needs.length} need{s.needs.length === 1 ? 's' : ''} you
          </span>
        )}
        {s.note && <span style={{ fontSize:10.5, color: SK.shade[800] }}>· {s.note}</span>}
      </button>

      {open && (
        <React.Fragment>
          {/* Attention first. No sub-headers — with six sections that would be
              a dozen labels; the accent rule on each row carries it instead. */}
          {s.needs.length > 0 && (
            <CandidateList items={s.needs} selectedId={selectedId} onSelect={onSelect}
              showSourceBadge vocab={vocab} triggerFor={atTrigger}/>
          )}
          {s.needs.length > 0 && s.rest.length > 0 && (
            <div style={{ height:1, background: SK.tint[80], margin:'0 16px' }}/>
          )}
          {s.rest.length > 0 && (
            <CandidateList items={s.rest} selectedId={selectedId} onSelect={onSelect}
              showSourceBadge vocab={vocab}/>
          )}
        </React.Fragment>
      )}
    </div>
  );
}

Object.assign(window, { LayoutStacked });
