// AUTOMATION — EVENTS sub-platform (5 tabs: Dashboard · Live Stream · Sources · Subscriptions · Activity)
const { useState: useEspState } = React;
const Tesp = window.ArbiterTokens;

// ── Live Stream (expanded) ───────────────────────────────────────────────
function AutoEventsLiveStream({ data }) {
  const au = window.__au;
  const [paused, setPaused] = useEspState(false);
  const [filter, setFilter] = useEspState('All');

  const sources = ['All', ...new Set(data.recentEvents.map(e => e.source))];
  const filtered = filter === 'All' ? data.recentEvents : data.recentEvents.filter(e => e.source === filter);

  const eps = Math.round(data.kpis.eventsPerDay / 86400 * 100) / 100;
  const windowEvts = data.eventTypes.filter(e => e.count30d > 500);

  return (
    <div>
      <AuHero
        accent={au.lime} bg={au.limeBg}
        title="Live event stream"
        description={<>Real-time feed of ingested events across all sources. Pause to inspect, filter by source. <b style={{ color: au.lime, fontFamily: Tesp.font.mono }}>{eps}</b> events/second · <b style={{ color: au.emerald, fontFamily: Tesp.font.mono }}>42ms</b> p95 ingest latency.</>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Live rate</span><span style={{ ...au.statValue, color: au.lime }}>{eps}<span style={{ fontSize: '12px', color: Tesp.color.text.tertiary, fontWeight: 500 }}> /s</span></span></div>
        <div style={au.stat}><span style={au.statLabel}>Events / day</span><span style={{ ...au.statValue, color: au.cobalt }}>{au.num(data.kpis.eventsPerDay)}</span></div>
        <div style={au.stat}><span style={au.statLabel}>In window</span><span style={au.statValue}>{filtered.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>High-volume types</span><span style={au.statValue}>{windowEvts.length}</span><span style={{ ...au.statDelta, color: Tesp.color.text.tertiary }}>&gt; 500/month</span></div>
        <div style={au.stat}><span style={au.statLabel}>Latency p95</span><span style={{ ...au.statValue, color: au.emerald }}>42 <span style={{ fontSize: '12px', color: Tesp.color.text.tertiary, fontWeight: 500 }}>ms</span></span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            Live event stream · {filtered.length}
            {!paused && <span style={{ display: 'inline-flex', alignItems: 'center', gap: '5px', fontSize: '10px', color: au.emerald, fontWeight: 700 }}><span style={{ width: '6px', height: '6px', background: au.emerald, borderRadius: '50%' }} />STREAMING</span>}
            {paused && <span style={{ fontSize: '10px', color: au.amber, fontWeight: 700 }}> PAUSED</span>}
          </span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <select value={filter} onChange={e => setFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tesp.color.border.light}`, borderRadius: '5px', background: Tesp.color.bg.card, color: Tesp.color.text.secondary }}>
              {sources.map(s => <option key={s} value={s}>Source: {s}</option>)}
            </select>
            <button onClick={() => setPaused(p => !p)} style={au.btnSecondary}>{paused ? '▶ Resume' : ' Pause'}</button>
            <button style={au.btnSecondary}>⇩ Export</button>
          </div>
        </div>
        <div>
          {filtered.map(ev => (
            <div key={ev.id} style={{ padding: '11px 16px', borderBottom: `1px solid ${Tesp.color.border.light}`, display: 'grid', gridTemplateColumns: '110px 70px 180px 1fr 100px', gap: '12px', alignItems: 'center', fontFamily: Tesp.font.mono }}>
              <span style={{ fontSize: '10px', color: Tesp.color.text.tertiary }}>{ev.at}</span>
              <span style={{ fontSize: '10px', color: au.lime, fontWeight: 700 }}>{ev.id}</span>
              <span style={{ fontSize: '11px', color: au.cobalt, fontWeight: 700 }}>{ev.type}</span>
              <span style={{ fontSize: '11px', color: Tesp.color.text.primary, fontFamily: Tesp.font.family }}>{ev.payload}</span>
              <span style={{ fontSize: '10px', color: ev.triggeredRuns > 0 ? au.lime : Tesp.color.text.tertiary, fontWeight: ev.triggeredRuns > 0 ? 700 : 400, textAlign: 'right' }}>→ {ev.triggeredRuns} run{ev.triggeredRuns === 1 ? '' : 's'}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── Sources (integration contribution) ───────────────────────────────────
function AutoEventsSources({ data }) {
  const au = window.__au;

  // Aggregate by integration kind
  const byKind = {};
  data.integrations.forEach(i => {
    if (!byKind[i.kind]) byKind[i.kind] = { events30d: 0, count: 0 };
    byKind[i.kind].events30d += i.events30d;
    byKind[i.kind].count += 1;
  });
  const kindRows = Object.entries(byKind).map(([k, d]) => ({ kind: k, ...d })).sort((a, b) => b.events30d - a.events30d);

  const topSources = [...data.integrations].sort((a, b) => b.events30d - a.events30d).slice(0, 10);
  const maxSrc = topSources[0]?.events30d || 1;
  const totalEvents = data.integrations.reduce((s, i) => s + i.events30d, 0);

  return (
    <div>
      <AuHero
        accent={au.cobalt} bg={au.cobaltBg}
        title="Event sources — producer contribution"
        description={<>Which integrations are actually producing events, and at what volume. <b style={{ fontFamily: Tesp.font.mono }}>{au.num(totalEvents)}</b> events in last 30d across <b>{kindRows.length}</b> connector kinds.</>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Integrations</span><span style={au.statValue}>{data.integrations.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Events 30d</span><span style={{ ...au.statValue, color: au.cobalt }}>{au.num(totalEvents)}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Top producer</span><span style={{ ...au.statValue, color: au.lime, fontSize: '13px' }}>{topSources[0]?.name.split(' ')[0] || '—'}</span><span style={{ ...au.statDelta, color: Tesp.color.text.tertiary }}>{au.num(topSources[0]?.events30d || 0)} events</span></div>
        <div style={au.stat}><span style={au.statLabel}>Connector kinds</span><span style={au.statValue}>{kindRows.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Health</span><span style={{ ...au.statValue, color: au.emerald }}>{Math.round(data.integrations.filter(i => i.status === 'Connected').length / data.integrations.length * 100)}%</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px', marginBottom: '14px' }}>
        <div style={au.card}>
          <div style={au.cardH}>By connector kind — 30d volume</div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={au.th}>Kind</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Connectors</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Events 30d</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Share</th>
              </tr>
            </thead>
            <tbody>
              {kindRows.map(k => {
                const ks = au.integrationStyle(k.kind);
                return (
                  <tr key={k.kind}>
                    <td style={au.td}><span style={{ ...au.tag, background: ks.bg, color: ks.color }}>{ks.icon} {k.kind}</span></td>
                    <td style={{ ...au.td, textAlign: 'right', fontFamily: Tesp.font.mono }}>{k.count}</td>
                    <td style={{ ...au.td, textAlign: 'right', fontFamily: Tesp.font.mono, fontWeight: 700 }}>{au.num(k.events30d)}</td>
                    <td style={{ ...au.td, textAlign: 'right', fontFamily: Tesp.font.mono, color: au.cobalt, fontWeight: 700 }}>{((k.events30d / totalEvents) * 100).toFixed(1)}%</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>Top 10 producing connectors</div>
          <div style={{ padding: '14px 16px' }}>
            {topSources.map(s => {
              const ks = au.integrationStyle(s.kind);
              return (
                <div key={s.id} style={{ marginBottom: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                    <span style={{ fontSize: '11px', fontWeight: 600, color: Tesp.color.text.primary }}><span style={{ color: ks.color, marginRight: '4px' }}>{ks.icon}</span>{s.name}</span>
                    <span style={{ fontSize: '11px', fontFamily: Tesp.font.mono, color: au.lime, fontWeight: 700 }}>{au.num(s.events30d)}</span>
                  </div>
                  <div style={{ height: '5px', background: Tesp.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                    <div style={{ width: `${(s.events30d / maxSrc) * 100}%`, height: '100%', background: ks.color }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>All source connectors — {data.integrations.length}</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>Connector</th>
              <th style={au.th}>Kind</th>
              <th style={au.th}>Scope</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Events 30d</th>
              <th style={au.th}>Last sync</th>
              <th style={au.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {data.integrations.map(i => {
              const ks = au.integrationStyle(i.kind);
              const ss = au.statusColor(i.status);
              return (
                <tr key={i.id}>
                  <td style={{ ...au.td, fontWeight: 600 }}>{i.name}</td>
                  <td style={au.td}><span style={{ ...au.tag, background: ks.bg, color: ks.color }}>{ks.icon} {i.kind}</span></td>
                  <td style={{ ...au.td, fontSize: '11px', color: Tesp.color.text.secondary, maxWidth: '240px' }}>{i.scope}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tesp.font.mono, fontWeight: 700, color: au.cobalt }}>{au.num(i.events30d)}</td>
                  <td style={{ ...au.td, fontFamily: Tesp.font.mono, fontSize: '11px', color: Tesp.color.text.tertiary }}>{i.lastSync}</td>
                  <td style={au.td}><span style={{ ...au.tag, background: ss.bg, color: ss.color }}>{i.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── Subscriptions (event → trigger mapping) ──────────────────────────────
function AutoEventsSubscriptions({ data }) {
  const au = window.__au;

  // Build event → triggers map
  const byEvent = {};
  data.eventTypes.forEach(e => byEvent[e.name] = []);
  data.triggers.forEach(t => {
    // Match trigger's "on" field against event names
    Object.keys(byEvent).forEach(evName => {
      if (t.on.toLowerCase().includes(evName.toLowerCase())) {
        byEvent[evName].push(t);
      }
    });
  });

  const totalSubs = Object.values(byEvent).reduce((s, a) => s + a.length, 0);
  const unsubscribed = Object.entries(byEvent).filter(([, a]) => a.length === 0);

  return (
    <div>
      <AuHero
        accent={au.violet} bg={au.violetBg}
        title="Event subscriptions"
        description={<>Which triggers subscribe to which events. Unsubscribed event types may indicate dead schemas. <b style={{ color: au.cobalt, fontFamily: Tesp.font.mono }}>{totalSubs}</b> subscriptions · <b style={{ color: unsubscribed.length > 0 ? au.amber : au.emerald, fontFamily: Tesp.font.mono }}>{unsubscribed.length}</b> orphaned events.</>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Event types</span><span style={au.statValue}>{data.eventTypes.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Triggers</span><span style={au.statValue}>{data.triggers.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Subscriptions</span><span style={{ ...au.statValue, color: au.cobalt }}>{totalSubs}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Dead-letter</span><span style={{ ...au.statValue, color: au.amber }}>0</span></div>
        <div style={au.stat}><span style={au.statLabel}>Unsubscribed</span><span style={{ ...au.statValue, color: unsubscribed.length > 0 ? au.amber : au.emerald }}>{unsubscribed.length}</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>Event → Trigger subscription matrix</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>Event type</th>
              <th style={au.th}>Category</th>
              <th style={{ ...au.th, textAlign: 'right' }}>30d volume</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Subscribers</th>
              <th style={au.th}>Wired triggers</th>
            </tr>
          </thead>
          <tbody>
            {data.eventTypes.map(e => {
              const subs = byEvent[e.name] || [];
              return (
                <tr key={e.id}>
                  <td style={{ ...au.td, fontFamily: Tesp.font.mono, fontSize: '11px', fontWeight: 700, color: au.cobalt }}>{e.name}</td>
                  <td style={au.td}><span style={{ ...au.tag, background: Tesp.color.bg.secondary, color: Tesp.color.text.secondary }}>{e.category}</span></td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tesp.font.mono, fontWeight: 700 }}>{au.num(e.count30d)}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tesp.font.mono, color: subs.length > 0 ? au.lime : au.amber, fontWeight: 700 }}>{subs.length}</td>
                  <td style={au.td}>
                    {subs.length === 0 ? (
                      <span style={{ fontSize: '10px', color: au.amber, fontStyle: 'italic' }}>No subscribers</span>
                    ) : (
                      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
                        {subs.map(t => {
                          const ks = au.triggerStyle(t.kind);
                          return (
                            <span key={t.id} style={{ ...au.tag, background: ks.bg, color: ks.color, fontFamily: Tesp.font.mono, fontSize: '9px' }}>
                              {t.id} · {t.name.length > 40 ? t.name.slice(0, 38) + '…' : t.name}
                            </span>
                          );
                        })}
                      </div>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── Events Activity ──────────────────────────────────────────────────────
function AutoEventsActivity({ data }) {
  const au = window.__au;
  const evActivity = data.activity.filter(a => a.action.toLowerCase().includes('event') || a.action.toLowerCase().includes('trigger') || a.action.toLowerCase().includes('cron') || a.action.toLowerCase().includes('webhook'));
  const list = evActivity.length > 0 ? evActivity : data.activity;
  return (
    <div>
      <AuHero
        accent={au.slate} bg={au.slateBg}
        title="Event activity stream"
        description={<>Filtered view of the platform activity stream — only event-, trigger-, cron-, and webhook-related entries. <b style={{ fontFamily: Tesp.font.mono }}>{list.length}</b> entries.</>}
      />
      <div style={au.card}>
        <div style={au.cardH}><span>Event / trigger activity — {list.length}</span></div>
      <div>
        {list.map(a => {
          const sev = a.severity === 'warn' ? au.amber : a.severity === 'critical' ? au.crimson : au.lime;
          return (
            <div key={a.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${Tesp.color.border.light}`, borderLeft: `3px solid ${sev}`, display: 'grid', gridTemplateColumns: '90px 140px 1fr 1fr', gap: '12px', alignItems: 'center' }}>
              <span style={{ fontFamily: Tesp.font.mono, fontSize: '10px', color: Tesp.color.text.tertiary }}>{a.time}</span>
              <span style={{ fontSize: '11px', fontWeight: 600, color: Tesp.color.text.primary }}>{a.actor}</span>
              <span style={{ fontSize: '11px', color: Tesp.color.text.secondary }}>{a.action}</span>
              <span style={{ fontSize: '11px', color: Tesp.color.text.primary, fontWeight: 500 }}>{a.target}</span>
            </div>
          );
        })}
      </div>
    </div>
    </div>
  );
}

