// assets/screen_alerts.jsx
function ScreenAlerts({ t }) {
  const [tab, setTab] = React.useState('active');
  const [editing, setEditing] = React.useState(null);
  const [alerts, setAlerts] = React.useState(ALERTS);

  const sevColor = { info: 'info', warning: 'warning', critical: 'danger' };
  const counts = {
    active: alerts.filter(a => a.enabled).length,
    fired_24h: ALERT_HISTORY.filter(h => Date.now() - h.ts < 86400000).length,
    unack: ALERT_HISTORY.filter(h => !h.ack).length,
  };

  return (
    <div className="page">
      <div className="page-head">
        <h1>Alerts</h1>
        <span className="page-sub">{counts.active} enabled · {counts.fired_24h} fired in 24h · {counts.unack} unack</span>
        <div className="page-actions">
          <button className="btn primary" onClick={() => { setEditing({}); setTab('add'); }}><Icon name="plus" size={12} /> New alert</button>
        </div>
      </div>

      <div className="tabs">
        <div className={`tab ${tab === 'active' ? 'active' : ''}`} onClick={() => setTab('active')}>
          <Icon name="alert" size={12} /> Active <span className="count">{alerts.length}</span>
        </div>
        <div className={`tab ${tab === 'add' ? 'active' : ''}`} onClick={() => { setTab('add'); setEditing(editing || {}); }}>
          <Icon name="plus" size={12} /> {editing?.id ? 'Edit' : 'Add'} alert
        </div>
        <div className={`tab ${tab === 'history' ? 'active' : ''}`} onClick={() => setTab('history')}>
          <Icon name="trace" size={12} /> History <span className="count">{ALERT_HISTORY.length}</span>
        </div>
        <div className={`tab ${tab === 'templates' ? 'active' : ''}`} onClick={() => setTab('templates')}>
          <Icon name="layers" size={12} /> Templates
        </div>
      </div>

      {tab === 'active' && (
        <div className="card">
          <div className="table-wrap">
            <table className="tbl">
              <thead><tr>
                <th style={{ width: 36 }}></th>
                <th>Name</th>
                <th>Type</th>
                <th>Condition</th>
                <th>Severity</th>
                <th>Cooldown</th>
                <th>Channels</th>
                <th>Last triggered</th>
                <th style={{ width: 120 }}></th>
              </tr></thead>
              <tbody>
                {alerts.map(a => (
                  <tr key={a.id}>
                    <td>
                      <span className={`toggle ${a.enabled ? 'on' : ''}`} onClick={() => setAlerts(prev => prev.map(x => x.id === a.id ? { ...x, enabled: !x.enabled } : x))} />
                    </td>
                    <td style={{ fontWeight: 500 }}>{a.name}</td>
                    <td><Mono>{a.type}</Mono></td>
                    <td className="dim2"><Mono>{a.condition}</Mono></td>
                    <td><Badge kind={sevColor[a.severity]}>{a.severity}</Badge></td>
                    <td className="dim"><Mono>{a.cooldown}</Mono></td>
                    <td>
                      {a.channels.map(c => <Badge key={c} kind="neutral" style={{ marginRight: 4 }}>{c}</Badge>)}
                    </td>
                    <td className="dim"><Mono>{a.last_triggered ? formatRel(a.last_triggered) : '—'}</Mono></td>
                    <td>
                      <button className="btn xs ghost" onClick={() => { setEditing(a); setTab('add'); }}><Icon name="edit" size={11} /></button>
                      <button className="btn xs ghost"><Icon name="trash" size={11} /></button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'add' && <AlertForm editing={editing || {}} onCancel={() => { setEditing(null); setTab('active'); }} onSave={(a) => { 
        if (a.id) setAlerts(prev => prev.map(x => x.id === a.id ? a : x));
        else setAlerts(prev => [...prev, { ...a, id: 'al-' + (prev.length + 1) }]);
        setEditing(null); setTab('active');
      }} />}

      {tab === 'history' && (
        <div className="card">
          <div className="table-wrap">
            <table className="tbl">
              <thead><tr>
                <th>Alert</th>
                <th>Triggered</th>
                <th>Value</th>
                <th>Severity</th>
                <th>Channels</th>
                <th>Ack</th>
                <th style={{ width: 110 }}></th>
              </tr></thead>
              <tbody>
                {ALERT_HISTORY.map(h => (
                  <tr key={h.id} className={!h.ack ? 'fp-suspect-row' : ''}>
                    <td style={{ fontWeight: 500 }}>{h.alert_name}</td>
                    <td className="dim"><Mono>{formatRel(h.ts)}</Mono></td>
                    <td className="dim2"><Mono>{h.value}</Mono></td>
                    <td><Badge kind={sevColor[h.severity]}>{h.severity}</Badge></td>
                    <td>{h.channels.map(c => <Badge key={c} kind="neutral" style={{ marginRight: 4 }}>{c}</Badge>)}</td>
                    <td>{h.ack
                      ? <span style={{ color: 'var(--success)', fontSize: 11, display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="check" size={11} /> {h.ack_by?.split('@')[0]}</span>
                      : <Badge kind="warning">pending</Badge>}</td>
                    <td>{!h.ack && <button className="btn xs">Acknowledge</button>}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'templates' && (
        <div className="grid cols-3">
          {[
            { name: 'Slow session > 20m', desc: 'session.duration > 20m', type: 'slow_session', sev: 'warning' },
            { name: 'Publish fail > 30%', desc: 'fail_rate > 30% in 1h window', type: 'publish_fail_spike', sev: 'critical' },
            { name: 'Hook FP > 5', desc: 'same hook fires > 5 times in one session', type: 'hook_fp_suspect', sev: 'warning' },
            { name: 'Daily cost > $500', desc: 'sum(cost) > $500 in 24h', type: 'cost_total_daily', sev: 'critical' },
            { name: 'Queue depth > 50', desc: 'celery queue length > 50', type: 'worker_queue_backlog', sev: 'warning' },
            { name: 'Same TS error > 10/h', desc: 'count(error_code) > 10 in 1h', type: 'deployment_error_pattern', sev: 'warning' },
          ].map(tpl => (
            <div key={tpl.name} className="card" style={{ padding: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icon name={ALERT_TYPES.find(t => t.value === tpl.type)?.icon || 'alert'} size={14} className="text-accent" />
                <h3 style={{ margin: 0, fontSize: 13 }}>{tpl.name}</h3>
                <Badge kind={sevColor[tpl.sev]} style={{ marginLeft: 'auto' }}>{tpl.sev}</Badge>
              </div>
              <div className="dim2 fs-12" style={{ margin: '6px 0 10px', fontFamily: 'var(--font-mono)' }}>{tpl.desc}</div>
              <button className="btn primary sm" style={{ width: '100%', justifyContent: 'center' }}>
                <Icon name="plus" size={11} /> Quick add
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function AlertForm({ editing, onCancel, onSave }) {
  const [name, setName] = React.useState(editing.name || '');
  const [type, setType] = React.useState(editing.type || 'slow_session');
  const [threshold, setThreshold] = React.useState(editing.threshold || '');
  const [window_, setWindow_] = React.useState(editing.window || '1h');
  const [severity, setSeverity] = React.useState(editing.severity || 'warning');
  const [cooldown, setCooldown] = React.useState(editing.cooldown || '15m');
  const [channels, setChannels] = React.useState(new Set(editing.channels || []));
  const [enabled, setEnabled] = React.useState(editing.enabled ?? true);

  const allChannels = [...DISCORD_CHANNELS.map(c => c.name), ...EMAIL_RECIPIENTS];
  const tpl = ALERT_TYPES.find(t => t.value === type);

  // Type-dependent threshold helpers
  const thresholdUnit = {
    slow_session: 'minutes',
    publish_fail_spike: '% (e.g. 30)',
    hook_fp_suspect: 'fires (e.g. 5)',
    cost_spike_merchant: '$ / hour',
    worker_queue_backlog: 'jobs',
    deployment_error_pattern: 'occurrences',
    cost_total_daily: '$ / day',
  };

  return (
    <div className="card" style={{ maxWidth: 720 }}>
      <div className="card-head">
        <h3>{editing.id ? 'Edit alert' : 'New alert'}</h3>
        <span className="sub">{editing.id ? editing.id : 'POST /admin/alerts'}</span>
      </div>
      <div className="card-body" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>

        <div>
          <label className="fs-11 dim2" style={{ display: 'block', marginBottom: 5, fontWeight: 500 }}>Name</label>
          <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Slow session > 20m" />
        </div>

        <div>
          <label className="fs-11 dim2" style={{ display: 'block', marginBottom: 5, fontWeight: 500 }}>Type</label>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
            {ALERT_TYPES.map(opt => (
              <div key={opt.value} onClick={() => setType(opt.value)}
                style={{ padding: '8px 10px', border: '1px solid', borderColor: type === opt.value ? 'var(--accent)' : 'var(--border-default)', borderRadius: 'var(--radius)', cursor: 'pointer', background: type === opt.value ? 'var(--accent-muted)' : 'transparent', display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icon name={opt.icon} size={14} className={type === opt.value ? 'text-accent' : 'dim'} />
                <span style={{ fontSize: 12, color: type === opt.value ? 'var(--accent)' : 'var(--text-primary)' }}>{opt.label}</span>
                <Mono dim style={{ marginLeft: 'auto', fontSize: 10 }}>{opt.value}</Mono>
              </div>
            ))}
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <label className="fs-11 dim2" style={{ display: 'block', marginBottom: 5, fontWeight: 500 }}>Threshold <span className="dim">· {thresholdUnit[type]}</span></label>
            <input className="input" value={threshold} onChange={e => setThreshold(e.target.value)} placeholder="20" />
          </div>
          <div>
            <label className="fs-11 dim2" style={{ display: 'block', marginBottom: 5, fontWeight: 500 }}>Time window</label>
            <select className="select" value={window_} onChange={e => setWindow_(e.target.value)}>
              <option value="live">live</option>
              <option value="5m">5m</option>
              <option value="15m">15m</option>
              <option value="1h">1h</option>
              <option value="24h">24h</option>
              <option value="session">session</option>
            </select>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <label className="fs-11 dim2" style={{ display: 'block', marginBottom: 5, fontWeight: 500 }}>Severity</label>
            <div className="segmented" style={{ width: '100%' }}>
              {['info', 'warning', 'critical'].map(s => (
                <button key={s} className={severity === s ? 'active' : ''} onClick={() => setSeverity(s)} style={{ flex: 1 }}>{s}</button>
              ))}
            </div>
          </div>
          <div>
            <label className="fs-11 dim2" style={{ display: 'block', marginBottom: 5, fontWeight: 500 }}>Cooldown</label>
            <select className="select" value={cooldown} onChange={e => setCooldown(e.target.value)}>
              <option value="5m">5m</option>
              <option value="15m">15m</option>
              <option value="1h">1h</option>
              <option value="24h">24h</option>
            </select>
          </div>
        </div>

        <div>
          <label className="fs-11 dim2" style={{ display: 'block', marginBottom: 5, fontWeight: 500 }}>Channels</label>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {allChannels.map(ch => {
              const on = channels.has(ch);
              return (
                <span key={ch} onClick={() => { const n = new Set(channels); if (on) n.delete(ch); else n.add(ch); setChannels(n); }}
                  className={`badge ${on ? 'accent' : 'outline'}`} style={{ cursor: 'pointer', padding: '4px 10px', fontSize: 11 }}>
                  <Icon name={ch.startsWith('#') ? 'discord' : 'mail'} size={11} /> {ch}
                </span>
              );
            })}
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className={`toggle ${enabled ? 'on' : ''}`} onClick={() => setEnabled(e => !e)} />
          <span style={{ fontSize: 12 }}>Enabled</span>
        </div>

        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', borderTop: '1px solid var(--border-subtle)', paddingTop: 12 }}>
          <button className="btn ghost" onClick={onCancel}>Cancel</button>
          <button className="btn primary" onClick={() => onSave({ ...editing, name, type, threshold, window: window_, severity, cooldown, channels: [...channels], enabled, condition: editing.condition || `${type} threshold ${threshold} in ${window_}` })}>
            <Icon name="check" size={12} /> {editing.id ? 'Save changes' : 'Create alert'}
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenAlerts });
