// ============================================================
//   LayoutFocus — "the minimal variant"
//
//   The same attention model as LayoutAttention, delivered WITHOUT the
//   restructure. Today's UI is untouched — same stage tabs, same sort row,
//   same candidate rows — and the intelligence is layered on top:
//
//     • within each stage tab, the list PARTITIONS: "Needs you" floats above
//       "Everyone else"
//     • the trigger reason rendered on each row
//     • a jobs-rail toggle that collapses the lower group when you want to
//       work with nothing else on screen
//
//   Why partition rather than re-sort: floating is a GROUPING operation, so it
//   never competes with the sort. Sort is applied once, independently, inside
//   each group — "sort by date applied" stays literally true in both, and the
//   stage filter is untouched because the split happens inside the tab you
//   already picked. A toggle alone would make you choose between "see
//   everything" and "see what needs me"; partitioning gives you both at once,
//   which is the actual job.
//
//   The bet being tested: is the VALUE the attention routing (which survives
//   here) or the reorganisation (which doesn't)? Every stakeholder objection
//   to the full layout has been about the restructure; every bit of
//   enthusiasm has been about the intelligence. This isolates them.
//
//   Reuses atTrigger() / AT_CAT from LayoutAttention.jsx — one definition of
//   the ladder, two presentations of it.
// ============================================================
const { color: FC } = window.FF;

// Stages a human owns, in the order the product shows them today.
const FOCUS_TABS = [
  { k:'sourcing',  label:'Sourcing'  },
  { k:'new',       label:'New'       },
  { k:'engaged',   label:'Engaged'   },
  { k:'review',    label:'Review'    },
  { k:'interview', label:'Interview' },
];

function LayoutFocus({ candidates, selectedId, onSelect, vocab, focusOnly }) {
  const [stage, setStage] = React.useState('engaged');
  const f = useFilterBar();

  const triggerOf = (c) => atTrigger(c);
  // Source + the secondary filters scope the stage before it's partitioned.
  const inStage   = (k) => candidates.filter(c => c.stage === k && f.matchSource(c) && f.matchSecondary(c));
  // Partition, then sort inside each half.
  const split = (k) => {
    const all   = inStage(k);
    const needs = all.filter(triggerOf).sort((a, b) => {
      const ta = triggerOf(a), tb = triggerOf(b);
      return ta.rank - tb.rank || ta.sort - tb.sort || (b.score || 0) - (a.score || 0);
    });
    return { needs, rest: all.filter(c => !triggerOf(c)).slice().sort(f.sortFn) };
  };

  const { needs, rest } = split(stage);
  // Tab counts follow the mode: normally the true total, and only the
  // attention subset while the rail toggle is focusing you.
  const tabs = FOCUS_TABS.map(t => {
    const g = split(t.k);
    return { ...t, n: focusOnly ? g.needs.length : g.needs.length + g.rest.length };
  });
  const stageLabel = FOCUS_TABS.find(t => t.k === stage).label;

  return (
    <React.Fragment>
      <FilterBar f={f}/>
      <TabRow tabs={tabs} active={stage} onChange={setStage}/>
      <div style={{ flex:1, overflow:'auto', borderTop:`1px solid ${FC.tint[80]}` }}>
        {/* NEEDS YOU — floated, never re-sorted around */}
        {needs.length > 0 && (
          <React.Fragment>
            <FocusGroupHeader label="Needs you" n={needs.length} accent={FC.primary[600]}/>
            <CandidateList items={needs} selectedId={selectedId} onSelect={onSelect}
              showSourceBadge vocab={vocab} triggerFor={triggerOf}/>
          </React.Fragment>
        )}

        {/* EVERYONE ELSE — real pipeline, just not blocked on you today.
            Collapsed (not removed) while the rail toggle is on. */}
        {!focusOnly && rest.length > 0 && (
          <React.Fragment>
            {/* Only labelled when there's a group above it — "everyone else"
                implies a preceding set, so with nothing needing you the stage
                just reads as today's plain list. */}
            {needs.length > 0 && (
              <FocusGroupHeader label="Everyone else" n={rest.length} accent={FC.shade[800]}
                note="waiting on them, or already handled"/>
            )}
            <CandidateList items={rest} selectedId={selectedId} onSelect={onSelect}
              showSourceBadge vocab={vocab}/>
          </React.Fragment>
        )}

        {focusOnly && rest.length > 0 && (
          <div style={{ padding:'11px 16px', borderTop:`1px solid ${FC.tint[80]}`, fontSize:11.5, color: FC.shade[600] }}>
            {rest.length} more in {stageLabel} — nothing blocked on you.
          </div>
        )}

        {!needs.length && !rest.length && (
          <div style={{ padding:'40px 24px', textAlign:'center', color: FC.shade[600] }}>
            <div style={{ fontSize:13, fontWeight:700, color: FC.shade[820] }}>No candidates in {stageLabel}.</div>
          </div>
        )}
        {!needs.length && rest.length > 0 && focusOnly && null}
      </div>
    </React.Fragment>
  );
}

// Section divider inside a stage. Sticky so you keep the grouping while
// scrolling a long stage.
function FocusGroupHeader({ label, n, accent, note }) {
  return (
    <div style={{
      position:'sticky', top:0, zIndex:1, background:'#fff',
      padding:'10px 16px 8px', borderBottom:`1px solid ${FC.tint[80]}`,
      display:'flex', alignItems:'baseline', gap:7,
    }}>
      <span style={{ fontSize:10.5, fontWeight:800, letterSpacing:'.06em', textTransform:'uppercase', color: accent }}>{label}</span>
      <span style={{ fontSize:11, fontWeight:700, color: FC.shade[800], fontVariantNumeric:'tabular-nums' }}>{n}</span>
      {note && <span style={{ fontSize:10.5, color: FC.shade[800] }}>· {note}</span>}
    </div>
  );
}

Object.assign(window, { LayoutFocus });
