// settings-extra.jsx — Settings sub-pages: Channels, Providers, MCP Servers

// ─────────────────────────────────────────────────────────────
// Shared: StatusDot
// ─────────────────────────────────────────────────────────────
function StatusDot({ status = 'off', size = 8 }) {
  const colors = { on: '#28c840', warn: '#febc2e', off: '#ff5f57', pending: '#febc2e' };
  return (
    <div style={{
      width: size, height: size, borderRadius: size / 2,
      background: colors[status] || colors.off,
      boxShadow: status === 'on' ? '0 0 6px rgba(40,200,64,0.4)' : 'none',
      flexShrink: 0,
    }} />
  );
}

// ─────────────────────────────────────────────────────────────
// Toggle component
// ─────────────────────────────────────────────────────────────
function Toggle({ on, dark }) {
  const t = dark ? G.d : G.l;
  return (
    <div style={{ width: 36, height: 22, borderRadius: 11, background: on ? t.fg : t.surface2, border: `1px solid ${t.border}`, position: 'relative', padding: 2, flexShrink: 0 }}>
      <div style={{ width: 16, height: 16, borderRadius: 8, background: on ? t.bg : t.fg, transition: 'all .2s', transform: on ? 'translateX(14px)' : 'translateX(0)' }} />
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// 1. CHANNELS — Telegram / Discord / Feishu / Weixin bridge
// ═════════════════════════════════════════════════════════════

const CHANNEL_PLATFORMS = [
  { id: 'telegram', label: 'Telegram', icon: '✈', color: '#2AABEE' },
  { id: 'discord', label: 'Discord', icon: '🎮', color: '#5865F2' },
  { id: 'feishu', label: 'Feishu', icon: '飞', color: '#3370FF' },
  { id: 'weixin', label: 'Weixin', icon: '微', color: '#07C160' },
];

// state: 'unconfigured' | 'configuring' | 'connected' | 'expired'
function ChannelsSettings({ dark, activeTab = 'telegram', tabStates }) {
  const t = dark ? G.d : G.l;
  const defaults = {
    telegram: { state: 'connected', token: '71038•••••:AAH', botName: '@ghast_bridge_bot', botAvatar: 'G',
      groups: [
        { name: 'Ghast Labs · 内部', status: 'active', messages: 1284, lastActive: '2 min ago' },
        { name: 'Design Review', status: 'active', messages: 437, lastActive: '18 min ago' },
        { name: '杂谈 · Off-topic', status: 'muted', messages: 89, lastActive: '3h ago' },
        { name: 'Alerts · Prod', status: 'active', messages: 2041, lastActive: 'just now' },
      ]},
    discord: { state: 'connected', token: 'MTI3•••••.GR', botName: 'Ghast#4291', botAvatar: 'G',
      groups: [
        { name: '#general', status: 'active', messages: 3102, lastActive: '5 min ago' },
        { name: '#engineering', status: 'active', messages: 891, lastActive: '1h ago' },
        { name: '#random', status: 'muted', messages: 210, lastActive: '6h ago' },
      ]},
    feishu: { state: 'configuring', token: 'cli_a5f•••', botName: '', botAvatar: '', groups: [] },
    weixin: { state: 'unconfigured', token: '', botName: '', botAvatar: '', groups: [] },
  };
  const states = tabStates || defaults;
  const platform = CHANNEL_PLATFORMS.find(p => p.id === activeTab);
  const data = states[activeTab];

  const statusMap = { connected: 'on', configuring: 'pending', expired: 'warn', unconfigured: 'off' };
  const statusLabel = { connected: 'Connected', configuring: 'Configuring…', expired: 'Token expired', unconfigured: 'Not configured' };

  return (
    <div className="gh-scroll" style={{ height: '100%', overflow: 'auto', /* full bleed */ }}>
        {/* Platform tabs */}
        <div style={{ display: 'flex', borderBottom: `1px solid ${t.border}`, padding: '0 32px' }}>
          {CHANNEL_PLATFORMS.map(p => {
            const isActive = p.id === activeTab;
            const st = states[p.id];
            return (
              <div key={p.id} style={{
                padding: '12px 18px', fontSize: 13, fontWeight: isActive ? 600 : 400,
                color: isActive ? t.fg : t.fg2,
                borderBottom: isActive ? `2px solid ${t.fg}` : '2px solid transparent',
                display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer',
              }}>
                <span style={{ fontSize: 14 }}>{p.icon}</span>
                {p.label}
                <StatusDot status={statusMap[st.state]} size={6} />
              </div>
            );
          })}
        </div>

        <div style={{ padding: '28px 32px', maxWidth: 680 }}>
          {/* ── Unconfigured state ── */}
          {data.state === 'unconfigured' && (
            <div style={{ textAlign: 'center', padding: '60px 40px' }}>
              <div style={{ width: 64, height: 64, borderRadius: 18, background: platform.color + '18', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px', fontSize: 28 }}>
                {platform.icon}
              </div>
              <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: -0.4 }}>Connect {platform.label}</div>
              <div style={{ fontSize: 13, color: t.fg2, marginTop: 6, maxWidth: 380, margin: '6px auto 0', lineHeight: 1.55 }}>
                Bridge your {platform.label} groups to Ghast. Messages flow both ways — your bot relays and responds.
              </div>
              <div style={{ marginTop: 24 }}>
                <Button variant="primary" size="lg">Set up {platform.label} bot</Button>
              </div>
            </div>
          )}

          {/* ── Configuring state ── */}
          {data.state === 'configuring' && (
            <>
              <SectionHeader title={`${platform.label} Bot`} sub="Paste your bot token to connect." dark={dark} />
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>Bot Token</div>
                  <div style={{
                    height: 44, padding: '0 14px', display: 'flex', alignItems: 'center', gap: 10,
                    background: t.surface, border: `1px solid ${t.border}`, borderRadius: 10,
                  }}>
                    <Icon name="lock" size={14} color={t.fg3} />
                    <span style={{ flex: 1, fontFamily: G.mono, fontSize: 13, color: t.fg, letterSpacing: 0.5 }}>{data.token || ''}</span>
                    <button style={{ background: 'transparent', border: 'none', color: t.fg3, cursor: 'pointer', padding: 4 }}><Icon name="eye" size={14} /></button>
                  </div>
                  <div style={{ fontSize: 11, color: t.fg3, marginTop: 6 }}>
                    Stored in your OS keychain. Never sent to our servers.
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 10 }}>
                  <Button variant="primary" size="md" icon={<Icon name="refresh" size={13} color={t.bg} />}>Test connection</Button>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <StatusDot status="pending" />
                    <span style={{ fontSize: 12, color: t.fg2 }}>Waiting for test…</span>
                  </div>
                </div>
              </div>
              <Divider style={{ margin: '24px 0' }} />
              <div style={{ padding: '20px 24px', background: t.surface2, borderRadius: 12, border: `1px solid ${t.border}` }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: t.fg3 }}>
                  <Icon name="info" size={16} />
                  <div style={{ fontSize: 12, lineHeight: 1.5 }}>
                    No groups joined yet. After connection succeeds, add your bot to a group and it will appear here.
                  </div>
                </div>
              </div>
            </>
          )}

          {/* ── Connected state ── */}
          {data.state === 'connected' && (
            <>
              <SectionHeader title={`${platform.label} Bot`} sub="Active and relaying messages." dark={dark} />
              {/* Bot info card */}
              <Card style={{ padding: 16, marginBottom: 20 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                  <div style={{ width: 44, height: 44, borderRadius: 12, background: platform.color, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, fontWeight: 600 }}>
                    {data.botAvatar}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 15, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}>
                      {data.botName}
                      <StatusDot status="on" />
                    </div>
                    <div style={{ fontSize: 12, color: t.fg3, fontFamily: G.mono, marginTop: 2 }}>
                      Token: {data.token}
                    </div>
                  </div>
                  <Button variant="secondary" size="sm">Replace token</Button>
                </div>
              </Card>

              {/* Token field (masked) */}
              <div style={{ marginBottom: 20 }}>
                <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>Bot Token</div>
                <div style={{
                  height: 44, padding: '0 14px', display: 'flex', alignItems: 'center', gap: 10,
                  background: t.surface, border: `1px solid ${t.border}`, borderRadius: 10,
                }}>
                  <Icon name="lock" size={14} color={t.fg3} />
                  <span style={{ flex: 1, fontFamily: G.mono, fontSize: 13, color: t.fg2 }}>{data.token}</span>
                  <button style={{ background: 'transparent', border: 'none', color: t.fg3, cursor: 'pointer', padding: 4 }}><Icon name="eye" size={14} /></button>
                </div>
                <div style={{ display: 'flex', gap: 10, marginTop: 10 }}>
                  <Button variant="secondary" size="sm" icon={<Icon name="refresh" size={12} />}>Test connection</Button>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <StatusDot status="on" />
                    <span style={{ fontSize: 12, color: t.fg2 }}>Connected</span>
                  </div>
                </div>
              </div>

              <Divider style={{ margin: '20px 0' }} />

              {/* Groups list */}
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
                <SectionHeader title="Joined Groups" sub={`${data.groups.length} groups bridged`} dark={dark} />
                <Button variant="secondary" size="sm" icon={<Icon name="plus" size={12} />}>Add via group link</Button>
              </div>
              <div style={{ background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12, overflow: 'hidden' }}>
                {data.groups.map((g, i) => (
                  <div key={i} style={{
                    display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px',
                    borderTop: i === 0 ? 'none' : `1px solid ${t.border2}`,
                  }}>
                    <div style={{
                      width: 32, height: 32, borderRadius: 8, background: platform.color + '18',
                      color: platform.color, display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontSize: 13, fontWeight: 600,
                    }}>{g.name[0]}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{g.name}</div>
                      <div style={{ fontSize: 11, color: t.fg3, marginTop: 1 }}>
                        {g.messages.toLocaleString()} messages · {g.lastActive}
                      </div>
                    </div>
                    <Tag variant={g.status === 'active' ? 'solid' : 'default'}>{g.status === 'active' ? 'Active' : 'Muted'}</Tag>
                    <button style={{ background: 'transparent', border: 'none', color: t.fg3, cursor: 'pointer', padding: 4 }}>
                      <Icon name="edit" size={13} />
                    </button>
                    <button style={{ background: 'transparent', border: 'none', color: t.fg3, cursor: 'pointer', padding: 4 }}>
                      <Icon name="moreH" size={14} />
                    </button>
                  </div>
                ))}
              </div>

              {/* Group rules entry */}
              <div style={{ marginTop: 16 }}>
                <SettingRow dark={dark} label="Group rules template" value=".rules.md — applied to all bridged groups" action="Edit rules" />
              </div>
            </>
          )}

          {/* ── Token expired state ── */}
          {data.state === 'expired' && (
            <>
              <SectionHeader title={`${platform.label} Bot`} sub="Token has expired — re-authenticate to resume." dark={dark} />
              <Card style={{ padding: 16, marginBottom: 20, border: `1px solid #ff5f57` }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                  <div style={{ width: 44, height: 44, borderRadius: 12, background: t.surface2, color: t.fg3, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, fontWeight: 600 }}>
                    {platform.icon}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 15, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}>
                      {data.botName || `${platform.label} Bot`}
                      <StatusDot status="off" />
                    </div>
                    <div style={{ fontSize: 12, color: '#ff5f57', marginTop: 2 }}>
                      Token expired on May 1, 2026. Groups are paused.
                    </div>
                  </div>
                  <Button variant="primary" size="sm">Re-authenticate</Button>
                </div>
              </Card>
              <div style={{ marginBottom: 20 }}>
                <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>Bot Token</div>
                <div style={{
                  height: 44, padding: '0 14px', display: 'flex', alignItems: 'center', gap: 10,
                  background: t.surface, border: `1px solid #ff5f57`, borderRadius: 10,
                }}>
                  <Icon name="lock" size={14} color="#ff5f57" />
                  <span style={{ flex: 1, fontFamily: G.mono, fontSize: 13, color: t.fg3, textDecoration: 'line-through' }}>{data.token}</span>
                </div>
              </div>
              <Divider style={{ margin: '20px 0' }} />
              <SectionHeader title="Paused Groups" sub="Will resume when token is refreshed." dark={dark} small />
              <div style={{ background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12, overflow: 'hidden', opacity: 0.6 }}>
                {(data.groups || []).map((g, i) => (
                  <div key={i} style={{
                    display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px',
                    borderTop: i === 0 ? 'none' : `1px solid ${t.border2}`,
                  }}>
                    <div style={{ width: 32, height: 32, borderRadius: 8, background: t.surface2, color: t.fg3, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 600 }}>{g.name[0]}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 500 }}>{g.name}</div>
                      <div style={{ fontSize: 11, color: t.fg3 }}>{g.messages.toLocaleString()} messages · paused</div>
                    </div>
                    <Tag>Paused</Tag>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
    </div>
  );
}

// ── Channels: Rules editor sub-view ──
function ChannelsRulesEditor({ dark, platform = 'telegram' }) {
  const t = dark ? G.d : G.l;
  const pl = CHANNEL_PLATFORMS.find(p => p.id === platform);
  const mdContent = `# Group Rules

## Behavior
- Reply only when mentioned or in reply threads
- Use the group's primary language
- Do not send unsolicited messages

## Tone
- Professional but friendly
- Match the energy of the group

## Restrictions
- No financial advice
- No personal data sharing
- Respect rate limits: max 5 msgs/min`;

  return (
    <div style={{ height: '100%', display: 'flex', /* full bleed */ }}>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '12px 24px', borderBottom: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: t.fg2 }}>
            <Icon name="file" size={13} /> .rules.md
            <span style={{ flex: 1 }} />
            <Tag>Markdown</Tag>
          </div>
          <div className="gh-scroll" style={{ flex: 1, overflow: 'auto', padding: '20px 28px', fontFamily: G.mono, fontSize: 13, lineHeight: 1.7, color: t.fg, whiteSpace: 'pre-wrap' }}>
            {mdContent}
          </div>
        </div>
        <div style={{ width: 320, borderLeft: `1px solid ${t.border}`, display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '12px 16px', borderBottom: `1px solid ${t.border}`, fontSize: 12, fontWeight: 500, color: t.fg2 }}>Preview</div>
          <div className="gh-scroll" style={{ flex: 1, overflow: 'auto', padding: '20px 20px', fontSize: 13, lineHeight: 1.65, color: t.fg }}>
            <h2 style={{ fontSize: 18, fontWeight: 600, marginTop: 0 }}>Group Rules</h2>
            <h3 style={{ fontSize: 14, fontWeight: 600, marginTop: 18 }}>Behavior</h3>
            <ul style={{ paddingLeft: 18, margin: '6px 0' }}>
              <li style={{ marginBottom: 4, color: t.fg2 }}>Reply only when mentioned or in reply threads</li>
              <li style={{ marginBottom: 4, color: t.fg2 }}>Use the group's primary language</li>
              <li style={{ marginBottom: 4, color: t.fg2 }}>Do not send unsolicited messages</li>
            </ul>
            <h3 style={{ fontSize: 14, fontWeight: 600, marginTop: 18 }}>Tone</h3>
            <ul style={{ paddingLeft: 18, margin: '6px 0' }}>
              <li style={{ marginBottom: 4, color: t.fg2 }}>Professional but friendly</li>
              <li style={{ marginBottom: 4, color: t.fg2 }}>Match the energy of the group</li>
            </ul>
            <h3 style={{ fontSize: 14, fontWeight: 600, marginTop: 18 }}>Restrictions</h3>
            <ul style={{ paddingLeft: 18, margin: '6px 0' }}>
              <li style={{ marginBottom: 4, color: t.fg2 }}>No financial advice</li>
              <li style={{ marginBottom: 4, color: t.fg2 }}>No personal data sharing</li>
              <li style={{ marginBottom: 4, color: t.fg2 }}>Respect rate limits: max 5 msgs/min</li>
            </ul>
          </div>
        </div>
    </div>
  );
}


// ═════════════════════════════════════════════════════════════
// 2. PROVIDERS — replaces Model page
// ═════════════════════════════════════════════════════════════

const ALL_PROVIDERS = [
  { id: 'anthropic', name: 'Anthropic', sub: 'Claude 4 · Claude 3.5 Sonnet', icon: 'A', configured: true, type: 'api', models: ['claude-4-opus', 'claude-4-sonnet', 'claude-3.5-sonnet', 'claude-3-haiku'], default: true },
  { id: 'openai', name: 'OpenAI', sub: 'GPT-5 · GPT-4.1 · o3', icon: 'O', configured: true, type: 'api', models: ['gpt-5', 'gpt-4.1', 'gpt-4.1-mini', 'o3', 'o4-mini'] },
  { id: 'google', name: 'Google', sub: 'Gemini 2.5 Pro · Flash', icon: 'G', configured: true, type: 'api', models: ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-2.0-flash'] },
  { id: 'claude-sub', name: 'Claude Subscription', sub: 'OAuth · no API key needed', icon: 'C', configured: true, type: 'oauth', models: ['claude-4-sonnet (sub)', 'claude-3.5-sonnet (sub)'] },
  { id: 'ollama', name: 'Ollama (Local)', sub: 'localhost:11434', icon: '🦙', configured: true, type: 'local', models: ['llama-3.3-70b', 'mistral-small', 'qwen2.5-72b', 'deepseek-r1'] },
  { id: '0g', name: '0G Compute', sub: 'Decentralized · Router or Advanced', icon: '0G', configured: true, type: '0g', models: ['llama-3.3-70b-instruct', 'deepseek-r1-distill-70b', 'qwen2.5-72b-instruct'] },
  { id: 'mistral', name: 'Mistral', sub: 'Large · Medium · Small', icon: 'M', configured: false, type: 'api', models: ['mistral-large', 'mistral-medium', 'mistral-small'] },
  { id: 'deepseek', name: 'DeepSeek', sub: 'DeepSeek-V3 · R1', icon: 'D', configured: false, type: 'api', models: ['deepseek-v3', 'deepseek-r1'] },
  { id: 'xai', name: 'xAI', sub: 'Grok 3', icon: 'X', configured: false, type: 'api', models: ['grok-3', 'grok-3-mini'] },
  { id: 'cohere', name: 'Cohere', sub: 'Command R+', icon: 'Co', configured: false, type: 'api', models: ['command-r-plus', 'command-r'] },
  { id: 'together', name: 'Together AI', sub: 'Hosted open-source', icon: 'T', configured: false, type: 'api', models: ['llama-3.3-70b', 'mixtral-8x22b'] },
  { id: 'groq', name: 'Groq', sub: 'Ultra-fast inference', icon: 'Gq', configured: false, type: 'api', models: ['llama-3.3-70b', 'mixtral-8x7b'] },
  { id: 'custom', name: 'OpenAI-compatible', sub: 'Custom base URL', icon: 'lucide:wrench', configured: false, type: 'custom', models: [] },
];

function ProvidersSettings({ dark, selectedProvider = 'anthropic', subState = {} }) {
  const t = dark ? G.d : G.l;
  const provider = ALL_PROVIDERS.find(p => p.id === selectedProvider);

  return (
    <div style={{ height: '100%', display: 'flex', /* full bleed */ }}>
        {/* Left: provider list */}
        <div className="gh-scroll" style={{ width: 280, flexShrink: 0, borderRight: `1px solid ${t.border}`, overflow: 'auto', padding: '16px 12px' }}>
          <div style={{ fontSize: 10, fontWeight: 600, color: t.fg3, letterSpacing: 1, padding: '4px 8px 8px', textTransform: 'uppercase' }}>Configured</div>
          {ALL_PROVIDERS.filter(p => p.configured).map(p => (
            <div key={p.id} style={{
              padding: '10px 12px', borderRadius: 10, marginBottom: 2, cursor: 'pointer',
              background: p.id === selectedProvider ? t.surface2 : 'transparent',
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <div style={{
                width: 32, height: 32, borderRadius: 8, background: t.surface, border: `1px solid ${t.border}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 13, fontWeight: 600, fontFamily: G.mono,
              }}>{p.icon.startsWith('lucide:') ? <Icon name={p.icon.slice(7)} size={15} color={t.fg2} /> : p.icon}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{p.name}</div>
                <div style={{ fontSize: 11, color: t.fg3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.sub}</div>
              </div>
              <Icon name="check" size={14} color={t.fg2} />
            </div>
          ))}

          <div style={{ fontSize: 10, fontWeight: 600, color: t.fg3, letterSpacing: 1, padding: '16px 8px 8px', textTransform: 'uppercase' }}>Available</div>
          {ALL_PROVIDERS.filter(p => !p.configured).map(p => (
            <div key={p.id} style={{
              padding: '10px 12px', borderRadius: 10, marginBottom: 2, cursor: 'pointer',
              background: p.id === selectedProvider ? t.surface2 : 'transparent',
              display: 'flex', alignItems: 'center', gap: 10, opacity: 0.7,
            }}>
              <div style={{
                width: 32, height: 32, borderRadius: 8, background: t.surface, border: `1px solid ${t.border}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 13, fontWeight: 600, fontFamily: G.mono,
              }}>{p.icon.startsWith('lucide:') ? <Icon name={p.icon.slice(7)} size={15} color={t.fg2} /> : p.icon}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{p.name}</div>
                <div style={{ fontSize: 11, color: t.fg3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.sub}</div>
              </div>
            </div>
          ))}

          <div style={{ padding: '12px 0' }}>
            <Button variant="secondary" size="sm" full icon={<Icon name="plus" size={12} />}>Add custom provider</Button>
          </div>
        </div>

        {/* Right: provider detail — 0G has its own panel, others share the default detail */}
        {provider.type === '0g'
          ? <ZeroGDetail dark={dark} mode={subState.zgMode || 'router'} sub={subState.zgSub || {}} />
          : <div className="gh-scroll" style={{ flex: 1, overflow: 'auto', padding: '28px 32px', maxWidth: 520 }}>
          {/* Header */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 24 }}>
            <div style={{
              width: 48, height: 48, borderRadius: 14, background: t.surface, border: `1px solid ${t.border}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 20, fontWeight: 600, fontFamily: G.mono,
            }}>{provider.icon.startsWith('lucide:') ? <Icon name={provider.icon.slice(7)} size={22} color={t.fg2} /> : provider.icon}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: -0.3, display: 'flex', alignItems: 'center', gap: 8 }}>
                {provider.name}
                {provider.configured && <Tag variant="solid">Configured</Tag>}
                {provider.default && <Tag>Default</Tag>}
              </div>
              <div style={{ fontSize: 12, color: t.fg3, marginTop: 2 }}>{provider.sub}</div>
            </div>
            <Toggle on={provider.configured} dark={dark} />
          </div>

          {/* Auth section — varies by type */}
          {provider.type === 'api' && (
            <>
              <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>API Key</div>
              <div style={{
                height: 44, padding: '0 14px', display: 'flex', alignItems: 'center', gap: 10,
                background: t.surface, border: `1px solid ${t.border}`, borderRadius: 10, marginBottom: 6,
              }}>
                <Icon name="lock" size={14} color={t.fg3} />
                <span style={{ flex: 1, fontFamily: G.mono, fontSize: 13, color: t.fg2 }}>
                  {provider.configured ? 'sk-ant-····················mQ' : ''}
                </span>
                {provider.configured && <button style={{ background: 'transparent', border: 'none', color: t.fg3, cursor: 'pointer' }}><Icon name="eye" size={14} /></button>}
              </div>
              <div style={{ fontSize: 11, color: t.fg3, marginBottom: 16 }}>Stored in your OS keychain.</div>
            </>
          )}
          {provider.type === 'oauth' && (
            <Card style={{ padding: 16, marginBottom: 16, display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: '#d97706', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, fontWeight: 600 }}>C</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>Signed in via OAuth</div>
                <div style={{ fontSize: 11, color: t.fg3, marginTop: 1 }}>liu@example.com · Claude Pro plan</div>
              </div>
              <Button variant="secondary" size="sm">Disconnect</Button>
            </Card>
          )}
          {provider.type === 'local' && (
            <>
              <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>Endpoint</div>
              <div style={{
                height: 44, padding: '0 14px', display: 'flex', alignItems: 'center', gap: 10,
                background: t.surface, border: `1px solid ${t.border}`, borderRadius: 10, marginBottom: 6,
              }}>
                <Icon name="plug" size={14} color={t.fg3} />
                <span style={{ flex: 1, fontFamily: G.mono, fontSize: 13, color: t.fg }}>http://localhost:11434</span>
              </div>
              <div style={{ display: 'flex', gap: 10, marginBottom: 16, alignItems: 'center' }}>
                <Button variant="secondary" size="sm" icon={<Icon name="refresh" size={12} />}>Refresh models</Button>
                <StatusDot status="on" />
                <span style={{ fontSize: 12, color: t.fg2 }}>Running · 4 models loaded</span>
              </div>
            </>
          )}
          {provider.type === 'custom' && (
            <>
              <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>Base URL</div>
              <div style={{
                height: 44, padding: '0 14px', display: 'flex', alignItems: 'center', gap: 10,
                background: t.surface, border: `1px solid ${t.border}`, borderRadius: 10, marginBottom: 12,
              }}>
                <span style={{ flex: 1, fontFamily: G.mono, fontSize: 13, color: t.fg3 }}>https://</span>
              </div>
              <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>API Key</div>
              <div style={{
                height: 44, padding: '0 14px', display: 'flex', alignItems: 'center', gap: 10,
                background: t.surface, border: `1px solid ${t.border}`, borderRadius: 10, marginBottom: 16,
              }}>
                <Icon name="lock" size={14} color={t.fg3} />
                <span style={{ flex: 1, fontFamily: G.mono, fontSize: 13, color: t.fg3 }}>Enter key…</span>
              </div>
            </>
          )}

          <Divider style={{ margin: '4px 0 20px' }} />

          {/* Models list */}
          <SectionHeader title="Models" sub={`${provider.models.length} available`} dark={dark} small />
          <div style={{ background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12, overflow: 'hidden', marginBottom: 20 }}>
            {provider.models.map((m, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px',
                borderTop: i === 0 ? 'none' : `1px solid ${t.border2}`,
              }}>
                <Icon name="sparkle" size={13} color={t.fg2} />
                <span style={{ flex: 1, fontSize: 13, fontFamily: G.mono }}>{m}</span>
                {i === 0 && <Tag variant="solid">Default</Tag>}
              </div>
            ))}
          </div>

          {/* Set as default / disable */}
          <SettingRow dark={dark} label="Set as default provider" toggle={provider.default || false} />
          {provider.configured && provider.type === 'api' && (
            <SettingRow dark={dark} label="Remove API key" value="Disconnect this provider." action="Remove" />
          )}
        </div>}
    </div>
  );
}

// Providers bottom section: default model selectors
function ProvidersDefaults({ dark }) {
  const t = dark ? G.d : G.l;

  const ModelSelect = ({ label, value }) => (
    <div style={{ marginBottom: 16 }}>
      <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>{label}</div>
      <div style={{
        height: 44, padding: '0 14px', display: 'flex', alignItems: 'center', gap: 10,
        background: t.surface, border: `1px solid ${t.border}`, borderRadius: 10,
      }}>
        <Icon name="sparkle" size={14} color={t.fg2} />
        <span style={{ flex: 1, fontSize: 13 }}>{value}</span>
        <Icon name="chevronDown" size={13} color={t.fg3} />
      </div>
    </div>
  );

  return (
    <div style={{ height: '100%', display: 'flex', /* full bleed */ }}>
        {/* Provider list (left) — same as above but scrolled to bottom */}
        <div className="gh-scroll" style={{ width: 280, flexShrink: 0, borderRight: `1px solid ${t.border}`, overflow: 'auto', padding: '16px 12px' }}>
          <div style={{ fontSize: 10, fontWeight: 600, color: t.fg3, letterSpacing: 1, padding: '4px 8px 8px', textTransform: 'uppercase' }}>Configured</div>
          {ALL_PROVIDERS.filter(p => p.configured).map(p => (
            <div key={p.id} style={{
              padding: '10px 12px', borderRadius: 10, marginBottom: 2,
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <div style={{ width: 32, height: 32, borderRadius: 8, background: t.surface, border: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 600, fontFamily: G.mono }}>{p.icon}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{p.name}</div>
                <div style={{ fontSize: 11, color: t.fg3 }}>{p.sub}</div>
              </div>
              <Icon name="check" size={14} color={t.fg2} />
            </div>
          ))}
          <div style={{ fontSize: 10, fontWeight: 600, color: t.fg3, letterSpacing: 1, padding: '16px 8px 8px', textTransform: 'uppercase' }}>Available</div>
          {ALL_PROVIDERS.filter(p => !p.configured).slice(0, 3).map(p => (
            <div key={p.id} style={{
              padding: '10px 12px', borderRadius: 10, marginBottom: 2, opacity: 0.7,
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <div style={{ width: 32, height: 32, borderRadius: 8, background: t.surface, border: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 600, fontFamily: G.mono }}>{p.icon}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{p.name}</div>
                <div style={{ fontSize: 11, color: t.fg3 }}>{p.sub}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Right: default model selectors */}
        <div className="gh-scroll" style={{ flex: 1, overflow: 'auto', padding: '28px 32px', maxWidth: 520 }}>
          <SectionHeader title="Default Models" sub="Choose which model handles each task type across all providers." dark={dark} />
          <ModelSelect label="Default chat model" value="claude-4-sonnet · Anthropic" />
          <ModelSelect label="Tool-calling model" value="gpt-5 · OpenAI" />
          <ModelSelect label="Vision model" value="gemini-2.5-pro · Google" />
          <Divider style={{ margin: '12px 0 20px' }} />
          <SectionHeader title="Behavior" dark={dark} small />
          <SettingRow dark={dark} label="Auto-select best model" value="Ghast picks the model per task." toggle={false} />
          <SettingRow dark={dark} label="Fallback on failure" value="Try next provider if primary fails." toggle={true} />
          <SettingRow dark={dark} label="Streaming" value="Token-by-token output." toggle={true} />
        </div>
    </div>
  );
}


// ═════════════════════════════════════════════════════════════
// 3. MCP SERVERS
// ═════════════════════════════════════════════════════════════

const MCP_SERVERS_DATA = [
  { name: 'GitHub', transport: 'stdio', status: 'on', tools: 12, lastCall: '2 min ago',
    toolList: [
      { name: 'get_file_contents', desc: 'Read a file from a repo', schema: '{ owner, repo, path, branch? }' },
      { name: 'create_pull_request', desc: 'Open a PR', schema: '{ owner, repo, title, body, head, base }' },
      { name: 'list_issues', desc: 'List issues with filters', schema: '{ owner, repo, state?, labels? }' },
      { name: 'search_code', desc: 'Search across repos', schema: '{ query, per_page? }' },
    ]},
  { name: 'Notion', transport: 'sse', status: 'on', tools: 8, lastCall: '15 min ago',
    toolList: [
      { name: 'search_pages', desc: 'Full-text search', schema: '{ query, filter? }' },
      { name: 'get_page', desc: 'Retrieve a page by ID', schema: '{ page_id }' },
      { name: 'update_block', desc: 'Update block content', schema: '{ block_id, content }' },
    ]},
  { name: 'Postgres', transport: 'stdio', status: 'on', tools: 3, lastCall: '1h ago',
    toolList: [
      { name: 'query', desc: 'Run a SELECT query', schema: '{ sql, params? }' },
      { name: 'describe_table', desc: 'Get table schema', schema: '{ table_name }' },
      { name: 'list_tables', desc: 'List all tables', schema: '{}' },
    ]},
  { name: 'Slack', transport: 'sse', status: 'off', tools: 6, lastCall: '3d ago',
    toolList: [
      { name: 'list_channels', desc: 'List authorized channels', schema: '{}' },
      { name: 'post_message', desc: 'Send a message', schema: '{ channel, text }' },
    ]},
  { name: 'Linear', transport: 'websocket', status: 'on', tools: 9, lastCall: '38 min ago',
    toolList: [
      { name: 'list_issues', desc: 'List issues', schema: '{ project?, assignee? }' },
      { name: 'create_issue', desc: 'Create a new issue', schema: '{ title, description, project }' },
    ]},
];

function MCPServersSettings({ dark, expandedServer = null, showAddDialog = false }) {
  const t = dark ? G.d : G.l;

  return (
    <div style={{ position: 'relative', height: '100%', /* full bleed */ }}>
        <div className="gh-scroll" style={{ height: '100%', overflow: 'auto', padding: '28px 32px', maxWidth: 720 }}>
          <SectionHeader title="MCP Servers" sub={`${MCP_SERVERS_DATA.filter(s => s.status === 'on').length} active · ${MCP_SERVERS_DATA.reduce((a, s) => a + s.tools, 0)} tools total`} dark={dark} />

          {/* Server list */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 24 }}>
            {MCP_SERVERS_DATA.map((srv, i) => {
              const isExpanded = expandedServer === srv.name;
              return (
                <div key={i} style={{
                  background: t.surface, border: `1px solid ${isExpanded ? t.fg : t.border}`,
                  borderRadius: 14, overflow: 'hidden', borderWidth: isExpanded ? 1.5 : 1,
                }}>
                  {/* Server row */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', cursor: 'pointer' }}>
                    <div style={{
                      width: 36, height: 36, borderRadius: 10, background: t.surface2, border: `1px solid ${t.border}`,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      <Icon name="plug" size={16} color={t.fg2} />
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}>
                        {srv.name}
                        <StatusDot status={srv.status} />
                      </div>
                      <div style={{ fontSize: 11, color: t.fg3, marginTop: 1 }}>
                        {srv.transport.toUpperCase()} · {srv.tools} tools · last call {srv.lastCall}
                      </div>
                    </div>
                    <div style={{ display: 'flex', gap: 6 }}>
                      {srv.status === 'on' ? (
                        <Button variant="ghost" size="sm">Disable</Button>
                      ) : (
                        <Button variant="ghost" size="sm">Enable</Button>
                      )}
                      <Button variant="ghost" size="sm" icon={<Icon name="refresh" size={12} />}>Restart</Button>
                      <Button variant="ghost" size="sm" style={{ color: '#ff5f57' }}>Remove</Button>
                    </div>
                    <Icon name={isExpanded ? 'chevronDown' : 'chevronRight'} size={14} color={t.fg3} />
                  </div>

                  {/* Expanded: tool catalog */}
                  {isExpanded && (
                    <div style={{ borderTop: `1px solid ${t.border}`, padding: '16px 20px' }}>
                      <div style={{ fontSize: 11, fontWeight: 600, color: t.fg3, letterSpacing: 0.8, marginBottom: 10, textTransform: 'uppercase' }}>Tool Catalog</div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                        {srv.toolList.map((tool, ti) => (
                          <div key={ti} style={{
                            padding: '10px 12px', background: t.surface2, borderRadius: 8, border: `1px solid ${t.border2}`,
                          }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                              <span style={{ fontFamily: G.mono, fontSize: 12, fontWeight: 600, color: t.fg }}>{tool.name}</span>
                              <span style={{ fontSize: 11, color: t.fg3 }}>— {tool.desc}</span>
                            </div>
                            <div style={{ fontFamily: G.mono, fontSize: 11, color: t.fg3, background: dark ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.03)', padding: '4px 8px', borderRadius: 4 }}>
                              {tool.schema}
                            </div>
                          </div>
                        ))}
                      </div>
                      <div style={{ marginTop: 12, fontSize: 11, color: t.fg3 }}>
                        Last call: {srv.lastCall} · Showing {srv.toolList.length} of {srv.tools} tools
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          {/* Quick links: MCP Store */}
          <Divider style={{ margin: '8px 0 20px' }} />
          <SectionHeader title="Install from MCP Store" sub="One-click install popular MCP servers." dark={dark} small />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
            {[
              { name: 'GitHub', desc: 'Read, write, branch, PR.', icon: 'git', installed: true },
              { name: 'Slack', desc: 'Read channels you authorize.', icon: 'sound', installed: true },
              { name: 'Stripe', desc: 'Read customers, refunds.', icon: 'star', installed: false },
              { name: 'Figma', desc: 'Read frames and styles.', icon: 'image', installed: false },
              { name: 'Jira', desc: 'Triage issues, update status.', icon: 'workflow', installed: false },
              { name: 'Supabase', desc: 'Query and manage tables.', icon: 'box', installed: false },
            ].map((item, i) => (
              <Card key={i} style={{ padding: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                  <div style={{ width: 28, height: 28, borderRadius: 8, background: t.surface2, border: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icon name={item.icon} size={14} color={t.fg2} />
                  </div>
                  <span style={{ fontSize: 13, fontWeight: 600 }}>{item.name}</span>
                </div>
                <div style={{ fontSize: 11, color: t.fg3, lineHeight: 1.4, marginBottom: 10 }}>{item.desc}</div>
                {item.installed ? (
                  <Tag variant="default"><Icon name="check" size={10} /> Installed</Tag>
                ) : (
                  <Button variant="secondary" size="sm" icon={<Icon name="plus" size={11} />}>Install</Button>
                )}
              </Card>
            ))}
          </div>
        </div>

        {/* Add MCP Server dialog */}
        {showAddDialog && (
          <>
            <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 10 }} />
            <div style={{
              position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
              width: 440, background: t.surface, border: `1px solid ${t.border}`, borderRadius: 18,
              boxShadow: t.shadowLg, zIndex: 11, padding: '28px 28px 24px',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
                <div style={{ fontSize: 18, fontWeight: 600 }}>Add MCP Server</div>
                <button style={{ background: 'transparent', border: 'none', color: t.fg3, cursor: 'pointer' }}><Icon name="close" size={18} /></button>
              </div>

              <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>Transport</div>
              <div style={{ display: 'flex', background: t.surface2, border: `1px solid ${t.border}`, borderRadius: 8, padding: 2, marginBottom: 16 }}>
                {['stdio', 'SSE', 'WebSocket'].map((tr, i) => (
                  <div key={tr} style={{
                    flex: 1, padding: '6px 0', textAlign: 'center', fontSize: 12, fontWeight: 500,
                    background: i === 0 ? t.surface : 'transparent',
                    color: i === 0 ? t.fg : t.fg3,
                    borderRadius: 6,
                  }}>{tr}</div>
                ))}
              </div>

              <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>Command</div>
              <div style={{
                height: 40, padding: '0 12px', display: 'flex', alignItems: 'center',
                background: t.surface, border: `1px solid ${t.border}`, borderRadius: 8, marginBottom: 12,
                fontFamily: G.mono, fontSize: 13, color: t.fg3,
              }}>npx -y @modelcontextprotocol/…</div>

              <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>Arguments</div>
              <div style={{
                height: 40, padding: '0 12px', display: 'flex', alignItems: 'center',
                background: t.surface, border: `1px solid ${t.border}`, borderRadius: 8, marginBottom: 12,
                fontFamily: G.mono, fontSize: 13, color: t.fg3,
              }}>--token $GITHUB_TOKEN</div>

              <div style={{ fontSize: 12, fontWeight: 500, color: t.fg2, marginBottom: 6 }}>Environment Variables</div>
              <div style={{
                height: 64, padding: '8px 12px',
                background: t.surface, border: `1px solid ${t.border}`, borderRadius: 8, marginBottom: 20,
                fontFamily: G.mono, fontSize: 12, color: t.fg3, lineHeight: 1.5,
              }}>
                GITHUB_TOKEN=ghp_••••••••<br/>
                NODE_ENV=production
              </div>

              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                <Button variant="secondary" size="md">Cancel</Button>
                <Button variant="primary" size="md">Connect</Button>
              </div>
            </div>
          </>
        )}
    </div>
  );
}

// Export all
Object.assign(window, {
  StatusDot, Toggle,
  ChannelsSettings, ChannelsRulesEditor,
  ProvidersSettings, ProvidersDefaults,
  MCPServersSettings,
  CHANNEL_PLATFORMS, ALL_PROVIDERS, MCP_SERVERS_DATA,
});
