// Integrations
function Integrations() {
  const featured = INTEGRATIONS.filter(i => i.featured);
  const groups = [
    { name: 'CRM', items: INTEGRATIONS.filter(i => i.kind.startsWith('CRM') && !i.featured) },
    { name: 'Email & messaging', items: INTEGRATIONS.filter(i => ['EMAIL', 'CHAT', 'SMS · VOICE'].includes(i.kind)) },
    { name: 'Paid & social', items: INTEGRATIONS.filter(i => ['PAID', 'SOCIAL'].includes(i.kind)) },
    { name: 'Data & ops', items: INTEGRATIONS.filter(i => ['ENRICH', 'PAYMENTS', 'EVENTS', 'COMPETITIVE INTEL'].includes(i.kind)) },
  ];
  const colorOf = (n) => ({
    'Go High Level': '#3aaf6c', VAPI: '#5b8def', 'x402': '#00d97e', 'Solana Tracker': '#9945ff',
    Salesforce: '#00a1e0', HubSpot: '#ff7a59', Gmail: '#ea4335', Slack: '#611f69', SendGrid: '#1a82e2',
    Twilio: '#f22f46', 'Meta Ads': '#0866ff', 'Google Ads': '#4285f4', LinkedIn: '#0a66c2',
    Clearbit: '#5cd2c6', Stripe: '#635bff', Segment: '#52bd95', SimilarWeb: '#092540',
  })[n] || '#8b6bff';

  return (
    <div>
      <div className="page-hd">
        <div className="page-hd-l">
          <div className="page-eyebrow">Integrations · {INTEGRATIONS.filter(i => i.status === 'connected').length} connected · {INTEGRATIONS.length} available</div>
          <h1 className="page-title">Integrations</h1>
          <div className="page-sub">Connect Demiurge to the systems your team already uses. Two-way sync, real-time events, no glue code.</div>
        </div>
        <div className="page-hd-r">
          <div className="cmd-bar" style={{ maxWidth: 280, marginLeft: 0 }}>
            <Icon.Search style={{ width: 14, height: 14, color: 'var(--text-faint)' }}/>
            <span>Search integrations…</span>
          </div>
          <button className="btn primary"><Icon.Plus className="icon"/>Request integration</button>
        </div>
      </div>

      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 24 }}>
        {/* Featured / native integrations */}
        <div>
          <div className="row" style={{ marginBottom: 12, justifyContent: 'space-between' }}>
            <h2 className="serif" style={{ margin: 0, fontSize: 20, fontStyle: 'italic' }}><span className="gradient-text">Native</span> integrations</h2>
            <span className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em' }}>FIRST-CLASS · NO GLUE CODE</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            {featured.map(i => <FeaturedIntegration key={i.id} item={i} color={colorOf(i.name)}/>)}
          </div>
        </div>        {groups.map(g => (
          <div key={g.name}>
            <div className="row" style={{ marginBottom: 12, justifyContent: 'space-between' }}>
              <h2 className="serif" style={{ margin: 0, fontSize: 20, fontStyle: 'italic' }}>{g.name}</h2>
              <span className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em' }}>{g.items.length} APPS</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
              {g.items.map(i => {
                const color = colorOf(i.name);
                return (
                  <div key={i.id} style={{
                    padding: 16,
                    background: 'rgba(255, 255, 255, 0.025)',
                    border: '1px solid var(--border)',
                    borderRadius: 'var(--radius-lg)',
                    cursor: 'pointer',
                    transition: 'all 0.15s',
                    display: 'flex', flexDirection: 'column', gap: 12,
                    backdropFilter: 'blur(20px)',
                  }}>
                    <div className="row" style={{ justifyContent: 'space-between' }}>
                      <div style={{
                        width: 40, height: 40, borderRadius: 10,
                        background: `linear-gradient(135deg, ${color}40, ${color}15)`,
                        border: `1px solid ${color}40`,
                        display: 'grid', placeItems: 'center',
                        fontFamily: 'var(--font-mono)',
                        fontSize: 16,
                        fontWeight: 700,
                        color: '#fff',
                        textShadow: `0 0 8px ${color}aa`,
                      }}>{i.name[0]}</div>
                      <StatusTag status={i.status}/>
                    </div>
                    <div>
                      <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 2 }}>{i.name}</div>
                      <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase' }}>{i.kind}</div>
                    </div>
                    <div className="row" style={{ justifyContent: 'space-between', paddingTop: 10, borderTop: '1px solid var(--border)' }}>
                      <span className="mono faint" style={{ fontSize: 10 }}>last sync · {i.last}</span>
                      {i.status === 'connected' && <button className="btn ghost sm">Manage</button>}
                      {i.status === 'disconnected' && <button className="btn sm">Connect</button>}
                      {i.status === 'degraded' && <button className="btn sm" style={{ color: 'var(--warn)' }}>Fix</button>}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        ))}

        {/* MCP servers */}
        <McpSection/>
      </div>
    </div>
  );
}

