// AUTOMATION PLATFORM — Events + Triggers tabs
const { useState: useAuEvState, useMemo: useAuEvMemo } = React;
const Taue = window.ArbiterTokens;

function AutoEvents({ data }) {
  const au = window.__au;
  const [categoryFilter, setCategoryFilter] = useAuEvState('All');
  const [search, setSearch] = useAuEvState('');

  const categories = useAuEvMemo(() => ['All', ...new Set(data.eventTypes.map(e => e.category))], [data]);
  const filteredTypes = data.eventTypes.filter(e =>
    (categoryFilter === 'All' || e.category === categoryFilter) &&
    (!search || e.name.toLowerCase().includes(search.toLowerCase()))
  );

  const totalEvents30d = data.eventTypes.reduce((s, e) => s + e.count30d, 0);
  const avgPerDay = Math.round(totalEvents30d / 30);

  // By category
  const byCat = {};
  data.eventTypes.forEach(e => {
    if (!byCat[e.category]) byCat[e.category] = { count: 0, types: 0, triggers: 0 };
    byCat[e.category].count    += e.count30d;
    byCat[e.category].types    += 1;
    byCat[e.category].triggers += e.triggersCount;
  });
  const catData = Object.entries(byCat).map(([c, d]) => ({ category: c, ...d })).sort((a, b) => b.count - a.count);

  // Top event types by volume
  const topEvents = [...data.eventTypes].sort((a, b) => b.count30d - a.count30d).slice(0, 10);
  const maxEventVol = topEvents[0]?.count30d || 1;

  // Trigger density: events with most triggers wired
  const byTriggers = [...data.eventTypes].sort((a, b) => b.triggersCount - a.triggersCount).slice(0, 8);
  const maxTriggers = Math.max(...byTriggers.map(e => e.triggersCount), 1);

  // Integration source counts from recent events
  const bySource = {};
  data.recentEvents.forEach(e => { bySource[e.source] = (bySource[e.source] || 0) + 1; });
  const sourceData = Object.entries(bySource).map(([s, c]) => ({ source: s, count: c })).sort((a, b) => b.count - a.count);
  const totalSource = sourceData.reduce((s, x) => s + x.count, 0);

  // 14-day trend as events proxy (scaled by avgPerDay)
  const daily = data.analytics.daily14;
  const maxDaily = Math.max(...daily.map(d => d.runs));

  const catColors = [au.lime, au.cobalt, au.violet, au.teal, au.amber, au.crimson, au.fuchsia, au.emerald, au.slate, au.orange];

  return (
    <div>
      <AuHero
        accent={au.cobalt} bg={au.cobaltBg}
        title={`Events dashboard — ${data.eventTypes.length} types`}
        description={<>
          Platform event catalog and volume. <b style={{ fontFamily: Taue.font.mono }}>{au.num(totalEvents30d)}</b> events in last 30 days (<b style={{ fontFamily: Taue.font.mono }}>{au.num(avgPerDay)}</b>/day rolling avg) wired into <b>{data.eventTypes.reduce((s, e) => s + e.triggersCount, 0)}</b> triggers.
        </>}
      />
      <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><span style={{ ...au.statDelta, color: Taue.color.text.tertiary }}>defined schemas</span></div>
        <div style={au.stat}><span style={au.statLabel}>Events · 30d</span><span style={{ ...au.statValue, color: au.cobalt }}>{au.num(totalEvents30d)}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Events / day</span><span style={{ ...au.statValue, color: au.lime }}>{au.num(avgPerDay)}</span><span style={{ ...au.statDelta, color: Taue.color.text.tertiary }}>rolling avg</span></div>
        <div style={au.stat}><span style={au.statLabel}>Triggers wired</span><span style={au.statValue}>{data.eventTypes.reduce((s, e) => s + e.triggersCount, 0)}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Categories</span><span style={au.statValue}>{categories.length - 1}</span></div>
      </div>

      {/* Row 1: Category donut-bar + 14-day trend */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: '14px', marginBottom: '14px' }}>
        <div style={au.card}>
          <div style={au.cardH}>Volume by category — 30d</div>
          <div style={{ padding: '14px 16px' }}>
            <div style={{ display: 'flex', height: '14px', borderRadius: '4px', overflow: 'hidden', marginBottom: '12px' }}>
              {catData.map((c, i) => (
                <div key={c.category} title={`${c.category}: ${au.num(c.count)}`} style={{ width: `${(c.count / totalEvents30d) * 100}%`, background: catColors[i % catColors.length] }} />
              ))}
            </div>
            {catData.map((c, i) => (
              <div key={c.category} style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px', marginBottom: '4px' }}>
                <span style={{ width: '10px', height: '10px', borderRadius: '2px', background: catColors[i % catColors.length], flexShrink: 0 }} />
                <span style={{ color: Taue.color.text.primary, fontWeight: 600 }}>{c.category}</span>
                <span style={{ color: Taue.color.text.tertiary, fontFamily: Taue.font.mono, marginLeft: 'auto' }}>
                  {au.num(c.count)} · <span style={{ color: au.cobalt, fontWeight: 700 }}>{c.triggers} trg</span>
                </span>
              </div>
            ))}
          </div>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>
            <span>Daily event flow · last 14 days</span>
            <span style={{ fontSize: '10px', color: Taue.color.text.tertiary, fontWeight: 500 }}>peak {maxDaily * 50} events / day</span>
          </div>
          <div style={{ padding: '18px 16px 14px', display: 'flex', gap: '5px', alignItems: 'flex-end', height: '160px' }}>
            {daily.map(d => (
              <div key={d.d} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '3px' }}>
                <div style={{ width: '100%', height: '120px', display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
                  <div style={{ width: '72%', height: `${(d.runs / maxDaily) * 100}%`, background: `linear-gradient(180deg, ${au.cobalt} 0%, ${au.violet} 100%)`, borderRadius: '3px 3px 0 0' }} />
                </div>
                <span style={{ fontSize: '9px', color: Taue.color.text.tertiary, fontFamily: Taue.font.mono }}>{d.d}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Row 2: Top event types + Trigger density + Source */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr 1fr', gap: '14px', marginBottom: '14px' }}>
        <div style={au.card}>
          <div style={au.cardH}>Top event types — by 30d volume</div>
          <div style={{ padding: '14px 16px' }}>
            {topEvents.map(e => (
              <div key={e.id} style={{ marginBottom: '8px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                  <span style={{ fontSize: '11px', fontFamily: Taue.font.mono, fontWeight: 600, color: au.lime }}>{e.name}</span>
                  <span style={{ fontSize: '11px', fontFamily: Taue.font.mono, color: Taue.color.text.primary, fontWeight: 700 }}>{au.num(e.count30d)}</span>
                </div>
                <div style={{ height: '5px', background: Taue.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                  <div style={{ width: `${(e.count30d / maxEventVol) * 100}%`, height: '100%', background: `linear-gradient(90deg, ${au.cobalt} 0%, ${au.violet} 100%)` }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>Trigger wiring density</div>
          <div style={{ padding: '14px 16px' }}>
            {byTriggers.map(e => (
              <div key={e.id} style={{ marginBottom: '8px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                  <span style={{ fontSize: '11px', fontFamily: Taue.font.mono, fontWeight: 600, color: Taue.color.text.primary }}>{e.name}</span>
                  <span style={{ fontSize: '11px', fontFamily: Taue.font.mono, color: au.cobalt, fontWeight: 700 }}>{e.triggersCount} trg</span>
                </div>
                <div style={{ height: '5px', background: Taue.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                  <div style={{ width: `${(e.triggersCount / maxTriggers) * 100}%`, height: '100%', background: au.cobalt }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>Recent events · by source</div>
          <div style={{ padding: '14px 16px' }}>
            {sourceData.map((s, i) => (
              <div key={s.source} style={{ marginBottom: '8px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                  <span style={{ fontSize: '11px', color: Taue.color.text.primary, fontWeight: 500 }}>{s.source}</span>
                  <span style={{ fontSize: '11px', fontFamily: Taue.font.mono, color: Taue.color.text.tertiary, fontWeight: 700 }}>{s.count}</span>
                </div>
                <div style={{ height: '5px', background: Taue.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                  <div style={{ width: `${(s.count / totalSource) * 100}%`, height: '100%', background: catColors[i % catColors.length] }} />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: '14px' }}>
        {/* Event types */}
        <div style={au.card}>
          <div style={au.cardH}>
            <span>Event type registry — {filteredTypes.length}</span>
            <div style={{ display: 'flex', gap: '6px' }}>
              <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search event…"
                style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taue.color.border.light}`, borderRadius: '5px', background: Taue.color.bg.card, color: Taue.color.text.primary, minWidth: '160px', fontFamily: Taue.font.family }} />
              <select value={categoryFilter} onChange={e => setCategoryFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taue.color.border.light}`, borderRadius: '5px', background: Taue.color.bg.card, color: Taue.color.text.secondary }}>
                {categories.map(c => <option key={c} value={c}>{c}</option>)}
              </select>
            </div>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={au.th}>Event name</th>
                <th style={au.th}>Category</th>
                <th style={{ ...au.th, textAlign: 'right' }}>30-day count</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Triggers</th>
              </tr>
            </thead>
            <tbody>
              {filteredTypes.map(e => (
                <tr key={e.id}>
                  <td style={{ ...au.td, fontFamily: Taue.font.mono, fontSize: '11px', color: au.lime, fontWeight: 600 }}>{e.name}</td>
                  <td style={au.td}><span style={{ ...au.tag, background: au.limeBg, color: au.limeDeep }}>{e.category}</span></td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Taue.font.mono, color: Taue.color.text.primary, fontWeight: 600 }}>{au.num(e.count30d)}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Taue.font.mono, color: au.cobalt, fontWeight: 700 }}>{e.triggersCount}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Recent event stream */}
        <div style={au.card}>
          <div style={au.cardH}>
            <span>Live event stream</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: '5px', fontSize: '10px', color: au.emerald, fontWeight: 600 }}><span style={{ width: '6px', height: '6px', background: au.emerald, borderRadius: '50%' }} />LIVE</span>
          </div>
          <div>
            {data.recentEvents.map(ev => (
              <div key={ev.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${Taue.color.border.light}` }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '3px' }}>
                  <span style={{ fontSize: '11px', fontFamily: Taue.font.mono, fontWeight: 700, color: au.cobalt }}>{ev.type}</span>
                  <span style={{ fontSize: '10px', fontFamily: Taue.font.mono, color: Taue.color.text.tertiary }}>{ev.at.split(' ')[1]}</span>
                </div>
                <div style={{ fontSize: '11px', color: Taue.color.text.primary, lineHeight: 1.4 }}>{ev.payload}</div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '3px' }}>
                  <span style={{ fontSize: '10px', color: Taue.color.text.tertiary, fontStyle: 'italic' }}>{ev.source}</span>
                  {ev.triggeredRuns > 0 && (
                    <span style={{ fontSize: '10px', color: au.lime, fontWeight: 700, fontFamily: Taue.font.mono }}>→ {ev.triggeredRuns} run{ev.triggeredRuns > 1 ? 's' : ''}</span>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function AutoTriggers({ data }) {
  const au = window.__au;
  const [kindFilter, setKindFilter] = useAuEvState('All');
  const [search, setSearch] = useAuEvState('');

  const kinds = useAuEvMemo(() => ['All', ...new Set(data.triggers.map(t => t.kind))], [data]);
  const filtered = data.triggers.filter(t =>
    (kindFilter === 'All' || t.kind === kindFilter) &&
    (!search || t.name.toLowerCase().includes(search.toLowerCase()) || t.on.toLowerCase().includes(search.toLowerCase()))
  );

  return (
    <div>
      <AuHero
        accent={au.violet} bg={au.violetBg}
        title={`Triggers — ${data.triggers.length} rules`}
        description={<>
          Automation rules that fire workflows on cron, webhook, event, or manual initiation. <b style={{ color: au.lime, fontFamily: Taue.font.mono }}>{data.triggers.filter(t => t.enabled).length}</b> enabled · <b style={{ fontFamily: Taue.font.mono }}>{data.triggers.reduce((s, t) => s + t.firedToday, 0)}</b> fired today · <b style={{ fontFamily: Taue.font.mono }}>{au.num(data.triggers.reduce((s, t) => s + t.firedYtd, 0))}</b> YTD.
        </>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Active triggers</span><span style={{ ...au.statValue, color: au.lime }}>{data.triggers.filter(t => t.enabled).length}</span><span style={{ ...au.statDelta, color: Taue.color.text.tertiary }}>of {data.triggers.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Fired today</span><span style={au.statValue}>{data.triggers.reduce((s, t) => s + t.firedToday, 0)}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Fired YTD</span><span style={au.statValue}>{au.num(data.triggers.reduce((s, t) => s + t.firedYtd, 0))}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Avg runtime</span><span style={au.statValue}>{Math.round(data.triggers.reduce((s, t) => s + t.avgRunMs, 0) / data.triggers.length)} <span style={{ fontSize: '12px', color: Taue.color.text.tertiary, fontWeight: 500 }}>ms</span></span></div>
        <div style={au.stat}><span style={au.statLabel}>Trigger kinds</span><span style={au.statValue}>{kinds.length - 1}</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Automation rules — {filtered.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search trigger / event…"
              style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taue.color.border.light}`, borderRadius: '5px', background: Taue.color.bg.card, color: Taue.color.text.primary, minWidth: '220px', fontFamily: Taue.font.family }} />
            <select value={kindFilter} onChange={e => setKindFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taue.color.border.light}`, borderRadius: '5px', background: Taue.color.bg.card, color: Taue.color.text.secondary }}>
              {kinds.map(k => <option key={k} value={k}>Kind: {k}</option>)}
            </select>
            <button style={au.btnPrimary}>+ New trigger</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>ID</th>
              <th style={au.th}>Name / Action</th>
              <th style={au.th}>Kind</th>
              <th style={au.th}>When</th>
              <th style={au.th}>Target</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Today</th>
              <th style={{ ...au.th, textAlign: 'right' }}>YTD</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Avg ms</th>
              <th style={au.th}>Enabled</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(t => {
              const ks = au.triggerStyle(t.kind);
              return (
                <tr key={t.id}>
                  <td style={{ ...au.td, fontFamily: Taue.font.mono, color: au.lime, fontWeight: 700 }}>{t.id}</td>
                  <td style={{ ...au.td, maxWidth: '380px' }}>
                    <div style={{ fontWeight: 600, color: Taue.color.text.primary, fontSize: '11px' }}>{t.name}</div>
                    <div style={{ fontSize: '10px', color: Taue.color.text.tertiary, marginTop: '2px', lineHeight: 1.4 }}>{t.action}</div>
                  </td>
                  <td style={au.td}><span style={{ ...au.tag, background: ks.bg, color: ks.color }}>{ks.icon} {t.kind}</span></td>
                  <td style={{ ...au.td, fontFamily: Taue.font.mono, fontSize: '10px', color: au.cobalt, maxWidth: '200px' }}>{t.on}</td>
                  <td style={{ ...au.td, fontSize: '11px', color: Taue.color.text.secondary }}>{t.target}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Taue.font.mono, color: au.lime, fontWeight: 700 }}>{t.firedToday}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Taue.font.mono, color: Taue.color.text.primary }}>{au.num(t.firedYtd)}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Taue.font.mono, fontSize: '11px', color: Taue.color.text.tertiary }}>{au.num(t.avgRunMs)}</td>
                  <td style={au.td}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: '5px', fontSize: '11px', fontWeight: 600, color: t.enabled ? au.emerald : Taue.color.text.tertiary }}>
                      <span style={{ width: '8px', height: '8px', borderRadius: '50%', background: t.enabled ? au.emerald : Taue.color.border.medium }} />
                      {t.enabled ? 'On' : 'Off'}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.AutoEvents   = AutoEvents;
window.AutoTriggers = AutoTriggers;
