'use client';

import { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Settings, Search, Filter, RefreshCw, Boxes, Zap,
  AlertTriangle, CheckCircle, Brain, Network, UserCog,
  ToggleLeft, Shield, Cpu, DollarSign, Lock, Unlock
} from 'lucide-react';
import { ModuleCard } from './module-card';
import { AgentProfileCard } from './agent-profile-card';
import { AgentHierarchyView } from './agent-hierarchy-view';
import { BackupRestorePanel } from './backup-restore-panel';

type TabId = 'modules' | 'agents' | 'hierarchy' | 'backup' | 'llm';

interface ModuleData {
  moduleId: string;
  name: string;
  description: string | null;
  category: string;
  icon: string | null;
  isEnabled: boolean;
  isCore: boolean;
  features: string[];
  tier: string;
  agentId: string | null;
  dependencies: unknown;
  sortOrder: number;
}

interface ModuleStats {
  total: number;
  enabled: number;
  available: number;
}

interface AgentProfile {
  agentId: string;
  name: string;
  title: string;
  domain: string;
  parentAgentId: string | null;
  moduleId: string | null;
  moduleName: string;
  moduleEnabled: boolean;
  avatarColor: string;
  personality: string;
  capabilities: string[];
  escalationTriggers: string[];
  status: string;
  maturityLevel: number;
  xp: number;
  totalInteractions: number;
  lastActiveAt: string | null;
  memoryCount: number;
  messagesSent: number;
  messagesReceived: number;
  associatedModules: { moduleId: string; name: string; enabled: boolean }[];
}

interface AgentSummary {
  totalAgents: number;
  activeAgents: number;
  dormantAgents: number;
  totalXP: number;
  totalMemories: number;
}

const CATEGORY_LABELS: Record<string, { label: string; color: string }> = {
  core: { label: 'Core Platform', color: 'text-brand' },
  operations: { label: 'Operations', color: 'text-blue-400' },
  intelligence: { label: 'Intelligence', color: 'text-brand-secondary-light' },
  addon: { label: 'Add-ons', color: 'text-amber-400' },
};

const TABS: { id: TabId; label: string; icon: React.ElementType; description: string }[] = [
  { id: 'modules', label: 'Module Control', icon: ToggleLeft, description: 'Enable/disable ERP modules' },
  { id: 'agents', label: 'Agent Profiles', icon: UserCog, description: 'Configure AI sub-agents' },
  { id: 'hierarchy', label: 'Agent Hierarchy', icon: Network, description: 'View agent org chart' },
  { id: 'llm', label: 'AI & LLM', icon: Cpu, description: 'Control external LLM usage & cost' },
  { id: 'backup', label: 'Backup & Restore', icon: Shield, description: 'Snapshot, restore, and schedule backups' },
];