// ── Platform entry ───────────────────────────────────────────────────────
function AutoEventsPlatform() {
  const [subTab, setSubTab] = useEspState('dashboard');
  const au = window.__au;
  const data = window.AUTO_DATA;

  const subTabs = [
    { id: 'dashboard',     label: 'Dashboard' },
    { id: 'livestream',    label: 'Live Stream' },
    { id: 'sources',       label: 'Sources' },
    { id: 'subscriptions', label: 'Subscriptions' },
    { id: 'triggers',      label: 'Triggers' },
    { id: 'schemas',       label: 'Schemas' },
    { id: 'activity',      label: 'Activity' },
  ];

  const renderSub = () => {
    switch (subTab) {
      case 'dashboard':     return <AutoEvents               data={data} />;
      case 'livestream':    return <AutoEventsLiveStream     data={data} />;
      case 'sources':       return <AutoEventsSources        data={data} />;
      case 'subscriptions': return <AutoEventsSubscriptions  data={data} />;
      case 'triggers':      return <AutoTriggers             data={data} />;
      case 'schemas':       return <AuthSchemas              data={data} />;
      case 'activity':      return <AutoEventsActivity       data={data} />;
      default:              return <AutoEvents               data={data} />;
    }
  };

  return (
    <div>
      <AuSubNav views={subTabs} active={subTab} onChange={setSubTab} accent={au.lime} />
      {renderSub()}
    </div>
  );
}

window.AutoEventsLiveStream    = AutoEventsLiveStream;
window.AutoEventsSources       = AutoEventsSources;
window.AutoEventsSubscriptions = AutoEventsSubscriptions;
window.AutoEventsActivity      = AutoEventsActivity;
window.AutoEventsPlatform      = AutoEventsPlatform;
