// ============================================================
//   LayoutSegment — Segment-aware workspace
//   The atom changes by mode:
//     Staffing  → person-in-a-call-queue (power recruiter)
//     Employer  → candidate-ready-to-decide (calm employer)
//   Same data, different object, different verbs, different chrome.
//   NOT "customize your dashboard" — opinionated presets.
// ============================================================
const { color: SGC } = window.FF;

function LayoutSegment({ candidates, selectedId, onSelect }) {
  const [mode, setMode] = React.useState('staffing');
  return (
    <React.Fragment>
      <ModeSwitch mode={mode} setMode={setMode}/>
      {mode === 'staffing'
        ? <StaffingMode candidates={candidates} selectedId={selectedId} onSelect={onSelect}/>
        : <EmployerMode candidates={candidates} selectedId={selectedId} onSelect={onSelect}/>
      }
    </React.Fragment>
  );
}

/* ---------- Mode switch (the only shared chrome) ---------- */
function ModeSwitch({ mode, setMode }) {
  const tab = (k, label, sub, icon) => {
    const on = mode === k;
    return (
      <button onClick={() => setMode(k)} style={{
        flex: 1, padding: '11px 14px', textAlign: 'left',
        background: on ? '#fff' : 'transparent',
        border: on ? `1px solid ${SGC.shade[840]}` : '1px solid transparent',
        borderRadius: 10, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10,
        boxShadow: on ? '0 1px 3px rgba(13,10,44,.08)' : 'none',
      }}>
        <span style={{
          width: 28, height: 28, borderRadius: 7, flex: 'none',
          background: on ? SGC.shade[880] : SGC.tint[40], color: on ? '#fff' : SGC.shade[820],
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 14,
        }}>{icon}</span>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: on ? SGC.shade[880] : SGC.shade[820], lineHeight: 1.2 }}>{label}</div>
          <div style={{ fontSize: 11, color: SGC.shade[700], whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</div>
        </div>
      </button>
    );
  };
  return (
    <div style={{ padding: '14px 18px 4px' }}>
      <div style={{
        display: 'flex', gap: 4, background: SGC.tint[20],
        border: `1px solid ${SGC.tint[80]}`, borderRadius: 12, padding: 4,
      }}>
        {tab('staffing', 'Staffing',        'Power queue · dialer · batch',     '⚙')}
        {tab('employer', 'Direct employer', 'Ready candidates · decisions',     '✓')}
      </div>
      <div style={{ fontSize: 11, color: SGC.shade[700], marginTop: 8, lineHeight: 1.4 }}>
        Same data, two products. Modes are opinionated — not a settings swamp.
      </div>
    </div>
  );
}

/* ============================================================
   STAFFING MODE — power queue + dialer + batch
   The atom: person-in-the-call-queue.
   Verbs: call, log attempt, leave VM, batch-message, export.
   ============================================================ */
function StaffingMode({ candidates, selectedId, onSelect }) {
  // Today's queue = anything that needs a human touch right now.
  const queue = candidates.filter(c =>
    c.stage === 'sourcing' || (c.stage === 'engaged' && (c.unread || c.justLanded || /awaiting|reminder/i.test(c.lastMsg || '')))
  ).slice(0, 14);

  return (
    <React.Fragment>
      {/* Queue stats strip */}
      <div style={{
        margin: '8px 18px 0', padding: '10px 12px',
        background: SGC.shade[880], color: '#fff', borderRadius: 8,
        display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14,
      }}>
        <QStat n={queue.length} label="In queue" col="#fff"/>
        <QStat n={42}            label="Calls today" col="#9FF6C1"/>
        <QStat n={11}            label="Connected" col="#9FF6C1"/>
        <QStat n="3:42"          label="Avg talk" col="#FFC8FF"/>
      </div>

      <div style={{
        padding: '10px 18px 8px', display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap',
      }}>
        <span style={{ fontSize: 11, fontWeight: 700, color: SGC.shade[700], textTransform: 'uppercase', letterSpacing: '.06em' }}>Today's queue</span>
        <div style={{ flex: 1 }}/>
        <button style={iconBtn}>📞 Dial all</button>
        <button style={iconBtn}>✉ Bulk SMS</button>
        <button style={iconBtn}>↓ Export</button>
      </div>

      <div style={{ flex: 1, overflow: 'auto', borderTop: `1px solid ${SGC.tint[80]}` }}>
        {queue.map((c, i) => (
          <StaffingRow key={c.id} c={c} idx={i + 1}
            selected={c.id === selectedId} onSelect={onSelect}/>
        ))}
      </div>
    </React.Fragment>
  );
}

