/* ELEV8 ATS - screens: Agents (the AI workforce + its guardrails) and Approvals (the human sign-off queue).
   Together they make the AI-first model legible: agents do the work, autonomy is a dial,
   and nothing customer-facing happens without a person signing off. */

const DSa = window.Stand8DesignSystem_b5c975;

const AUTONOMY = {
  suggest: { label: 'Suggest', caption: 'Surfaces ideas in Approvals - acts on nothing.' },
  draft: { label: 'Draft', caption: 'Prepares the work; you approve before it goes anywhere.' },
  auto: { label: 'Auto', caption: 'Runs on schedule inside guardrails - every action logged and reversible.' },
};

/* ============================== AGENTS ============================== */
function AgentsScreen({ focus }) {
  const D = window.E8DATA;
  const { showToast } = React.useContext(E8Ctx);
  /* Stored settings merge OVER seed defaults, so agents added in later rounds
     (e.g. Watchtower in R81) never come back undefined from an older localStorage. */
  const [autonomy, setAutonomy] = React.useState(() => {
    const seed = Object.fromEntries(D.agents.map((a) => [a.id, a.autonomy]));
    try { const s = JSON.parse(localStorage.getItem('e8-agents-v1')); if (s && s.autonomy) return Object.assign(seed, s.autonomy); } catch (e) {}
    return seed;
  });
  const [paused, setPaused] = React.useState(() => {
    const seed = Object.fromEntries(D.agents.map((a) => [a.id, a.status === 'paused']));
    try { const s = JSON.parse(localStorage.getItem('e8-agents-v1')); if (s && s.paused) return Object.assign(seed, s.paused); } catch (e) {}
    return seed;
  });
  React.useEffect(() => { try { localStorage.setItem('e8-agents-v1', JSON.stringify({ autonomy, paused })); } catch (e) {} }, [autonomy, paused]);

  const [reviewCount, setReviewCount] = React.useState(() => window.E8Queue.counts().review);
  React.useEffect(() => window.E8Events.subscribe(['queue:changed'], () => setReviewCount(window.E8Queue.counts().review)), []);
  const [railsOpen, setRailsOpen] = React.useState(false);
  const activeCount = D.agents.filter((a) => !paused[a.id]).length;

  return (
    <React.Fragment>
      <Topbar
        crumbs={[{ label: 'Agents' }]}
        actions={
          <React.Fragment>
            <DSa.Button variant="secondary" size="sm" icon="inbox" onClick={() => navigate('approvals')}>Review queue · {reviewCount}</DSa.Button>
            <DSa.Button variant="primary" size="sm" icon="add">New agent</DSa.Button>
          </React.Fragment>
        }
      />
      <div className="e8-content">
        <div className="e8-page" style={{ maxWidth: 1040 }}>
          <div className="e8-pagehead">
            <div>
              <h1 className="e8-h1">Agents</h1>
              <div className="e8-pagehead-sub" style={{ maxWidth: 640 }}>
                Your AI workforce. Each agent has one job, a clear autonomy level, and guardrails you control - anything client-facing waits for your approval.
              </div>
            </div>
            <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8, flex: 'none' }}>
              <DSa.Badge tone="success" dot>{activeCount} active</DSa.Badge>
              {D.agents.length - activeCount > 0 ? <DSa.Badge tone="neutral">{D.agents.length - activeCount} paused</DSa.Badge> : null}
              <DSa.Badge tone="accent">{reviewCount} awaiting review</DSa.Badge>
            </div>
          </div>

          <div className="e8-agent-grid">
            {D.agents.map((a) => {
              const isPaused = paused[a.id];
              const level = autonomy[a.id];
              return (
                <div key={a.id} className={'e8-agent-card' + (focus === a.id ? ' focus' : '')}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                    <span className="e8-agent-glyph"><span className="material-symbols-outlined">{a.icon}</span></span>
                    <span style={{ fontSize: 'var(--ui-text-md)', fontWeight: 500 }}>{a.name}</span>
                    <DSa.Badge tone={isPaused ? 'neutral' : 'success'} dot>{isPaused ? 'Paused' : 'Active'}</DSa.Badge>
                    <span style={{ marginLeft: 'auto' }}>
                      <DSa.MenuButton
                        items={[
                          ...(a.id === 'watchtower' ? [
                            { icon: 'radar', label: 'Sweep now', onClick: async () => { const r = await window.E8Watch.sweep({ force: true, ai: true }); showToast('Watchtower: ' + r.findings.length + ' flags · ' + r.queued + ' new in Approvals', r.queued ? 'Open' : undefined, r.queued ? () => navigate('approvals') : undefined); } },
                            { icon: 'restart_alt', label: 'Reset flag history', onClick: () => { window.E8Watch.reset(); showToast('Watchtower flag history cleared - the next sweep can re-raise everything'); } },
                          ] : []),
                          { icon: 'history', label: 'View runs', onClick: () => navigate('audit?agent=' + encodeURIComponent(a.name)) },
                          { icon: isPaused ? 'play_arrow' : 'pause', label: isPaused ? 'Resume agent' : 'Pause agent', onClick: () => { setPaused((p) => ({ ...p, [a.id]: !isPaused })); showToast(a.name + (isPaused ? ' resumed' : ' paused'), 'Undo', () => setPaused((p) => ({ ...p, [a.id]: isPaused }))); } },
                          { icon: 'tune', label: 'Edit guardrails', onClick: () => setRailsOpen(true) },
                        ]}
                      />
                    </span>
                  </div>

                  <p style={{ margin: 0, fontSize: 'var(--ui-text-sm)', lineHeight: 1.5, color: 'var(--ui-text-secondary)' }}>{a.desc}</p>

                  {a.criteria ? (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                      <span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>Criteria weights</span>
                      {a.criteria.map(([c, w]) => <DSa.SkillChip key={c} color={1}>{c} ×{w}</DSa.SkillChip>)}
                      <button type="button" className="e8-whybtn" onClick={() => showToast('Weight editor opens here - changes re-rank every open job')}>edit</button>
                    </div>
                  ) : null}

                  <div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <span style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)', flex: 'none' }}>Autonomy</span>
                      <DSa.SubTabs
                        items={[{ id: 'suggest', label: 'Suggest' }, { id: 'draft', label: 'Draft' }, { id: 'auto', label: 'Auto' }]}
                        active={level}
                        onChange={(v) => { setAutonomy((s) => ({ ...s, [a.id]: v })); showToast(a.name + ' set to ' + AUTONOMY[v].label.toLowerCase(), 'Undo', () => setAutonomy((s) => ({ ...s, [a.id]: level }))); }}
                      />
                    </div>
                    <div style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)', marginTop: 5 }}>{AUTONOMY[level].caption}</div>
                  </div>

                  <div className="e8-agent-stats">
                    {a.stats.map(([k, v]) => (
                      <div key={k}>
                        <div style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)', whiteSpace: 'nowrap' }}>{k}</div>
                        <div className="tnum" style={{ fontSize: 'var(--ui-text-md)', fontWeight: 500, marginTop: 1 }}>{v}</div>
                      </div>
                    ))}
                  </div>

                  <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)', borderTop: '1px solid var(--ui-border)', paddingTop: 9 }}>
                    <span className="material-symbols-outlined" style={{ fontSize: 14 }}>shield</span>
                    <span style={{ flex: 1, minWidth: 0 }}>{a.guardrail}</span>
                    <span className="tnum" style={{ flex: 'none', whiteSpace: 'nowrap' }}>{a.last}</span>
                  </div>
                </div>
              );
            })}
          </div>

          <p style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-tertiary)', margin: '16px 2px 0', maxWidth: 640 }}>
            Every agent action is attributed in record timelines and the audit log. Raising autonomy never removes the audit trail - it only changes when you’re asked.
          </p>
        </div>
      </div>
      <GuardrailsPanel open={railsOpen} onClose={() => setRailsOpen(false)} />
    </React.Fragment>
  );
}

