// Screen 1 — CCC Triage Dashboard · v2
// Switchboard view for the team leader. Delegation is the centerpiece.
// Clicking the Glad row → Screen 2 (reply review).

const { useState: useDash } = React;

/* -------------------- Team + queue data -------------------- */
const PEOPLE = {
  sarah:  { id: 'sarah',  type: 'person', initials: 'SM', name: 'Sarah Mitchell', short: 'Sarah M.', role: 'Team lead',     load: 1, cap: 6, online: true },
  jay:    { id: 'jay',    type: 'person', initials: 'JC', name: 'Jay Chen',       short: 'Jay C.',   role: 'CCC · Tier 1',  load: 5, cap: 8, online: true },
  priya:  { id: 'priya',  type: 'person', initials: 'PN', name: 'Priya Nair',     short: 'Priya N.', role: 'CCC',            load: 3, cap: 8, online: true },
  marco:  { id: 'marco',  type: 'person', initials: 'MR', name: 'Marco Russo',    short: 'Marco R.', role: 'CCC',            load: 4, cap: 8, online: true },
  tom:    { id: 'tom',    type: 'person', initials: 'TA', name: 'Tom Aulsebrook', short: 'Tom A.',   role: 'CCC',            load: 2, cap: 8, online: true },
  ben:    { id: 'ben',    type: 'person', initials: 'BK', name: 'Ben Kowalski',   short: 'Ben K.',   role: 'CCC',            load: 0, cap: 8, online: false },
  accts:  { id: 'accts',  type: 'team',   initials: 'AC', name: 'Accounts',       short: 'Accounts',      role: '2 of 4 online', load: 7, cap: 16, online: true },
  svcadm: { id: 'svcadm', type: 'team',   initials: 'SA', name: 'Service Admin',  short: 'Service Admin', role: '1 of 2 online', load: 5, cap: 8,  online: true },
  whse:   { id: 'whse',   type: 'team',   initials: 'WH', name: 'Warehouse',      short: 'Warehouse',     role: '3 of 4 online', load: 4, cap: 16, online: true },
};

