// ============================================================
//   LayoutLinear — "Action list" (Linear-style)
//   Scraps the list→detail split entirely. One full-width,
//   dense, grouped list where every row carries its own context
//   AND its own action. You don't click in to find out what to
//   do — the row tells you, and you do it from the row.
//
//   Grouped by what you should act on (not by source, not by
//   stage): Needs your review → In conversation → Waiting → AI
//   working. The page IS the queue of actions.
// ============================================================
const { color: LNC, font: LNF } = window.FF;

// Derive an action-group + verb for each candidate.
function ln_group(c) {
  if (c.unread || c.justLanded) return 'review';
  if (c.stage === 'sourcing') return 'ai';
  const m = (c.lastMsg || '').toLowerCase();
  if (/awaiting|reminder|screening questions/.test(m)) return 'waiting';
  if (c.stage === 'new') return 'review';
  return 'talking';
}

const LN_GROUPS = [
  { key:'review',  label:'Needs your review', dot: LNC.primary[500],  verb:'Review',   hint:'They replied — your move' },
  { key:'talking', label:'In conversation',   dot: LNC.inform[500],   verb:'Open',     hint:'Active back-and-forth' },
  { key:'waiting', label:'Waiting on them',   dot: LNC.caution[500],  verb:'Nudge',    hint:'Ball is in their court' },
  { key:'ai',      label:'AI working',        dot: LNC.copilot[500],  verb:null,       hint:"You don't need these yet", dim:true },
];

// Tracking view ("Everyone") — the human's ATS pipeline, post-handoff.
// These are real tracking stages, NOT the ownership/attention axis.
function ln_track(c) {
  if (c.stage === 'sourcing') return 'aiworking';      // not yours yet
  if (c.stage === 'new') return 'newtoyou';            // just became yours
  const m = (c.lastMsg || '').toLowerCase();
  if (/scheduled|confirm|copilot|booked|interview/.test(m)) return 'interviewing';
  const h = c.id.split('').reduce((a, ch) => a + ch.charCodeAt(0), 0);
  if (h % 9 === 0) return 'offer';
  if (h % 13 === 0) return 'hired';
  return 'reviewing';
}
const LN_TRACK = [
  { key:'newtoyou',     label:'New — to review',  dot: LNC.inform[500],    hint:'Just handed to you',      status:'New' },
  { key:'reviewing',    label:'Reviewing',         dot: LNC.caution[500],   hint:"You're evaluating",        status:'Review' },
  { key:'interviewing', label:'Interviewing',      dot: LNC.highlight[500], hint:'Scheduled or in interview',status:'Interview' },
  { key:'offer',        label:'Offer',             dot: LNC.primary[500],   hint:'Offer extended',          status:'Offer' },
  { key:'hired',        label:'Hired',             dot: LNC.primary[700],   hint:'Closed',                  status:'Hired' },
  { key:'aiworking',    label:'AI working',        dot: LNC.copilot[500],   hint:'Not in your pipeline yet',status:'Sourcing', dim:true },
];

const LN_MEMORY = {
  c19:{ t:'Also applied: CNC Setup', tone:'info' },
  c20:{ t:'Former employee', tone:'info' },
  c22:{ t:'Said no in March', tone:'warn' },
  c23:{ t:'2nd application', tone:'info' },
  c27:{ t:'Interviewed Feb', tone:'info' },
  c16:{ t:'Do not hire', tone:'stop' },
  c10:{ t:'Applied 4×', tone:'warn' },
};

function ln_timeago(c) {
  const h = c.id.split('').reduce((a, ch) => a + ch.charCodeAt(0), 0);
  if (c.unread || c.justLanded) return ['12m','34m','1h','2h'][h % 4];
  return ['Today','Yesterday','2d','3d','5d'][h % 5];
}

