/* ============================================================
   Screen 11 — Integratsiyalar (Channel Health)
   ============================================================ */

function ScreenIntegrations() {
  const [tab, setTab] = useState('overview');
  const [logLevel, setLogLevel] = useState('all');

  // Channels
  const CHANNELS = [
    {
      id: 'bot', name: '@oziq_ovqat_info_bot', kind: 'Telegram Bot', uz: 'Asosiy bot',
      status: 'healthy', uptime: 99.94, throughput: 184, errRate: 0.12,
      lastMsg: '14:30:08', total24h: 2647, total30d: 78420,
      version: 'v3.2.1', members: 18472, color: 'var(--accent)',
    },
    {
      id: 'group', name: '@oziq_ovqat_chat', kind: 'Telegram Group', uz: 'Fermerlar guruhi',
      status: 'healthy', uptime: 99.88, throughput: 96, errRate: 0.04,
      lastMsg: '14:30:14', total24h: 1382, total30d: 41850,
      version: '—', members: 12341, color: 'var(--accent-ink)',
    },
    {
      id: 'channel', name: '@oziq_ovqat_kanal', kind: 'Telegram Channel', uz: 'Eʼlon kanali',
      status: 'healthy', uptime: 99.94, throughput: 28, errRate: 0.1,
      lastMsg: '14:29:32', total24h: 36, total30d: 1042,
      version: '—', members: 9874, color: 'var(--accent-ink)',
    },
    {
      id: 'email', name: 'alerts@mof.uz', kind: 'SMTP', uz: 'Elektron pochta',
      status: 'healthy', uptime: 99.99, throughput: 48, errRate: 0.0,
      lastMsg: '14:29:55', total24h: 412, total30d: 12340,
      version: 'SMTP/DKIM', members: null, color: 'var(--ink-2)',
    },
    {
      id: 'webhook', name: 'https://api.mof.uz/oziq/webhook', kind: 'Webhook', uz: 'Tashqi tizimga',
      status: 'healthy', uptime: 100, throughput: 8, errRate: 0.0,
      lastMsg: '14:29:18', total24h: 96, total30d: 2840,
      version: '—', members: null, color: 'var(--plum)',
    },
    {
      id: 'web', name: 'oziq.mof.uz/yuborish', kind: 'Web form', uz: 'Veb-shakl',
      status: 'planned', uptime: null, throughput: 0, errRate: 0,
      lastMsg: '—', total24h: 0, total30d: 0,
      version: 'rejada', members: null, color: 'var(--ink-4)',
    },
  ];

  // Webhook log entries
  const WEBHOOK_LOG = [
    { t: '14:30:08.412', m: 'POST', uri: '/webhook/telegram', code: 200, dur: 84, lvl: 'info', payload: 'message · F0234 · onion' },
    { t: '14:29:57.318', m: 'POST', uri: '/webhook/telegram', code: 200, dur: 67, lvl: 'info', payload: 'message · F0178 · logistic' },
    { t: '14:29:44.122', m: 'POST', uri: '/webhook/channel-post', code: 200, dur: 24, lvl: 'info', payload: 'narx-yangiligi · @oziq_ovqat_kanal' },
    { t: '14:29:30.842', m: 'POST', uri: '/webhook/telegram', code: 200, dur: 92, lvl: 'info', payload: 'edited_message · F0091' },
    { t: '14:29:18.011', m: 'POST', uri: '/webhook/external', code: 200, dur: 142, lvl: 'info', payload: 'state-of-stocks broadcast' },
    { t: '14:28:42.668', m: 'POST', uri: '/webhook/channel-post', code: 429, dur: 38, lvl: 'warn', payload: 'rate-limit · @oziq_ovqat_kanal' },
    { t: '14:28:38.301', m: 'POST', uri: '/webhook/telegram', code: 200, dur: 78, lvl: 'info', payload: 'message · F0156 · beef' },
    { t: '14:28:24.450', m: 'POST', uri: '/webhook/telegram', code: 200, dur: 81, lvl: 'info', payload: 'message · F0204 · flour' },
    { t: '14:28:12.901', m: 'POST', uri: '/webhook/telegram', code: 429, dur: 12, lvl: 'warn', payload: 'rate-limit · retried' },
    { t: '14:28:01.224', m: 'POST', uri: '/webhook/telegram', code: 200, dur: 71, lvl: 'info', payload: 'photo · F0244' },
    { t: '14:27:48.117', m: 'POST', uri: '/webhook/telegram', code: 200, dur: 88, lvl: 'info', payload: 'message · F0123 · rice' },
    { t: '14:27:32.844', m: 'POST', uri: '/webhook/telegram', code: 200, dur: 65, lvl: 'info', payload: 'message · F0098 · potato' },
    { t: '14:27:14.508', m: 'POST', uri: '/webhook/channel-post', code: 200, dur: 31, lvl: 'info', payload: 'kunlik-xulosa · @oziq_ovqat_kanal' },
    { t: '14:27:01.122', m: 'POST', uri: '/webhook/telegram', code: 200, dur: 73, lvl: 'info', payload: 'message · F0285 · oil' },
    { t: '14:26:48.901', m: 'POST', uri: '/webhook/telegram', code: 200, dur: 80, lvl: 'info', payload: 'message · F0167 · sugar' },
    { t: '14:26:32.115', m: 'POST', uri: '/webhook/external', code: 200, dur: 124, lvl: 'info', payload: 'daily-summary broadcast' },
  ];

  const filteredLog = logLevel === 'all' ? WEBHOOK_LOG : WEBHOOK_LOG.filter(l => l.lvl === logLevel);

  // Bot commands
  const COMMANDS = [
    { cmd: '/start',     desc: 'Botni ishga tushirish',  uses24h: 487, uses30d: 14210, success: 99.8, color: 'var(--accent)' },
    { cmd: '/savol',     desc: 'Yangi murojaat yuborish',uses24h: 1842, uses30d: 51420, success: 98.2, color: 'var(--jade)' },
    { cmd: '/holat',     desc: 'Murojaatim holati',     uses24h: 634, uses30d: 18420, success: 99.4, color: 'var(--accent-ink)' },
    { cmd: '/narx',      desc: 'Joriy narxlar',         uses24h: 412, uses30d: 12340, success: 99.9, color: 'var(--amber)' },
    { cmd: '/bog\'lanish',desc: 'Bo\'lim bilan bog\'lanish',uses24h: 198, uses30d: 5840, success: 96.3, color: 'var(--plum)' },
    { cmd: '/yordam',    desc: 'Yordam menyusi',        uses24h: 142, uses30d: 4120, success: 99.7, color: 'var(--ink-3)' },
    { cmd: '/til',       desc: 'Tilni o\'zgartirish',    uses24h: 88,  uses30d: 2840, success: 100,  color: 'var(--ink-4)' },
    { cmd: '/obuna',     desc: 'Mavzu kuzatuvi',         uses24h: 62,  uses30d: 1840, success: 98.4, color: 'var(--rose)' },
  ];

  // Throughput trend
  const THROUGHPUT_TREND = useMemo(() => {
    const arr = [];
    for (let h = 0; h < 24; h++) {
      const peakHour = h >= 8 && h <= 18 ? 1.4 : 0.4;
      const noise = 0.7 + rand() * 0.6;
      arr.push(Math.round(180 * peakHour * noise));
    }
    return arr;
  }, []);

  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)' }}>Integratsiyalar</span>
          </div>
          <h1 className="page-title">Integratsiyalar<span className="ru">Интеграции · Channel health</span></h1>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="refresh" size={12} /> Test ulanishlar</button>
          <button className="btn btn-primary"><Icon name="plus" size={12} /> Yangi kanal</button>
        </div>
      </div>

      {/* Summary KPI strip */}
      <div className="kpi-strip mb-12" style={{ gridTemplateColumns: 'repeat(5, 1fr)' }}>
        <div className="kpi">
          <div className="kpi-label">Faol kanallar</div>
          <div className="kpi-value">{CHANNELS.filter(c => c.status === 'healthy').length}<span className="unit"> / {CHANNELS.filter(c => c.status !== 'planned').length}</span></div>
          <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>{CHANNELS.filter(c => c.status === 'degraded').length} ta sekin</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Bugungi qabul</div>
          <div className="kpi-value">{formatNum(CHANNELS.reduce((s, c) => s + c.total24h, 0))}</div>
          <div className="kpi-delta delta-up">↑ 8.2% · kechagidan</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Joriy uzatish</div>
          <div className="kpi-value">{CHANNELS.reduce((s, c) => s + c.throughput, 0)}<span className="unit"> msg/min</span></div>
          <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>peak: 348 (12:00)</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Xatolik darajasi</div>
          <div className="kpi-value">0.48<span className="unit">%</span></div>
          <div className="kpi-delta delta-up">↓ 0.12 · 24s</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">O'rt. uptime</div>
          <div className="kpi-value">99.46<span className="unit">%</span></div>
          <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>oxirgi 30 kun</div>
        </div>
      </div>

      {/* Channel cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 16 }}>
        {CHANNELS.map(ch => <ChannelCard key={ch.id} ch={ch} />)}
      </div>

      {/* Tabs */}
      <div className="tabs mb-12">
        <button className={`tab ${tab === 'overview' ? 'on' : ''}`} onClick={() => setTab('overview')}>Umumiy ko'rinish</button>
        <button className={`tab ${tab === 'commands' ? 'on' : ''}`} onClick={() => setTab('commands')}>Bot buyruqlari</button>
        <button className={`tab ${tab === 'webhooks' ? 'on' : ''}`} onClick={() => setTab('webhooks')}>Webhook jurnali</button>
        <button className={`tab ${tab === 'rate' ? 'on' : ''}`} onClick={() => setTab('rate')}>Limit va siyosatlar</button>
      </div>

      {tab === 'overview' && (
        <div className="grid-2 mb-12">
          <Panel title="24 soatlik uzatish" sub="msg/min · soat bo'yicha" num="01">
            <ThroughputChart data={THROUGHPUT_TREND} />
          </Panel>

          <Panel title="Xatolik dinamikasi" sub="oxirgi 30 kun" num="02">
            <ErrorRateChart />
          </Panel>
        </div>
      )}

      {tab === 'commands' && (
        <Panel title="Bot buyruqlari ishlatilishi" sub={`${COMMANDS.length} ta buyruq · 24 soat va 30 kun`} num="01" body={false}>
          <table className="tbl">
            <thead>
              <tr>
                <th>Buyruq</th>
                <th>Tavsif</th>
                <th>24 soat</th>
                <th>24 soat dinamikasi</th>
                <th>30 kun</th>
                <th>Muvaffaqiyat %</th>
                <th>—</th>
              </tr>
            </thead>
            <tbody>
              {COMMANDS.map(c => (
                <tr key={c.cmd}>
                  <td>
                    <span className="mono" style={{ fontSize: 13, fontWeight: 600, color: 'var(--accent-ink)', background: 'var(--accent-soft)', padding: '2px 6px', borderRadius: 3 }}>{c.cmd}</span>
                  </td>
                  <td style={{ fontSize: 11.5 }}>{c.desc}</td>
                  <td className="mono" style={{ fontSize: 12, fontWeight: 500 }}>{formatNum(c.uses24h)}</td>
                  <td style={{ width: 180 }}>
                    <Sparkline
                      data={Array.from({ length: 12 }, () => Math.max(1, c.uses24h / 12 + (rand() - 0.5) * c.uses24h / 6))}
                      width={170} height={24} color={c.color} fill strokeWidth={1.2}
                    />
                  </td>
                  <td className="mono" style={{ fontSize: 11.5, color: 'var(--ink-2)' }}>{formatNum(c.uses30d)}</td>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <div style={{ width: 80, height: 4, background: 'var(--bg-sunken)', borderRadius: 1, overflow: 'hidden' }}>
                        <div style={{ width: `${c.success}%`, height: '100%', background: c.success >= 99 ? 'var(--jade)' : c.success >= 96 ? 'var(--amber)' : 'var(--rose)' }} />
                      </div>
                      <span className="mono" style={{ fontSize: 11 }}>{c.success.toFixed(1)}%</span>
                    </div>
                  </td>
                  <td>
                    <button className="btn btn-ghost btn-sm" title="Tahrirlash"><Icon name="gear" size={11} /></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <div style={{ padding: '10px 14px', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-3)' }}>
            <span><span className="mono" style={{ color: 'var(--ink)' }}>{formatNum(COMMANDS.reduce((s, c) => s + c.uses24h, 0))}</span> ta buyruq · 24 soatda</span>
            <span>Eng mashhur: <span className="mono" style={{ color: 'var(--accent-ink)' }}>/savol</span> ({((COMMANDS[1].uses24h / COMMANDS.reduce((s, c) => s + c.uses24h, 0)) * 100).toFixed(0)}% trafik)</span>
            <span>O'rt. javob: <span className="mono">{(COMMANDS.reduce((s, c) => s + c.success, 0) / COMMANDS.length).toFixed(2)}%</span></span>
          </div>
        </Panel>
      )}

      {tab === 'webhooks' && (
        <Panel
          title="Webhook jurnali"
          sub={`${WEBHOOK_LOG.length} ta yozuv · live`}
          num="01"
          body={false}
          actions={
            <>
              <Seg value={logLevel} onChange={setLogLevel} options={[
                { value: 'all',   label: 'Hammasi' },
                { value: 'info',  label: 'Info' },
                { value: 'warn',  label: 'Warn' },
                { value: 'error', label: 'Error' },
              ]} />
              <button className="btn btn-ghost btn-sm"><Icon name="download" size={12} /></button>
              <button className="btn btn-ghost btn-sm"><Icon name="refresh" size={12} /></button>
            </>
          }
        >
          <div style={{ background: 'oklch(0.16 0.012 250)', fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'oklch(0.85 0.008 250)', maxHeight: 480, overflowY: 'auto', lineHeight: 1.55 }}>
            {filteredLog.map((l, i) => {
              const lvlColor = l.lvl === 'error' ? 'oklch(0.72 0.16 25)' : l.lvl === 'warn' ? 'oklch(0.80 0.14 75)' : 'oklch(0.72 0.10 155)';
              const codeColor = l.code >= 500 ? 'oklch(0.72 0.16 25)' : l.code >= 400 ? 'oklch(0.80 0.14 75)' : 'oklch(0.72 0.10 155)';
              return (
                <div key={i} style={{ padding: '4px 14px', borderBottom: '1px solid oklch(0.22 0.012 250)', display: 'grid', gridTemplateColumns: '124px 70px 38px 280px 70px 1fr', gap: 12, alignItems: 'center' }}>
                  <span style={{ color: 'oklch(0.55 0.008 250)' }}>{l.t}</span>
                  <span style={{ color: lvlColor, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em', fontSize: 10 }}>{l.lvl}</span>
                  <span style={{ color: 'oklch(0.85 0.008 250)' }}>{l.m}</span>
                  <span style={{ color: 'oklch(0.92 0.008 250)' }}>{l.uri}</span>
                  <span style={{ color: codeColor, fontWeight: 600 }}>{l.code} · {l.dur < 1000 ? l.dur + 'ms' : (l.dur / 1000).toFixed(1) + 's'}</span>
                  <span style={{ color: 'oklch(0.7 0.008 250)' }}>{l.payload}</span>
                </div>
              );
            })}
          </div>
        </Panel>
      )}

      {tab === 'rate' && (
        <div className="grid-2 mb-12">
          <Panel title="Tezlik limitlari" sub="kanal bo'yicha" num="01">
            {[
              { ch: 'Telegram Bot', current: 184, limit: 300, unit: 'msg/min' },
              { ch: 'Telegram Group', current: 96, limit: 200, unit: 'msg/min' },
              { ch: 'Telegram Kanal', current: 28, limit: 80, unit: 'post/min' },
              { ch: 'Email (SMTP)', current: 48, limit: 100, unit: 'msg/min' },
              { ch: 'Webhook out', current: 8, limit: 30, unit: 'req/min' },
            ].map((r, i) => {
              const pct = (r.current / r.limit) * 100;
              return (
                <div key={i} style={{ padding: '10px 0', borderBottom: i < 4 ? '1px solid var(--line)' : 'none' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
                    <span style={{ fontSize: 12, fontWeight: 500 }}>{r.ch}</span>
                    <span className="mono" style={{ fontSize: 11 }}>
                      <span style={{ color: pct > 80 ? 'var(--rose)' : 'var(--ink)' }}>{r.current}</span>
                      <span style={{ color: 'var(--ink-4)' }}> / {r.limit} {r.unit}</span>
                    </span>
                  </div>
                  <div style={{ height: 6, background: 'var(--bg-sunken)', borderRadius: 1, overflow: 'hidden', position: 'relative' }}>
                    <div style={{ width: `${Math.min(100, pct)}%`, height: '100%', background: pct > 80 ? 'var(--rose)' : pct > 60 ? 'var(--amber)' : 'var(--jade)' }} />
                    {/* threshold marker */}
                    <div style={{ position: 'absolute', left: '80%', top: -2, bottom: -2, width: 1, background: 'var(--ink-4)' }} />
                  </div>
                  <div style={{ fontSize: 9.5, color: 'var(--ink-4)', marginTop: 2 }}>
                    {pct.toFixed(0)}% to'la · backoff: {pct > 80 ? 'yoqilgan' : 'normal'}
                  </div>
                </div>
              );
            })}
          </Panel>

          <Panel title="Retry siyosati" sub="xatolik holati uchun" num="02">
            <RuleField label="Maksimum urinishlar"><input className="input" defaultValue="5" /></RuleField>
            <RuleField label="Backoff strategiyasi"><select className="select"><option>Exponential (2^n)</option><option>Linear</option><option>Constant</option></select></RuleField>
            <RuleField label="Boshlang'ich kutish"><input className="input" defaultValue="2000 ms" /></RuleField>
            <RuleField label="Maksimum kutish"><input className="input" defaultValue="60 000 ms" /></RuleField>
            <RuleField label="Jitter"><span className="toggle on" /></RuleField>
            <RuleField label="Circuit breaker"><span className="toggle on" /></RuleField>
            <RuleField label="Dead letter queue"><span className="mono" style={{ fontSize: 11 }}>dlq.mof.uz · 0 yozuv</span></RuleField>
            <div style={{ marginTop: 14, padding: 12, background: 'var(--bg-sunken)', borderRadius: 4, fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.5 }}>
              <strong style={{ color: 'var(--ink)' }}>Sinov natijasi:</strong> Mobiuz API uchun retry siyosati so'nggi 24 soatda 4 ta uzilishni avtomatik tikladi. O'rtacha tiklash vaqti — 12 soniya.
            </div>
          </Panel>
        </div>
      )}
    </div>
  );
}

// ============================================================
// Channel card
// ============================================================
function ChannelCard({ ch }) {
  const statusColor = ch.status === 'healthy' ? 'var(--jade)' : ch.status === 'degraded' ? 'var(--amber)' : ch.status === 'down' ? 'var(--rose)' : 'var(--ink-4)';
  const statusLabel = { healthy: 'Sogʻlom', degraded: 'Sekin', down: 'Tushib qoldi', planned: 'Rejada' }[ch.status];

  // synth uptime sparkline (30 days)
  const uptimeSpark = useMemo(() => {
    const arr = [];
    for (let i = 0; i < 30; i++) {
      const dip = 99 + rand();
      arr.push(Math.min(100, dip));
    }
    return arr;
  }, [ch.id]);

  return (
    <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
      <div style={{ padding: '14px 14px 12px', borderBottom: '1px solid var(--line)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div style={{ fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{ch.kind}</div>
            <div className="mono" style={{ fontSize: 13, fontWeight: 600, marginTop: 2, letterSpacing: '-0.01em' }}>{ch.name}</div>
            <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{ch.uz} · <span className="mono">{ch.version}</span></div>
          </div>
          <span className="chip" style={{ background: statusColor, color: 'white', borderColor: 'transparent', fontSize: 9.5 }}>
            <span className="dot" style={{ background: 'white' }} />
            {statusLabel}
          </span>
        </div>
      </div>

      {ch.status === 'planned' ? (
        <div style={{ padding: 24, textAlign: 'center', color: 'var(--ink-3)', fontSize: 11.5 }}>
          <Icon name="plug" size={20} stroke={1.2} />
          <div style={{ marginTop: 8 }}>Hali ulanmagan · 2026 Q3 rejada</div>
        </div>
      ) : (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 1, background: 'var(--line)' }}>
            <ChCell label="Bugun" value={formatNum(ch.total24h)} hint="xabar" />
            <ChCell label="30 kun" value={formatNum(ch.total30d)} hint="xabar" />
            <ChCell label="Uzatish" value={ch.throughput} hint="msg/min" />
            <ChCell label="Xatolik" value={`${ch.errRate.toFixed(2)}`} hint="%" color={ch.errRate > 1 ? 'var(--amber)' : ch.errRate > 4 ? 'var(--rose)' : 'var(--jade)'} />
          </div>

          <div style={{ padding: '10px 14px', borderTop: '1px solid var(--line)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
              <span style={{ fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Uptime · 30 kun</span>
              <span className="mono" style={{ fontSize: 11, fontWeight: 600, color: ch.uptime >= 99.9 ? 'var(--jade)' : ch.uptime >= 99 ? 'var(--ink)' : 'var(--amber)' }}>{ch.uptime.toFixed(2)}%</span>
            </div>
            <UptimeBars data={uptimeSpark} />
          </div>

          <div style={{ padding: '10px 14px', borderTop: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 10.5, color: 'var(--ink-3)' }}>
            <span>oxirgi xabar:</span>
            <span className="mono" style={{ color: 'var(--ink)' }}>{ch.lastMsg}</span>
            {ch.members !== null && (
              <>
                <span>·</span>
                <span>aʼzo: <span className="mono" style={{ color: 'var(--ink)' }}>{formatNum(ch.members)}</span></span>
              </>
            )}
          </div>
        </>
      )}
    </div>
  );
}

function ChCell({ label, value, hint, color }) {
  return (
    <div style={{ padding: '10px 14px', background: 'var(--panel)' }}>
      <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</div>
      <div className="mono" style={{ fontSize: 18, fontWeight: 500, letterSpacing: '-0.02em', color: color || 'var(--ink)' }}>{value}</div>
      <div style={{ fontSize: 9.5, color: 'var(--ink-4)' }}>{hint}</div>
    </div>
  );
}

// ============================================================
// Uptime bars (one per day, color by uptime)
// ============================================================
function UptimeBars({ data }) {
  return (
    <div style={{ display: 'flex', gap: 1.5, alignItems: 'flex-end', height: 22 }}>
      {data.map((v, i) => {
        const t = v / 100;
        const color = v >= 99.9 ? 'var(--jade)' : v >= 99 ? 'oklch(0.72 0.10 145)' : v >= 95 ? 'var(--amber)' : 'var(--rose)';
        return (
          <div key={i} style={{ flex: 1, height: `${100 - (100 - v) * 5}%`, minHeight: 8, background: color, opacity: 0.85, borderRadius: 0.5 }} title={`${i + 1}-kun: ${v.toFixed(2)}%`} />
        );
      })}
    </div>
  );
}

// ============================================================
// Throughput chart (24 hours)
// ============================================================
function ThroughputChart({ data }) {
  const [ref, size] = useSize();
  const w = size.w || 600;
  const h = 240;
  const padL = 40, padR = 8, padT = 16, padB = 28;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const max = Math.max(...data) * 1.1;
  const barW = innerW / 24;
  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>
          ))}
          {/* working hours band */}
          <rect x={padL + 8 * barW} y={padT} width={11 * barW} height={innerH} fill="var(--accent-soft)" opacity="0.4" />
          <text x={padL + 13 * barW} y={padT + 12} fontSize="9" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--accent-ink)" fontWeight="600">ish vaqti</text>
          {/* bars */}
          {data.map((v, i) => {
            const bh = (v / max) * innerH;
            return (
              <rect key={i} x={padL + i * barW + 2} y={padT + innerH - bh} width={barW - 4} height={bh} fill="var(--accent)" opacity="0.85" rx="1" />
            );
          })}
          {[0, 4, 8, 12, 16, 20].map(i => (
            <text key={i} x={padL + i * barW + barW / 2} y={h - 10} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-4)">{String(i).padStart(2, '0')}:00</text>
          ))}
          <text x={padL + innerW / 2} y={h - 2} fontSize="10" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-3)">soat (lokal vaqt UTC+5)</text>
        </svg>
      )}
    </div>
  );
}

// ============================================================
// Error rate stacked area
// ============================================================
function ErrorRateChart() {
  const [ref, size] = useSize();
  const data = useMemo(() => {
    const arr = [];
    for (let i = 0; i < 30; i++) {
      arr.push({
        bot: 0.05 + rand() * 0.15,
        channel: 0.02 + rand() * 0.18 + (i === 22 || i === 17 ? 0.3 : 0),
        email: 0.01 + rand() * 0.06,
      });
    }
    return arr;
  }, []);
  const w = size.w || 600;
  const h = 240;
  const padL = 40, padR = 8, padT = 14, padB = 26;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;
  const max = 8;
  const xs = (i) => padL + (i / (data.length - 1)) * innerW;
  const y = (v) => padT + innerH - (v / max) * innerH;

  const linePath = (key) => data.map((d, i) => (i === 0 ? `M ${xs(i)} ${y(d[key])}` : `L ${xs(i)} ${y(d[key])}`)).join(' ');

  return (
    <div ref={ref} style={{ width: '100%' }}>
      {size.w > 0 && (
        <svg width={w} height={h}>
          {[0, 2, 4, 6, 8].map(v => (
            <g key={v}>
              <line x1={padL} x2={w - padR} y1={y(v)} y2={y(v)} stroke="var(--line)" strokeWidth="0.5" strokeDasharray={v === 0 ? '0' : '2 3'} />
              <text x={padL - 6} y={y(v) + 3} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="end" fill="var(--ink-4)">{v}%</text>
            </g>
          ))}
          <line x1={padL} x2={w - padR} y1={y(1)} y2={y(1)} stroke="var(--jade)" strokeWidth="1" strokeDasharray="4 2" />
          <text x={w - padR - 4} y={y(1) - 4} fontSize="9" fontFamily="var(--font-mono)" textAnchor="end" fill="var(--jade)">SLO 1%</text>
          <path d={linePath('channel')} stroke="var(--accent-ink)" strokeWidth="1.5" fill="none" />
          <path d={linePath('bot')} stroke="var(--accent)" strokeWidth="1.5" fill="none" />
          <path d={linePath('email')} stroke="var(--ink-3)" strokeWidth="1.5" fill="none" />
          {[0, 7, 14, 21, 29].map(i => (
            <text key={i} x={xs(i)} y={h - 10} fontSize="9.5" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--ink-4)">{29 - i}k</text>
          ))}
          <g transform={`translate(${padL + 12}, 2)`}>
            <rect x={0} y={0} width={8} height={6} fill="var(--accent)" />
            <text x={12} y={6} fontSize="9.5" fontFamily="var(--font-mono)" fill="var(--ink-2)">Bot</text>
            <rect x={42} y={0} width={8} height={6} fill="var(--accent-ink)" />
            <text x={54} y={6} fontSize="9.5" fontFamily="var(--font-mono)" fill="var(--ink-2)">Kanal</text>
            <rect x={92} y={0} width={8} height={6} fill="var(--ink-3)" />
            <text x={104} y={6} fontSize="9.5" fontFamily="var(--font-mono)" fill="var(--ink-2)">Email</text>
          </g>
        </svg>
      )}
    </div>
  );
}

window.ScreenIntegrations = ScreenIntegrations;