const QUEUE = [
  {
    id: 'wool2', priority: 'p1', priorityWhy: 'Tier-1 client · breakdown · SLA breach in 48 min',
    tier: 'Tier 1', client: 'Woolworths Group', site: 'Marsden Park RDC, NSW',
    subject: 'T16 #T16-AU2218 — fault E-47, scrubber down',
    category: 'Breakdown',
    assigneeId: 'jay', assignedBy: 'ai', rule: 'Breakdown / parts → CCC by availability',
    statusLine: 'In progress · Jay diagnosing',
    sla: '48m', slaState: 'crit',
  },
  {
    id: 'bun', priority: 'atrisk', priorityWhy: 'Tier-1 client · SLA in 2 h 11 m',
    tier: 'Tier 1', client: 'Bunnings Group', site: 'Hawthorn, VIC',
    subject: 'Cylindrical brush deck — what fits the T16 serial 4129-AU?',
    category: 'Parts request',
    assigneeId: 'marco', assignedBy: 'manual', reassignedFrom: 'Tom A.', rule: null,
    statusLine: 'AI draft ready · 2 part options',
    aiDraft: true,
    sla: '2h 11m', slaState: 'warn',
  },
  {
    id: 'wool1', priority: 'atrisk', priorityWhy: 'Tier-1 client · SLA in 2 h 45 m',
    tier: 'Tier 1', client: 'Woolworths Group', site: 'Erskine Park DC, NSW',
    subject: 'Re: Invoice EF4933 — site visit confirmation required',
    category: 'Invoice query',
    assigneeId: 'accts', assignedBy: 'ai', rule: 'Invoice queries → Accounts',
    statusLine: 'Routed to Accounts at 02:14',
    sla: '2h 45m', slaState: 'warn',
  },
  {
    id: 'glad', priority: 'atrisk', priorityWhy: 'Tier-1 client · SLA in 3 h 20 m',
    tier: 'Tier 1', client: 'Glad Manufacturing', site: 'Smithfield Plant, NSW',
    subject: 'Squeegee for the T20 keeps coming loose — can you sort us out?',
    category: 'Parts request',
    assigneeId: 'priya', assignedBy: 'ai', rule: 'Breakdown / parts → CCC by availability',
    statusLine: 'AI draft ready · awaiting approval',
    aiDraft: true,
    sla: '3h 20m', slaState: 'warn',
    target: 2,
  },
  {
    id: 'coles', priority: 'normal', priorityWhy: 'Tier-1 client · 4 h 55 m to SLA · scheduling',
    tier: 'Tier 1', client: 'Coles Group', site: 'Eastern Creek DC, NSW',
    subject: 'Re: Q2 service plan — Tier 1 review',
    category: 'Service scheduling',
    assigneeId: 'sarah', assignedBy: 'manual', reassignedFrom: 'Priya N.', rule: null,
    statusLine: 'AI draft ready · you edited',
    aiDraft: true, feedbackOpen: true,
    sla: '4h 55m', slaState: 'normal',
  },
  {
    id: 'rental', priority: 'normal', priorityWhy: 'Tier-2 · routine purchase order',
    tier: 'Tier 2', client: 'Ace Rental · Penrith', site: 'Penrith depot, NSW',
    subject: 'Order status — PO 22418, S30 sweeper hire',
    category: 'Purchase order',
    assigneeId: 'svcadm', assignedBy: 'ai', rule: 'Purchase orders → Service Admin',
    statusLine: 'Auto-replied · ETA confirmed Wed 06:30',
    sla: '+1 day', slaState: 'normal',
  },
  {
    id: 'auck', priority: 'normal', priorityWhy: 'Tier-2 · stock query',
    tier: 'Tier 2', client: 'Auckland Council', site: 'Henderson depot, NZ',
    subject: 'Need price on 4 × T7 pad drivers — NZ stock?',
    category: 'Stock check',
    assigneeId: 'whse', assignedBy: 'ai', rule: 'Stock queries → Warehouse',
    statusLine: 'Awaiting NZ10 stock confirmation',
    sla: '+1 day', slaState: 'normal',
  },
  {
    id: 'aldi', priority: 'normal', priorityWhy: 'Tier-2 · thank-you, no action required',
    tier: 'Tier 2', client: 'ALDI Stores', site: 'Minchinbury DC, NSW',
    subject: 'Thanks — quick note on Friday\'s callout',
    category: 'Thank-you',
    assigneeId: 'tom', assignedBy: 'ai', rule: 'Thank-you → log to operator',
    statusLine: 'Acknowledged · logged to Jay\'s record',
    sla: '+2 days', slaState: 'normal',
  },
];

const ARCHIVED = [
  { n: 12, why: 'Duplicate PO confirmations from customer portal', rule: 'Portal-confirmed PO duplicate' },
  { n: 18, why: 'Out-of-office auto-replies',                       rule: 'OOO / auto-reply detected' },
  { n: 9,  why: 'Marketing & newsletter subscriptions',             rule: 'Promotional sender list' },
  { n: 8,  why: 'Read-receipt / delivery notifications',            rule: 'System notification' },
];

const RULE_TABS = [
  {
    k: 'active',
    label: 'Active',
    rules: [
      { if: 'Purchase orders',                then: 'Service Admin',                  matches: 47, lastFired: '06:12' },
      { if: 'Invoice queries',                then: 'Accounts',                       matches: 33, lastFired: '06:14' },
      { if: 'Breakdown / parts',              then: 'Customer Care — by availability', matches: 22, lastFired: '06:21' },
      { if: 'Stock & price checks',           then: 'Warehouse',                      matches: 14, lastFired: '06:18' },
      { if: 'Portal-confirmed PO duplicates', then: 'Auto-archive',                   matches: 12, lastFired: '05:48' },
    ],
  },
  {
    k: 'suggested',
    label: 'Suggested',
    rules: [
      { if: 'Battery fault / E-47 keywords', then: 'Jay Chen — escalate priority',  basis: 'Pattern · 9 hits this week, all Jay handled' },
      { if: 'NZ stock keywords',              then: 'Warehouse NZ10 — direct',        basis: 'Pattern · 6 hits routed via CCC then forwarded' },
      { if: 'Thank-you / closure',            then: 'Auto-log · no human',            basis: 'Pattern · 14 hits, 0 needed action' },
    ],
    suggested: true,
  },
  {
    k: 'paused',
    label: 'Paused',
    rules: [
      { if: 'Newsletter & marketing',         then: 'Auto-archive', pausedSince: '12 May', pausedBy: 'Sarah M.', note: 'Customer complained about one missed legitimate email' },
    ],
    paused: true,
  },
];

/* -------------------- Small pieces -------------------- */

function PriorityBadge({ row }) {
  const label = row.priority === 'p1' ? 'P1' : row.priority === 'atrisk' ? 'At risk' : 'Normal';
  return (
    <span className={'pri ' + row.priority} onClick={(e) => e.stopPropagation()}>
      {label}
      <span className="ttip">{row.priorityWhy}</span>
    </span>
  );
}

function AssigneeChip({ row, open, onToggle, onPick }) {
  const p = PEOPLE[row.assigneeId];
  if (!p) return null;
  const isTeam = p.type === 'team';
  return (
    <div style={{ position: 'relative', display: 'inline-block' }}>
      <div
        className={'asg ' + (isTeam ? 'team ' : '') + (row.assignedBy === 'manual' ? 'manual' : 'ai')}
        onClick={(e) => { e.stopPropagation(); onToggle(); }}
        title={row.assignedBy === 'ai' ? ('Auto-assigned · ' + (row.rule || 'by availability')) : ('Reassigned from ' + (row.reassignedFrom || 'auto-assignment'))}
      >
        <div className="av">
          {p.initials}
          <span className="src">{row.assignedBy === 'ai' ? 'AI' : 'M'}</span>
        </div>
        <div className="col">
          <div className="nm">{p.short}</div>
          <div className="ro">{isTeam ? 'team' : p.role.replace('CCC · ', '').replace('CCC', 'CCC')}</div>
        </div>
        <Icon name="chevron_down" size={12} className="cv" />
      </div>
      {open && <ReassignMenu currentId={row.assigneeId} onPick={onPick} onClose={onToggle} />}
    </div>
  );
}

function ReassignMenu({ currentId, onPick }) {
  const people = ['sarah', 'jay', 'priya', 'marco', 'tom', 'ben'];
  const teams = ['accts', 'svcadm', 'whse'];
  const Row = ({ id }) => {
    const p = PEOPLE[id];
    return (
      <div className={'opt' + (id === currentId ? ' current' : '')} onClick={(e) => { e.stopPropagation(); onPick(id); }}>
        <div style={{
          width: 22, height: 22, borderRadius: p.type === 'team' ? 4 : 999,
          background: p.type === 'team' ? 'var(--tn-steel-200)' : 'var(--tn-steel-300)',
          color: 'var(--fg-1)', display: 'grid', placeItems: 'center',
          fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 10
        }}>{p.initials}</div>
        <div>
          <div className="nm">{p.name}</div>
          <div className="lo" style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--fg-3)' }}>{p.role}</div>
        </div>
        <div className="lo">{p.load}/{p.cap}</div>
      </div>
    );
  };
  return (
    <div className="reassign-menu" onClick={(e) => e.stopPropagation()}>
      <div className="grp">Customer Care</div>
      {people.map(id => <Row key={id} id={id} />)}
      <div className="grp">Other teams</div>
      {teams.map(id => <Row key={id} id={id} />)}
    </div>
  );
}

function ApprovalBar({ onReject, onEdit }) {
  return (
    <div className="approve-bar" onClick={(e) => e.stopPropagation()}>
      <button className="approve"><Icon name="check" size={11} stroke={2.5} />Approve & send</button>
      <button onClick={onEdit}><Icon name="edit" size={11} />Edit</button>
      <button className="reject" onClick={onReject}><Icon name="x" size={11} />Reject</button>
    </div>
  );
}

function FeedbackRow() {
  return (
    <div className="feedback-box" onClick={(e) => e.stopPropagation()}>
      <div className="h"><Icon name="sparkles" size={11} />Help the model improve — one line, why did you edit?</div>
      <div className="input">
        <input defaultValue="Customer asked for Truganina-specific schedule; AI used the generic Q2 template." />
        <button className="save">Save & send</button>
      </div>
      <div className="quick">
        <span style={{ fontSize: 11, color: '#5C4400', alignSelf: 'center', marginRight: 4 }}>Quick reasons:</span>
        <button className="qbtn">Wrong tone</button>
        <button className="qbtn">Missing context</button>
        <button className="qbtn">Wrong recipient</button>
        <button className="qbtn">Out of date info</button>
      </div>
    </div>
  );
}

/* -------------------- Main screen -------------------- */
const FILTER_CHIPS = [
  { k: 'all',   l: 'All',            test: () => true },
  { k: 'mine',  l: 'Awaiting me',    test: (r) => !!r.aiDraft },
  { k: 'ccc',   l: 'Customer Care',  test: (r) => PEOPLE[r.assigneeId].type === 'person' },
  { k: 'other', l: 'Other teams',    test: (r) => PEOPLE[r.assigneeId].type === 'team' },
  { k: 'ai',    l: 'Auto-handled',   test: (r) => r.assignedBy === 'ai' && !r.aiDraft },
];

const SORT_OPTIONS = [
  { k: 'pri-sla', l: 'Priority, then SLA' },
  { k: 'sla',     l: 'SLA urgency' },
  { k: 'tier',    l: 'Customer tier' },
  { k: 'newest',  l: 'Newest first' },
];

const SUB_FILTERS = [
  { k: 'tier1',     l: 'Tier 1 only',          test: (r) => r.tier === 'Tier 1' },
  { k: 'aiDraft',   l: 'Has AI draft',         test: (r) => !!r.aiDraft },
  { k: 'manual',    l: 'Manually reassigned',  test: (r) => r.assignedBy === 'manual' },
  { k: 'sla-warn',  l: 'SLA warn or critical', test: (r) => r.slaState === 'warn' || r.slaState === 'crit' },
];

const PRI_RANK = { p1: 0, atrisk: 1, normal: 2 };
const SLA_RANK = (r) => r.slaState === 'crit' ? 0 : r.slaState === 'warn' ? 1 : 2;
const TIER_RANK = (r) => r.tier === 'Tier 1' ? 0 : r.tier === 'Tier 2' ? 1 : 2;