/* ============================== INBOX ============================== */
const CONF_LABELS = { high: ['confirmed', 'High confidence'], medium: ['suggested', 'Medium confidence'], mixed: ['suggested', 'Mixed confidence'] };

function ApprovalsScreen() {
  const { showToast } = React.useContext(E8Ctx);
  /* R78: the queue is live (E8Queue). R82: guardrails hold blocked actions with the rule
     cited, the stream is keyboard-first (J/K/A/E/R), and the median stat is measured. */
  const [items, setItems] = React.useState(() => window.E8Queue.list());
  const [tab, setTab] = React.useState('review');
  const [sel, setSel] = React.useState(0);
  const [railsOpen, setRailsOpen] = React.useState(false);
  const isMobile = useIsMobile();
  const listRef = React.useRef(null);

  React.useEffect(() => window.E8Events.subscribe(['queue:changed', 'store:changed', 'policy:changed'], () => setItems(window.E8Queue.list())), []);

  const move = (id, to, opts) => {
    const res = window.E8Queue.decide(id, to, opts);
    if (!res) return;
    if (res.held) {
      showToast('Held by guardrail \u00b7 ' + res.verdict.label + ' - ' + res.verdict.reason, 'Undo', () => res.undo());
      return;
    }
    showToast(
      to === 'done' ? '\u201c' + res.item.title.split(' - ')[0] + (opts && opts.override ? '\u201d approved (guardrail overridden)' : res.item.action ? '\u201d approved - done' : '\u201d approved') : 'Dismissed',
      'Undo',
      () => res.undo()
    );
  };

  const counts = { review: 0, held: 0, done: 0 };
  items.forEach((i) => { if (counts[i.state] != null) counts[i.state] += 1; });
  const rows = items.filter((i) => i.state === tab);

  /* Measured median time-to-clear over live items (enqueue timestamp -> decision). */
  const clearSecs = items
    .filter((i) => i.at && i.decidedAt && (i.state === 'done' || i.state === 'dismissed'))
    .map((i) => (new Date(i.decidedAt) - new Date(i.at)) / 1000)
    .filter((x) => x >= 0)
    .sort((a, b) => a - b);
  const median = clearSecs.length ? (clearSecs.length % 2 ? clearSecs[(clearSecs.length - 1) / 2] : (clearSecs[clearSecs.length / 2 - 1] + clearSecs[clearSecs.length / 2]) / 2) : null;
  const fmtDur = (x) => x == null ? 'no decisions yet' : x < 90 ? Math.round(x) + ' seconds' : x < 5400 ? Math.round(x / 60) + ' minutes' : Math.round(x / 3600) + ' hours';

  /* R82: the J/K/A/E/R stream. One clamped index drives the ring AND the key target;
     A/R only act on tabs whose buttons offer them (never on Done). */
  const selIdx = Math.min(sel, Math.max(0, rows.length - 1));
  React.useEffect(() => { setSel(0); }, [tab]);
  React.useEffect(() => { setSel((v) => Math.min(v, Math.max(0, rows.length - 1))); }, [rows.length]);
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.metaKey || e.ctrlKey || e.altKey) return;
      const t = e.target;
      if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable)) return;
      const k = e.key.toLowerCase();
      if (['j', 'k', 'a', 'e', 'r'].indexOf(k) === -1) return;
      e.preventDefault();
      if (k === 'j') setSel((v) => Math.min(v + 1, Math.max(0, rows.length - 1)));
      if (k === 'k') setSel((v) => Math.max(v - 1, 0));
      const cur = rows[selIdx];
      if (!cur) return;
      if (k === 'a' && tab !== 'done') move(cur.id, 'done', tab === 'held' ? { override: true } : undefined);
      if (k === 'r' && tab !== 'done') move(cur.id, 'dismissed');
      if (k === 'e' && cur.route) navigate(cur.route);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [rows, selIdx, tab]);
  React.useEffect(() => {
    const el = listRef.current && listRef.current.children[selIdx];
    if (el && el.scrollIntoView) el.scrollIntoView({ block: 'nearest' });
  }, [selIdx, tab]);

  return (
    <React.Fragment>
      <Topbar
        crumbs={[{ label: 'Approvals' }]}
        actions={
          <React.Fragment>
            <NotifyBell audience="recruiter" />
            <DSa.Button variant="secondary" size="sm" icon="shield" onClick={() => setRailsOpen(true)}>Guardrails</DSa.Button>
            <DSa.Button variant="secondary" size="sm" icon="smart_toy" onClick={() => navigate('agents')}>Tune autonomy</DSa.Button>
            {counts.review > 1 ? <DSa.Button variant="primary" size="sm" icon="done_all" onClick={() => { const undos = items.filter((i) => i.state === 'review').map((i) => window.E8Queue.decide(i.id, 'done', { batch: true })).filter(Boolean); const held = undos.filter((u) => u.held).length; showToast((undos.length - held) + ' approved' + (held ? ' \u00b7 ' + held + ' held by guardrails' : ''), 'Undo', () => undos.forEach((u) => u.undo())); }}>Approve all</DSa.Button> : null}
          </React.Fragment>
        }
      />
      <div className="e8-content">
        <div className="e8-page" style={{ maxWidth: 1020 }}>
          <div className="e8-pagehead">
            <div>
              <h1 className="e8-h1">Approvals</h1>
              <div className="e8-pagehead-sub">Everything the agents drafted or flagged for you. Approve it, edit it, or let it go - nothing moves without you.</div>
            </div>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '0 0 14px', flexWrap: 'wrap' }}>
            <DSa.SubTabs
              items={[
                { id: 'review', label: 'Needs review', count: counts.review },
                { id: 'held', label: 'Held by guardrails', count: counts.held },
                { id: 'done', label: 'Done', count: counts.done },
              ]}
              active={tab}
              onChange={setTab}
            />
            {!isMobile ? <span style={{ marginLeft: 'auto', fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}><b>J/K</b> navigate · <b>A</b> {tab === 'held' ? 'override & approve' : 'approve'} · <b>R</b> dismiss · <b>E</b> open</span> : null}
          </div>

          <div className="e8-record-2col">
            <div ref={listRef} style={{ flex: 1, minWidth: 0, display: 'grid', gap: 8 }}>
              {rows.map((i, idx) => {
                const conf = i.conf ? CONF_LABELS[i.conf] : null;
                const item = (
                  <div className="e8-inbox-item" style={idx === selIdx && !isMobile ? { boxShadow: 'var(--ui-focus-ring)', borderRadius: 'var(--ui-radius-xl)' } : undefined} onMouseMove={() => { if (idx !== sel) setSel(idx); }}>
                    <span className="e8-inbox-glyph"><span className="material-symbols-outlined">{i.icon}</span></span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 'var(--ui-text-base)', fontWeight: 500, lineHeight: 1.35 }}>{i.title}</div>
                      <div style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-secondary)', marginTop: 3, lineHeight: 1.5, maxWidth: 560, textWrap: 'pretty' }}>{i.detail}</div>
                      {i.state === 'held' ? (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6, fontSize: 'var(--ui-text-sm)', color: 'var(--ui-warning-text)' }}>
                          <span className="material-symbols-outlined" style={{ fontSize: 14 }}>shield</span>
                          <b>{i.heldRule || 'Guardrail'}</b>
                          <span style={{ color: 'var(--ui-text-secondary)' }}>- {i.heldReason || 'blocked by policy'}</span>
                        </div>
                      ) : null}
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 7, flexWrap: 'wrap' }}>
                        <DSa.AgentChip name={i.agent} />
                        <DSa.ProvenanceBadge kind={i.prov} />
                        {conf ? <DSa.ConfidenceChip state={conf[0]}>{conf[1]}</DSa.ConfidenceChip> : null}
                        <span className="tnum" style={{ fontSize: 'var(--ui-text-xs)', color: 'var(--ui-text-tertiary)' }}>{i.decidedAt ? 'Decided ' + new Date(i.decidedAt).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) : i.when}</span>
                        {i.route ? (
                          <a className="e8-link" style={{ fontSize: 'var(--ui-text-sm)' }} tabIndex={0} onKeyDown={window.keyActivate} onClick={() => navigate(i.route)}>Open record →</a>
                        ) : null}
                      </div>
                    </div>
                    {tab === 'review' ? (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flex: 'none' }}>
                        <DSa.Button variant="accept" size="sm" icon="check" onClick={() => move(i.id, 'done')}>{i.primary || 'Approve'}</DSa.Button>
                        {i.secondary ? <DSa.Button variant="ghost" size="sm" icon="edit" onClick={() => showToast('Editor opens here - contents are editable before anything sends')}>{i.secondary}</DSa.Button> : null}
                        <DSa.Button variant="ghost" size="sm" icon="close" iconOnly title="Dismiss" onClick={() => move(i.id, 'dismissed')}></DSa.Button>
                      </div>
                    ) : tab === 'held' ? (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flex: 'none' }}>
                        <DSa.Button variant="secondary" size="sm" icon="shield" onClick={() => move(i.id, 'done', { override: true })}>Override & approve</DSa.Button>
                        <DSa.Button variant="ghost" size="sm" icon="close" iconOnly title="Dismiss" onClick={() => move(i.id, 'dismissed')}></DSa.Button>
                      </div>
                    ) : (
                      <DSa.Badge tone="success" dot>Done</DSa.Badge>
                    )}
                  </div>
                );
                return isMobile && tab === 'review' ? (
                  <SwipeTriage key={i.id}
                    left={{ label: 'Approve', icon: 'check_circle', bg: 'var(--ui-success)' }}
                    right={{ label: 'Dismiss', icon: 'do_not_disturb_on', bg: 'var(--ui-danger)' }}
                    onCommit={(dir) => move(i.id, dir === 'advance' ? 'done' : 'dismissed')}>
                    {item}
                  </SwipeTriage>
                ) : (
                  <React.Fragment key={i.id}>{item}</React.Fragment>
                );
              })}
              {!rows.length ? (
                <div className="e8-card" style={{ boxShadow: 'none' }}>
                  <DSa.EmptyState
                    icon={tab === 'held' ? 'shield' : 'fact_check'}
                    title={tab === 'review' ? 'Queue clear - nothing needs you' : tab === 'held' ? 'Nothing held' : 'Nothing here yet'}
                    body={tab === 'review' ? 'New drafts and flags land here as the agents work. You\u2019ll also see a badge in the sidebar.' : tab === 'held' ? 'Actions a guardrail blocks land here with the rule cited - override or dismiss.' : 'Approved and sent items keep their full provenance in the audit log.'}
                  />
                </div>
              ) : null}
            </div>

            <div className="e8-rail">
              <div className="e8-rail-block">
                <div className="e8-rail-title">How approvals work</div>
                {[
                  'Agents draft; you approve. Nothing reaches a client or candidate without sign-off.',
                  'Guardrails run in code: blocked actions are held with the rule cited.',
                  'Every approval is logged with who, when and what changed.',
                ].map((t, i) => (
                  <div key={i} style={{ display: 'flex', gap: 7, fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-secondary)', padding: '3px 0', lineHeight: 1.45 }}>
                    <span className="material-symbols-outlined" style={{ fontSize: 14, marginTop: 2, flex: 'none' }}>check</span>
                    {t}
                  </div>
                ))}
                <div style={{ marginTop: 10, display: 'flex', gap: 6 }}>
                  <DSa.Button variant="secondary" size="sm" icon="shield" onClick={() => setRailsOpen(true)}>Guardrails</DSa.Button>
                  <DSa.Button variant="ghost" size="sm" icon="smart_toy" onClick={() => navigate('agents')}>Autonomy</DSa.Button>
                </div>
              </div>
              <div className="e8-rail-block">
                <div className="e8-rail-title">Today</div>
                <div className="e8-kv"><span className="e8-kv-k">Drafted</span><span className="e8-kv-v tnum">{items.length} items</span></div>
                <div className="e8-kv"><span className="e8-kv-k">Approved</span><span className="e8-kv-v tnum">{counts.done}</span></div>
                <div className="e8-kv"><span className="e8-kv-k">Held</span><span className="e8-kv-v tnum">{counts.held}</span></div>
                <div className="e8-kv"><span className="e8-kv-k">Median time to clear</span><span className="e8-kv-v tnum">{fmtDur(median)}</span></div>
                <div className="e8-kv"><span className="e8-kv-k">Sends today</span><span className="e8-kv-v tnum">{window.E8Policy ? window.E8Policy.sendsToday() + ' / ' + (window.E8Policy.rule('send-cap').params.perDay) : '-'}</span></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <GuardrailsPanel open={railsOpen} onClose={() => setRailsOpen(false)} />
    </React.Fragment>
  );
}

