// AUTOMATION PLATFORM — Integrations + Templates tabs
const { useState: useAuInState, useMemo: useAuInMemo } = React;
const Taui = window.ArbiterTokens;

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

  const kinds = useAuInMemo(() => ['All', ...new Set(data.integrations.map(i => i.kind))], [data]);
  const filtered = data.integrations.filter(i =>
    (kindFilter === 'All' || i.kind === kindFilter) &&
    (!search || i.name.toLowerCase().includes(search.toLowerCase()))
  );
  const totalEvents = data.integrations.reduce((s, i) => s + i.events30d, 0);

  return (
    <div>
      <AuHero
        accent={au.teal} bg={au.tealBg}
        title={`Integrations — ${data.integrations.length} connectors`}
        description={<>
          External system connectors supplying events and acting as workflow sinks. <b style={{ color: au.lime, fontFamily: Taui.font.mono }}>{data.integrations.filter(i => i.status === 'Connected').length}</b> connected · <b style={{ fontFamily: Taui.font.mono }}>{au.num(totalEvents)}</b> events ingested in last 30d.
        </>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Connectors</span><span style={au.statValue}>{data.integrations.length}</span><span style={{ ...au.statDelta, color: Taui.color.text.tertiary }}>{data.integrations.filter(i => i.status === 'Connected').length} connected</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}>Categories</span><span style={au.statValue}>{kinds.length - 1}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Paused</span><span style={{ ...au.statValue, color: au.amber }}>{data.integrations.filter(i => i.status === 'Paused').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><span style={{ ...au.statDelta, color: Taui.color.text.tertiary }}>uptime 30d</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Connector catalog — {filtered.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search connector…"
              style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taui.color.border.light}`, borderRadius: '5px', background: Taui.color.bg.card, color: Taui.color.text.primary, minWidth: '200px', fontFamily: Taui.font.family }} />
            <select value={kindFilter} onChange={e => setKindFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taui.color.border.light}`, borderRadius: '5px', background: Taui.color.bg.card, color: Taui.color.text.secondary }}>
              {kinds.map(k => <option key={k} value={k}>Kind: {k}</option>)}
            </select>
            <button style={au.btnPrimary}>+ Add connector</button>
          </div>
        </div>
        <div style={{ padding: '14px 16px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px' }}>
          {filtered.map(i => {
            const ks = au.integrationStyle(i.kind);
            const ss = au.statusColor(i.status);
            return (
              <div key={i.id} style={{ padding: '14px', border: `1px solid ${Taui.color.border.light}`, borderRadius: '8px', background: Taui.color.bg.card }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '8px' }}>
                  <div style={{ width: '32px', height: '32px', borderRadius: '6px', background: ks.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', color: ks.color, fontSize: '16px', fontWeight: 700 }}>{ks.icon}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: '12px', fontWeight: 700, color: Taui.color.text.primary, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{i.name}</div>
                    <div style={{ fontSize: '10px', color: Taui.color.text.tertiary, fontFamily: Taui.font.mono }}>{i.id} · {i.kind}</div>
                  </div>
                  <span style={{ ...au.tag, background: ss.bg, color: ss.color }}>{i.status}</span>
                </div>
                <div style={{ fontSize: '11px', color: Taui.color.text.secondary, marginBottom: '10px', lineHeight: 1.4 }}>{i.scope}</div>
                <div style={{ display: 'flex', justifyContent: 'space-between', paddingTop: '8px', borderTop: `1px solid ${Taui.color.border.light}` }}>
                  <div>
                    <div style={{ fontSize: '9px', color: Taui.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Events 30d</div>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: au.lime, fontFamily: Taui.font.mono }}>{au.num(i.events30d)}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: '9px', color: Taui.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Last sync</div>
                    <div style={{ fontSize: '11px', color: Taui.color.text.primary, fontFamily: Taui.font.mono }}>{i.lastSync}</div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

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

  const categories = useAuInMemo(() => ['All', ...new Set(data.templates.map(t => t.category))], [data]);
  const filtered = data.templates.filter(t =>
    (categoryFilter === 'All' || t.category === categoryFilter) &&
    (!search || t.name.toLowerCase().includes(search.toLowerCase()) || t.description.toLowerCase().includes(search.toLowerCase()))
  );

  return (
    <div>
      <AuHero
        accent={au.fuchsia} bg={au.fuchsiaBg}
        title={`Templates — ${data.templates.length} starter workflows`}
        description={<>
          Curated workflow blueprints ready to instantiate per matter. <b style={{ color: au.lime, fontFamily: Taui.font.mono }}>{au.num(data.templates.reduce((s, t) => s + t.usedCount, 0))}</b> instantiations YTD across <b>{categories.length - 1}</b> categories. Browse the team marketplace for shared variants.
        </>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Templates</span><span style={au.statValue}>{data.templates.length}</span><span style={{ ...au.statDelta, color: Taui.color.text.tertiary }}>ready to instantiate</span></div>
        <div style={au.stat}><span style={au.statLabel}>Total uses YTD</span><span style={{ ...au.statValue, color: au.lime }}>{au.num(data.templates.reduce((s, t) => s + t.usedCount, 0))}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Categories</span><span style={au.statValue}>{categories.length - 1}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Avg steps</span><span style={au.statValue}>{Math.round(data.templates.reduce((s, t) => s + t.steps, 0) / data.templates.length)}</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Template library — {filtered.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search template…"
              style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taui.color.border.light}`, borderRadius: '5px', background: Taui.color.bg.card, color: Taui.color.text.primary, minWidth: '220px', fontFamily: Taui.font.family }} />
            <select value={categoryFilter} onChange={e => setCategoryFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taui.color.border.light}`, borderRadius: '5px', background: Taui.color.bg.card, color: Taui.color.text.secondary }}>
              {categories.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
            <button style={au.btnPrimary}>+ New template</button>
          </div>
        </div>
        <div style={{ padding: '14px 16px', display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px' }}>
          {filtered.map(t => (
            <div key={t.id} style={{ padding: '14px', border: `1px solid ${Taui.color.border.light}`, borderRadius: '8px', background: Taui.color.bg.card, display: 'flex', flexDirection: 'column', gap: '8px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: '10px', color: Taui.color.text.tertiary, fontFamily: Taui.font.mono, marginBottom: '2px' }}>{t.id}</div>
                  <div style={{ fontSize: '13px', fontWeight: 700, color: Taui.color.text.primary, letterSpacing: '-0.01em' }}>{t.name}</div>
                </div>
                <span style={{ ...au.tag, background: au.limeBg, color: au.limeDeep }}>{t.category}</span>
              </div>
              <div style={{ fontSize: '11px', color: Taui.color.text.secondary, lineHeight: 1.45 }}>{t.description}</div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: '8px', borderTop: `1px solid ${Taui.color.border.light}` }}>
                <div style={{ display: 'flex', gap: '16px' }}>
                  <div>
                    <div style={{ fontSize: '9px', color: Taui.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Steps</div>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: au.cobalt, fontFamily: Taui.font.mono }}>{t.steps}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '9px', color: Taui.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Uses YTD</div>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: au.lime, fontFamily: Taui.font.mono }}>{au.num(t.usedCount)}</div>
                  </div>
                </div>
                <button style={au.btnSecondary}>▶ Use</button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.AutoIntegrations = AutoIntegrations;
window.AutoTemplates    = AutoTemplates;