export function ConfigurationDashboard() {
  const [activeTab, setActiveTab] = useState<TabId>('modules');

  // Module state
  const [modules, setModules] = useState<ModuleData[]>([]);
  const [stats, setStats] = useState<ModuleStats>({ total: 0, enabled: 0, available: 0 });
  const [moduleLoading, setModuleLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<string>('all');
  const [togglingModule, setTogglingModule] = useState<string | null>(null);

  // Agent state
  const [agentProfiles, setAgentProfiles] = useState<AgentProfile[]>([]);
  const [agentSummary, setAgentSummary] = useState<AgentSummary | null>(null);
  const [agentLoading, setAgentLoading] = useState(false);

  // Toast
  const [toast, setToast] = useState<{ type: 'success' | 'error'; message: string } | null>(null);

  const fetchModules = useCallback(async () => {
    try {
      const res = await fetch('/api/modules');
      const data = await res.json();
      if (data.modules) {
        setModules(data.modules);
        setStats(data.stats);
      }
    } catch (err) {
      console.error('Failed to fetch modules:', err);
    } finally {
      setModuleLoading(false);
    }
  }, []);

  const fetchAgentProfiles = useCallback(async () => {
    setAgentLoading(true);
    try {
      const res = await fetch('/api/agents/profiles');
      const data = await res.json();
      if (data.profiles) {
        setAgentProfiles(data.profiles);
        setAgentSummary(data.summary);
      }
    } catch (err) {
      console.error('Failed to fetch agent profiles:', err);
    } finally {
      setAgentLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchModules();
  }, [fetchModules]);

  useEffect(() => {
    if (activeTab === 'agents' || activeTab === 'hierarchy') {
      fetchAgentProfiles();
    }
  }, [activeTab, fetchAgentProfiles]);

  const handleToggle = async (moduleId: string, action: 'enable' | 'disable') => {
    setTogglingModule(moduleId);
    try {
      const res = await fetch('/api/modules', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ moduleId, action }),
      });
      const data = await res.json();
      if (res.ok) {
        setToast({ type: 'success', message: data.message });
        await fetchModules();
        // Refresh agent profiles too if on those tabs
        if (activeTab === 'agents' || activeTab === 'hierarchy') {
          await fetchAgentProfiles();
        }
      } else {
        setToast({ type: 'error', message: data.error });
      }
    } catch {
      setToast({ type: 'error', message: 'Failed to toggle module' });
    } finally {
      setTogglingModule(null);
      setTimeout(() => setToast(null), 4000);
    }
  };

  const handleSync = async () => {
    setModuleLoading(true);
    try {
      await fetch('/api/modules/sync', { method: 'POST' });
      await fetchModules();
      setToast({ type: 'success', message: 'Module registry synced successfully.' });
      setTimeout(() => setToast(null), 3000);
    } catch {
      setToast({ type: 'error', message: 'Failed to sync registry' });
      setTimeout(() => setToast(null), 3000);
    } finally {
      setModuleLoading(false);
    }
  };

  // Filter & search modules
  const filtered = modules.filter(m => {
    const matchesSearch = !searchQuery ||
      m.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (m.description || '').toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory = categoryFilter === 'all' || m.category === categoryFilter;
    return matchesSearch && matchesCategory;
  });

  const grouped = Object.entries(CATEGORY_LABELS).reduce((acc, [cat]) => {
    acc[cat] = filtered.filter(m => m.category === cat).sort((a, b) => a.sortOrder - b.sortOrder);
    return acc;
  }, {} as Record<string, ModuleData[]>);

  if (moduleLoading && modules.length === 0) {
    return (
      <div className="flex items-center justify-center h-64">
        <RefreshCw className="w-6 h-6 text-brand animate-spin" />
        <span className="ml-2 text-gray-400">Loading configuration...</span>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Toast */}
      <AnimatePresence>
        {toast && (
          <motion.div
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            className={`fixed top-4 right-4 z-50 flex items-center gap-2 px-4 py-3 rounded-lg border ${
              toast.type === 'success'
                ? 'bg-green-500/10 border-green-500/30 text-green-400'
                : 'bg-red-500/10 border-red-500/30 text-red-400'
            }`}
          >
            {toast.type === 'success' ? <CheckCircle className="w-4 h-4" /> : <AlertTriangle className="w-4 h-4" />}
            <span className="text-sm">{toast.message}</span>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Summary Stats Row */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-3">
          <div className="flex items-center gap-2 text-brand">
            <Boxes className="w-4 h-4" />
            <span className="text-[10px] uppercase tracking-wider text-gray-400">Total Modules</span>
          </div>
          <p className="text-xl font-bold text-white mt-1">{stats.total}</p>
        </div>
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-3">
          <div className="flex items-center gap-2 text-green-400">
            <Zap className="w-4 h-4" />
            <span className="text-[10px] uppercase tracking-wider text-gray-400">Active Modules</span>
          </div>
          <p className="text-xl font-bold text-white mt-1">{stats.enabled}</p>
        </div>
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-3">
          <div className="flex items-center gap-2 text-amber-400">
            <Settings className="w-4 h-4" />
            <span className="text-[10px] uppercase tracking-wider text-gray-400">Available</span>
          </div>
          <p className="text-xl font-bold text-white mt-1">{stats.available}</p>
        </div>
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-3">
          <div className="flex items-center gap-2 text-brand-secondary-light">
            <Brain className="w-4 h-4" />
            <span className="text-[10px] uppercase tracking-wider text-gray-400">Active Agents</span>
          </div>
          <p className="text-xl font-bold text-white mt-1">{agentSummary?.activeAgents ?? '—'}</p>
        </div>
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-3">
          <div className="flex items-center gap-2 text-blue-400">
            <Network className="w-4 h-4" />
            <span className="text-[10px] uppercase tracking-wider text-gray-400">Total XP</span>
          </div>
          <p className="text-xl font-bold text-white mt-1">{agentSummary?.totalXP ?? '—'}</p>
        </div>
      </div>

      {/* Tab Navigation */}
      <div className="flex items-center gap-2 border-b border-slate-700/50 pb-0">
        {TABS.map(tab => {
          const TabIcon = tab.icon;
          return (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-all duration-200 -mb-[1px] ${
                activeTab === tab.id
                  ? 'border-brand-deep text-brand'
                  : 'border-transparent text-gray-500 hover:text-gray-300 hover:border-gray-600'
              }`}
            >
              <TabIcon className="w-4 h-4" />
              {tab.label}
            </button>
          );
        })}
      </div>

      {/* Tab Content */}
      <AnimatePresence mode="wait">
        {activeTab === 'modules' && (
          <motion.div
            key="modules"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="space-y-4"
          >
            {/* Search & Filters */}
            <div className="flex items-center gap-3 flex-wrap">
              <div className="relative flex-1 min-w-[200px]">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                <input
                  type="text"
                  value={searchQuery}
                  onChange={e => setSearchQuery(e.target.value)}
                  placeholder="Search modules..."
                  className="w-full pl-9 pr-4 py-2 bg-slate-800/60 border border-slate-700/50 rounded-lg text-sm text-white placeholder:text-gray-500 focus:outline-none focus:ring-1 focus:ring-brand-deep/50"
                />
              </div>
              <div className="flex items-center gap-1">
                <Filter className="w-4 h-4 text-gray-500 mr-1" />
                {['all', ...Object.keys(CATEGORY_LABELS)].map(cat => (
                  <button
                    key={cat}
                    onClick={() => setCategoryFilter(cat)}
                    className={`px-3 py-1.5 text-xs rounded-lg border transition-colors ${
                      categoryFilter === cat
                        ? 'bg-brand-deep/10 border-brand-deep/30 text-brand'
                        : 'bg-slate-800/40 border-slate-700/50 text-gray-400 hover:text-gray-200'
                    }`}
                  >
                    {cat === 'all' ? 'All' : CATEGORY_LABELS[cat]?.label}
                  </button>
                ))}
              </div>
              <button
                onClick={handleSync}
                className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-slate-800/40 border border-slate-700/50 text-gray-400 hover:text-brand rounded-lg transition-colors"
              >
                <RefreshCw className={`w-3.5 h-3.5 ${moduleLoading ? 'animate-spin' : ''}`} />
                Sync Registry
              </button>
            </div>

            {/* Module cards by category */}
            {Object.entries(grouped).map(([cat, mods]) => {
              if (mods.length === 0) return null;
              const catLabel = CATEGORY_LABELS[cat];
              return (
                <div key={cat}>
                  <h3 className={`text-sm font-semibold ${catLabel?.color || 'text-gray-400'} mb-3 flex items-center gap-2`}>
                    <div className={`w-2 h-2 rounded-full ${catLabel?.color?.replace('text-', 'bg-') || 'bg-gray-400'}`} />
                    {catLabel?.label || cat}
                    <span className="text-xs text-gray-500">({mods.length})</span>
                  </h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
                    {mods.map(mod => (
                      <ModuleCard
                        key={mod.moduleId}
                        module={mod}
                        onToggle={handleToggle}
                        isToggling={togglingModule === mod.moduleId}
                      />
                    ))}
                  </div>
                </div>
              );
            })}

            {filtered.length === 0 && (
              <div className="text-center py-12 text-gray-500">
                <Boxes className="w-8 h-8 mx-auto mb-2 opacity-50" />
                <p>No modules match your search.</p>
              </div>
            )}
          </motion.div>
        )}

        {activeTab === 'agents' && (
          <motion.div
            key="agents"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="space-y-4"
          >
            {agentLoading && agentProfiles.length === 0 ? (
              <div className="flex items-center justify-center h-32">
                <RefreshCw className="w-5 h-5 text-brand-secondary-light animate-spin" />
                <span className="ml-2 text-gray-400">Loading agent profiles...</span>
              </div>
            ) : (
              <>
                {/* CEO First */}
                {agentProfiles.filter(a => a.parentAgentId === null).map(agent => (
                  <div key={agent.agentId} className="max-w-lg">
                    <h4 className="text-xs font-semibold text-brand mb-2 flex items-center gap-1.5">
                      <Brain className="w-3.5 h-3.5" /> Agent CEO
                    </h4>
                    <AgentProfileCard agent={agent} />
                  </div>
                ))}

                {/* Sub-Agents Grid */}
                <h4 className="text-xs font-semibold text-brand-secondary-light flex items-center gap-1.5 pt-2">
                  <Network className="w-3.5 h-3.5" /> Domain Sub-Agents
                </h4>
                <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                  {agentProfiles.filter(a => a.parentAgentId !== null).map(agent => (
                    <AgentProfileCard key={agent.agentId} agent={agent} />
                  ))}
                </div>
              </>
            )}
          </motion.div>
        )}

        {activeTab === 'hierarchy' && (
          <motion.div
            key="hierarchy"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
          >
            {agentLoading && agentProfiles.length === 0 ? (
              <div className="flex items-center justify-center h-32">
                <RefreshCw className="w-5 h-5 text-brand-secondary-light animate-spin" />
                <span className="ml-2 text-gray-400">Loading hierarchy...</span>
              </div>
            ) : (
              <AgentHierarchyView profiles={agentProfiles} />
            )}
          </motion.div>
        )}

        {activeTab === 'llm' && (
          <motion.div
            key="llm"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
          >
            <LLMGatePanel />
          </motion.div>
        )}

        {activeTab === 'backup' && (
          <motion.div
            key="backup"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
          >
            <BackupRestorePanel />
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

// ═══════════════════════════════════════════
// LLM GATE PANEL — Zero-Cost Controls
// ═══════════════════════════════════════════

interface LLMGateState {
  mode: 'zero-cost' | 'selective' | 'unrestricted';
  summary: string;
  config: {
    globalEnabled: boolean;
    scopes: Record<string, boolean>;
    lastModifiedBy: string;
    lastModifiedAt: string;
    lastModifiedReason: string;
  };
}

const SCOPE_LABELS: Record<string, { label: string; description: string; icon: React.ElementType }> = {
  agents: { label: 'Agent Interactions', description: 'Chat with domain agents (Tes, Ledger, Pipeline, etc.)', icon: Brain },
  'dark-factory': { label: 'The Hearth Builds', description: 'Complex code/UI generation that exceeds local model capability', icon: Cpu },
  perception: { label: 'Perception & Signals', description: 'Document analysis, anomaly detection, email processing', icon: AlertTriangle },
  'self-mod': { label: 'Self-Modification', description: 'AI-driven system improvement proposals', icon: RefreshCw },
  observer: { label: 'Observer Intelligence', description: 'Pattern detection and action recommendations', icon: Search },
  companion: { label: 'Tes Companion Chat', description: 'Conversational AI companion (Talk to Tes)', icon: UserCog },
};

function LLMGatePanel() {
  const [state, setState] = useState<LLMGateState | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  const fetchGateStatus = useCallback(async () => {
    try {
      const res = await fetch('/api/gfs/llm-gate');
      const data = await res.json();
      setState(data);
    } catch (err) {
      console.error('Failed to fetch LLM gate status:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchGateStatus();
  }, [fetchGateStatus]);

  const toggleGlobal = async () => {
    if (!state) return;
    setSaving(true);
    try {
      const res = await fetch('/api/gfs/llm-gate', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          globalEnabled: !state.config.globalEnabled,
          reason: !state.config.globalEnabled ? 'Operator enabled external LLM' : 'Operator restored zero-cost mode',
        }),
      });
      const data = await res.json();
      setState(data);
    } catch (err) {
      console.error('Failed to toggle LLM gate:', err);
    } finally {
      setSaving(false);
    }
  };

  const toggleScope = async (scope: string) => {
    if (!state) return;
    setSaving(true);
    try {
      const newScopes = { ...state.config.scopes, [scope]: !state.config.scopes[scope] };
      const res = await fetch('/api/gfs/llm-gate', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          scopes: newScopes,
          reason: `Operator toggled ${scope} scope`,
        }),
      });
      const data = await res.json();
      setState(data);
    } catch (err) {
      console.error('Failed to toggle scope:', err);
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <RefreshCw className="w-6 h-6 text-gray-400 animate-spin" />
        <span className="ml-3 text-gray-400">Loading AI & LLM configuration...</span>
      </div>
    );
  }

  if (!state) {
    return <div className="text-gray-400 text-center py-10">Failed to load LLM gate configuration.</div>;
  }

  const modeColor = state.mode === 'zero-cost' ? 'text-green-400' : state.mode === 'selective' ? 'text-amber-400' : 'text-red-400';
  const modeBg = state.mode === 'zero-cost' ? 'bg-green-500/20' : state.mode === 'selective' ? 'bg-amber-500/20' : 'bg-red-500/20';

  return (
    <div className="space-y-6">
      {/* Mode Banner */}
      <div className={`glass-card rounded-xl p-6 border ${state.mode === 'zero-cost' ? 'border-green-500/30' : state.mode === 'selective' ? 'border-amber-500/30' : 'border-red-500/30'}`}>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div className={`p-3 rounded-xl ${modeBg}`}>
              {state.mode === 'zero-cost' ? <Lock className={`w-6 h-6 ${modeColor}`} /> : <Unlock className={`w-6 h-6 ${modeColor}`} />}
            </div>
            <div>
              <h3 className="text-lg font-bold text-white">
                {state.mode === 'zero-cost' ? 'Zero-Cost Mode' : state.mode === 'selective' ? 'Selective LLM Mode' : 'Unrestricted LLM Mode'}
              </h3>
              <p className="text-sm text-gray-400">{state.summary}</p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <div className={`px-3 py-1.5 rounded-full text-xs font-medium ${modeBg} ${modeColor}`}>
              <DollarSign className="w-3 h-3 inline mr-1" />
              {state.mode === 'zero-cost' ? '$0.00 / query' : 'Cloud credits apply'}
            </div>
          </div>
        </div>
      </div>

      {/* Master Toggle */}
      <div className="glass-card rounded-xl p-6">
        <div className="flex items-center justify-between">
          <div>
            <h4 className="text-white font-semibold flex items-center gap-2">
              <Cpu className="w-4 h-4 text-brand" />
              Allow External LLM Calls (Master Switch)
            </h4>
            <p className="text-sm text-gray-400 mt-1">
              When OFF, all agents and The Hearth use RAG + deterministic rules only. Zero external API cost.
              When ON, individual scopes below control which subsystems may call cloud LLMs.
            </p>
          </div>
          <button
            onClick={toggleGlobal}
            disabled={saving}
            className={`relative w-14 h-7 rounded-full transition-colors ${
              state.config.globalEnabled ? 'bg-amber-500' : 'bg-gray-600'
            } ${saving ? 'opacity-50' : ''}`}
          >
            <div className={`absolute top-0.5 left-0.5 w-6 h-6 rounded-full bg-white shadow transition-transform ${
              state.config.globalEnabled ? 'translate-x-7' : 'translate-x-0'
            }`} />
          </button>
        </div>
        {state.config.lastModifiedAt && (
          <p className="text-xs text-gray-500 mt-3">
            Last modified by {state.config.lastModifiedBy} — {state.config.lastModifiedReason}
          </p>
        )}
      </div>

      {/* Scope Toggles */}
      <div className="space-y-3">
        <h4 className="text-white font-semibold text-sm uppercase tracking-wider px-1">Per-Scope Controls</h4>
        {Object.entries(SCOPE_LABELS).map(([scope, { label, description, icon: Icon }]) => {
          const enabled = state.config.globalEnabled && (state.config.scopes[scope] ?? false);
          const globalOff = !state.config.globalEnabled;
          return (
            <div key={scope} className={`glass-card rounded-lg p-4 ${globalOff ? 'opacity-50' : ''}`}>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <Icon className={`w-4 h-4 ${enabled ? 'text-amber-400' : 'text-gray-500'}`} />
                  <div>
                    <span className="text-white text-sm font-medium">{label}</span>
                    <p className="text-xs text-gray-500">{description}</p>
                  </div>
                </div>
                <button
                  onClick={() => toggleScope(scope)}
                  disabled={saving || globalOff}
                  className={`relative w-11 h-6 rounded-full transition-colors ${
                    enabled ? 'bg-amber-500' : 'bg-gray-600'
                  } ${(saving || globalOff) ? 'cursor-not-allowed' : ''}`}
                >
                  <div className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform ${
                    enabled ? 'translate-x-5' : 'translate-x-0'
                  }`} />
                </button>
              </div>
            </div>
          );
        })}
      </div>

      {/* Info Panel */}
      <div className="glass-card rounded-xl p-6 border border-brand-deep/30">
        <h4 className="text-white font-semibold mb-3 flex items-center gap-2">
          <CheckCircle className="w-4 h-4 text-green-400" />
          Zero-Cost Reasoning Stack
        </h4>
        <div className="grid md:grid-cols-2 gap-4 text-sm text-gray-400">
          <div>
            <p className="text-white text-xs font-semibold uppercase tracking-wider mb-2">Always Active (Free)</p>
            <ul className="space-y-1.5">
              <li className="flex items-center gap-2"><CheckCircle className="w-3 h-3 text-green-400 flex-shrink-0" /> RAG retrieval from business docs</li>
              <li className="flex items-center gap-2"><CheckCircle className="w-3 h-3 text-green-400 flex-shrink-0" /> Standing Orders enforcement</li>
              <li className="flex items-center gap-2"><CheckCircle className="w-3 h-3 text-green-400 flex-shrink-0" /> Domain-specific rule engines</li>
              <li className="flex items-center gap-2"><CheckCircle className="w-3 h-3 text-green-400 flex-shrink-0" /> Live database queries</li>
              <li className="flex items-center gap-2"><CheckCircle className="w-3 h-3 text-green-400 flex-shrink-0" /> Template-based code generation</li>
              <li className="flex items-center gap-2"><CheckCircle className="w-3 h-3 text-green-400 flex-shrink-0" /> Intent classification (rule-based)</li>
            </ul>
          </div>
          <div>
            <p className="text-white text-xs font-semibold uppercase tracking-wider mb-2">Optional (Requires Toggle)</p>
            <ul className="space-y-1.5">
              <li className="flex items-center gap-2"><Lock className="w-3 h-3 text-amber-400 flex-shrink-0" /> Cloud LLM for complex reasoning</li>
              <li className="flex items-center gap-2"><Lock className="w-3 h-3 text-amber-400 flex-shrink-0" /> Natural language code generation</li>
              <li className="flex items-center gap-2"><Lock className="w-3 h-3 text-amber-400 flex-shrink-0" /> Deep document analysis</li>
              <li className="flex items-center gap-2"><Lock className="w-3 h-3 text-amber-400 flex-shrink-0" /> Advanced anomaly reasoning</li>
              <li className="flex items-center gap-2"><Lock className="w-3 h-3 text-amber-400 flex-shrink-0" /> Free-form AI companion chat</li>
            </ul>
            <p className="mt-3 text-xs text-gray-500">Local model support: Set LOCAL_LLM_ENABLED=true in .env for Ollama/LM Studio</p>
          </div>
        </div>
      </div>
    </div>
  );
}
