/* ============================================================
   Screen 9 — Bildirishnomalar (Alerts & Escalation)
   ============================================================ */

function ScreenAlerts() {
  const [tab, setTab] = useState('active');
  const [selectedRule, setSelectedRule] = useState('r1');
  const [channels, setChannels] = useState({ inapp: true, telegram: true, sms: false, email: true });

  // Active alerts (richer than the small list in dashboard)
  const ACTIVE = [
    { id: 'AL-2026-0418', sev: 'critical', uz: 'Piyoz narxi anomaliya — Samarqand viloyatida 38% pasaydi', rule: 'Narx anomaliya', topic: 'onion', region: 'sam', mins: 12, ack: false, by: null, value: '−38%', threshold: '±15%', count: 47 },
    { id: 'AL-2026-0417', sev: 'critical', uz: 'Mol go\'shti narxi 12% ko\'tarildi — Fargʻona', rule: 'Narx anomaliya', topic: 'beef', region: 'fer', mins: 38, ack: false, by: null, value: '+12%', threshold: '±10%', count: 23 },
    { id: 'AL-2026-0416', sev: 'warning',  uz: 'Logistika murojaatlari +47% (24 soat) — Qashqadaryo', rule: 'Hajm portlash', topic: 'logistic', region: 'qsh', mins: 64, ack: false, by: null, value: '+47%', threshold: '+30%', count: 89 },
    { id: 'AL-2026-0415', sev: 'warning',  uz: 'AI ishonchliligi 78% gacha tushdi (Naslchilik)', rule: 'Model degradatsiyasi', topic: 'breeding', mins: 122, ack: true, by: 'F. Tojiyeva', value: '78%', threshold: '<85%', count: 12 },
    { id: 'AL-2026-0414', sev: 'warning',  uz: 'SLA buzilishi — 8 ta shoshilinch murojaat 2 soatdan ortiq kutmoqda', rule: 'SLA monitor', mins: 184, ack: false, by: null, value: '8 ta', threshold: '>5 ta', count: 8 },
    { id: 'AL-2026-0413', sev: 'info',     uz: 'Kunlik hisobot tayyor', rule: 'Tizim hodisalari', mins: 220, ack: true, by: 'Tizim', value: 'PDF · 12 bet', threshold: '—', count: 1 },
    { id: 'AL-2026-0412', sev: 'critical', uz: 'Bot ulanishi 4 daqiqa uzilib qoldi', rule: 'Servis nazorat', mins: 256, ack: true, by: 'A. Karimov', value: '247s', threshold: '>60s', count: 1 },
    { id: 'AL-2026-0411', sev: 'warning',  uz: 'Salbiy sentiment ulushi 28% (Un mavzusi)', rule: 'Sentiment monitor', topic: 'flour', mins: 312, ack: false, by: null, value: '28%', threshold: '>20%', count: 34 },
    { id: 'AL-2026-0410', sev: 'info',     uz: 'Yangi tahlilchi tizimga qoʻshildi: O. Nazarov', rule: 'Tizim hodisalari', mins: 412, ack: true, by: 'Tizim', value: '+1 a\'zo', threshold: '—', count: 1 },
    { id: 'AL-2026-0409', sev: 'warning',  uz: 'Eksport so\'rovlari +52% (Guruch) — 7 kun', rule: 'Hajm portlash', topic: 'rice', mins: 588, ack: true, by: 'D. Yusupova', value: '+52%', threshold: '+30%', count: 71 },
  ];

  const RULES = [
    { id: 'r1', name: 'Narx anomaliyasi', uz: 'Narx anomaliyasi', metric: 'price_change', cond: 'abs > 15%', window: '6 soat', sev: 'critical', channels: ['telegram', 'email'], active: true, fired30d: 14 },
    { id: 'r2', name: 'Hajm portlashi', uz: 'Hajm portlashi', metric: 'volume_pct', cond: '> +30%', window: '24 soat', sev: 'warning', channels: ['inapp', 'telegram'], active: true, fired30d: 22 },
    { id: 'r3', name: 'AI degradatsiyasi', uz: 'AI degradatsiyasi', metric: 'ai_confidence', cond: '< 85%', window: '1 soat', sev: 'warning', channels: ['email'], active: true, fired30d: 4 },
    { id: 'r4', name: 'SLA buzilishi', uz: 'SLA buzilishi', metric: 'urgent_overdue', cond: '> 5 ta', window: '15 daqiqa', sev: 'critical', channels: ['telegram', 'sms', 'email'], active: true, fired30d: 31 },
    { id: 'r5', name: 'Sentiment monitoring', uz: 'Sentiment monitoringi', metric: 'sentiment_neg', cond: '> 20%', window: '24 soat', sev: 'warning', channels: ['inapp'], active: true, fired30d: 18 },
    { id: 'r6', name: 'Bot uzilishi', uz: 'Servis nazorati', metric: 'service_down', cond: '> 60s', window: 'live', sev: 'critical', channels: ['telegram', 'sms', 'email'], active: true, fired30d: 2 },
    { id: 'r7', name: 'Tinch davr', uz: 'Tinch davr', metric: 'volume_pct', cond: '< -50%', window: '6 soat', sev: 'info', channels: ['inapp'], active: false, fired30d: 0 },
  ];

  const sel = RULES.find(r => r.id === selectedRule) || RULES[0];

  // Escalation chain
  const CHAIN = [
    { level: 1, name: 'Navbatchi tahlilchi', who: 'Mansublik bo\'yicha (smena bo\'yicha)', timeout: '15 daqiqa', sample: ['B. Rashidov', 'R. Ismoilov', 'O. Nazarov'] },
    { level: 2, name: 'Bo\'lim boshlig\'i', who: 'AI nazorat boshlig\'i', timeout: '30 daqiqa', sample: ['F. Tojiyeva'] },
    { level: 3, name: 'Vazir o\'rinbosari', who: 'Oziq-ovqat masalalari bo\'yicha', timeout: '2 soat', sample: ['M. Saidov'] },
    { level: 4, name: 'Vazir kabineti', who: 'Faqat critical bo\'yicha', timeout: '—', sample: ['Vazir oldida'] },
  ];

  const sevColor = { critical: 'var(--rose)', warning: 'var(--amber)', info: 'var(--accent)' };
  const sevLabel = { critical: 'Kritik', warning: 'Ogohlantirish', info: 'Maʼlumot' };

  // Trend: alerts fired per day (30 days)
  const ALERT_TREND = useMemo(() => {
    const arr = [];
    for (let i = 0; i < 30; i++) {
      arr.push({
        critical: Math.max(0, Math.round(gauss() * 2 + (i > 22 ? 4 : 2))),
        warning: Math.max(0, Math.round(gauss() * 3 + 5)),
        info: Math.max(0, Math.round(rand() * 2 + 1)),
      });
    }
    return arr;
  }, []);

  const counts = {
    critical: ACTIVE.filter(a => a.sev === 'critical').length,
    warning: ACTIVE.filter(a => a.sev === 'warning').length,
    info: ACTIVE.filter(a => a.sev === 'info').length,
    unack: ACTIVE.filter(a => !a.ack).length,
  };

  return (
    <div className="page" style={{ maxWidth: '100%' }}>
      <div className="page-head">
        <div>
          <div className="page-crumbs">
            <span>Asosiy</span><span>/</span><span style={{ color: 'var(--ink-2)' }}>Bildirishnomalar</span>
          </div>
          <h1 className="page-title">Bildirishnomalar<span className="ru">Оповещения · Alerts & escalation</span></h1>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="bell" size={12} /> Test ogohlantirish</button>
          <button className="btn btn-primary"><Icon name="plus" size={12} /> Yangi qoida</button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="kpi-strip mb-12" style={{ gridTemplateColumns: 'repeat(5, 1fr)' }}>
        <SeverityKpi sev="critical" count={counts.critical} unack={ACTIVE.filter(a => a.sev === 'critical' && !a.ack).length} />
        <SeverityKpi sev="warning"  count={counts.warning}  unack={ACTIVE.filter(a => a.sev === 'warning' && !a.ack).length} />
        <SeverityKpi sev="info"     count={counts.info}     unack={0} />
        <div className="kpi">
          <div className="kpi-label">Tasdiqlanmagan</div>
          <div className="kpi-value">{counts.unack}</div>
          <div className="kpi-delta delta-down">↓ 2 · 1 soatda</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Faol qoidalar</div>
          <div className="kpi-value">{RULES.filter(r => r.active).length}<span className="unit"> / {RULES.length}</span></div>
          <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>oxirgi 30 kun: {RULES.reduce((s, r) => s + r.fired30d, 0)} marta</div>
        </div>
      </div>

      {/* Tabs */}
      <div className="tabs mb-12">
        <button className={`tab ${tab === 'active' ? 'on' : ''}`} onClick={() => setTab('active')}>Faol ogohlantirishlar <span style={{ marginLeft: 6, color: 'var(--rose)', fontWeight: 600 }}>{counts.unack}</span></button>
        <button className={`tab ${tab === 'rules' ? 'on' : ''}`} onClick={() => setTab('rules')}>Qoidalar konstruktori</button>
        <button className={`tab ${tab === 'escalation' ? 'on' : ''}`} onClick={() => setTab('escalation')}>Eskalatsiya zanjiri</button>
        <button className={`tab ${tab === 'channels' ? 'on' : ''}`} onClick={() => setTab('channels')}>Kanallar</button>
      </div>

      {tab === 'active' && (
        <>
          {/* Trend strip */}
          <Panel title="Ogohlantirishlar dinamikasi" sub="30 kun · severity bo'yicha" num="01" className="mb-12">
            <AlertTrend data={ALERT_TREND} />
          </Panel>

          <div className="grid-2-1">
            <Panel title="Faol ogohlantirishlar" sub="eng yangi tepada · bosish → tasdiqlash" num="02" body={false}>
              <div>
                {ACTIVE.map(a => (
                  <div key={a.id} style={{
                    display: 'grid',
                    gridTemplateColumns: '5px 24px 1fr auto auto auto',
                    gap: 12, alignItems: 'start',
                    padding: '12px 14px',
                    borderBottom: '1px solid var(--line)',
                    background: !a.ack ? 'var(--panel)' : 'var(--bg-sunken)',
                    opacity: a.ack ? 0.75 : 1,
                  }}>
                    <div style={{ width: 4, alignSelf: 'stretch', background: sevColor[a.sev], borderRadius: 1 }} />
                    <span style={{ marginTop: 2, width: 18, height: 18, borderRadius: '50%', background: sevColor[a.sev], color: 'white', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700 }}>
                      {a.sev === 'critical' ? '!' : a.sev === 'warning' ? '⚠' : 'i'}
                    </span>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, color: 'var(--ink-4)' }}>{a.id}</span>
                        <span className="chip" style={{ fontSize: 9.5 }}>{a.rule}</span>
                        {a.topic && (
                          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 10.5, color: 'var(--ink-3)' }}>
                            <TopicMark topicId={a.topic} size={11} />
                            {TOPIC_BY_ID[a.topic].uz}
                          </span>
                        )}
                        {a.region && <span style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>· {REGION_BY_ID[a.region].uz}</span>}
                      </div>
                      <div style={{ fontSize: 12.5, color: 'var(--ink)', marginTop: 4, lineHeight: 1.4, fontWeight: !a.ack ? 500 : 400 }}>{a.uz}</div>
                      <div style={{ display: 'flex', gap: 6, marginTop: 6, fontSize: 10.5, fontFamily: 'var(--font-mono)', color: 'var(--ink-4)' }}>
                        <span><span style={{ color: 'var(--ink-3)' }}>qiymat:</span> <strong style={{ color: sevColor[a.sev] }}>{a.value}</strong></span>
                        <span>·</span>
                        <span><span style={{ color: 'var(--ink-3)' }}>chegara:</span> {a.threshold}</span>
                        {a.count > 1 && <>
                          <span>·</span>
                          <span><span style={{ color: 'var(--ink-3)' }}>ta'sirlangan:</span> {a.count} ta murojaat</span>
                        </>}
                      </div>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      <div className="mono" style={{ fontSize: 11, color: 'var(--ink-2)' }}>{a.mins < 60 ? `${a.mins} daq` : `${(a.mins / 60).toFixed(1)} soat`}</div>
                      <div style={{ fontSize: 9.5, color: 'var(--ink-4)' }}>oldin</div>
                    </div>
                    <div>
                      {a.ack
                        ? <span className="chip chip-jade" style={{ fontSize: 10 }}>✓ {a.by}</span>
                        : <span className="chip chip-rose" style={{ fontSize: 10 }}>kutmoqda</span>}
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                      {!a.ack && <button className="btn btn-sm btn-primary">Tasdiqlash</button>}
                      <button className="btn btn-sm">Tafsilot</button>
                    </div>
                  </div>
                ))}
              </div>
            </Panel>

            <Panel title="Ogohlantirishlar manzili" sub="qaerga yo'naltirilgan" num="03">
              <div style={{ padding: 4 }}>
                {[
                  { name: 'F. Tojiyeva',   role: 'Bo\'lim boshlig\'i',  alerts: 12, urgent: 4, channel: ['inapp', 'telegram', 'email'] },
                  { name: 'A. Karimov',    role: 'Bosh tahlilchi',     alerts: 8,  urgent: 2, channel: ['inapp', 'telegram'] },
                  { name: 'S. Mirzayeva',  role: 'Logistika',           alerts: 14, urgent: 5, channel: ['inapp', 'telegram', 'sms'] },
                  { name: 'B. Rashidov',   role: 'Narx-navo',           alerts: 9,  urgent: 3, channel: ['inapp', 'email'] },
                  { name: 'D. Yusupova',   role: 'Sabzavot',            alerts: 6,  urgent: 1, channel: ['inapp'] },
                ].map(p => (
                  <div key={p.name} style={{ padding: '10px 0', borderBottom: '1px solid var(--line)' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <Avatar name={p.name} size={26} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 12, fontWeight: 500 }}>{p.name}</div>
                        <div style={{ fontSize: 10, color: 'var(--ink-4)' }}>{p.role}</div>
                      </div>
                      <div style={{ textAlign: 'right' }}>
                        <div className="mono" style={{ fontSize: 13, fontWeight: 500 }}>{p.alerts}</div>
                        <div style={{ fontSize: 9.5, color: 'var(--ink-4)' }}>30 kun</div>
                      </div>
                    </div>
                    <div style={{ display: 'flex', gap: 4, marginTop: 6, alignItems: 'center' }}>
                      {p.urgent > 0 && <span className="chip chip-rose" style={{ fontSize: 9.5 }}>{p.urgent} shosh.</span>}
                      <div style={{ display: 'flex', gap: 3, marginLeft: 'auto' }}>
                        {p.channel.includes('inapp')    && <span className="chip" style={{ fontSize: 9 }}>App</span>}
                        {p.channel.includes('telegram') && <span className="chip chip-accent" style={{ fontSize: 9 }}>TG</span>}
                        {p.channel.includes('sms')      && <span className="chip chip-amber" style={{ fontSize: 9 }}>SMS</span>}
                        {p.channel.includes('email')    && <span className="chip" style={{ fontSize: 9 }}>Email</span>}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </Panel>
          </div>
        </>
      )}

      {tab === 'rules' && (
        <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: 16 }}>
          <Panel title="Qoidalar" sub={`${RULES.length} ta`} num="01" body={false}>
            <div>
              {RULES.map(r => (
                <div key={r.id} onClick={() => setSelectedRule(r.id)} style={{
                  padding: '10px 14px',
                  borderBottom: '1px solid var(--line)',
                  borderLeft: `3px solid ${selectedRule === r.id ? sevColor[r.sev] : 'transparent'}`,
                  background: selectedRule === r.id ? 'var(--bg-sunken)' : '',
                  cursor: 'pointer',
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                    <span style={{ fontSize: 12, fontWeight: selectedRule === r.id ? 600 : 500 }}>{r.uz}</span>
                    <span className={`toggle ${r.active ? 'on' : ''}`} style={{ flexShrink: 0 }} />
                  </div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', marginTop: 3 }}>{r.cond} · {r.window}</div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 6 }}>
                    <span className={`chip chip-${r.sev === 'critical' ? 'rose' : r.sev === 'warning' ? 'amber' : 'accent'}`} style={{ fontSize: 9.5 }}>{sevLabel[r.sev]}</span>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-4)' }}>{r.fired30d}× / 30k</span>
                  </div>
                </div>
              ))}
            </div>
          </Panel>

          <Panel title={`Qoida tahriri · ${sel.uz}`} sub="agar ... bo'lsa, unda ..." num="02">
            <RuleEditor rule={sel} />
          </Panel>
        </div>
      )}

      {tab === 'escalation' && (
        <Panel title="Eskalatsiya zanjiri" sub="agar tasdiqlanmasa, keyingi darajaga yuborish" num="01">
          <div style={{ position: 'relative', padding: '20px 12px' }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 32, position: 'relative' }}>
              {CHAIN.map((c, i) => (
                <div key={c.level}>
                  {/* arrow connector */}
                  {i < CHAIN.length - 1 && (
                    <div style={{
                      position: 'absolute', top: 64, left: `${(i + 1) * 25 - 1}%`,
                      width: 'calc(8% + 0px)', height: 1, background: 'var(--line-strong)',
                      transform: 'translateX(-50%)',
                      zIndex: 0,
                    }} />
                  )}
                  <div className="panel" style={{ padding: 16, position: 'relative', zIndex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
                      <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--ink)', color: 'var(--bg)', display: 'grid', placeItems: 'center', fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600 }}>{c.level}</div>
                      <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)' }}>+{c.timeout}</span>
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: '-0.01em' }}>{c.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 3 }}>{c.who}</div>
                    <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--line)' }}>
                      <div style={{ fontSize: 9, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 5 }}>Joriy mas'ul</div>
                      {c.sample.map(s => (
                        <div key={s} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '2px 0', fontSize: 11.5 }}>
                          {s.startsWith('Vazir') ? <span className="dot" style={{ background: 'var(--ink)' }} /> : <Avatar name={s} size={18} />}
                          <span>{s}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div style={{ marginTop: 6, paddingTop: 14, borderTop: '1px solid var(--line)', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
            <RuleField label="Avto-eskalatsiya">
              <span className="toggle on" /> <span style={{ marginLeft: 8, fontSize: 11 }}>Yoqilgan</span>
            </RuleField>
            <RuleField label="Critical → darajani o'tkazib yuborish">
              <select className="select"><option>Hech qaysi</option><option>1-daraja</option><option>1 va 2-daraja</option></select>
            </RuleField>
            <RuleField label="Ish vaqtidan tashqari xatti-harakat">
              <select className="select"><option>SMS + Telegram</option><option>Faqat Telegram</option><option>Faqat ertasi kun</option></select>
            </RuleField>
          </div>
        </Panel>
      )}

      {tab === 'channels' && (
        <div className="grid-2 mb-12">
          {[
            { id: 'inapp',    name: 'Ichki bildirishnoma', desc: 'Brauzerda bell ikonkasi · push-notif', count: 218, latency: '<1 s', status: 'jade', color: 'var(--accent)', icon: 'bell' },
            { id: 'telegram', name: 'Telegram',             desc: '@oziq_alerts_bot · DM va guruhga', count: 187, latency: '~2 s', status: 'jade', color: 'var(--accent-ink)', icon: 'pulse' },
            { id: 'sms',      name: 'SMS',                  desc: 'Mobiuz / Beeline shlyuzi', count: 24, latency: '~12 s', status: 'amber', color: 'var(--amber)', icon: 'plug' },
            { id: 'email',    name: 'Elektron pochta',      desc: 'mof.uz domeni · DKIM faol', count: 142, latency: '~8 s', status: 'jade', color: 'var(--ink-3)', icon: 'doc' },
          ].map(ch => (
            <Panel key={ch.id} title={ch.name} sub={ch.desc} num={ch.id === 'inapp' ? '01' : ch.id === 'telegram' ? '02' : ch.id === 'sms' ? '03' : '04'}
              actions={
                <>
                  <button className="btn btn-sm">Test</button>
                  <span className={`toggle ${channels[ch.id] ? 'on' : ''}`} onClick={() => setChannels(c => ({ ...c, [ch.id]: !c[ch.id] }))} />
                </>
              }
            >
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 14 }}>
                <div>
                  <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Bugun yuborildi</div>
                  <div className="mono" style={{ fontSize: 18, fontWeight: 500 }}>{ch.count}</div>
                </div>
                <div>
                  <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Kechikish</div>
                  <div className="mono" style={{ fontSize: 18, fontWeight: 500 }}>{ch.latency}</div>
                </div>
                <div>
                  <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Holat</div>
                  <div style={{ fontSize: 14, fontWeight: 500, color: ch.status === 'jade' ? 'var(--jade)' : 'var(--amber)' }}>
                    <span className="dot" style={{ background: ch.status === 'jade' ? 'var(--jade)' : 'var(--amber)', marginRight: 5 }} />
                    {ch.status === 'jade' ? 'Sogʻlom' : 'Sekin'}
                  </div>
                </div>
              </div>

              <div style={{ display: 'grid', gap: 8 }}>
                {ch.id === 'inapp' && <>
                  <RuleField label="Tovush"><span className="toggle on" /></RuleField>
                  <RuleField label="Bosh sahifaga banner"><span className="toggle on" /></RuleField>
                </>}
                {ch.id === 'telegram' && <>
                  <RuleField label="Bot tokeni"><input className="input" defaultValue="••••••••••••••••••••" type="password" /></RuleField>
                  <RuleField label="Default chat"><span className="mono" style={{ fontSize: 11 }}>@oziq_alerts (gov)</span></RuleField>
                  <RuleField label="Critical → minister"><span className="toggle on" /></RuleField>
                </>}
                {ch.id === 'sms' && <>
                  <RuleField label="Shlyuz"><select className="select"><option>Mobiuz API</option><option>Beeline</option><option>UMS</option></select></RuleField>
                  <RuleField label="Faqat critical"><span className="toggle on" /></RuleField>
                  <RuleField label="Ish vaqtida"><span className="toggle" /></RuleField>
                </>}
                {ch.id === 'email' && <>
                  <RuleField label="Yuboruvchi"><span className="mono" style={{ fontSize: 11 }}>alerts@mof.uz</span></RuleField>
                  <RuleField label="HTML shabloni"><select className="select"><option>Vazirlik standarti</option><option>Sodda</option></select></RuleField>
                </>}
              </div>

              <div style={{ marginTop: 14, padding: 10, background: 'var(--bg-sunken)', borderRadius: 4, fontSize: 11 }}>
                <div style={{ fontSize: 9, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 4 }}>Soʻnggi yuborish</div>
                <div className="mono" style={{ color: 'var(--ink-2)' }}>14.05.2026 · 14:28:12 — "Piyoz narxi anomaliya..."</div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', marginTop: 2 }}>OK · 200 · {ch.latency}</div>
              </div>
            </Panel>
          ))}
        </div>
      )}
    </div>
  );
}