function ScreenDashboard({ onNavigate }) {
  const [filter, setFilter] = useDash('all');
  const [archiveOpen, setArchiveOpen] = useDash(false);
  const [openMenu, setOpenMenu] = useDash(null);
  const [rows, setRows] = useDash(QUEUE);
  const [feedbackId, setFeedbackId] = useDash('coles');
  const [sortFilterOpen, setSortFilterOpen] = useDash(false);
  const [sortBy, setSortBy] = useDash('pri-sla');
  const [subActive, setSubActive] = useDash([]); // sub-filter keys
  const [assigneeFilter, setAssigneeFilter] = useDash([]); // person/team ids
  const [ruleTab, setRuleTab] = useDash('active');

  const archivedTotal = ARCHIVED.reduce((s, r) => s + r.n, 0);

  // Apply chip filter + sub-filters + sort
  const visibleRows = (() => {
    const chip = FILTER_CHIPS.find(c => c.k === filter);
    let out = rows.filter(r => chip ? chip.test(r) : true);
    for (const key of subActive) {
      const sf = SUB_FILTERS.find(s => s.k === key);
      if (sf) out = out.filter(sf.test);
    }
    if (assigneeFilter.length) {
      out = out.filter(r => assigneeFilter.includes(r.assigneeId));
    }
    const sorted = [...out];
    if (sortBy === 'pri-sla') {
      sorted.sort((a, b) => (PRI_RANK[a.priority] - PRI_RANK[b.priority]) || (SLA_RANK(a) - SLA_RANK(b)));
    } else if (sortBy === 'sla') {
      sorted.sort((a, b) => SLA_RANK(a) - SLA_RANK(b));
    } else if (sortBy === 'tier') {
      sorted.sort((a, b) => TIER_RANK(a) - TIER_RANK(b));
    }
    return sorted;
  })();

  // Counts per chip (filtered against current sub-filters so they don't lie)
  const chipCounts = FILTER_CHIPS.reduce((acc, c) => {
    let pool = rows.filter(c.test);
    for (const key of subActive) {
      const sf = SUB_FILTERS.find(s => s.k === key);
      if (sf) pool = pool.filter(sf.test);
    }
    if (assigneeFilter.length) {
      pool = pool.filter(r => assigneeFilter.includes(r.assigneeId));
    }
    acc[c.k] = pool.length;
    return acc;
  }, {});

  const reassign = (rowId, newAssigneeId) => {
    setRows(rs => rs.map(r => r.id === rowId
      ? { ...r, assigneeId: newAssigneeId, assignedBy: 'manual', reassignedFrom: PEOPLE[r.assigneeId].short }
      : r));
    setOpenMenu(null);
  };

  const toggleSub = (k) => {
    setSubActive(prev => prev.includes(k) ? prev.filter(x => x !== k) : [...prev, k]);
  };

  const toggleAssignee = (id) => {
    setAssigneeFilter(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  };

  const clearFilters = () => {
    setSortBy('pri-sla');
    setSubActive([]);
    setAssigneeFilter([]);
  };

  const handleRowClick = (row) => {
    if (row.target) onNavigate(row.target);
  };

  return (
    <div className="screen" data-screen-label="01 Switchboard">
      {/* Header */}
      <div className="dash-head" data-comment-anchor="dash-head">
        <div>
          <h1>Inbox · Mon 18 May</h1>
          <div className="meta" style={{ marginTop: 3 }}>142 inbound today · 0 backlog · 38 m avg first response</div>
        </div>
        <div className="right">
          <div className="learn-badge" title="AI updates from your edits and rejections this week">
            <Icon name="sparkles" size={13} className="ic" />
            AI improved from <b>14 corrections</b> this week
            <a>see log</a>
          </div>
          <button className="tn-btn tn-btn--ghost tn-btn--sm">Compose</button>
        </div>
      </div>

      {/* Stats strip — flat, the one Jye called out */}
      <div className="stats-strip" data-comment-anchor="stats">
        <div className="cell">
          <div className="lab">Processing</div>
          <div className="num">14</div>
          <div className="sub">Being classified now</div>
        </div>
        <div className="cell">
          <div className="lab">AI drafted</div>
          <div className="num">24</div>
          <div className="sub">Reply written, not sent</div>
        </div>
        <div className="cell needs">
          <div className="lab">Awaiting approval</div>
          <div className="num">8</div>
          <div className="sub">Your queue · 3 over 2 h old</div>
        </div>
        <div className="cell">
          <div className="lab">Auto-handled</div>
          <div className="num">243</div>
          <div className="sub">No human touch needed</div>
        </div>
      </div>

      {/* Auto-archived strip */}
      <div className={'archive-strip' + (archiveOpen ? ' open' : '')} onClick={() => setArchiveOpen(o => !o)} data-comment-anchor="archive">
        <Icon name="filter" size={14} className="ic" />
        <div><span className="n">{archivedTotal}</span> filtered out this morning — didn't need a human</div>
        <div className="more">{archiveOpen ? 'hide' : 'view rules'} <Icon name={archiveOpen ? 'chevron_left' : 'chevron_right'} size={11} /></div>
      </div>
      {archiveOpen && (
        <div className="archive-detail">
          {ARCHIVED.map((a, i) => (
            <div className="row" key={i}>
              <div className="n">{a.n}</div>
              <div className="why">{a.why}</div>
              <div className="rule">rule · {a.rule}</div>
            </div>
          ))}
        </div>
      )}

      {/* Full-width queue — columned, neat, no row dividers */}
      <div className="q-card" onClick={() => { setOpenMenu(null); setSortFilterOpen(false); }}>
        <div className="q-filters">
          {FILTER_CHIPS.map(c => (
            <span
              key={c.k}
              className={'q-chip' + (filter === c.k ? ' is-active' : '')}
              onClick={(e) => { e.stopPropagation(); setFilter(c.k); }}
            >
              {c.l} <span className="ct">{chipCounts[c.k]}</span>
            </span>
          ))}
          <div className="right" style={{ position: 'relative' }}>
            <button
              className={'filter-btn' + (sortBy !== 'pri-sla' || subActive.length || assigneeFilter.length ? ' active' : '')}
              onClick={(e) => { e.stopPropagation(); setSortFilterOpen(o => !o); }}
            >
              <Icon name="filter" size={13} />
              Sort &amp; filter
              {(sortBy !== 'pri-sla' || subActive.length > 0 || assigneeFilter.length > 0) && (
                <span className="dot">{(sortBy !== 'pri-sla' ? 1 : 0) + subActive.length + assigneeFilter.length}</span>
              )}
              <Icon name="chevron_down" size={11} />
            </button>
            {sortFilterOpen && (
              <div className="sf-pop" onClick={(e) => e.stopPropagation()}>
                <div className="sf-section">
                  <div className="sf-h">Sort by</div>
                  {SORT_OPTIONS.map(o => (
                    <label key={o.k} className={'sf-opt' + (sortBy === o.k ? ' is-on' : '')}>
                      <input
                        type="radio"
                        name="sortby"
                        checked={sortBy === o.k}
                        onChange={() => setSortBy(o.k)}
                      />
                      <span className="sf-radio"></span>
                      <span>{o.l}</span>
                    </label>
                  ))}
                </div>
                <div className="sf-section">
                  <div className="sf-h">Filter by</div>
                  {SUB_FILTERS.map(o => (
                    <label key={o.k} className={'sf-opt' + (subActive.includes(o.k) ? ' is-on' : '')}>
                      <input
                        type="checkbox"
                        checked={subActive.includes(o.k)}
                        onChange={() => toggleSub(o.k)}
                      />
                      <span className="sf-check">{subActive.includes(o.k) && <Icon name="check" size={10} stroke={3} />}</span>
                      <span>{o.l}</span>
                    </label>
                  ))}
                </div>

                <div className="sf-section">
                  <div className="sf-h">
                    Assignee
                    {assigneeFilter.length > 0 && (
                      <span className="sf-clear-inline" onClick={() => setAssigneeFilter([])}>clear ({assigneeFilter.length})</span>
                    )}
                  </div>
                  <div className="sf-asg-grp">Customer Care</div>
                  {['sarah', 'jay', 'priya', 'marco', 'tom', 'ben'].map(id => {
                    const p = PEOPLE[id];
                    const on = assigneeFilter.includes(id);
                    return (
                      <label key={id} className={'sf-opt sf-opt-asg' + (on ? ' is-on' : '')}>
                        <input
                          type="checkbox"
                          checked={on}
                          onChange={() => toggleAssignee(id)}
                        />
                        <span className="sf-check">{on && <Icon name="check" size={10} stroke={3} />}</span>
                        <span className="sf-av" style={{ borderRadius: 999 }}>
                          {p.initials}
                          <span className={'sf-on' + (p.online ? '' : ' off')}></span>
                        </span>
                        <span className="sf-asg-nm">{p.short}</span>
                        <span className="sf-asg-load">{p.load}/{p.cap}</span>
                      </label>
                    );
                  })}
                  <div className="sf-asg-grp">Other teams</div>
                  {['accts', 'svcadm', 'whse'].map(id => {
                    const p = PEOPLE[id];
                    const on = assigneeFilter.includes(id);
                    return (
                      <label key={id} className={'sf-opt sf-opt-asg' + (on ? ' is-on' : '')}>
                        <input
                          type="checkbox"
                          checked={on}
                          onChange={() => toggleAssignee(id)}
                        />
                        <span className="sf-check">{on && <Icon name="check" size={10} stroke={3} />}</span>
                        <span className="sf-av" style={{ borderRadius: 4 }}>{p.initials}</span>
                        <span className="sf-asg-nm">{p.name}</span>
                        <span className="sf-asg-load">{p.load}/{p.cap}</span>
                      </label>
                    );
                  })}
                </div>
                <div className="sf-foot">
                  <button className="sf-clear" onClick={clearFilters}>Clear</button>
                  <button className="sf-done" onClick={() => setSortFilterOpen(false)}>Done</button>
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="q-grid">
          <div className="q-grid-head">
            <div>Priority</div>
            <div>Customer · subject</div>
            <div>Category</div>
            <div>Assignee</div>
            <div>Status</div>
          </div>

          {visibleRows.length === 0 ? (
            <div className="q-empty">
              <div className="ttl">Nothing matches these filters.</div>
              <div className="sub">Try clearing a filter or switching to <a onClick={() => setFilter('all')}>All</a>.</div>
            </div>
          ) : visibleRows.map(r => (
            <React.Fragment key={r.id}>
              <div
                className={'q-grid-row' + (r.feedbackOpen && feedbackId === r.id ? ' row-feedback' : '')}
                onClick={() => handleRowClick(r)}
              >
                <div className="cell cell-pri"><PriorityBadge row={r} /></div>
                <div className="cell cell-cust">
                  <div className="cust-head">
                    <span className={'tn-tier tn-tier--' + (r.tier === 'Tier 1' ? 'gold' : r.tier === 'Tier 2' ? 'silver' : 'standard')}>{r.tier}</span>
                    <span className="cust-name">{r.client}</span>
                  </div>
                  <div className="cust-subj">{r.subject}</div>
                  <div className="cust-site">{r.site}</div>
                </div>
                <div className="cell cell-cat"><span className="cat">{r.category}</span></div>
                <div className="cell cell-asg">
                  <AssigneeChip
                    row={r}
                    open={openMenu === r.id}
                    onToggle={() => setOpenMenu(m => m === r.id ? null : r.id)}
                    onPick={(newId) => reassign(r.id, newId)}
                  />
                  {r.reassignedFrom && (
                    <div className="reassigned-from">← from {r.reassignedFrom}</div>
                  )}
                </div>
                <div className="cell cell-sla">
                  <div className={'sla-line ' + (r.slaState || '')}>SLA · {r.sla}</div>
                  <div className="status-line">{r.statusLine}</div>
                  {r.aiDraft && (
                    <span className="ai-pill ready" style={{ marginTop: 8 }}><span className="d"></span>AI draft ready</span>
                  )}
                  {r.aiDraft && (
                    <ApprovalBar
                      onReject={() => setFeedbackId(r.id)}
                      onEdit={() => r.target ? onNavigate(r.target) : setFeedbackId(r.id)}
                    />
                  )}
                </div>
              </div>
              {r.feedbackOpen && feedbackId === r.id && (
                <div className="q-grid-feedback" onClick={(e) => e.stopPropagation()}>
                  <FeedbackRow />
                </div>
              )}
            </React.Fragment>
          ))}
        </div>

        <div className="q-foot">
          <div>Showing {visibleRows.length} of {rows.length} in this view · 142 inbound today</div>
          <div>Last sync 06:28 · next 06:58</div>
        </div>
      </div>

      {/* Below queue — Team availability + Auto-assignment rules side by side */}
      <div className="below-queue" data-comment-anchor="below-queue">
        <div className="rcard rcard--wide" data-comment-anchor="team-availability">
          <h4>Team availability · who has the ball
            <span className="ed"><Icon name="external" size={11} />roster</span>
          </h4>
          <div className="team-grid">
            {['sarah', 'jay', 'priya', 'marco', 'tom', 'ben'].map(id => {
              const p = PEOPLE[id];
              const pct = Math.round((p.load / p.cap) * 100);
              return (
                <div key={id} className="team-cell">
                  <div className="av">
                    {p.initials}
                    <span className={'on' + (p.online ? '' : ' off')}></span>
                  </div>
                  <div className="who">
                    <div className="nm">{p.short}</div>
                    <div className="ro">{p.role}</div>
                  </div>
                  <div className="load">
                    <div className="b"><i className={pct >= 75 ? 'full' : ''} style={{ width: pct + '%' }}></i></div>
                    <div className="n">{p.load}/{p.cap}</div>
                  </div>
                </div>
              );
            })}
          </div>

          <div className="team-divider">Other teams</div>
          <div className="team-grid">
            {['accts', 'svcadm', 'whse'].map(id => {
              const p = PEOPLE[id];
              const pct = Math.round((p.load / p.cap) * 100);
              return (
                <div key={id} className="team-cell team">
                  <div className="av">{p.initials}</div>
                  <div className="who">
                    <div className="nm">{p.name}</div>
                    <div className="ro">{p.role}</div>
                  </div>
                  <div className="load">
                    <div className="b"><i className={pct >= 75 ? 'full' : ''} style={{ width: pct + '%' }}></i></div>
                    <div className="n">{p.load}/{p.cap}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="rcard rcard--rules" data-comment-anchor="rules">
          <div className="rules-head">
            <h4 style={{ margin: 0, padding: 0, border: 0 }}>Auto-assignment rules</h4>
            <span className="rules-edit"><Icon name="edit" size={11} />edit</span>
          </div>

          <div className="rules-tabs" role="tablist">
            {RULE_TABS.map(t => (
              <div
                key={t.k}
                role="tab"
                aria-selected={ruleTab === t.k}
                className={'rules-tab' + (ruleTab === t.k ? ' is-active' : '')}
                onClick={() => setRuleTab(t.k)}
              >
                {t.label}
                <span className="rules-tab-ct">{t.rules.length}</span>
              </div>
            ))}
          </div>

          <div className="rules-body">
            {(() => {
              const tab = RULE_TABS.find(t => t.k === ruleTab);
              return tab.rules.map((r, i) => (
                <div key={i} className={'rule-row' + (tab.paused ? ' is-paused' : '') + (tab.suggested ? ' is-suggested' : '')}>
                  <div className="rule-main">
                    <span className="if">{r.if}</span>
                    <span className="arr">→</span>
                    <span className="then">{r.then}</span>
                  </div>
                  {tab.k === 'active' && (
                    <div className="rule-foot-line">
                      <span>{r.matches} matches today</span>
                      <span>·</span>
                      <span>last fired {r.lastFired}</span>
                    </div>
                  )}
                  {tab.k === 'suggested' && (
                    <div className="rule-suggest">
                      <div className="rule-foot-line">{r.basis}</div>
                      <div className="rule-actions">
                        <button className="rb-promote">Promote to active</button>
                        <button className="rb-dismiss">Dismiss</button>
                      </div>
                    </div>
                  )}
                  {tab.k === 'paused' && (
                    <div className="rule-paused">
                      <div className="rule-foot-line">Paused since {r.pausedSince} by {r.pausedBy}</div>
                      <div className="rule-paused-note">"{r.note}"</div>
                      <div className="rule-actions">
                        <button className="rb-promote">Reactivate</button>
                        <button className="rb-dismiss">Delete</button>
                      </div>
                    </div>
                  )}
                </div>
              ));
            })()}
          </div>

          <div className="rule-foot-meta">
            {ruleTab === 'active' && <>Active · last edited by Sarah · 14 May</>}
            {ruleTab === 'suggested' && <>3 patterns the AI noticed this week — review &amp; promote</>}
            {ruleTab === 'paused' && <>Rules here aren't routing anything right now</>}
          </div>
        </div>
      </div>
    </div>
  );
}

window.ScreenDashboard = ScreenDashboard;