const iconBtn = {
  display: 'inline-flex', alignItems: 'center', gap: 4, padding: '5px 10px',
  background: '#fff', border: `1px solid ${SGC.tint[100]}`, borderRadius: 6,
  fontSize: 12, fontWeight: 600, color: SGC.shade[820], cursor: 'pointer',
};

function QStat({ n, label, col }) {
  return (
    <div>
      <div style={{ fontSize: 18, fontWeight: 800, color: col, lineHeight: 1.1, fontVariantNumeric: 'tabular-nums' }}>{n}</div>
      <div style={{ fontSize: 10.5, color: 'rgba(255,255,255,.65)', marginTop: 1 }}>{label}</div>
    </div>
  );
}

function StaffingRow({ c, idx, selected, onSelect }) {
  return (
    <div onClick={() => onSelect?.(c.id)} style={{
      position: 'relative', padding: '10px 18px 10px 14px',
      borderBottom: `1px solid ${SGC.tint[80]}`, cursor: 'pointer',
      background: selected ? SGC.highlight[50] + '66' : '#fff',
      display: 'flex', alignItems: 'center', gap: 10,
    }}>
      {selected && <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: SGC.highlight[500] }}/>}
      <span style={{
        width: 22, fontSize: 11, fontWeight: 700, color: SGC.shade[700],
        textAlign: 'right', flex: 'none', fontVariantNumeric: 'tabular-nums',
      }}>{idx}</span>

      <div style={{
        width: 28, height: 28, borderRadius: '50%', background: SGC.tint[60],
        color: SGC.shade[820], display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 11, fontWeight: 700, flex: 'none',
      }}>{c.name.split(' ').map(s => s[0]).slice(0, 2).join('')}</div>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <h3 style={{ margin: 0, fontSize: 13, fontWeight: 700, color: SGC.shade[880], whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.name}</h3>
          <span style={{ fontSize: 10.5, color: SGC.shade[700], flex: 'none' }}>★{c.score}</span>
        </div>
        <div style={{ fontSize: 11.5, color: SGC.shade[700], whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {c.role} · {c.loc.split(',')[0]}
        </div>
      </div>

      <div style={{
        fontSize: 10.5, color: SGC.shade[700], fontFamily: 'ui-monospace,SFMono-Regular,monospace',
        flex: 'none', minWidth: 92, textAlign: 'right',
      }}>336-{200 + ((c.id.charCodeAt(0) * 7) % 800)}-{1000 + ((c.id.charCodeAt(1) || 0) * 17) % 9000}</div>

      <button onClick={e => e.stopPropagation()} style={{
        padding: '5px 10px', background: SGC.primary[500], color: '#fff',
        border: 0, borderRadius: 6, fontSize: 12, fontWeight: 700, cursor: 'pointer', flex: 'none',
      }}>Call</button>
    </div>
  );
}

/* ============================================================
   EMPLOYER MODE — calm, decision-focused
   The atom: candidate-ready-to-decide.
   Verbs: schedule, hire, reject. No dialer. No sequence.
   No sourcing mechanics. Just "what needs your call?"
   ============================================================ */
function EmployerMode({ candidates, selectedId, onSelect }) {
  const ready    = candidates.filter(c => (c.unread || c.justLanded) && c.stage === 'engaged');
  const inFlight = candidates.filter(c => c.stage === 'engaged' && !c.unread && !c.justLanded
                                       && /scheduled|confirmed|booked|i'm still interested/i.test(c.lastMsg || ''));
  const waiting  = candidates.filter(c => c.stage === 'engaged' && /awaiting|sent reminder|screening questions/i.test(c.lastMsg || ''));

  return (
    <div style={{ flex: 1, overflow: 'auto' }}>
      <Section title="Decisions needed" hint="The AI has done its part. Your call." count={ready.length}>
        {ready.map(c => <EmployerRow key={c.id} c={c} kind="decide"
          selected={c.id === selectedId} onSelect={onSelect}/>)}
      </Section>

      <Section title="Interviews this week" hint="Already scheduled." count={inFlight.length}>
        {inFlight.map(c => <EmployerRow key={c.id} c={c} kind="interview"
          selected={c.id === selectedId} onSelect={onSelect}/>)}
        {!inFlight.length && <Empty>Nothing scheduled yet.</Empty>}
      </Section>

      <Section title="Waiting on candidate" hint="No action needed — they have the ball." count={waiting.length} dim>
        {waiting.slice(0, 3).map(c => <EmployerRow key={c.id} c={c} kind="waiting"
          selected={c.id === selectedId} onSelect={onSelect}/>)}
      </Section>

      <div style={{ padding: '20px 22px', fontSize: 11, color: SGC.shade[600], lineHeight: 1.5, borderTop: `1px solid ${SGC.tint[80]}` }}>
        Your AI recruiter is sourcing, contacting, and screening candidates in the background. 17 in progress. <a href="#" onClick={e => e.preventDefault()} style={{ color: SGC.shade[820], fontWeight: 600 }}>See activity →</a>
      </div>
    </div>
  );
}

function Section({ title, hint, count, dim, children }) {
  return (
    <div style={{ padding: '14px 22px 4px', opacity: dim ? .75 : 1 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 2 }}>
        <h3 style={{ margin: 0, fontSize: 15, fontWeight: 800, color: SGC.shade[880], letterSpacing: '-.005em' }}>{title}</h3>
        <span style={{ fontSize: 12, color: SGC.shade[700], fontVariantNumeric: 'tabular-nums' }}>{count}</span>
      </div>
      <div style={{ fontSize: 12, color: SGC.shade[700], marginBottom: 10 }}>{hint}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 12 }}>
        {children}
      </div>
    </div>
  );
}