// ============================================================
// Helpers
// ============================================================
function SeverityKpi({ sev, count, unack }) {
  const map = {
    critical: { uz: 'Kritik',           color: 'var(--rose)', soft: 'var(--rose-soft)' },
    warning:  { uz: 'Ogohlantirish',     color: 'var(--amber)', soft: 'var(--amber-soft)' },
    info:     { uz: 'Maʼlumot',          color: 'var(--accent)', soft: 'var(--accent-soft)' },
  };
  const m = map[sev];
  return (
    <div className="kpi" style={{ position: 'relative' }}>
      <div className="kpi-label" style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: m.color }} />
        {m.uz}
      </div>
      <div className="kpi-value">{count}</div>
      <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>
        {unack > 0 ? <span style={{ color: m.color }}>{unack} tasdiqlanmagan</span> : 'hammasi tasdiqlangan'}
      </div>
    </div>
  );
}

function RuleField({ label, children }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0', borderBottom: '1px dotted var(--line)' }}>
      <span style={{ fontSize: 11, color: 'var(--ink-3)', width: 140, flexShrink: 0 }}>{label}</span>
      <div style={{ flex: 1 }}>{children}</div>
    </div>
  );
}

function RuleEditor({ rule }) {
  return (
    <div>
      {/* Visual rule sentence */}
      <div style={{ padding: 14, background: 'var(--bg-sunken)', borderRadius: 4, fontFamily: 'var(--font-serif)', fontSize: 16, lineHeight: 1.5, marginBottom: 16, letterSpacing: '-0.01em' }}>
        Agar <strong className="mono" style={{ background: 'var(--accent-soft)', padding: '1px 6px', borderRadius: 3, fontFamily: 'var(--font-mono)', fontSize: 13 }}>{rule.metric}</strong> {' '}
        qiymati <strong className="mono" style={{ background: 'var(--accent-soft)', padding: '1px 6px', borderRadius: 3, fontFamily: 'var(--font-mono)', fontSize: 13 }}>{rule.cond}</strong> {' '}
        bo‘lsa <strong className="mono" style={{ background: 'var(--accent-soft)', padding: '1px 6px', borderRadius: 3, fontFamily: 'var(--font-mono)', fontSize: 13 }}>{rule.window}</strong> ichida,{' '}
        unda <strong className={`chip chip-${rule.sev === 'critical' ? 'rose' : rule.sev === 'warning' ? 'amber' : 'accent'}`} style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>{rule.sev}</strong> darajadagi ogohlantirish yarat va{' '}
        {rule.channels.map((c, i) => (
          <React.Fragment key={c}>
            <strong className="chip chip-accent" style={{ fontFamily: 'var(--font-mono)', fontSize: 11 }}>{c}</strong>{i < rule.channels.length - 1 ? ', ' : ''}
          </React.Fragment>
        ))} orqali yubor.
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <div>
          <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 8 }}>Shart</div>
          <RuleField label="Ko'rsatkich">
            <select className="select" value={rule.metric} onChange={() => {}}>
              <option value="price_change">Narx o'zgarishi</option>
              <option value="volume_pct">Hajm o'zgarishi (%)</option>
              <option value="ai_confidence">AI ishonchliligi</option>
              <option value="sentiment_neg">Salbiy sentiment %</option>
              <option value="urgent_overdue">Shoshilinch SLA buzilgan</option>
              <option value="service_down">Servis ishlamayotgan vaqt</option>
            </select>
          </RuleField>
          <RuleField label="Operator">
            <select className="select" defaultValue=">">
              <option>{'>'}</option>
              <option>{'>='}</option>
              <option>{'<'}</option>
              <option>{'<='}</option>
              <option>abs {'>'}</option>
              <option>{'≠'}</option>
            </select>
          </RuleField>
          <RuleField label="Qiymat">
            <input className="input" defaultValue="15" />
          </RuleField>
          <RuleField label="Vaqt oynasi">
            <select className="select" defaultValue={rule.window}>
              <option>15 daqiqa</option>
              <option>1 soat</option>
              <option>6 soat</option>
              <option>24 soat</option>
              <option>jonli</option>
            </select>
          </RuleField>
          <RuleField label="Filtrlar">
            <input className="input" placeholder="masalan: topic = onion AND region = sam" />
          </RuleField>
        </div>

        <div>
          <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 8 }}>Harakat</div>
          <RuleField label="Daraja">
            <Seg value={rule.sev} onChange={() => {}} options={[
              { value: 'critical', label: 'Kritik' },
              { value: 'warning',  label: 'Ogoh.' },
              { value: 'info',     label: 'Maʼlumot' },
            ]} />
          </RuleField>
          <RuleField label="Kanallar">
            <div style={{ display: 'flex', gap: 4 }}>
              {['inapp', 'telegram', 'sms', 'email'].map(c => (
                <span key={c} className={`chip ${rule.channels.includes(c) ? 'chip-accent' : ''}`} style={{ fontSize: 10, cursor: 'pointer' }}>{c}</span>
              ))}
            </div>
          </RuleField>
          <RuleField label="Qabul qiluvchilar">
            <input className="input" placeholder="@username, email yoki @rol" defaultValue="@bo'lim_logistika, @minister-deputy" />
          </RuleField>
          <RuleField label="Eskalatsiya">
            <span className="toggle on" /> <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--ink-3)' }}>tasdiqlanmasa keyingi darajaga</span>
          </RuleField>
          <RuleField label="Cooldown">
            <select className="select" defaultValue="30">
              <option value="0">Yo'q</option>
              <option value="15">15 daqiqa</option>
              <option value="30">30 daqiqa</option>
              <option value="60">1 soat</option>
              <option value="240">4 soat</option>
            </select>
          </RuleField>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 6, marginTop: 16, paddingTop: 14, borderTop: '1px solid var(--line)' }}>
        <span style={{ fontSize: 10.5, color: 'var(--ink-4)', alignSelf: 'center', flex: 1 }}>
          oxirgi 30 kun: <span className="mono">{rule.fired30d}</span> marta ishga tushgan
        </span>
        <button className="btn">Sinov ishga tushirish</button>
        <button className="btn">Bekor qilish</button>
        <button className="btn btn-primary"><Icon name="check" size={11} /> Saqlash</button>
      </div>
    </div>
  );
}

