// automations.jsx — Main Automations screen
// ─────────────────────────────────────────────────────────────────
// Tabs: Rules · Library · Activity · Schedules · Notifications
// All state via window.AutoEngine; React for UI only.
// ─────────────────────────────────────────────────────────────────
(function () {
  if (typeof window === 'undefined') return;
  const { useState: _S, useEffect: _E, useMemo: _M, useReducer: _R } = React;

  // Ensure default seed rules exist (idempotent on first load).
  function seedDefaultRules() {
    const E = window.AutoEngine;
    if (!E) return;
    if (window.__AUTO_DEFAULTS_SEEDED) return;
    window.__AUTO_DEFAULTS_SEEDED = true;
    if (E.listRules().length > 0) return;
    // Pick three recipes as starter rules
    const starters = (window.AUTO_RECIPES || []).filter(r =>
      ['recipe-leak-high', 'recipe-bbrank-likely', 'recipe-stmt-variance'].includes(r.id)
    );
    starters.forEach(rec => {
      const rule = E.newRule(Object.assign({}, rec.rule, { fromRecipe: rec.id }));
      E.saveRule(rule);
    });
    E.seedDemoActivity();
  }

  // Subscribe to rule/run mutations to trigger re-renders.
  function useEngineTick() {
    const [, force] = _R(x => x + 1, 0);
    _E(() => {
      const onChange = () => force();
      window.addEventListener('astro-auto-rules-changed', onChange);
      window.addEventListener('astro-auto-run', onChange);
      return () => {
        window.removeEventListener('astro-auto-rules-changed', onChange);
        window.removeEventListener('astro-auto-run', onChange);
      };
    }, []);
  }

  // ─── Shared chrome ─────────────────────────────────────────────
  const Mono = ({ children, size = 10, color = 'var(--ink-3)', upper = true, style = {} }) => (
    <span className="ff-mono" style={{ fontSize: size, color, letterSpacing: '.12em', textTransform: upper ? 'uppercase' : 'none', ...style }}>{children}</span>
  );
  const StatChip = ({ on }) => (
    <span className="ff-mono upper" style={{
      fontSize: 9, padding: '2px 7px', letterSpacing: '.12em', fontWeight: 600,
      color: on ? '#0a8754' : 'var(--ink-3)',
      border: '1px solid ' + (on ? '#0a8754' : 'var(--rule)'),
    }}>{on ? 'ON' : 'OFF'}</span>
  );

  // ─── Rule editor (drawer) ──────────────────────────────────────
  function RuleEditor({ rule, onClose, onSave, onDelete }) {
    const E = window.AutoEngine;
    const [draft, setDraft] = _S(JSON.parse(JSON.stringify(rule)));
    const trigger = E.triggerById(draft.trigger);
    const fields = trigger?.fields || [];

    function update(k, v)        { setDraft(d => ({ ...d, [k]: v })); }
    function updateCond(i, k, v) { setDraft(d => { const c = d.conditions.slice(); c[i] = { ...c[i], [k]: v }; return { ...d, conditions: c }; }); }
    function addCond()           { setDraft(d => ({ ...d, conditions: [...d.conditions, { field: fields[0] || '', op: 'eq', value: '' }] })); }
    function delCond(i)          { setDraft(d => ({ ...d, conditions: d.conditions.filter((_, idx) => idx !== i) })); }
    function updateAct(i, k, v)  { setDraft(d => { const a = d.actions.slice(); a[i] = { ...a[i], [k]: v }; return { ...d, actions: a }; }); }
    function updateActParam(i, k, v) { setDraft(d => { const a = d.actions.slice(); a[i] = { ...a[i], params: { ...(a[i].params||{}), [k]: v } }; return { ...d, actions: a }; }); }
    function addAct()            { setDraft(d => ({ ...d, actions: [...d.actions, { action: E.ACTIONS[0].id, params: {} }] })); }
    function delAct(i)           { setDraft(d => ({ ...d, actions: d.actions.filter((_, idx) => idx !== i) })); }

    return (
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(15,12,8,.32)', zIndex: 80 }}>
        <div onClick={e => e.stopPropagation()} style={{
          position: 'absolute', top: 0, right: 0, width: 620, height: '100%',
          background: 'var(--bg)', borderLeft: '1px solid var(--rule)', overflowY: 'auto',
          display: 'flex', flexDirection: 'column',
        }}>
          {/* Header */}
          <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--rule)', display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ flex: 1 }}>
              <Mono size={9} style={{ display: 'block' }}>{rule.id.startsWith('rule-') && draft.runCount === 0 ? 'NEW RULE' : 'EDIT RULE'}</Mono>
              <div style={{ fontSize: 18, fontWeight: 600, marginTop: 4, letterSpacing: '-0.01em' }}>{draft.name || 'Untitled'}</div>
            </div>
            <StatChip on={draft.enabled}/>
            <button onClick={onClose} style={{ border: 0, background: 'transparent', fontSize: 18, cursor: 'pointer', color: 'var(--ink-3)' }}>×</button>
          </div>

          {/* Body */}
          <div style={{ padding: '20px 24px', flex: 1 }}>
            {/* Name */}
            <div style={{ marginBottom: 18 }}>
              <Mono style={{ display: 'block', marginBottom: 6 }}>NAME</Mono>
              <input value={draft.name} onChange={e => update('name', e.target.value)}
                style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--rule)', background: 'var(--bg)', fontSize: 14, fontWeight: 500 }}/>
            </div>
            <div style={{ marginBottom: 22 }}>
              <Mono style={{ display: 'block', marginBottom: 6 }}>DESCRIPTION</Mono>
              <textarea value={draft.description} onChange={e => update('description', e.target.value)} rows={2}
                style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--rule)', background: 'var(--bg)', fontSize: 12, fontFamily: 'inherit', resize: 'vertical' }}/>
            </div>

            {/* TRIGGER */}
            <div style={{ marginBottom: 22, padding: 16, border: '1px solid var(--rule)', background: 'var(--bg-2)' }}>
              <Mono size={9} style={{ display: 'block', marginBottom: 10 }}>WHEN · TRIGGER</Mono>
              <select value={draft.trigger} onChange={e => update('trigger', e.target.value)}
                style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--rule)', background: 'var(--bg)', fontSize: 13 }}>
                {Object.entries(groupByGroup(E.TRIGGERS)).map(([g, items]) => (
                  <optgroup key={g} label={g}>
                    {items.map(t => <option key={t.id} value={t.id}>{t.label}</option>)}
                  </optgroup>
                ))}
              </select>
              <Mono size={9} style={{ display: 'block', marginTop: 8 }}>EVENT FIELDS · {fields.join(' · ') || 'NONE'}</Mono>
            </div>

            {/* CONDITIONS */}
            <div style={{ marginBottom: 22, padding: 16, border: '1px solid var(--rule)', background: 'var(--bg-2)' }}>
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: 10 }}>
                <Mono size={9}>IF · CONDITIONS</Mono>
                <span style={{ flex: 1 }}/>
                <select value={draft.conditionMode} onChange={e => update('conditionMode', e.target.value)}
                  style={{ padding: '4px 8px', border: '1px solid var(--rule)', background: 'var(--bg)', fontSize: 11 }}>
                  <option value="all">match all</option>
                  <option value="any">match any</option>
                </select>
              </div>
              {draft.conditions.map((c, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 80px 1fr 28px', gap: 6, marginBottom: 6 }}>
                  <select value={c.field} onChange={e => updateCond(i, 'field', e.target.value)}
                    style={{ padding: '8px', border: '1px solid var(--rule)', background: 'var(--bg)', fontSize: 12 }}>
                    {fields.map(f => <option key={f} value={f}>{f}</option>)}
                  </select>
                  <select value={c.op} onChange={e => updateCond(i, 'op', e.target.value)}
                    style={{ padding: '8px', border: '1px solid var(--rule)', background: 'var(--bg)', fontSize: 12, textAlign: 'center' }}>
                    {E.OPERATORS.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
                  </select>
                  <input value={c.value} onChange={e => updateCond(i, 'value', e.target.value)} placeholder="value"
                    style={{ padding: '8px', border: '1px solid var(--rule)', background: 'var(--bg)', fontSize: 12 }}/>
                  <button onClick={() => delCond(i)} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--ink-3)', fontSize: 16 }}>×</button>
                </div>
              ))}
              <button onClick={addCond} className="ff-mono upper" style={{ padding: '6px 10px', background: 'transparent', border: '1px dashed var(--rule)', fontSize: 10, letterSpacing: '.12em', cursor: 'pointer', color: 'var(--ink-2)', marginTop: 4 }}>+ ADD CONDITION</button>
            </div>

            {/* ACTIONS */}
            <div style={{ marginBottom: 22, padding: 16, border: '1px solid var(--rule)', background: 'var(--bg-2)' }}>
              <Mono size={9} style={{ display: 'block', marginBottom: 10 }}>THEN · ACTIONS</Mono>
              {draft.actions.map((a, i) => {
                const def = E.actionById(a.action);
                return (
                  <div key={i} style={{ marginBottom: 8, padding: 10, background: 'var(--bg)', border: '1px solid var(--rule-soft)' }}>
                    <div style={{ display: 'flex', gap: 6, marginBottom: 6 }}>
                      <select value={a.action} onChange={e => updateAct(i, 'action', e.target.value)}
                        style={{ flex: 1, padding: '6px 8px', border: '1px solid var(--rule)', background: 'var(--bg)', fontSize: 12 }}>
                        {Object.entries(groupByGroup(E.ACTIONS)).map(([g, items]) => (
                          <optgroup key={g} label={g}>{items.map(x => <option key={x.id} value={x.id}>{x.label}</option>)}</optgroup>
                        ))}
                      </select>
                      <button onClick={() => delAct(i)} style={{ border: 0, background: 'transparent', cursor: 'pointer', color: 'var(--ink-3)', fontSize: 16, width: 24 }}>×</button>
                    </div>
                    {def?.params?.length > 0 && (
                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(' + Math.min(def.params.length, 2) + ', 1fr)', gap: 6 }}>
                        {def.params.map(p => (
                          <div key={p}>
                            <Mono size={8} style={{ display: 'block', marginBottom: 2 }}>{p.toUpperCase()}</Mono>
                            <input value={a.params?.[p] || ''} onChange={e => updateActParam(i, p, e.target.value)}
                              style={{ width: '100%', padding: '6px 8px', border: '1px solid var(--rule)', background: 'var(--bg)', fontSize: 11, boxSizing: 'border-box' }}/>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                );
              })}
              <button onClick={addAct} className="ff-mono upper" style={{ padding: '6px 10px', background: 'transparent', border: '1px dashed var(--rule)', fontSize: 10, letterSpacing: '.12em', cursor: 'pointer', color: 'var(--ink-2)', marginTop: 4 }}>+ ADD ACTION</button>
            </div>
          </div>

          {/* Footer */}
          <div style={{ padding: '16px 24px', borderTop: '1px solid var(--rule)', display: 'flex', gap: 10, alignItems: 'center' }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, cursor: 'pointer' }}>
              <input type="checkbox" checked={draft.enabled} onChange={e => update('enabled', e.target.checked)}/>
              <span>Enabled</span>
            </label>
            <span style={{ flex: 1 }}/>
            {onDelete && draft.id && draft.runCount !== undefined && (
              <button onClick={() => { if (confirm('Delete this rule?')) onDelete(draft.id); }} style={{ padding: '8px 14px', background: 'transparent', border: '1px solid var(--rule)', color: 'var(--ink-3)', fontSize: 12, cursor: 'pointer' }}>Delete</button>
            )}
            <button onClick={onClose} style={{ padding: '8px 14px', background: 'transparent', border: '1px solid var(--rule)', fontSize: 12, cursor: 'pointer' }}>Cancel</button>
            <button onClick={() => { onSave(draft); }} style={{ padding: '8px 18px', background: 'var(--ink)', color: 'var(--bg)', border: 0, fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>Save rule</button>
          </div>
        </div>
      </div>
    );
  }

  function groupByGroup(arr) {
    const out = {};
    arr.forEach(x => { (out[x.group] = out[x.group] || []).push(x); });
    return out;
  }

  // ─── Rules tab ─────────────────────────────────────────────────
  function RulesTab({ openEditor }) {
    useEngineTick();
    const E = window.AutoEngine;
    const rules = E.listRules();

    function toggle(rule) { E.saveRule({ ...rule, enabled: !rule.enabled }); }
    function newBlank()   { openEditor(E.newRule({ name: 'Untitled rule' })); }

    return (
      <div>
        <div style={{ padding: '0 0 18px', display: 'flex', alignItems: 'center', gap: 14 }}>
          <Mono size={10} style={{ letterSpacing: '.14em' }}>{rules.length} RULES · {rules.filter(r => r.enabled).length} ACTIVE</Mono>
          <span style={{ flex: 1 }}/>
          <button onClick={newBlank} style={{ padding: '8px 14px', background: 'var(--ink)', color: 'var(--bg)', border: 0, fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>+ New rule</button>
        </div>

        {rules.length === 0 && (
          <div style={{ padding: 60, textAlign: 'center', border: '1px dashed var(--rule)', color: 'var(--ink-3)' }}>
            <Mono size={11} style={{ display: 'block', marginBottom: 8 }}>NO RULES YET</Mono>
            <div style={{ fontSize: 13 }}>Pick a template from the Library, or build one from scratch.</div>
          </div>
        )}

        <div>
          {rules.length > 0 && (
            <div className="ff-mono upper" style={{
              display: 'grid', gridTemplateColumns: '40px 1fr 220px 220px 90px 90px 36px',
              gap: 12, padding: '10px 14px', fontSize: 9, color: 'var(--ink-3)',
              background: 'var(--bg-2)', borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)', letterSpacing: '.12em',
            }}>
              <span/><span>NAME</span><span>WHEN</span><span>THEN</span>
              <span style={{ textAlign: 'right' }}>RUNS</span><span>STATUS</span><span/>
            </div>
          )}
          {rules.map(rule => {
            const trig = E.triggerById(rule.trigger);
            const actLabels = (rule.actions || []).map(a => E.actionById(a.action)?.label || a.action);
            return (
              <div key={rule.id} onClick={() => openEditor(rule)} style={{
                display: 'grid', gridTemplateColumns: '40px 1fr 220px 220px 90px 90px 36px',
                gap: 12, padding: '14px', borderBottom: '1px solid var(--rule-soft)',
                alignItems: 'center', cursor: 'pointer',
              }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <button onClick={e => { e.stopPropagation(); toggle(rule); }} title={rule.enabled ? 'Disable' : 'Enable'}
                  style={{
                    width: 32, height: 18, position: 'relative', background: rule.enabled ? 'var(--ink)' : 'var(--rule)',
                    border: 0, cursor: 'pointer', padding: 0,
                  }}>
                  <span style={{ position: 'absolute', top: 2, left: rule.enabled ? 16 : 2, width: 14, height: 14, background: 'var(--bg)', transition: 'left .15s' }}/>
                </button>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 500 }}>{rule.name}</div>
                  {rule.description && <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{rule.description}</div>}
                </div>
                <span style={{ fontSize: 12, color: 'var(--ink-2)' }}>{trig?.label || rule.trigger}</span>
                <span style={{ fontSize: 12, color: 'var(--ink-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {actLabels.length === 0 ? <span style={{ color: 'var(--ink-3)' }}>— no actions —</span> : actLabels.slice(0, 2).join(', ')}
                  {actLabels.length > 2 && <span style={{ color: 'var(--ink-3)' }}> +{actLabels.length - 2}</span>}
                </span>
                <span className="ff-mono num" style={{ textAlign: 'right', fontSize: 13, fontWeight: 500 }}>{rule.runCount || 0}</span>
                <StatChip on={rule.enabled}/>
                <span style={{ color: 'var(--ink-3)', fontSize: 14 }}>›</span>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  // ─── Library tab (recipes) ─────────────────────────────────────
  function LibraryTab({ openEditor }) {
    const E = window.AutoEngine;
    const [filter, setFilter] = _S(null);
    const recipes = window.AUTO_RECIPES || [];
    const cats = ['ALL', ...new Set(recipes.map(r => r.category))];
    const filtered = filter && filter !== 'ALL' ? recipes.filter(r => r.category === filter) : recipes;

    function useRecipe(r) {
      const rule = E.newRule(Object.assign({}, r.rule, { fromRecipe: r.id }));
      openEditor(rule);
    }

    return (
      <div>
        <div style={{ padding: '0 0 18px' }}>
          <Mono size={10} style={{ letterSpacing: '.14em' }}>{recipes.length} RECIPES · CLONE & EDIT</Mono>
        </div>
        <div style={{ display: 'flex', gap: 0, borderBottom: '1px solid var(--rule)', marginBottom: 20 }}>
          {cats.map(c => (
            <button key={c} onClick={() => setFilter(c === 'ALL' ? null : c)} className="ff-mono upper" style={{
              padding: '10px 14px', background: 'transparent', border: 0,
              borderBottom: '2px solid ' + ((filter === c || (!filter && c === 'ALL')) ? 'var(--ink)' : 'transparent'),
              cursor: 'pointer', fontSize: 10, letterSpacing: '.12em',
              color: (filter === c || (!filter && c === 'ALL')) ? 'var(--ink)' : 'var(--ink-3)',
              fontWeight: (filter === c || (!filter && c === 'ALL')) ? 600 : 400,
            }}>{c}</button>
          ))}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 16 }}>
          {filtered.map(r => (
            <div key={r.id} style={{ padding: 18, border: '1px solid var(--rule)', background: 'var(--bg)', display: 'flex', flexDirection: 'column' }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 8 }}>
                <span style={{ fontSize: 24, color: 'var(--ink-2)' }}>{r.icon}</span>
                <Mono size={9}>{r.category.toUpperCase()}</Mono>
              </div>
              <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 6, letterSpacing: '-0.01em' }}>{r.name}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5, flex: 1 }}>{r.description}</div>
              <div style={{ display: 'flex', gap: 6, marginTop: 14, flexWrap: 'wrap' }}>
                <span className="ff-mono upper" style={{ fontSize: 9, padding: '2px 6px', background: 'var(--bg-2)', letterSpacing: '.1em', color: 'var(--ink-2)' }}>
                  {(E.triggerById(r.rule.trigger)?.label || r.rule.trigger)}
                </span>
                {(r.rule.actions || []).slice(0, 2).map((a, i) => (
                  <span key={i} className="ff-mono upper" style={{ fontSize: 9, padding: '2px 6px', background: 'var(--ink)', color: 'var(--bg)', letterSpacing: '.1em' }}>
                    {E.actionById(a.action)?.label || a.action}
                  </span>
                ))}
              </div>
              <button onClick={() => useRecipe(r)} style={{ marginTop: 14, padding: '8px 12px', background: 'transparent', border: '1px solid var(--ink)', fontSize: 11, fontWeight: 600, cursor: 'pointer' }}>USE THIS</button>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ─── Activity tab ──────────────────────────────────────────────
  function ActivityTab() {
    useEngineTick();
    const E = window.AutoEngine;
    const runs = E.listRuns({ limit: 200 });

    const groups = _M(() => {
      const out = {};
      runs.forEach(r => {
        const day = new Date(r.ts).toISOString().slice(0, 10);
        (out[day] = out[day] || []).push(r);
      });
      return out;
    }, [runs.length]);

    const totals = _M(() => ({
      total: runs.length,
      success: runs.filter(r => r.status === 'success').length,
      partial: runs.filter(r => r.status === 'partial').length,
    }), [runs.length]);

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)', marginBottom: 24 }}>
          <div style={{ padding: '20px 22px', borderRight: '1px solid var(--rule)' }}>
            <Mono size={9}>TOTAL RUNS</Mono>
            <div className="ff-mono num" style={{ fontSize: 28, fontWeight: 600, marginTop: 6 }}>{totals.total}</div>
          </div>
          <div style={{ padding: '20px 22px', borderRight: '1px solid var(--rule)' }}>
            <Mono size={9}>SUCCESS</Mono>
            <div className="ff-mono num" style={{ fontSize: 28, fontWeight: 600, color: '#0a8754', marginTop: 6 }}>{totals.success}</div>
          </div>
          <div style={{ padding: '20px 22px' }}>
            <Mono size={9}>PARTIAL</Mono>
            <div className="ff-mono num" style={{ fontSize: 28, fontWeight: 600, color: '#a35418', marginTop: 6 }}>{totals.partial}</div>
          </div>
        </div>

        {runs.length === 0 && (
          <div style={{ padding: 60, textAlign: 'center', border: '1px dashed var(--rule)', color: 'var(--ink-3)' }}>
            <Mono size={11} style={{ display: 'block', marginBottom: 8 }}>NO ACTIVITY YET</Mono>
            <div style={{ fontSize: 13 }}>Rule runs will appear here as events fire.</div>
          </div>
        )}

        {Object.entries(groups).map(([day, items]) => (
          <div key={day} style={{ marginBottom: 28 }}>
            <Mono size={10} style={{ display: 'block', marginBottom: 10, letterSpacing: '.14em' }}>{day} · {items.length} RUNS</Mono>
            {items.map(run => (
              <div key={run.id} style={{ display: 'grid', gridTemplateColumns: '70px 1fr 1fr 90px 90px',
                gap: 12, padding: '12px 14px', borderBottom: '1px solid var(--rule-soft)', alignItems: 'center', fontSize: 12 }}>
                <span className="ff-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                  {new Date(run.ts).toTimeString().slice(0, 5)}
                </span>
                <div>
                  <div style={{ fontWeight: 500 }}>{run.ruleName}</div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 2 }}>{run.triggerLabel}</div>
                </div>
                <div style={{ fontSize: 11, color: 'var(--ink-2)', overflow: 'hidden' }}>
                  {run.actions.map((a, i) => (
                    <div key={i} style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      <span style={{ color: a.status === 'success' ? '#0a8754' : '#a32a18' }}>{a.status === 'success' ? '✓' : '!'}</span>
                      &nbsp;{a.message}
                    </div>
                  ))}
                </div>
                <span className="ff-mono num" style={{ textAlign: 'right', fontSize: 11, color: 'var(--ink-3)' }}>{run.actions.length} act</span>
                <span className="ff-mono upper" style={{ fontSize: 9, letterSpacing: '.12em', textAlign: 'right',
                  color: run.status === 'success' ? '#0a8754' : run.status === 'partial' ? '#a35418' : 'var(--ink-3)' }}>{run.status}</span>
              </div>
            ))}
          </div>
        ))}
      </div>
    );
  }

  // ─── Schedules tab ─────────────────────────────────────────────
  function SchedulesTab() {
    useEngineTick();
    const E = window.AutoEngine;
    const rules = E.listRules().filter(r => r.schedule);

    const SCHEDULES = [
      { kind: 'interval', minutes: 60,  label: 'Hourly DSP sync',         hint: 'Pulls latest plays from connected platforms' },
      { kind: 'daily',    hour: 8,      label: 'Morning leak scan',       hint: 'Runs ML leak engine across full catalog' },
      { kind: 'daily',    hour: 22,     label: 'Nightly fingerprint',     hint: 'Catches new audio uploads that missed the queue' },
      { kind: 'weekly',   day: 'mon', hour: 9, label: 'Weekly BB-rank',   hint: 'Re-scores black-box pool for the week' },
      { kind: 'weekly',   day: 'fri', hour: 17,label: 'Weekly recoupment',hint: 'Recomputes balances before weekend' },
      { kind: 'monthly',  dayOfMonth: 1, hour: 9, label: 'Monthly statements', hint: 'Auto-generates counterparty statement PDFs' },
      { kind: 'monthly',  dayOfMonth: 15, hour: 8, label: 'Mid-month CWR sweep', hint: 'Resubmits stuck registrations' },
    ];

    return (
      <div>
        <Mono size={10} style={{ letterSpacing: '.14em', display: 'block', paddingBottom: 18 }}>SCHEDULED JOBS · TIME-DRIVEN AUTOMATIONS</Mono>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(360px, 1fr))', gap: 14 }}>
          {SCHEDULES.map((s, i) => (
            <div key={i} style={{ padding: 18, border: '1px solid var(--rule)', background: 'var(--bg)' }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 6 }}>
                <Mono size={10} style={{ color: 'var(--ink)', fontWeight: 600 }}>{E.describeSchedule(s)}</Mono>
                <span style={{ flex: 1 }}/>
                <StatChip on={true}/>
              </div>
              <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 4 }}>{s.label}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.5, marginBottom: 12 }}>{s.hint}</div>
              <div style={{ display: 'flex', justifyContent: 'space-between', paddingTop: 10, borderTop: '1px solid var(--rule-soft)' }}>
                <Mono size={9}>NEXT RUN</Mono>
                <span className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-2)' }}>
                  {new Date(E.nextRunAt(s)).toLocaleString().slice(0, 17)}
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ─── Notifications tab (alerts inbox) ──────────────────────────
  function NotificationsTab() {
    useEngineTick();
    const E = window.AutoEngine;
    // Pull all runs that produced inbox/email/slack notifications.
    const all = E.listRuns({ limit: 200 });
    const notifs = all.filter(r => r.actions.some(a => a.action.startsWith('notify.')));
    const [filter, setFilter] = _S('all');
    const filtered = filter === 'all' ? notifs : notifs.filter(r =>
      r.actions.some(a => a.action === 'notify.' + filter)
    );

    const counts = {
      all: notifs.length,
      inbox: notifs.filter(r => r.actions.some(a => a.action === 'notify.inbox')).length,
      email: notifs.filter(r => r.actions.some(a => a.action === 'notify.email')).length,
      slack: notifs.filter(r => r.actions.some(a => a.action === 'notify.slack')).length,
    };

    return (
      <div>
        <Mono size={10} style={{ letterSpacing: '.14em', display: 'block', paddingBottom: 18 }}>NOTIFICATION CENTER · {counts.all} ALERTS · LAST 30 DAYS</Mono>

        <div style={{ display: 'flex', gap: 0, borderBottom: '1px solid var(--rule)', marginBottom: 20 }}>
          {['all', 'inbox', 'email', 'slack'].map(k => (
            <button key={k} onClick={() => setFilter(k)} className="ff-mono upper" style={{
              padding: '10px 16px', background: 'transparent', border: 0,
              borderBottom: '2px solid ' + (filter === k ? 'var(--ink)' : 'transparent'),
              cursor: 'pointer', fontSize: 10, letterSpacing: '.12em',
              color: filter === k ? 'var(--ink)' : 'var(--ink-3)', fontWeight: filter === k ? 600 : 400,
            }}>{k} <span style={{ color: 'var(--ink-3)' }}>· {counts[k]}</span></button>
          ))}
        </div>

        {filtered.length === 0 && (
          <div style={{ padding: 60, textAlign: 'center', border: '1px dashed var(--rule)', color: 'var(--ink-3)' }}>
            <Mono size={11} style={{ display: 'block', marginBottom: 8 }}>NO NOTIFICATIONS</Mono>
          </div>
        )}

        <div>
          {filtered.map(run => {
            const notifyActions = run.actions.filter(a => a.action.startsWith('notify.'));
            return notifyActions.map((a, i) => (
              <div key={run.id + ':' + i} style={{
                display: 'grid', gridTemplateColumns: '70px 90px 1fr 200px',
                gap: 14, padding: '14px', borderBottom: '1px solid var(--rule-soft)',
                alignItems: 'center', fontSize: 12,
              }}>
                <span className="ff-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                  {new Date(run.ts).toTimeString().slice(0, 5)}
                </span>
                <span className="ff-mono upper" style={{
                  fontSize: 9, padding: '3px 7px', textAlign: 'center', letterSpacing: '.12em', fontWeight: 600,
                  background: a.action === 'notify.inbox' ? 'var(--ink)' : 'transparent',
                  color: a.action === 'notify.inbox' ? 'var(--bg)' : 'var(--ink-2)',
                  border: a.action === 'notify.inbox' ? '0' : '1px solid var(--rule)',
                }}>{a.action.split('.')[1]}</span>
                <div>
                  <div style={{ fontWeight: 500 }}>{a.message}</div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 2 }}>via "{run.ruleName}" · {run.triggerLabel}</div>
                </div>
                <span className="ff-mono" style={{ fontSize: 10, color: 'var(--ink-3)', textAlign: 'right' }}>
                  {new Date(run.ts).toLocaleDateString()}
                </span>
              </div>
            ));
          })}
        </div>
      </div>
    );
  }

  // ─── MAIN screen ───────────────────────────────────────────────
  function ScreenAutomations({ go, payload }) {
    const [tab, setTab] = _S(payload?.tab || 'rules');
    const [editing, setEditing] = _S(null);

    _E(() => { seedDefaultRules(); }, []);

    function openEditor(rule) { setEditing(rule); }
    function saveRule(rule) {
      window.AutoEngine.saveRule(rule);
      setEditing(null);
    }
    function deleteRule(id) {
      window.AutoEngine.deleteRule(id);
      setEditing(null);
    }

    const TABS = [
      { k: 'rules',         l: 'Rules' },
      { k: 'library',       l: 'Library' },
      { k: 'activity',      l: 'Activity' },
      { k: 'schedules',     l: 'Schedules' },
      { k: 'notifications', l: 'Notifications' },
    ];

    return (
      <div>
        {window.PageHeader && (
          <window.PageHeader
            eyebrow={['OPERATIONS', 'AUTOMATIONS', 'RULES + SCHEDULES']}
            title="automations."
            highlight="automations"
            sub="Tell ASTRO what to do when things happen. Trigger rules off CWR acks, ML signals, statements, and DSP events; fire actions like claim filing, payout holds, takedowns, and notifications. Time-based jobs live alongside event-driven rules."
          />
        )}

        <div style={{ borderBottom: '1px solid var(--rule)', display: 'flex', gap: 0 }}>
          {TABS.map(t => (
            <button key={t.k} onClick={() => setTab(t.k)} style={{
              padding: '14px 22px', background: 'transparent', border: 0,
              borderBottom: '2px solid ' + (tab === t.k ? 'var(--ink)' : 'transparent'),
              cursor: 'pointer', color: tab === t.k ? 'var(--ink)' : 'var(--ink-3)',
              fontSize: 13, fontWeight: tab === t.k ? 600 : 400,
            }}>{t.l}</button>
          ))}
        </div>

        <div style={{ paddingTop: 24 }}>
          {tab === 'rules'         && <RulesTab openEditor={openEditor}/>}
          {tab === 'library'       && <LibraryTab openEditor={openEditor}/>}
          {tab === 'activity'      && <ActivityTab/>}
          {tab === 'schedules'     && <SchedulesTab/>}
          {tab === 'notifications' && <NotificationsTab/>}
        </div>

        {editing && (
          <RuleEditor rule={editing} onClose={() => setEditing(null)} onSave={saveRule} onDelete={deleteRule}/>
        )}
      </div>
    );
  }

  window.ScreenAutomations = ScreenAutomations;
  console.log('[Automations] screen loaded');
})();
