'use client';

import { useState, useEffect, useCallback } from 'react';

/* ── Types ─────────────────────────────────────────────────────────────── */
interface QuickReply {
  id: string;
  shortcut: string;
  text: string;
}

interface AutoReply {
  id: string;
  keyword: string;
  text: string;
  matchType: 'contains' | 'starts_with' | 'exact';
  enabled: boolean;
}

interface Settings {
  system_prompt: string;
  prompt_stage_Nuevo: string;
  prompt_stage_Calificado: string;
  prompt_stage_Demo_Agendada: string;
  prompt_stage_Contrato: string;
  bot_name: string;
  bot_response_delay: string;
  welcome_enabled: boolean;
  welcome_message: string;
  business_hours_enabled: boolean;
  business_hours_start: string;
  business_hours_end: string;
  business_days: number[];
  away_message: string;
  quick_replies: QuickReply[];
  auto_replies: AutoReply[];
}

interface StatsData {
  total_conversations: number;
  convos_ai: number;
  convos_human: number;
  messages_today_ai: number;
  messages_today_human: number;
  messages_today_user: number;
}

type Tab = 'business' | 'ai' | 'quick' | 'auto' | 'stats' | 'knowledge' | 'security';

const DAY_LABELS = ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'];
const MATCH_TYPE_LABELS: Record<string, string> = {
  contains: 'Contiene',
  starts_with: 'Empieza con',
  exact: 'Exacto',
};

/* ── Toast ─────────────────────────────────────────────────────────────── */
function Toast({ message, type }: { message: string; type: string }) {
  if (!message) return null;
  return (
    <div
      className="absolute top-4 right-4 z-50 px-4 py-3 rounded-xl shadow-lg border text-sm flex items-center gap-2 animate-fade-in"
      style={{
        background: type === 'success' ? 'rgba(16, 185, 129, 0.15)' : 'rgba(239, 68, 68, 0.15)',
        borderColor: type === 'success' ? 'rgba(16, 185, 129, 0.3)' : 'rgba(239, 68, 68, 0.3)',
        color: type === 'success' ? '#34d399' : '#f87171',
      }}
    >
      {type === 'success' ? (
        <svg className="w-4 h-4 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
        </svg>
      ) : (
        <svg className="w-4 h-4 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
        </svg>
      )}
      {message}
    </div>
  );
}

/* ── Stat Card ─────────────────────────────────────────────────────────── */
function StatCard({ label, value, color, icon }: { label: string; value: number | string; color: string; icon: string }) {
  return (
    <div
      className="card-epic p-5 flex flex-col gap-2"
      style={{ border: `1px solid ${color}22` }}
    >
      <div className="flex items-center justify-between">
        <span className="text-2xl">{icon}</span>
        <span className="text-2xl font-bold" style={{ color }}>{value}</span>
      </div>
      <p className="text-xs text-slate-400 font-medium">{label}</p>
    </div>
  );
}

/* ── Toggle Switch ─────────────────────────────────────────────────────── */
function ToggleSwitch({ checked, onChange, color = '#10b981' }: { checked: boolean; onChange: (v: boolean) => void; color?: string }) {
  return (
    <button
      type="button"
      onClick={() => onChange(!checked)}
      className="relative w-11 h-6 rounded-full transition-all duration-300 shrink-0"
      style={{
        background: checked ? color : 'var(--switch-unchecked, #374151)',
        boxShadow: checked ? `0 0 10px ${color}44` : 'none',
      }}
    >
      <div
        className="absolute top-[3px] w-[18px] h-[18px] rounded-full bg-white shadow-md transition-all duration-300"
        style={{ left: checked ? 'calc(100% - 21px)' : '3px' }}
      />
    </button>
  );
}

interface SettingsPanelProps {
  onClose?: () => void;
  mode?: 'settings' | 'security';
  embedded?: boolean;
}