// ============================================================
// Alert trend stacked bar
// ============================================================
function AlertTrend({ data }) {
  const [ref, size] = useSize();
  const w = size.w || 600;
  const h = 160;
  const padL = 36, padR = 8, padT = 12, padB = 22;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const max = Math.max(...data.map(d => d.critical + d.warning + d.info));
  const barW = innerW / data.length;

  return (
    <div ref={ref} style={{ width: '100%' }}>
      {size.w > 0 && (
        <svg width={w} height={h}>
          {[0, 0.5, 1].map(t => (
            <g key={t}>
              <line x1={padL} x2={w - padR} y1={padT + (1 - t) * innerH} y2={padT + (1 - t) * innerH} stroke="var(--line)" strokeWidth="0.5" strokeDasharray={t === 0 ? '0' : '2 3'} />
              <text x={padL - 6} y={padT + (1 - t) * innerH + 3} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="end" fill="var(--ink-4)">{Math.round(max * t)}</text>
            </g>
          ))}
          {data.map((d, i) => {
            const total = d.critical + d.warning + d.info;
            const x = padL + i * barW + 1.5;
            const wBar = barW - 3;
            let yCur = padT + innerH;
            const blocks = [
              { v: d.info, c: 'var(--accent)' },
              { v: d.warning, c: 'var(--amber)' },
              { v: d.critical, c: 'var(--rose)' },
            ];
            return blocks.map((b, j) => {
              const bh = (b.v / max) * innerH;
              yCur -= bh;
              return <rect key={`${i}-${j}`} x={x} y={yCur} width={wBar} height={bh} fill={b.c} opacity="0.85" />;
            });
          })}
          {[0, 7, 14, 21, 29].map(i => (
            <text key={i} x={padL + i * barW + barW / 2} y={h - 8} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-4)">{29 - i}k</text>
          ))}
          {/* legend */}
          <g transform={`translate(${w - 200}, 6)`}>
            <rect x={0} y={0} width={8} height={6} fill="var(--rose)" /><text x={12} y={6} fontSize="9.5" fontFamily="var(--font-mono)" fill="var(--ink-2)">kritik</text>
            <rect x={50} y={0} width={8} height={6} fill="var(--amber)" /><text x={62} y={6} fontSize="9.5" fontFamily="var(--font-mono)" fill="var(--ink-2)">ogoh.</text>
            <rect x={108} y={0} width={8} height={6} fill="var(--accent)" /><text x={120} y={6} fontSize="9.5" fontFamily="var(--font-mono)" fill="var(--ink-2)">maʼlumot</text>
          </g>
        </svg>
      )}
    </div>
  );
}

window.ScreenAlerts = ScreenAlerts;