function McpSection() {
  const cats = ['ALL', ...Array.from(new Set(MCP_SERVERS.map(m => m.cat || 'Other')))];
  const [cat, setCat] = React.useState('ALL');
  const [q, setQ] = React.useState('');
  const filtered = MCP_SERVERS.filter(m =>
    (cat === 'ALL' || (m.cat || 'Other') === cat) &&
    (!q || m.name.toLowerCase().includes(q.toLowerCase()) || (m.desc || '').toLowerCase().includes(q.toLowerCase()))
  );
  const liveCount = MCP_SERVERS.filter(m => m.status === 'live').length;
  return (
    <div>
      <div className="row" style={{ marginBottom: 12, justifyContent: 'space-between' }}>
        <h2 className="serif" style={{ margin: 0, fontSize: 20, fontStyle: 'italic' }}><span className="gradient-text">Custom</span> MCP servers</h2>
        <div className="row" style={{ gap: 10 }}>
          <span className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em' }}>MODEL CONTEXT PROTOCOL · {liveCount} LIVE · {MCP_SERVERS.length} INSTALLED</span>
          <button className="btn primary sm"><Icon.Plus className="icon"/>Install MCP server</button>
        </div>
      </div>
      <div className="panel" style={{
        background: 'linear-gradient(135deg, rgba(139, 107, 255, 0.04), rgba(75, 232, 255, 0.02))',
        borderColor: 'rgba(139, 107, 255, 0.2)',
      }}>
        <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="dim" style={{ fontSize: 12, lineHeight: 1.6, maxWidth: 760 }}>
            Plug any MCP-compatible server in and your agents get the tools instantly. Self-hosted, community-published, or first-party from vendors — top installs from the remote-mcp directory shown below. Every tool call hits the audit log; per-tool spend caps and permission scopes are enforced server-side.
          </div>

          <div className="row" style={{ gap: 10, flexWrap: 'wrap' }}>
            <div className="cmd-bar" style={{ maxWidth: 280, margin: 0 }}>
              <Icon.Search style={{ width: 14, height: 14, color: 'var(--text-faint)' }}/>
              <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search MCP servers…" style={{ flex: 1, fontSize: 11, fontFamily: 'var(--font-mono)' }}/>
            </div>
            <div className="row" style={{ flexWrap: 'wrap', gap: 4 }}>
              {cats.map(c => (
                <button key={c} onClick={() => setCat(c)} className="tag" style={{
                  cursor: 'pointer',
                  color: cat === c ? 'var(--cyan)' : 'var(--text-dim)',
                  borderColor: cat === c ? 'rgba(75, 232, 255, 0.4)' : 'var(--border)',
                  background: cat === c ? 'rgba(75, 232, 255, 0.08)' : 'rgba(255, 255, 255, 0.04)',
                }}>{c}{cat === c ? '' : ''}</button>
              ))}
            </div>
            <span className="mono faint" style={{ fontSize: 10, marginLeft: 'auto' }}>{filtered.length} servers</span>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(310px, 1fr))', gap: 10, maxHeight: 720, overflowY: 'auto', paddingRight: 4 }}>
            {filtered.map(m => {
              const I = Icon[m.icon] || Icon.Code;
              return (
                <div key={m.id} style={{
                  padding: 14,
                  background: 'rgba(0, 0, 0, 0.25)',
                  border: '1px solid var(--border)',
                  borderRadius: 'var(--radius-lg)',
                  display: 'flex', flexDirection: 'column', gap: 10,
                }}>
                  <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div className="row" style={{ gap: 10, minWidth: 0 }}>
                      <div style={{
                        width: 30, height: 30, borderRadius: 7,
                        background: 'linear-gradient(135deg, rgba(139, 107, 255, 0.2), rgba(75, 232, 255, 0.08))',
                        border: '1px solid rgba(139, 107, 255, 0.25)',
                        display: 'grid', placeItems: 'center', flexShrink: 0,
                      }}>
                        <I style={{ width: 13, height: 13, color: 'var(--cyan)' }}/>
                      </div>
                      <div style={{ minWidth: 0 }}>
                        <div className="row" style={{ gap: 5 }}>
                          <span className="mono" style={{ fontSize: 12, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.name}</span>
                          {m.verified && <span title="Official / verified" style={{ color: 'var(--cyan)', fontSize: 10 }}>✓</span>}
                        </div>
                        <div className="mono faint" style={{ fontSize: 10, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>by {m.author}</div>
                      </div>
                    </div>
                    <StatusTag status={m.status}/>
                  </div>
                  <div className="dim" style={{ fontSize: 11, lineHeight: 1.5, minHeight: 32 }}>{m.desc}</div>
                  <div className="row" style={{ justifyContent: 'space-between', paddingTop: 8, borderTop: '1px solid var(--border)' }}>
                    <span className="mono faint" style={{ fontSize: 9 }}>{m.tools} tools · {m.calls24h.toLocaleString()} calls/24h</span>
                    <button className="btn ghost sm" style={{ padding: '3px 8px', fontSize: 10 }}>Configure</button>
                  </div>
                </div>
              );
            })}
          </div>

          <div style={{
            padding: 16,
            background: 'rgba(0, 0, 0, 0.3)',
            border: '1px dashed rgba(139, 107, 255, 0.3)',
            borderRadius: 'var(--radius-lg)',
            display: 'flex', alignItems: 'center', gap: 14,
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: 10,
              background: 'linear-gradient(135deg, rgba(139, 107, 255, 0.25), rgba(75, 232, 255, 0.1))',
              border: '1px solid rgba(139, 107, 255, 0.3)',
              display: 'grid', placeItems: 'center',
              flexShrink: 0,
            }}>
              <Icon.Code style={{ width: 16, height: 16, color: 'var(--violet)' }}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, marginBottom: 4 }}>Connect your own MCP server</div>
              <div className="dim mono" style={{ fontSize: 11 }}>Paste the URL or stdio command. Demiurge will verify the schema, scope permissions, and roll it out to the agents you authorise.</div>
            </div>
            <div className="row" style={{ gap: 6 }}>
              <input
                placeholder="https://your-server.com/sse  ·  or  ·  npx your-mcp-package"
                style={{
                  padding: '8px 12px',
                  background: 'rgba(0, 0, 0, 0.4)',
                  border: '1px solid var(--border)',
                  borderRadius: 'var(--radius)',
                  fontFamily: 'var(--font-mono)',
                  fontSize: 11,
                  width: 340,
                  color: 'var(--text)',
                }}
              />
              <button className="btn primary sm">Install</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function FeaturedIntegration({ item: i, color }) {
  const features = {
    'Go High Level': {
      tagline: 'Agency CRM · two-way sync',
      desc: 'Push every contact, conversation, and pipeline event to GHL in real time. Sync sub-account settings, snapshots, and AI workflows.',
      capabilities: [
        { l: 'Contacts · Two-way sync', v: '4.2k synced' },
        { l: 'Pipelines · stage mapping', v: '12 pipelines' },
        { l: 'Sub-accounts · snapshots', v: '5 accounts' },
        { l: 'Calendars · booking sync', v: 'live' },
        { l: 'Workflows · trigger bridge', v: '38 mapped' },
      ],
    },
    VAPI: {
      tagline: 'Voice AI · realtime dialer',
      desc: "Power Hermes and your custom voice agents on Vapi's low-latency stack. Outbound dials, inbound receptionist, and warm transfers — all routed through Demiurge.",
      capabilities: [
        { l: 'Voice models · ElevenLabs + Cartesia', v: '4 active' },
        { l: 'Outbound minutes · 30d', v: '4,128 min' },
        { l: 'Inbound numbers · provisioned', v: '6 UK · 2 US' },
        { l: 'Avg latency · time-to-first-token', v: '218ms' },
        { l: 'Call recording + transcript', v: 'live' },
      ],
    },
    'x402': {
      tagline: 'HTTP 402 · agent-native payments',
      desc: 'Open protocol from Coinbase. Your agents pay for API calls, data, voice minutes, and compute autonomously — settling in USDC on Base or Solana. No API keys, no rate limits, no human in the loop.',
      capabilities: [
        { l: 'Protocol · HTTP 402 Payment Required', v: 'v0.4' },
        { l: 'Settlement · USDC on Base + Solana', v: 'sub-1s' },
        { l: 'Agent autonomous spend · 24h', v: '£18.42 · 1,408 txns' },
        { l: 'Avg cost per agent call', v: '£0.013' },
        { l: 'Facilitator · Coinbase x402 relay', v: 'connected' },
        { l: 'Spend cap · per agent / per day', v: '£50.00' },
      ],
    },
    'Solana Tracker': {
      tagline: 'Solana market data + swap APIs',
      desc: 'Real-time token data, prices, and swap routing across every Solana DEX. Drives the on-chain side of x402 settlement and powers crypto-aware agents.',
      capabilities: [
        { l: 'Token metadata · Jupiter routing', v: 'live' },
        { l: 'Price feeds · 7-day cache', v: 'real-time' },
        { l: 'Swap API · best-route execution', v: 'connected' },
        { l: 'Wallet PnL · agent treasuries', v: '8 wallets' },
        { l: 'WebSocket · price subscriptions', v: '14 streams' },
      ],
    },
  };
  const f = features[i.name];
  return (
    <div className="panel" style={{
      borderColor: `${color}40`,
      background: `linear-gradient(135deg, ${color}06, rgba(255, 255, 255, 0.025))`,
      position: 'relative',
      overflow: 'hidden',
    }}>
      <div style={{ position: 'absolute', top: -60, right: -60, width: 200, height: 200, background: `radial-gradient(circle, ${color}30, transparent 70%)`, pointerEvents: 'none' }}/>
      <div className="panel-hd" style={{ position: 'relative' }}>
        <div className="row" style={{ gap: 12 }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12,
            background: `linear-gradient(135deg, ${color}50, ${color}20)`,
            border: `1px solid ${color}50`,
            display: 'grid', placeItems: 'center',
            fontFamily: 'var(--font-mono)',
            fontSize: 18,
            fontWeight: 700,
            color: '#fff',
            textShadow: `0 0 12px ${color}`,
          }}>{i.name[0]}</div>
          <div>
            <div className="row" style={{ gap: 8 }}>
              <span style={{ fontSize: 16, fontWeight: 500 }}>{i.name}</span>
              <StatusTag status={i.status}/>
            </div>
            <span className="mono faint" style={{ fontSize: 11, letterSpacing: '0.08em' }}>{f.tagline}</span>
          </div>
        </div>
        <button className="btn sm">Manage <Icon.ChevronR className="icon" style={{ width: 12, height: 12 }}/></button>
      </div>
      <div className="panel-body" style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div className="dim" style={{ fontSize: 12, lineHeight: 1.55 }}>{f.desc}</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {f.capabilities.map((c, idx) => (
            <div key={idx} className="row" style={{ justifyContent: 'space-between', padding: '8px 10px', background: 'rgba(0, 0, 0, 0.25)', border: '1px solid var(--border)', borderRadius: 'var(--radius)' }}>
              <span className="row" style={{ gap: 8, fontSize: 12 }}>
                <Icon.Check style={{ width: 12, height: 12, color: 'var(--good)' }}/>
                {c.l}
              </span>
              <span className="mono" style={{ fontSize: 11, color }}>{c.v}</span>
            </div>
          ))}
        </div>
        <div className="row mono faint" style={{ fontSize: 10, justifyContent: 'space-between' }}>
          <span>last sync · {i.last}</span>
          <span>OAuth · v3 · ratelimit 1000/min</span>
        </div>
      </div>
    </div>
  );
}

window.Integrations = Integrations;