/* ============================== GUARDRAILS ============================== */
/* R82: the editor for E8Policy - toggles and parameters for rules that are genuinely
   consulted by the queue, the composer and the notification bridge. */
function GuardrailsPanel({ open, onClose }) {
  const { showToast } = React.useContext(E8Ctx);
  const [rules, setRules] = React.useState(() => (window.E8Policy ? window.E8Policy.rules() : []));
  const [dncInput, setDncInput] = React.useState('');
  React.useEffect(() => { if (open) { setRules(window.E8Policy.rules()); setDncInput(''); } }, [open]);
  if (!open) return null;
  const set = (id, patch, msg) => {
    window.E8Policy.setRule(id, patch);
    setRules(window.E8Policy.rules());
    if (msg) showToast(msg);
  };
  const num = (v, lo, hi) => Math.max(lo, Math.min(hi, parseInt(v, 10) || 0));
  return (
    <DSa.Modal title="Guardrails" icon="shield" ariaLabel="Guardrails" onClose={onClose} style={{ width: 560, maxWidth: '92vw' }}>
        <div style={{ padding: '6px 16px 14px', display: 'grid', gap: 4, maxHeight: '70vh', overflowY: 'auto' }}>
          <div style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-tertiary)', margin: '4px 0 8px' }}>
            Enforced in code - the approvals queue, the composer and notifications consult these before acting. Blocked actions are held with the rule cited.
          </div>
          {rules.map((r) => (
            <div key={r.id} style={{ borderTop: '1px solid var(--ui-border)', padding: '10px 0' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                <span className="material-symbols-outlined" style={{ fontSize: 17, color: r.enabled ? 'var(--ui-accent)' : 'var(--ui-text-tertiary)' }}>{r.icon}</span>
                <span style={{ fontSize: 'var(--ui-text-base)', fontWeight: 500, flex: 1 }}>{r.label}</span>
                {r.invariant
                  ? <DSa.Badge tone="neutral"><span className="material-symbols-outlined" style={{ fontSize: 12, verticalAlign: '-2px' }}>lock</span> Always on</DSa.Badge>
                  : <DSa.Toggle checked={r.enabled} onChange={() => set(r.id, { enabled: !r.enabled }, r.label + (r.enabled ? ' off' : ' on'))} />}
              </div>
              <div style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-secondary)', margin: '4px 0 0 26px', lineHeight: 1.45 }}>{r.desc}{r.id === 'no-overwrite-human' ? ' First producer: enrichment field updates (a later round) - the check is live for any queued field write today.' : ''}</div>
              {r.enabled && r.id === 'quiet-hours' ? (
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '8px 0 0 26px', fontSize: 'var(--ui-text-sm)' }}>
                  Working hours
                  <input type="number" min="0" max="23" value={r.params.start} onChange={(e) => set(r.id, { params: { start: num(e.target.value, 0, 23) } })} style={{ width: 52 }} className="e8-ap-filter" aria-label="Quiet hours start" />
                  :00 to
                  <input type="number" min="0" max="23" value={r.params.end} onChange={(e) => set(r.id, { params: { end: num(e.target.value, 0, 23) } })} style={{ width: 52 }} className="e8-ap-filter" aria-label="Quiet hours end" />
                  :00
                </div>
              ) : null}
              {r.enabled && r.id === 'send-cap' ? (
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '8px 0 0 26px', fontSize: 'var(--ui-text-sm)' }}>
                  Max
                  <input type="number" min="1" max="500" value={r.params.perDay} onChange={(e) => set(r.id, { params: { perDay: num(e.target.value, 1, 500) } })} style={{ width: 64 }} className="e8-ap-filter" aria-label="Daily send cap" />
                  sends per day <span style={{ color: 'var(--ui-text-tertiary)' }}>· used today: {window.E8Policy.sendsToday()}</span>
                </div>
              ) : null}
              {r.enabled && r.id === 'dnc' ? (
                <div style={{ margin: '8px 0 0 26px' }}>
                  <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap', marginBottom: 6 }}>
                    {(r.params.names || []).map((n) => (
                      <span key={n} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 'var(--ui-text-sm)', padding: '2px 8px', borderRadius: 'var(--ui-radius-pill)', background: 'var(--ui-fill)' }}>
                        {n}
                        <button type="button" className="e8-whybtn" style={{ padding: 0 }} aria-label={'Remove ' + n} onClick={() => set(r.id, { params: { names: (r.params.names || []).filter((x) => x !== n) } }, n + ' removed from do-not-contact')}>×</button>
                      </span>
                    ))}
                    {!(r.params.names || []).length ? <span style={{ fontSize: 'var(--ui-text-sm)', color: 'var(--ui-text-tertiary)' }}>Nobody listed</span> : null}
                  </div>
                  <div style={{ display: 'flex', gap: 6 }}>
                    <input className="e8-ap-filter" placeholder="Add a name…" value={dncInput} onChange={(e) => setDncInput(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter' && dncInput.trim()) { set(r.id, { params: { names: (r.params.names || []).concat([dncInput.trim()]) } }, dncInput.trim() + ' added to do-not-contact'); setDncInput(''); } }} aria-label="Add to do-not-contact" style={{ flex: 1 }} />
                    <DSa.Button variant="secondary" size="sm" icon="add" disabled={!dncInput.trim()} onClick={() => { set(r.id, { params: { names: (r.params.names || []).concat([dncInput.trim()]) } }, dncInput.trim() + ' added to do-not-contact'); setDncInput(''); }}>Add</DSa.Button>
                  </div>
                </div>
              ) : null}
            </div>
          ))}
        </div>
    </DSa.Modal>
  );
}

Object.assign(window, { AgentsScreen, ApprovalsScreen, GuardrailsPanel });