export function SettingsPanel({ onClose, mode = 'settings', embedded = false }: SettingsPanelProps) {
  const [activeTab, setActiveTab] = useState<Tab>(mode === 'security' ? 'security' : 'business');
  const [loading, setLoading] = useState(true);
  const [toast, setToast] = useState({ text: '', type: '' });

  // Knowledge Base state
  const [articles, setArticles] = useState<any[]>([]);
  const [newTitle, setNewTitle] = useState('');
  const [newContent, setNewContent] = useState('');
  const [newCategory, setNewCategory] = useState('');
  const [selectedPromptType, setSelectedPromptType] = useState<'general' | 'Nuevo' | 'Calificado' | 'Demo_Agendada' | 'Contrato'>('general');

  // Settings state
  const [settings, setSettings] = useState<Settings>({
    system_prompt: '',
    prompt_stage_Nuevo: '',
    prompt_stage_Calificado: '',
    prompt_stage_Demo_Agendada: '',
    prompt_stage_Contrato: '',
    bot_name: 'Asistente Virtual',
    bot_response_delay: '0',
    welcome_enabled: false,
    welcome_message: '',
    business_hours_enabled: false,
    business_hours_start: '09:00',
    business_hours_end: '18:00',
    business_days: [1, 2, 3, 4, 5],
    away_message: '',
    quick_replies: [],
    auto_replies: [],
  });

  // Stats state
  const [stats, setStats] = useState<StatsData | null>(null);
  const [statsLoading, setStatsLoading] = useState(false);

  // Form states — Quick Reply
  const [newShortcut, setNewShortcut] = useState('');
  const [newQuickText, setNewQuickText] = useState('');

  // Form states — Auto Reply
  const [newKeyword, setNewKeyword] = useState('');
  const [newAutoText, setNewAutoText] = useState('');
  const [newMatchType, setNewMatchType] = useState<AutoReply['matchType']>('contains');

  // Security state
  const [apiKeys, setApiKeys] = useState<any[]>([]);
  const [apiKeyLabel, setApiKeyLabel] = useState('');
  const [apiKeyScopes, setApiKeyScopes] = useState<string[]>(['read', 'write']);
  const [apiKeyRateLimit, setApiKeyRateLimit] = useState(60);
  const [newlyCreatedKey, setNewlyCreatedKey] = useState<any | null>(null);
  const [auditLogs, setAuditLogs] = useState<any[]>([]);
  const [securityLoading, setSecurityLoading] = useState(false);

  const fetchSecurityData = async () => {
    setSecurityLoading(true);
    try {
      const keysRes = await fetch('/api/api-keys');
      if (keysRes.ok) {
        const keysData = await keysRes.json();
        setApiKeys(keysData);
      }
      const logsRes = await fetch('/api/audit-logs');
      if (logsRes.ok) {
        const logsData = await logsRes.json();
        setAuditLogs(logsData);
      }
    } catch (err) {
      console.error('Error fetching security data:', err);
    } finally {
      setSecurityLoading(false);
    }
  };

  const handleCreateApiKey = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await fetch('/api/api-keys', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          label: apiKeyLabel.trim() || null,
          scopes: apiKeyScopes,
          rate_limit: Number(apiKeyRateLimit)
        })
      });
      if (res.ok) {
        const data = await res.json();
        setNewlyCreatedKey(data);
        setApiKeyLabel('');
        setApiKeyScopes(['read', 'write']);
        setApiKeyRateLimit(60);
        fetchSecurityData();
        showToast('API Key creada ✓', 'success');
      } else {
        showToast('Error al crear API Key', 'error');
      }
    } catch {
      showToast('Error de conexión', 'error');
    }
  };

  const handleDeleteApiKey = async (id: string) => {
    try {
      const res = await fetch(`/api/api-keys/${id}`, { method: 'DELETE' });
      if (res.ok) {
        fetchSecurityData();
        showToast('API Key revocada', 'success');
      } else {
        showToast('Error al revocar API Key', 'error');
      }
    } catch {
      showToast('Error de conexión', 'error');
    }
  };

  // Saving states
  const [savingBusiness, setSavingBusiness] = useState(false);
  const [savingPrompt, setSavingPrompt] = useState(false);

  const showToast = useCallback((text: string, type: 'success' | 'error') => {
    setToast({ text, type });
    setTimeout(() => setToast({ text: '', type: '' }), 3000);
  }, []);

  /* ── Fetch settings ── */
  useEffect(() => {
    const fetch_ = async () => {
      try {
        const res = await fetch('/api/settings');
        const data = await res.json();
        if (res.ok) {
          setSettings({
            system_prompt: data.system_prompt || '',
            prompt_stage_Nuevo: data.prompt_stage_Nuevo || '',
            prompt_stage_Calificado: data.prompt_stage_Calificado || '',
            prompt_stage_Demo_Agendada: data.prompt_stage_Demo_Agendada || '',
            prompt_stage_Contrato: data.prompt_stage_Contrato || '',
            bot_name: data.bot_name || 'Asistente Virtual',
            bot_response_delay: data.bot_response_delay || '0',
            welcome_enabled: data.welcome_enabled ?? false,
            welcome_message: data.welcome_message || '',
            business_hours_enabled: data.business_hours_enabled ?? false,
            business_hours_start: data.business_hours_start || '09:00',
            business_hours_end: data.business_hours_end || '18:00',
            business_days: data.business_days || [1, 2, 3, 4, 5],
            away_message: data.away_message || '',
            quick_replies: data.quick_replies || [],
            auto_replies: (data.auto_replies || []).map((r: any) => ({
              ...r,
              matchType: r.matchType || 'contains',
              enabled: r.enabled !== false,
            })),
          });
        }
      } catch (err) {
        console.error('Error fetching settings:', err);
      } finally {
        setLoading(false);
      }
    };
    fetch_();
  }, []);

  /* ── Fetch stats ── */
  const fetchStats = useCallback(async () => {
    setStatsLoading(true);
    try {
      const res = await fetch('/api/stats');
      const data = await res.json();
      if (res.ok) setStats(data);
    } catch {}
    finally { setStatsLoading(false); }
  }, []);

  const fetchArticles = async () => {
    try {
      const res = await fetch('/api/knowledge');
      const data = await res.json();
      if (res.ok) setArticles(data);
    } catch (err) {
      console.error('Error fetching articles:', err);
    }
  };

  const handleAddArticle = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newTitle.trim() || !newContent.trim()) return;
    try {
      const res = await fetch('/api/knowledge', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: newTitle.trim(),
          content: newContent.trim(),
          category: newCategory.trim() || null
        })
      });
      if (res.ok) {
        setNewTitle('');
        setNewContent('');
        setNewCategory('');
        fetchArticles();
        showToast('Artículo agregado ✓', 'success');
      } else {
        showToast('Error al guardar artículo', 'error');
      }
    } catch {
      showToast('Error de conexión', 'error');
    }
  };

  const handleDeleteArticle = async (id: number) => {
    try {
      const res = await fetch(`/api/knowledge/${id}`, { method: 'DELETE' });
      if (res.ok) {
        fetchArticles();
        showToast('Artículo eliminado', 'success');
      } else {
        showToast('Error al eliminar artículo', 'error');
      }
    } catch {
      showToast('Error de conexión', 'error');
    }
  };

  useEffect(() => {
    if (activeTab === 'stats') fetchStats();
    if (activeTab === 'knowledge') fetchArticles();
    if (activeTab === 'security') fetchSecurityData();
  }, [activeTab, fetchStats]);

  /* ── Persist helper ── */
  const saveSettings = async (partial: Partial<Settings>) => {
    const res = await fetch('/api/settings', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(partial),
    });
    return res.ok;
  };

  /* ── Tab: Negocio ── */
  const handleSaveBusiness = async () => {
    setSavingBusiness(true);
    try {
      const ok = await saveSettings({
        bot_name: settings.bot_name,
        welcome_enabled: settings.welcome_enabled,
        welcome_message: settings.welcome_message,
        business_hours_enabled: settings.business_hours_enabled,
        business_hours_start: settings.business_hours_start,
        business_hours_end: settings.business_hours_end,
        business_days: settings.business_days,
        away_message: settings.away_message,
      });
      showToast(ok ? 'Configuración de negocio guardada ✓' : 'Error al guardar', ok ? 'success' : 'error');
    } catch {
      showToast('Error de conexión', 'error');
    } finally {
      setSavingBusiness(false);
    }
  };

  const toggleDay = (day: number) => {
    setSettings(prev => ({
      ...prev,
      business_days: prev.business_days.includes(day)
        ? prev.business_days.filter(d => d !== day)
        : [...prev.business_days, day].sort(),
    }));
  };

  /* ── Tab: AI ── */
  const handleSavePrompt = async () => {
    setSavingPrompt(true);
    try {
      const ok = await saveSettings({
        system_prompt: settings.system_prompt,
        prompt_stage_Nuevo: settings.prompt_stage_Nuevo,
        prompt_stage_Calificado: settings.prompt_stage_Calificado,
        prompt_stage_Demo_Agendada: settings.prompt_stage_Demo_Agendada,
        prompt_stage_Contrato: settings.prompt_stage_Contrato,
        bot_response_delay: settings.bot_response_delay,
      });
      showToast(ok ? 'Instrucciones guardadas ✓' : 'Error al guardar', ok ? 'success' : 'error');
    } catch {
      showToast('Error de conexión', 'error');
    } finally {
      setSavingPrompt(false);
    }
  };

  /* ── Tab: Quick Replies ── */
  const handleAddQuickReply = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newShortcut.trim() || !newQuickText.trim()) return;
    let shortcut = newShortcut.trim();
    if (!shortcut.startsWith('/')) shortcut = '/' + shortcut;

    const newItem: QuickReply = { id: Date.now().toString(), shortcut, text: newQuickText.trim() };
    const updated = [...settings.quick_replies, newItem];
    setSettings(prev => ({ ...prev, quick_replies: updated }));
    setNewShortcut(''); setNewQuickText('');

    const ok = await saveSettings({ quick_replies: updated });
    showToast(ok ? 'Respuesta rápida agregada ✓' : 'Error al guardar', ok ? 'success' : 'error');
  };

  const handleDeleteQuickReply = async (id: string) => {
    const updated = settings.quick_replies.filter(r => r.id !== id);
    setSettings(prev => ({ ...prev, quick_replies: updated }));
    await saveSettings({ quick_replies: updated });
    showToast('Respuesta eliminada', 'success');
  };

  /* ── Tab: Auto Replies ── */
  const handleAddAutoReply = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newKeyword.trim() || !newAutoText.trim()) return;
    const newItem: AutoReply = {
      id: Date.now().toString(),
      keyword: newKeyword.trim(),
      text: newAutoText.trim(),
      matchType: newMatchType,
      enabled: true,
    };
    const updated = [...settings.auto_replies, newItem];
    setSettings(prev => ({ ...prev, auto_replies: updated }));
    setNewKeyword(''); setNewAutoText('');

    const ok = await saveSettings({ auto_replies: updated });
    showToast(ok ? 'Regla agregada ✓' : 'Error al guardar', ok ? 'success' : 'error');
  };

  const handleToggleAutoReply = async (id: string) => {
    const updated = settings.auto_replies.map(r =>
      r.id === id ? { ...r, enabled: !r.enabled } : r
    );
    setSettings(prev => ({ ...prev, auto_replies: updated }));
    await saveSettings({ auto_replies: updated });
  };

  const handleDeleteAutoReply = async (id: string) => {
    const updated = settings.auto_replies.filter(r => r.id !== id);
    setSettings(prev => ({ ...prev, auto_replies: updated }));
    await saveSettings({ auto_replies: updated });
    showToast('Regla eliminada', 'success');
  };

  /* ── Loading state ── */
  if (loading) {
    return (
      <div className="h-full flex flex-col items-center justify-center bg-transparent gap-4">
        <div className="spinner-epic" style={{ width: '32px', height: '32px' }} />
        <span className="text-[10px] font-extrabold uppercase tracking-widest text-slate-400 select-none">Cargando configuraciones…</span>
      </div>
    );
  }

  const tabs: { id: Tab; label: string; icon: React.ReactNode }[] = [
    { id: 'business', label: 'Negocio', icon: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" /></svg> },
    { id: 'ai', label: 'Agente IA', icon: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" /></svg> },
    { id: 'knowledge', label: 'Base de Conocimiento', icon: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" /></svg> },
    { id: 'quick', label: 'Resp. Rápidas', icon: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" /></svg> },
    { id: 'auto', label: 'Auto-Respuestas', icon: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" /><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /></svg> },
    { id: 'stats', label: 'Estadísticas', icon: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" /></svg> },
    { id: 'security', label: 'Seguridad', icon: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg> },
  ];

  const tabColors: Record<Tab, string> = {
    business: '#10b981',
    ai: '#34d399',
    quick: '#8b5cf6',
    auto: '#38bdf8',
    stats: '#fbbf24',
    knowledge: '#a855f7',
    security: '#ef4444',
  };

  const activeColor = tabColors[activeTab];

  const visibleTabs = tabs.filter(tab => {
    if (mode === 'security') {
      return tab.id === 'security';
    } else {
      return tab.id !== 'security';
    }
  });

  return (
    <div className="h-full flex flex-col relative overflow-hidden bg-transparent">
      <Toast message={toast.text} type={toast.type} />

      {!embedded && (
        <div className="drawer-head">
          <h2>Configuración del Sistema</h2>
          {onClose && (
            <button type="button" className="close-drawer" onClick={onClose}>
              &times;
            </button>
          )}
        </div>
      )}

      {/* ── Tab Header ── */}
      {mode === 'settings' && (
        <div
          className="shrink-0 overflow-x-auto"
          style={{
            borderBottom: '1px solid rgba(148,163,184,0.1)',
            background: 'rgba(255,255,255,0.015)',
            padding: '0 24px',
          }}
        >
          <div style={{ display: 'flex', gap: '2px', alignItems: 'center', height: '56px' }}>
            {visibleTabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '7px',
                  padding: '7px 14px',
                  borderRadius: '10px',
                  fontSize: '0.76rem',
                  fontWeight: 600,
                  whiteSpace: 'nowrap',
                  cursor: 'pointer',
                  transition: 'all 0.2s ease',
                  border: activeTab === tab.id ? `1px solid ${tabColors[tab.id]}25` : '1px solid transparent',
                  color: activeTab === tab.id ? tabColors[tab.id] : '#64748b',
                  background: activeTab === tab.id ? `${tabColors[tab.id]}10` : 'transparent',
                  boxShadow: activeTab === tab.id ? `0 0 12px ${tabColors[tab.id]}10` : 'none',
                }}
              >
                {tab.icon}
                {tab.label}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* ── Content ── */}
      <div className="flex-1 overflow-y-auto" style={{ padding: '28px 32px', display: 'flex', flexDirection: 'column', gap: '20px' }}>

        {/* ════════════════════════════════ TAB: NEGOCIO ════════════════════════════════ */}
        {activeTab === 'business' && (
          <div className="max-w-2xl space-y-6 animate-fade-in">
            <div>
              <h3 className="text-lg font-bold text-slate-200 mb-1">Información del Negocio</h3>
              <p className="text-xs text-slate-400 leading-relaxed">
                Configura la identidad del bot, mensajes de bienvenida y horarios de atención.
              </p>
            </div>

            {/* Bot Name */}
            <div className="card-epic p-5 space-y-3">
              <h4 className="text-xs font-bold uppercase tracking-wider text-emerald-400">Identidad del Bot</h4>
              <div>
                <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Nombre del Asistente</label>
                <input
                  type="text"
                  value={settings.bot_name}
                  onChange={e => setSettings(p => ({ ...p, bot_name: e.target.value }))}
                  className="input-epic py-2.5 text-sm"
                  placeholder="Ej: Sofia, Asistente de Ventas..."
                />
              </div>
            </div>

            {/* Welcome Message */}
            <div className="card-epic p-5 space-y-3">
              <div className="flex items-center justify-between">
                <h4 className="text-xs font-bold uppercase tracking-wider text-emerald-400">Mensaje de Bienvenida</h4>
                <div className="flex items-center gap-2">
                  <span className="text-[11px] text-slate-400">{settings.welcome_enabled ? 'Activo' : 'Inactivo'}</span>
                  <ToggleSwitch
                    checked={settings.welcome_enabled}
                    onChange={v => setSettings(p => ({ ...p, welcome_enabled: v }))}
                  />
                </div>
              </div>
              <p className="text-[11px] text-slate-500">
                Se envía automáticamente cuando un cliente escribe por primera vez.
              </p>
              <textarea
                value={settings.welcome_message}
                onChange={e => setSettings(p => ({ ...p, welcome_message: e.target.value }))}
                disabled={!settings.welcome_enabled}
                className="input-epic text-sm leading-relaxed min-h-24"
                placeholder="¡Hola! Gracias por contactarnos. ¿En qué podemos ayudarte?"
                style={{ resize: 'vertical', opacity: settings.welcome_enabled ? 1 : 0.4 }}
              />
            </div>

            {/* Business Hours */}
            <div className="card-epic p-5 space-y-4">
              <div className="flex items-center justify-between">
                <h4 className="text-xs font-bold uppercase tracking-wider text-sky-400">Horario de Atención</h4>
                <div className="flex items-center gap-2">
                  <span className="text-[11px] text-slate-400">{settings.business_hours_enabled ? 'Activo' : 'Inactivo'}</span>
                  <ToggleSwitch
                    checked={settings.business_hours_enabled}
                    onChange={v => setSettings(p => ({ ...p, business_hours_enabled: v }))}
                    color="#0ea5e9"
                  />
                </div>
              </div>
              <p className="text-[11px] text-slate-500">
                Fuera del horario configurado, el bot enviará el mensaje de "fuera de horario" en lugar de responder con IA.
              </p>

              <div className={`space-y-4 transition-opacity duration-200 ${settings.business_hours_enabled ? '' : 'opacity-40 pointer-events-none'}`}>
                {/* Days */}
                <div>
                  <label className="block text-[11px] text-slate-400 mb-2 font-medium">Días Activos</label>
                  <div className="flex gap-1.5 flex-wrap">
                    {DAY_LABELS.map((label, idx) => (
                      <button
                        key={idx}
                        type="button"
                        onClick={() => toggleDay(idx)}
                        className="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all duration-150"
                        style={
                          settings.business_days.includes(idx)
                            ? { background: 'rgba(14,165,233,0.15)', color: '#38bdf8', border: '1px solid rgba(14,165,233,0.3)' }
                            : { background: 'rgba(255,255,255,0.03)', color: '#475569', border: '1px solid rgba(255,255,255,0.06)' }
                        }
                      >
                        {label}
                      </button>
                    ))}
                  </div>
                </div>

                {/* Hours */}
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Hora de inicio</label>
                    <input
                      type="time"
                      value={settings.business_hours_start}
                      onChange={e => setSettings(p => ({ ...p, business_hours_start: e.target.value }))}
                      className="input-epic py-2.5 text-sm"
                    />
                  </div>
                  <div>
                    <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Hora de cierre</label>
                    <input
                      type="time"
                      value={settings.business_hours_end}
                      onChange={e => setSettings(p => ({ ...p, business_hours_end: e.target.value }))}
                      className="input-epic py-2.5 text-sm"
                    />
                  </div>
                </div>

                {/* Away message */}
                <div>
                  <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Mensaje fuera de horario</label>
                  <textarea
                    value={settings.away_message}
                    onChange={e => setSettings(p => ({ ...p, away_message: e.target.value }))}
                    className="input-epic text-sm leading-relaxed min-h-20"
                    placeholder="Estamos fuera del horario de atención. Te responderemos pronto 🙏"
                    style={{ resize: 'vertical' }}
                  />
                </div>
              </div>
            </div>

            <div className="flex justify-end">
              <button
                onClick={handleSaveBusiness}
                disabled={savingBusiness}
                className="btn-epic flex items-center justify-center gap-2 px-6"
                style={{ width: 'auto', marginTop: 0 }}
              >
                {savingBusiness ? (
                  <div className="spinner-epic" style={{ width: '14px', height: '14px', borderWidth: '2px', borderTopColor: '#fff' }} />
                ) : (
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2v-9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
                  </svg>
                )}
                {savingBusiness ? 'Guardando…' : 'Guardar Negocio'}
              </button>
            </div>
          </div>
        )}

        {/* ════════════════════════════════ TAB: AI PROMPT ════════════════════════════════ */}
        {activeTab === 'ai' && (
          <div className="max-w-2xl space-y-5 animate-fade-in">
            <div>
              <h3 className="text-lg font-bold text-slate-200 mb-1">Instrucciones del Bot (System Prompt)</h3>
              <p className="text-xs text-slate-400 leading-relaxed">
                Define el comportamiento, tono y límites del asistente virtual. Puedes tener instrucciones generales o específicas según la etapa del cliente.
              </p>
            </div>
            
            <div className="card-epic p-5 space-y-3">
              <h4 className="text-xs font-bold uppercase tracking-wider text-sky-400">Retraso de Respuesta</h4>
              <p className="text-[11px] text-slate-500">Segundos de espera antes de que el bot responda (0 para respuesta inmediata):</p>
              <div className="flex items-center gap-3">
                <input
                  type="number"
                  min="0"
                  max="60"
                  value={settings.bot_response_delay || '0'}
                  onChange={e => setSettings(p => ({ ...p, bot_response_delay: e.target.value }))}
                  className="input-epic w-20 py-2 text-sm text-center font-mono"
                />
                <span className="text-xs text-slate-400">segundos</span>
              </div>
            </div>

            {/* Selector de tipo de Prompt (General o por Etapa) */}
            <div className="card-epic p-4 space-y-3">
              <h4 className="text-xs font-bold uppercase tracking-wider text-slate-400">Seleccionar Prompt a Editar</h4>
              <div className="flex gap-2 flex-wrap">
                {(['general', 'Nuevo', 'Calificado', 'Demo_Agendada', 'Contrato'] as const).map(type => (
                  <button
                    key={type}
                    type="button"
                    onClick={() => setSelectedPromptType(type)}
                    className="px-3 py-1.5 rounded-lg text-xs font-semibold transition-all"
                    style={
                      selectedPromptType === type
                        ? { background: 'rgba(52,211,153,0.15)', color: '#34d399', border: '1px solid rgba(52,211,153,0.3)' }
                        : { background: 'rgba(255,255,255,0.03)', color: '#94a3b8', border: '1px solid rgba(255,255,255,0.06)' }
                    }
                  >
                    {type === 'general' ? 'Prompt General' : `Etapa: ${type.replace('_', ' ')}`}
                  </button>
                ))}
              </div>
            </div>

            <div className="space-y-4">
              <textarea
                value={
                  selectedPromptType === 'general' ? settings.system_prompt :
                  selectedPromptType === 'Nuevo' ? settings.prompt_stage_Nuevo :
                  selectedPromptType === 'Calificado' ? settings.prompt_stage_Calificado :
                  selectedPromptType === 'Demo_Agendada' ? settings.prompt_stage_Demo_Agendada :
                  settings.prompt_stage_Contrato
                }
                onChange={e => {
                  const val = e.target.value;
                  setSettings(p => ({
                    ...p,
                    system_prompt: selectedPromptType === 'general' ? val : p.system_prompt,
                    prompt_stage_Nuevo: selectedPromptType === 'Nuevo' ? val : p.prompt_stage_Nuevo,
                    prompt_stage_Calificado: selectedPromptType === 'Calificado' ? val : p.prompt_stage_Calificado,
                    prompt_stage_Demo_Agendada: selectedPromptType === 'Demo_Agendada' ? val : p.prompt_stage_Demo_Agendada,
                    prompt_stage_Contrato: selectedPromptType === 'Contrato' ? val : p.prompt_stage_Contrato,
                  }));
                }}
                className="input-epic min-h-64 text-sm font-mono leading-relaxed"
                placeholder={
                  selectedPromptType === 'general' ? "Escribe el prompt general del bot aquí..." :
                  `Escribe el prompt específico para clientes en etapa "${selectedPromptType.replace('_', ' ')}" (si se deja vacío, usará el prompt general)...`
                }
                style={{ resize: 'vertical' }}
              />
              <div className="flex items-center justify-between">
                <span className="text-[11px] text-slate-500">
                  {
                    (selectedPromptType === 'general' ? settings.system_prompt :
                     selectedPromptType === 'Nuevo' ? settings.prompt_stage_Nuevo :
                     selectedPromptType === 'Calificado' ? settings.prompt_stage_Calificado :
                     selectedPromptType === 'Demo_Agendada' ? settings.prompt_stage_Demo_Agendada :
                     settings.prompt_stage_Contrato).length
                  } caracteres
                </span>
                 <button
                  onClick={handleSavePrompt}
                  disabled={savingPrompt}
                  className="btn-epic flex items-center justify-center gap-2 px-6"
                  style={{ width: 'auto', marginTop: 0 }}
                >
                  {savingPrompt ? (
                    <>
                      <div className="spinner-epic" style={{ width: '14px', height: '14px', borderWidth: '2px', borderTopColor: '#fff' }} />
                      Guardando…
                    </>
                  ) : (
                    <>
                      <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2v-9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
                      </svg>
                      Guardar Prompts
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* ════════════════════════════════ TAB: QUICK REPLIES ════════════════════════════════ */}
        {activeTab === 'quick' && (
          <div className="max-w-4xl space-y-8 animate-fade-in">
            <div>
              <h3 className="text-lg font-bold text-slate-200 mb-1">Plantillas de Respuestas Rápidas</h3>
              <p className="text-xs text-slate-400 leading-relaxed">
                Guarda atajos (ej. <span className="font-mono text-violet-400">/precios</span>) para que los agentes puedan insertarlos al instante con el botón ⚡ en el chat.
              </p>
            </div>

            {/* Form */}
            <form onSubmit={handleAddQuickReply} className="card-epic p-5 space-y-4 max-w-xl">
              <h4 className="text-xs font-bold uppercase tracking-wider text-violet-400">Nueva Respuesta Rápida</h4>
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div className="sm:col-span-1">
                  <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Atajo (ej: /hola)</label>
                  <input
                    type="text"
                    required
                    value={newShortcut}
                    onChange={e => setNewShortcut(e.target.value)}
                    placeholder="/atajo"
                    className="input-epic py-2 text-xs font-mono"
                  />
                </div>
                <div className="sm:col-span-2">
                  <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Mensaje de Respuesta</label>
                  <textarea
                    required
                    value={newQuickText}
                    onChange={e => setNewQuickText(e.target.value)}
                    placeholder="El mensaje completo que se insertará en el chat..."
                    className="input-epic text-xs min-h-[60px]"
                    style={{ resize: 'vertical' }}
                  />
                </div>
              </div>
              <div className="flex justify-end">
                <button
                  type="submit"
                  className="px-4 py-2.5 rounded-xl font-semibold text-xs text-white transition-all duration-200 hover:scale-[1.01]"
                  style={{ background: 'linear-gradient(135deg, #8b5cf6, #7c3aed)', boxShadow: '0 0 12px rgba(139,92,246,0.2)' }}
                >
                  + Agregar Atajo
                </button>
              </div>
            </form>

            {/* List */}
            <div className="space-y-3">
              <h4 className="text-xs font-bold uppercase tracking-wider text-slate-400">
                Respuestas Guardadas ({settings.quick_replies.length})
              </h4>
              {settings.quick_replies.length === 0 ? (
                <div className="card-epic p-6 text-center text-xs text-slate-500 max-w-xl">
                  No hay respuestas rápidas configuradas. Agrega una arriba.
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {settings.quick_replies.map(item => (
                    <div key={item.id} className="card-epic p-4 flex flex-col justify-between border border-white/5">
                      <div className="space-y-2">
                        <span className="inline-block text-xs font-bold font-mono px-2 py-0.5 rounded bg-violet-500/10 text-violet-400">
                          {item.shortcut}
                        </span>
                        <p className="text-xs text-slate-300 leading-relaxed whitespace-pre-wrap">{item.text}</p>
                      </div>
                      <div className="flex justify-end mt-3 border-t border-white/5 pt-2">
                        <button
                          onClick={() => handleDeleteQuickReply(item.id)}
                          className="text-[10px] font-semibold text-red-400 hover:text-red-300 flex items-center gap-1 cursor-pointer transition-colors"
                        >
                          <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                          </svg>
                          Eliminar
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}

        {/* ════════════════════════════════ TAB: AUTO REPLIES ════════════════════════════════ */}
        {activeTab === 'auto' && (
          <div className="max-w-4xl space-y-8 animate-fade-in">
            <div>
              <h3 className="text-lg font-bold text-slate-200 mb-1">Respuestas Automáticas por Palabra Clave</h3>
              <p className="text-xs text-slate-400 leading-relaxed">
                El bot responde al instante si el mensaje contiene la palabra clave. Usa <span className="font-mono text-sky-400">{'{nombre}'}</span> para insertar el nombre del cliente.
              </p>
            </div>

            {/* Form */}
            <form onSubmit={handleAddAutoReply} className="card-epic p-5 space-y-4 max-w-xl">
              <h4 className="text-xs font-bold uppercase tracking-wider text-sky-400">Nueva Regla Automática</h4>
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div>
                  <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Palabra Clave</label>
                  <input
                    type="text"
                    required
                    value={newKeyword}
                    onChange={e => setNewKeyword(e.target.value)}
                    placeholder="precio, hola..."
                    className="input-epic py-2 text-xs"
                  />
                </div>
                <div>
                  <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Tipo de Coincidencia</label>
                  <select
                    value={newMatchType}
                    onChange={e => setNewMatchType(e.target.value as AutoReply['matchType'])}
                    className="input-epic py-2 text-xs"
                  >
                    <option value="contains">Contiene</option>
                    <option value="starts_with">Empieza con</option>
                    <option value="exact">Exacto</option>
                  </select>
                </div>
                <div className="sm:col-span-3">
                  <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">
                    Respuesta Automática <span className="text-sky-500/60">(usa {'{nombre}'} para el nombre del cliente)</span>
                  </label>
                  <textarea
                    required
                    value={newAutoText}
                    onChange={e => setNewAutoText(e.target.value)}
                    placeholder="Hola {nombre}, con gusto te ayudo..."
                    className="input-epic text-xs min-h-[60px]"
                    style={{ resize: 'vertical' }}
                  />
                </div>
              </div>
              <div className="flex justify-end">
                <button
                  type="submit"
                  className="px-4 py-2.5 rounded-xl font-semibold text-xs text-white transition-all duration-200 hover:scale-[1.01]"
                  style={{ background: 'linear-gradient(135deg, #0ea5e9, #0284c7)', boxShadow: '0 0 12px rgba(14,165,233,0.2)' }}
                >
                  + Agregar Regla
                </button>
              </div>
            </form>

            {/* List */}
            <div className="space-y-3">
              <h4 className="text-xs font-bold uppercase tracking-wider text-slate-400">
                Reglas Activas ({settings.auto_replies.filter(r => r.enabled).length}/{settings.auto_replies.length})
              </h4>
              {settings.auto_replies.length === 0 ? (
                <div className="card-epic p-6 text-center text-xs text-slate-500 max-w-xl">
                  No hay reglas configuradas. Agrega una arriba.
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {settings.auto_replies.map(item => (
                    <div
                      key={item.id}
                      className="card-epic p-4 flex flex-col justify-between border border-white/5 transition-opacity duration-200"
                      style={{ opacity: item.enabled ? 1 : 0.5 }}
                    >
                      <div className="space-y-2">
                        <div className="flex items-center gap-2 flex-wrap">
                          <span className="text-[10px] text-slate-500 font-medium">Si</span>
                          <span className="text-[10px] font-semibold px-1.5 py-0.5 rounded bg-slate-700/50 text-slate-400">
                            {MATCH_TYPE_LABELS[item.matchType] || 'Contiene'}
                          </span>
                          <span className="text-xs font-bold px-2 py-0.5 rounded bg-sky-500/10 text-sky-400">
                            "{item.keyword}"
                          </span>
                        </div>
                        <p className="text-xs text-slate-300 leading-relaxed whitespace-pre-wrap">{item.text}</p>
                      </div>
                      <div className="flex items-center justify-between mt-3 border-t border-white/5 pt-2">
                        <div className="flex items-center gap-1.5">
                          <ToggleSwitch checked={item.enabled} onChange={() => handleToggleAutoReply(item.id)} color="#0ea5e9" />
                          <span className="text-[10px] text-slate-500">{item.enabled ? 'Activa' : 'Pausada'}</span>
                        </div>
                        <button
                          onClick={() => handleDeleteAutoReply(item.id)}
                          className="text-[10px] font-semibold text-red-400 hover:text-red-300 flex items-center gap-1 cursor-pointer transition-colors"
                        >
                          <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                          </svg>
                          Eliminar
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}

        {/* ════════════════════════════════ TAB: STATS ════════════════════════════════ */}
        {activeTab === 'stats' && (
          <div className="max-w-3xl space-y-6 animate-fade-in">
            <div className="flex items-center justify-between">
              <div>
                <h3 className="text-lg font-bold text-slate-200 mb-1">Estadísticas del CRM</h3>
                <p className="text-xs text-slate-400">Actividad general y métricas del día.</p>
              </div>
              <button
                onClick={fetchStats}
                disabled={statsLoading}
                className="text-xs font-semibold px-3 py-2 rounded-lg transition-all duration-200 flex items-center gap-1.5"
                style={{ background: 'rgba(245,158,11,0.1)', color: '#fbbf24', border: '1px solid rgba(245,158,11,0.2)' }}
              >
                {statsLoading ? (
                  <div className="spinner-epic" style={{ width: '12px', height: '12px', borderWidth: '1.5px', borderTopColor: '#fbbf24' }} />
                ) : (
                  <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                  </svg>
                )}
                Actualizar
              </button>
            </div>

            {stats ? (
              <>
                <div>
                  <p className="text-[11px] font-bold uppercase tracking-wider text-slate-500 mb-3">Conversaciones Totales</p>
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                    <StatCard label="Total de Contactos" value={stats.total_conversations} color="#10b981" icon="👥" />
                    <StatCard label="En Modo IA" value={stats.convos_ai} color="#10b981" icon="🤖" />
                    <StatCard label="En Modo Humano" value={stats.convos_human} color="#8b5cf6" icon="👤" />
                  </div>
                </div>
                <div>
                  <p className="text-[11px] font-bold uppercase tracking-wider text-slate-500 mb-3">Actividad Hoy</p>
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                    <StatCard label="Mensajes de Clientes" value={stats.messages_today_user} color="#f59e0b" icon="💬" />
                    <StatCard label="Respuestas del Bot IA" value={stats.messages_today_ai} color="#10b981" icon="🤖" />
                    <StatCard label="Respuestas Humanas" value={stats.messages_today_human} color="#8b5cf6" icon="✍️" />
                  </div>
                </div>

                {/* Mini chart / progress */}
                <div className="card-epic p-5 space-y-4">
                  <h4 className="text-xs font-bold uppercase tracking-wider text-slate-400">Distribución de Respuestas Hoy</h4>
                  {(() => {
                    const total = stats.messages_today_ai + stats.messages_today_human;
                    const aiPct = total > 0 ? Math.round((stats.messages_today_ai / total) * 100) : 0;
                    const humanPct = 100 - aiPct;
                    return (
                      <div className="space-y-3">
                        <div className="space-y-1">
                          <div className="flex justify-between text-[11px]">
                            <span className="text-emerald-400 font-semibold">🤖 Bot IA</span>
                            <span className="text-slate-400">{aiPct}%</span>
                          </div>
                          <div className="h-2 rounded-full bg-white/5 overflow-hidden">
                            <div className="h-full rounded-full transition-all duration-700" style={{ width: `${aiPct}%`, background: 'linear-gradient(90deg, #10b981, #059669)' }} />
                          </div>
                        </div>
                        <div className="space-y-1">
                          <div className="flex justify-between text-[11px]">
                            <span className="text-violet-400 font-semibold">👤 Agente Humano</span>
                            <span className="text-slate-400">{humanPct}%</span>
                          </div>
                          <div className="h-2 rounded-full bg-white/5 overflow-hidden">
                            <div className="h-full rounded-full transition-all duration-700" style={{ width: `${humanPct}%`, background: 'linear-gradient(90deg, #8b5cf6, #7c3aed)' }} />
                          </div>
                        </div>
                        {total === 0 && (
                          <p className="text-xs text-slate-550 text-center pt-2">Sin actividad hoy todavía.</p>
                        )}
                      </div>
                    );
                  })()}
                </div>
              </>
            ) : (
              <div className="flex flex-col items-center justify-center py-20 gap-3">
                <div className="spinner-epic" style={{ width: '28px', height: '28px', borderTopColor: '#fbbf24' }} />
                <span className="text-[10px] font-extrabold uppercase tracking-widest text-slate-550 select-none">Cargando métricas…</span>
              </div>
            )}
          </div>
        )}

        {/* ════════════════════════════════ TAB: KNOWLEDGE BASE ════════════════════════════════ */}
        {activeTab === 'knowledge' && (
          <div className="max-w-4xl space-y-8 animate-fade-in">
            <div>
              <h3 className="text-lg font-bold text-slate-200 mb-1">Base de Conocimiento de la IA</h3>
              <p className="text-xs text-slate-400 leading-relaxed">
                Agrega artículos o fragmentos de información (precios, horarios, políticas) para que el bot responda de forma contextual usando hechos reales de tu negocio.
              </p>
            </div>

            {/* Form */}
            <form onSubmit={handleAddArticle} className="card-epic p-5 space-y-4 max-w-xl">
              <h4 className="text-xs font-bold uppercase tracking-wider text-purple-400 font-bold">Nuevo Artículo de Conocimiento</h4>
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div className="sm:col-span-2">
                  <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Título o Pregunta (ej: Horario de Piscina)</label>
                  <input
                    type="text"
                    required
                    value={newTitle}
                    onChange={e => setNewTitle(e.target.value)}
                    placeholder="Título del artículo..."
                    className="input-epic py-2.5 text-xs"
                  />
                </div>
                <div className="sm:col-span-1">
                  <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Categoría (ej: FAQ, Precios)</label>
                  <input
                    type="text"
                    value={newCategory}
                    onChange={e => setNewCategory(e.target.value)}
                    placeholder="Categoría..."
                    className="input-epic py-2.5 text-xs"
                  />
                </div>
                <div className="sm:col-span-3">
                  <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Contenido / Respuesta</label>
                  <textarea
                    required
                    value={newContent}
                    onChange={e => setNewContent(e.target.value)}
                    placeholder="Escribe la información detallada aquí..."
                    className="input-epic text-xs min-h-[100px]"
                    style={{ resize: 'vertical' }}
                  />
                </div>
              </div>
              <div className="flex justify-end">
                <button
                  type="submit"
                  className="px-4 py-2.5 rounded-xl font-semibold text-xs text-white transition-all duration-200 hover:scale-[1.01]"
                  style={{ background: 'linear-gradient(135deg, #a855f7, #9333ea)', boxShadow: '0 0 12px rgba(168,85,247,0.2)' }}
                >
                  + Agregar Artículo
                </button>
              </div>
            </form>

            {/* List */}
            <div className="space-y-3">
              <h4 className="text-xs font-bold uppercase tracking-wider text-slate-400 font-bold">
                Artículos de Referencia ({articles.length})
              </h4>
              {articles.length === 0 ? (
                <div className="card-epic p-6 text-center text-xs text-slate-500 max-w-xl">
                  No hay artículos configurados. Agrega uno arriba para entrenar a tu IA.
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {articles.map(item => (
                    <div key={item.id} className="card-epic p-4 flex flex-col justify-between border border-white/5">
                      <div className="space-y-2">
                        <div className="flex items-center gap-2">
                          <h5 className="text-xs font-bold text-slate-200">{item.title}</h5>
                          {item.category && (
                            <span className="text-[9px] font-semibold px-1.5 py-0.5 rounded bg-purple-500/10 text-purple-400 font-mono">
                              {item.category}
                            </span>
                          )}
                        </div>
                        <p className="text-xs text-slate-400 leading-relaxed whitespace-pre-wrap">{item.content}</p>
                      </div>
                      <div className="flex justify-end mt-3 border-t border-white/5 pt-2">
                        <button
                          onClick={() => handleDeleteArticle(item.id)}
                          className="text-[10px] font-semibold text-red-400 hover:text-red-300 flex items-center gap-1 cursor-pointer transition-colors"
                        >
                          <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                          </svg>
                          Eliminar
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}

        {/* ════════════════════════════════ TAB: SECURIDAD Y AUDITORÍA ════════════════════════════════ */}
        {activeTab === 'security' && (
          <div className="max-w-6xl space-y-8 animate-fade-in">
            <div>
              <h3 className="text-lg font-bold text-slate-200 mb-1">Seguridad y Auditoría</h3>
              <p className="text-xs text-slate-400 leading-relaxed">
                Gestione las API Keys para integraciones externas y consulte el registro de acciones realizadas en el sistema.
              </p>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
              {/* Left Column: API Keys (5/12 cols) */}
              <div className="lg:col-span-5 space-y-6">
                {/* Form to Create Key */}
                <form onSubmit={handleCreateApiKey} className="card-epic p-5 space-y-4">
                  <h4 className="text-xs font-bold uppercase tracking-wider text-rose-400 font-bold">Generar API Key</h4>
                  
                  <div>
                    <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Etiqueta de la Clave</label>
                    <input
                      type="text"
                      required
                      value={apiKeyLabel}
                      onChange={e => setApiKeyLabel(e.target.value)}
                      placeholder="Ej: Zapier, CRM, n8n..."
                      className="input-epic py-2 text-xs"
                    />
                  </div>

                  <div>
                    <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Permisos (Ámbitos)</label>
                    <div className="flex gap-4 mt-2">
                      <label className="flex items-center gap-2 text-xs text-slate-350 cursor-pointer select-none">
                        <input
                          type="checkbox"
                          checked={apiKeyScopes.includes('read')}
                          onChange={e => {
                            if (e.target.checked) {
                              setApiKeyScopes(p => [...p, 'read']);
                            } else {
                              setApiKeyScopes(p => p.filter(s => s !== 'read'));
                            }
                          }}
                          className="rounded border-slate-700 bg-slate-900 text-rose-500 focus:ring-rose-500 w-4 h-4"
                        />
                        Lectura (read)
                      </label>
                      <label className="flex items-center gap-2 text-xs text-slate-350 cursor-pointer select-none">
                        <input
                          type="checkbox"
                          checked={apiKeyScopes.includes('write')}
                          onChange={e => {
                            if (e.target.checked) {
                              setApiKeyScopes(p => [...p, 'write']);
                            } else {
                              setApiKeyScopes(p => p.filter(s => s !== 'write'));
                            }
                          }}
                          className="rounded border-slate-700 bg-slate-900 text-rose-500 focus:ring-rose-500 w-4 h-4"
                        />
                        Escritura (write)
                      </label>
                    </div>
                  </div>

                  <div>
                    <label className="block text-[11px] text-slate-400 mb-1.5 font-medium">Límite de Peticiones (por minuto)</label>
                    <input
                      type="number"
                      required
                      min={1}
                      max={10000}
                      value={apiKeyRateLimit}
                      onChange={e => setApiKeyRateLimit(Number(e.target.value))}
                      className="input-epic py-2 text-xs"
                    />
                  </div>

                  <button
                    type="submit"
                    disabled={apiKeyScopes.length === 0}
                    className="w-full py-2 rounded-xl font-semibold text-xs text-white transition-all duration-200 hover:scale-[1.01] cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                    style={{ background: 'linear-gradient(135deg, #ef4444, #b91c1c)', boxShadow: '0 0 12px rgba(239,68,68,0.2)' }}
                  >
                    Generar Clave
                  </button>
                </form>

                {/* Display Newly Created Key */}
                {newlyCreatedKey && (
                  <div className="card-epic p-5 border border-rose-500/30 bg-rose-500/5 space-y-3 animate-fade-in">
                    <div className="flex items-center justify-between">
                      <h4 className="text-xs font-bold uppercase tracking-wider text-rose-400">⚠️ Copia tu API Key ahora</h4>
                      <button 
                        onClick={() => setNewlyCreatedKey(null)} 
                        className="text-slate-400 hover:text-white text-xs cursor-pointer"
                      >
                        Cerrar
                      </button>
                    </div>
                    <p className="text-[10px] text-slate-400 leading-normal">
                      Por razones de seguridad, esta clave no se volverá a mostrar en el panel.
                    </p>
                    <div className="flex gap-2 items-center bg-slate-950 p-3 rounded-xl border border-white/5 font-mono text-xs text-rose-355 select-all overflow-x-auto">
                      <span>{newlyCreatedKey.key}</span>
                    </div>
                  </div>
                )}

                {/* Active Keys List */}
                <div className="space-y-3">
                  <h4 className="text-xs font-bold uppercase tracking-wider text-slate-400">Claves Activas</h4>
                  {apiKeys.length === 0 ? (
                    <div className="card-epic p-5 text-center text-xs text-slate-500">
                      No hay API Keys generadas.
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {apiKeys.map(key => {
                        let parsedScopes: string[] = [];
                        try { parsedScopes = JSON.parse(key.scopes); } catch {}
                        return (
                          <div key={key.id} className="card-epic p-4 border border-white/5 space-y-2.5">
                            <div className="flex justify-between items-start">
                              <div>
                                <h5 className="text-xs font-bold text-slate-200">{key.label || 'Sin etiqueta'}</h5>
                                <p className="text-[10px] text-slate-500 font-mono mt-0.5">ID: {key.id.slice(0, 8)}...</p>
                              </div>
                              <button
                                onClick={() => handleDeleteApiKey(key.id)}
                                className="text-[10px] text-red-405 hover:text-red-350 font-semibold flex items-center gap-1 cursor-pointer transition-colors"
                              >
                                Revocar
                              </button>
                            </div>
                            <div className="flex gap-1.5 items-center">
                              {parsedScopes.map(s => (
                                <span key={s} className="text-[8px] font-extrabold uppercase px-1.5 py-0.5 rounded bg-rose-500/10 text-rose-450 font-mono">
                                  {s}
                                </span>
                              ))}
                              <span className="text-[9px] text-slate-400 ml-auto font-medium">
                                Límite: <span className="font-bold text-slate-200">{key.rate_limit}</span>/min
                              </span>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              </div>

              {/* Right Column: Audit Logs (7/12 cols) */}
              <div className="lg:col-span-7 space-y-3">
                <div className="flex items-center justify-between">
                  <h4 className="text-xs font-bold uppercase tracking-wider text-slate-400">Historial de Auditoría</h4>
                  <button 
                    onClick={fetchSecurityData} 
                    className="text-[10px] text-rose-400 hover:text-rose-350 font-bold uppercase tracking-wider flex items-center gap-1 cursor-pointer"
                  >
                    Actualizar
                  </button>
                </div>

                {securityLoading && auditLogs.length === 0 ? (
                  <div className="card-epic p-10 flex flex-col items-center justify-center gap-3">
                    <div className="spinner-epic" style={{ width: '24px', height: '24px', borderTopColor: '#ef4444' }} />
                    <span className="text-[10px] font-bold uppercase tracking-widest text-slate-500">Cargando logs...</span>
                  </div>
                ) : auditLogs.length === 0 ? (
                  <div className="card-epic p-10 text-center text-xs text-slate-500">
                    No se han registrado eventos de auditoría aún.
                  </div>
                ) : (
                  <div className="card-epic p-0 border border-white/5 overflow-hidden">
                    <div className="max-h-[580px] overflow-y-auto">
                      <table className="w-full text-left border-collapse text-xs">
                        <thead>
                          <tr className="border-b border-white/5 bg-white/[0.01] sticky top-0 backdrop-blur z-10 text-slate-400 font-bold text-[10px] uppercase tracking-wider">
                            <th className="p-3">Fecha</th>
                            <th className="p-3">Operador</th>
                            <th className="p-3">Acción</th>
                            <th className="p-3">Detalles</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-white/[0.03]">
                          {auditLogs.map(log => {
                            const dateStr = new Date(log.created_at * 1000).toLocaleString('es-ES', {
                              month: 'short',
                              day: 'numeric',
                              hour: '2-digit',
                              minute: '2-digit'
                            });
                            
                            let detailsText = '';
                            try {
                              const parsed = JSON.parse(log.details);
                              if (log.action === 'settings.update') {
                                detailsText = `Campos modif: ${parsed.updated_fields?.join(', ') || 'ninguno'}`;
                              } else if (log.action === 'lead.update_status') {
                                detailsText = `Lead #${parsed.lead_id} → ${parsed.new_status}`;
                              } else if (log.action === 'lead.delete') {
                                detailsText = `Lead #${parsed.lead_id} eliminado`;
                              } else if (log.action === 'conversation.mode_update') {
                                detailsText = `Chat #${parsed.conversation_id} (${parsed.phone.split('@')[0]}) → ${parsed.new_mode}`;
                              } else if (log.action === 'conversation.mode_global_update') {
                                detailsText = `Todo el sistema → ${parsed.new_mode}`;
                              } else if (log.action === 'conversation.delete') {
                                detailsText = `Conversación #${parsed.conversation_id} eliminada`;
                              } else if (log.action === 'api_key.create') {
                                detailsText = `Creada id: ${parsed.id.slice(0,8)}... label: ${parsed.label || 'ninguno'}`;
                              } else if (log.action === 'api_key.delete') {
                                detailsText = `Revocada id: ${parsed.id.slice(0,8)}...`;
                              } else if (log.action === 'webhook.create') {
                                detailsText = `Creado: ${parsed.url.slice(0,25)}...`;
                              } else if (log.action === 'webhook.delete') {
                                detailsText = `Eliminado webhook: ${parsed.id.slice(0,8)}...`;
                              } else if (log.action === 'knowledge.create') {
                                detailsText = `Creado art: "${parsed.title.slice(0,20)}..."`;
                              } else if (log.action === 'knowledge.delete') {
                                detailsText = `Eliminado artículo: ${parsed.id}`;
                              } else if (log.action === 'message.send_external') {
                                detailsText = `Msg enviado a ${parsed.phone.split('@')[0]}`;
                              } else {
                                detailsText = JSON.stringify(parsed);
                              }
                            } catch {
                              detailsText = log.details || '-';
                            }

                            // Color de la acción
                            let actionColor = 'text-slate-300';
                            if (log.action.includes('delete') || log.action.includes('revocation')) {
                              actionColor = 'text-red-400 font-medium';
                            } else if (log.action.includes('create') || log.action.includes('send')) {
                              actionColor = 'text-emerald-400 font-medium';
                            } else if (log.action.includes('update')) {
                              actionColor = 'text-amber-400 font-medium';
                            }

                            return (
                              <tr key={log.id} className="hover:bg-white/[0.01] transition-colors">
                                <td className="p-3 text-slate-400 whitespace-nowrap">{dateStr}</td>
                                <td className="p-3 font-mono text-[10px] text-slate-350">{log.operator}</td>
                                <td className={`p-3 font-mono text-[10px] ${actionColor}`}>{log.action}</td>
                                <td className="p-3 text-slate-300 max-w-[200px] truncate" title={detailsText}>{detailsText}</td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </table>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