function LayoutLinear({ candidates, selectedId, onSelect }) {
  const [done, setDone] = React.useState({});
  const [collapsed, setCollapsed] = React.useState({ ai:true, aiworking:true });
  const [tab, setTab] = React.useState('needs');

  const decorated = candidates.filter(c => !done[c.id]).map(c => ({ ...c, _g: ln_group(c) }));
  // "Needs you" is attention only — AI-working candidates are NOT here.
  const needsGroups = LN_GROUPS.filter(g => g.key !== 'ai');
  const grouped = needsGroups.map(g => ({ ...g, items: decorated.filter(c => c._g === g.key) }));
  const aiWorkingN = candidates.filter(c => ln_group(c) === 'ai').length;
  const needsTotal = grouped.reduce((n, g) => n + g.items.length, 0);

  const act = (id) => setDone(d => ({ ...d, [id]: true }));
  const toggle = (k) => setCollapsed(s => ({ ...s, [k]: !s[k] }));

  // "Everyone" = tracking view: grouped by where they are in the process,
  // not by what needs you. No action buttons — it's the record.
  const trackDecorated = candidates.map(c => ({ ...c, _t: ln_track(c) }));
  const tracked = LN_TRACK.map(g => ({ ...g, items: trackDecorated.filter(c => c._t === g.key) }));
  const view = tab === 'everyone' ? tracked : grouped;
  const TABS = [
    { key:'needs', label:'Needs you' },
    { key:'everyone', label:'Everyone' },
    { key:'activity', label:'Activity' },
  ];

  return (
    <div style={{ flex:1, minWidth:0, display:'flex', flexDirection:'column', minHeight:0, background:'#fff' }}>
      {/* header — tabs in the spirit of Linear "My Issues" */}
      <div style={{ padding:'18px 28px 0' }}>
        <div style={{ fontSize:18, fontWeight:800, letterSpacing:'-.01em', color: LNC.shade[880], marginBottom:12 }}>
          Machine Operator I
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:6, borderBottom:`1px solid ${LNC.tint[80]}`, paddingBottom:0 }}>
          {TABS.map(tb => {
            const on = tab === tb.key;
            return (
              <button key={tb.key} onClick={() => setTab(tb.key)} style={{
                padding:'8px 12px', marginBottom:-1, background:'transparent', cursor:'pointer',
                border:0, borderBottom:`2px solid ${on ? LNC.shade[880] : 'transparent'}`,
                fontSize:13.5, fontWeight: on ? 700 : 500, color: on ? LNC.shade[880] : LNC.shade[700],
              }}>{tb.label}</button>
            );
          })}
        </div>
      </div>

      {tab === 'activity' ? (
        <LinearActivity/>
      ) : (
      /* the list */
      <div style={{ flex:1, overflow:'auto' }}>
        {tab === 'needs' && aiWorkingN > 0 && (
          <div style={{ display:'flex', alignItems:'center', gap:8, padding:'9px 28px', borderBottom:`1px solid ${LNC.tint[60]}`, background:'#fff' }}>
            <span className="ai-dot" style={{ width:7, height:7, flex:'none' }}/>
            <span style={{ fontSize:12, color: LNC.copilot[700] }}>
              <strong style={{ fontWeight:700 }}>AI is working {aiWorkingN}</strong> in the background — sourcing, contacting, screening. You’ll see them when they’re ready.
            </span>
          </div>
        )}
        {tab === 'needs' && needsTotal === 0 && (
          <div style={{ padding:'56px 24px', textAlign:'center' }}>
            <div style={{ fontSize:34, marginBottom:10 }}>✓</div>
            <div style={{ fontSize:16, fontWeight:800, color: LNC.shade[880], marginBottom:4 }}>You’re caught up.</div>
            <div style={{ fontSize:13, color: LNC.shade[700] }}>Nothing needs you on this job right now. The AI will surface people as they’re ready.</div>
          </div>
        )}
        {view.map(g => (
          <div key={g.key}>
            {/* group header bar */}
            <button onClick={() => toggle(g.key)} style={{
              width:'100%', textAlign:'left', cursor:'pointer', border:0,
              background: LNC.tint[20], padding:'7px 28px',
              borderBottom:`1px solid ${LNC.tint[80]}`, borderTop:`1px solid ${LNC.tint[80]}`,
              display:'flex', alignItems:'center', gap:9,
            }}>
              <span style={{ fontSize:10, color: LNC.shade[600], width:10, transition:'transform .12s', transform: collapsed[g.key] ? 'rotate(-90deg)' : 'none' }}>▼</span>
              <span style={{ width:8, height:8, borderRadius:'50%', background: g.dot, flex:'none' }}/>
              <span style={{ fontSize:13, fontWeight:700, color: LNC.shade[880] }}>{g.label}</span>
              <span style={{ fontSize:12, fontWeight:700, color: LNC.shade[600], fontVariantNumeric:'tabular-nums' }}>{g.items.length}</span>
              <span style={{ fontSize:11.5, color: LNC.shade[600], marginLeft:4 }}>· {g.hint}</span>
            </button>

            {!collapsed[g.key] && g.items.map(c => (
              <LinearRow key={c.id} c={c} group={g} tracking={tab === 'everyone'} selected={c.id === selectedId} onSelect={onSelect} onAct={act}/>
            ))}
            {!collapsed[g.key] && !g.items.length && (
              <div style={{ padding:'12px 28px 12px 55px', fontSize:12, color: LNC.shade[600], fontStyle:'italic', borderBottom:`1px solid ${LNC.tint[60]}` }}>Nothing here.</div>
            )}
          </div>
        ))}
      </div>
      )}
    </div>
  );
}