function Empty({ children }) {
  return (
    <div style={{
      padding: '14px', textAlign: 'center', color: SGC.shade[700], fontSize: 12,
      border: `1px dashed ${SGC.tint[100]}`, borderRadius: 8,
    }}>{children}</div>
  );
}

function EmployerRow({ c, kind, selected, onSelect }) {
  return (
    <div onClick={() => onSelect?.(c.id)} style={{
      position: 'relative', padding: '12px 14px', borderRadius: 10,
      border: `1px solid ${selected ? SGC.highlight[500] : SGC.tint[80]}`,
      background: selected ? SGC.highlight[50] + '66' : '#fff',
      cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: '50%', background: SGC.tint[60],
        color: SGC.shade[820], display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 13, fontWeight: 700, flex: 'none',
      }}>{c.name.split(' ').map(s => s[0]).slice(0, 2).join('')}</div>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
          <h4 style={{ margin: 0, fontSize: 14, fontWeight: 700, color: SGC.shade[880] }}>{c.name}</h4>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 3, padding: '1px 5px 1px 3px',
            background: SGC.primary[500], color: '#fff', fontSize: 10.5, fontWeight: 700, borderRadius: 3,
          }}>★{c.score}</span>
        </div>
        <div style={{ fontSize: 12, color: SGC.shade[700], whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {kind === 'interview' && <span>📅 {c.lastMsg || 'Phone screen scheduled'}</span>}
          {kind === 'decide'    && <span style={{ color: SGC.shade[820] }}>"{c.lastMsg || 'Interested — what shift?'}"</span>}
          {kind === 'waiting'   && <span>{c.lastMsg || 'Awaiting response'} · {c.time.replace(/^May 1[12] /, '')}</span>}
        </div>
      </div>

      {kind === 'decide' && (
        <div style={{ display: 'flex', gap: 6, flex: 'none' }}>
          <button onClick={e => e.stopPropagation()} style={ghostBtn}>Reject</button>
          <button onClick={e => e.stopPropagation()} style={primaryBtn}>Schedule</button>
        </div>
      )}
      {kind === 'interview' && (
        <button onClick={e => e.stopPropagation()} style={ghostBtn}>View details</button>
      )}
      {kind === 'waiting' && (
        <span style={{ fontSize: 11, color: SGC.shade[700], flex: 'none' }}>Day 2</span>
      )}
    </div>
  );
}

const ghostBtn = {
  padding: '6px 12px', background: '#fff', border: `1px solid ${SGC.tint[100]}`,
  borderRadius: 6, fontSize: 12, fontWeight: 600, color: SGC.shade[820], cursor: 'pointer',
};
const primaryBtn = {
  padding: '6px 12px', background: SGC.shade[880], color: '#fff',
  border: 0, borderRadius: 6, fontSize: 12, fontWeight: 600, cursor: 'pointer',
};

Object.assign(window, { LayoutSegment });