function LinearRow({ c, group, tracking, selected, onSelect, onAct }) {
  const [hover, setHover] = React.useState(false);
  const mem = LN_MEMORY[c.id];
  const memColor = mem ? ({ info: LNC.inform, warn: LNC.caution, stop: LNC.critical }[mem.tone]) : null;
  return (
    <div
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      onClick={() => onSelect?.(c.id)}
      style={{
        position:'relative', display:'flex', alignItems:'center', gap:12,
        padding:'9px 28px', cursor:'pointer',
        borderBottom:`1px solid ${LNC.tint[60]}`,
        background: selected ? LNC.highlight[50] + '66' : hover ? LNC.tint[20] : '#fff',
        opacity: group.dim ? .62 : 1,
      }}>
      {selected && <div style={{ position:'absolute', left:0, top:0, bottom:0, width:3, background: LNC.highlight[500] }}/>}

      {/* checkbox on hover, status dot otherwise */}
      <span style={{ width:16, flex:'none', display:'flex', justifyContent:'center' }}>
        {hover
          ? <input type="checkbox" onClick={e => e.stopPropagation()} style={{ width:14, height:14, accentColor: LNC.highlight[500] }}/>
          : <span style={{ width:9, height:9, borderRadius:'50%', background: group.dot }}/>
        }
      </span>

      {/* name + inline context */}
      <div style={{ flex:1, minWidth:0, display:'flex', alignItems:'baseline', gap:8 }}>
        <span style={{ fontSize:13.5, fontWeight:600, color: LNC.shade[880], flex:'none' }}>{c.name}</span>
        <span style={{ fontSize:12.5, color: LNC.shade[700], whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', minWidth:0 }}>
          {c.lastMsg || `${c.role} · ${c.company}`}
        </span>
      </div>

      {/* right cluster: memory, score, time / action */}
      <div style={{ display:'flex', alignItems:'center', gap:10, flex:'none' }}>
        {mem && (
          <span style={{
            fontSize:10.5, fontWeight:600, padding:'2px 8px', borderRadius:9999,
            background: memColor[50], color: memColor[700],
            border: mem.tone === 'stop' ? `1px solid ${memColor[300]}` : 'none',
            textTransform: mem.tone === 'stop' ? 'uppercase' : 'none', letterSpacing: mem.tone === 'stop' ? '.03em' : 0,
          }}>{mem.t}</span>
        )}
        <span style={{ fontSize:11, fontWeight:700, color: LNC.primary[700], width:30, textAlign:'right' }}>★{c.score}</span>

        {/* tracking view: status pill + time, no action. else: action on hover, time otherwise */}
        {tracking ? (
          <React.Fragment>
            <span style={{
              fontSize:10.5, fontWeight:700, padding:'2px 9px', borderRadius:9999,
              background: LNC.tint[40], color: LNC.shade[700],
            }}>{group.status}</span>
            <span style={{ fontSize:11.5, color: LNC.shade[600], width:64, textAlign:'right' }}>{ln_timeago(c)}</span>
          </React.Fragment>
        ) : hover && group.verb ? (
          <button onClick={e => { e.stopPropagation(); onAct(c.id); }} style={{
            padding:'4px 11px', background: LNC.shade[880], color:'#fff', border:0, borderRadius:6,
            fontSize:12, fontWeight:600, cursor:'pointer', width:78, textAlign:'center',
          }}>{group.verb}</button>
        ) : (
          <span style={{ fontSize:11.5, color: LNC.shade[600], width:78, textAlign:'right' }}>{ln_timeago(c)}</span>
        )}
      </div>
    </div>
  );
}

/* Activity tab — a reverse-chron log, Linear-style. Read-only history. */
function LinearActivity() {
  const ACT = [
    { who:'AI', t:'12m ago',  text:'Marcus Doyle replied — interested in 2nd shift', kind:'reply' },
    { who:'AI', t:'34m ago',  text:'Sent screening questions to 4 sourced candidates', kind:'send' },
    { who:'You',t:'1h ago',   text:'Advanced Tania Briggs to Interviewing', kind:'move' },
    { who:'AI', t:'2h ago',   text:'Sourced 9 new candidates matching Machine Operator I', kind:'source' },
    { who:'AI', t:'Today',    text:'Kevin Ortiz re-opened — shift conflict resolved', kind:'reply' },
    { who:'You',t:'Yesterday',text:'Rejected 3 candidates after review', kind:'reject' },
    { who:'AI', t:'Yesterday',text:'Booked phone screen with Dana Whitfield, Thu 2pm', kind:'move' },
    { who:'AI', t:'2d ago',   text:'Contacted 23 sourced candidates (1st touch SMS)', kind:'send' },
  ];
  const COL = { reply: LNC.primary[500], send: LNC.copilot[500], move: LNC.inform[500], source: LNC.copilot[500], reject: LNC.shade[600] };
  return (
    <div style={{ flex:1, overflow:'auto', padding:'8px 0' }}>
      {ACT.map((a, i) => (
        <div key={i} style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 28px', borderBottom:`1px solid ${LNC.tint[60]}` }}>
          <span style={{ width:8, height:8, borderRadius:'50%', background: COL[a.kind], flex:'none' }}/>
          <span style={{
            fontSize:10.5, fontWeight:700, width:30, flex:'none',
            color: a.who === 'AI' ? LNC.copilot[700] : LNC.shade[700],
          }}>{a.who}</span>
          <span style={{ flex:1, fontSize:13, color: LNC.shade[820], minWidth:0 }}>{a.text}</span>
          <span style={{ fontSize:11.5, color: LNC.shade[600], flex:'none' }}>{a.t}</span>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { LayoutLinear });
