// API Service with auth
const API_BASE = window.location.origin + '/api';

function getToken() {
  return localStorage.getItem('token');
}

const api = {
  async fetch(endpoint, options = {}) {
    const token = getToken();
    const headers = {
      'Content-Type': 'application/json',
      ...options.headers
    };
    
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    
    const response = await fetch(`${API_BASE}${endpoint}`, {
      ...options,
      headers
    });
    
    if (response.status === 401) {
      localStorage.removeItem('token');
      window.location.reload();
      return;
    }
    
    if (!response.ok) {
      throw new Error(`API Error: ${response.status}`);
    }
    
    return response.json();
  },
  
  login: (username, password) => fetch(`${API_BASE}/auth/login`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password })
  }).then(r => r.json()),
  
  getChats: () => api.fetch('/chats'),
  getChat: (userId) => api.fetch(`/chats/${userId}`),
  sendMessage: (userId, message) => api.fetch('/messages/send', {
    method: 'POST',
    body: JSON.stringify({ userId, message })
  }),
  getAnalytics: () => api.fetch('/analytics'),
  getStatus: () => api.fetch('/status'),
  
  getContacts: (filters = {}) => {
    const params = new URLSearchParams(filters);
    return api.fetch(`/contacts?${params}`);
  },
  createContact: (data) => api.fetch('/contacts', {
    method: 'POST',
    body: JSON.stringify(data)
  }),
  deleteContact: (id) => api.fetch(`/contacts/${id}`, { method: 'DELETE' }),
  importContacts: (formData) => fetch(`${API_BASE}/contacts/import`, {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${getToken()}` },
    body: formData
  }).then(r => r.json()),
  
  getCampaigns: () => api.fetch('/campaigns'),
  createCampaignWithMedia: (formData) => fetch(`${API_BASE}/campaigns`, {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${getToken()}` },
    body: formData
  }).then(r => r.json()),
  addRecipients: (id, filter_tags) => api.fetch(`/campaigns/${id}/recipients`, {
    method: 'POST',
    body: JSON.stringify({ filter_tags })
  }),
  startCampaign: (id) => api.fetch(`/campaigns/${id}/start`, { method: 'POST' }),
  pauseCampaign: (id) => api.fetch(`/campaigns/${id}/pause`, { method: 'POST' }),
  deleteCampaign: (id) => api.fetch(`/campaigns/${id}`, { method: 'DELETE' }),
  
  reconnect: () => api.fetch('/reconnect', { method: 'POST' }),
  logoutBot: () => api.fetch('/logout', { method: 'POST' }),

  // Persona Engine API
  getPersonas: () => api.fetch('/personas'),
  getPersona: (id) => api.fetch(`/personas/${id}`),
  createPersona: (data) => api.fetch('/personas', { method: 'POST', body: JSON.stringify(data) }),
  updatePersona: (id, data) => api.fetch(`/personas/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  deletePersona: (id) => api.fetch(`/personas/${id}`, { method: 'DELETE' }),
  assignPersona: (jid, prompt_id) => api.fetch('/personas/assign', { method: 'POST', body: JSON.stringify({ jid, prompt_id, assigned_by: 'dashboard' }) }),
  getContactPersona: (jid) => api.fetch(`/personas/contact/${encodeURIComponent(jid)}`),
  testPersona: (prompt_id, test_message) => api.fetch('/personas/test', { method: 'POST', body: JSON.stringify({ prompt_id, test_message }) }),
  addPersonaRule: (id, rule_text, priority) => api.fetch(`/personas/${id}/rules`, { method: 'POST', body: JSON.stringify({ rule_text, priority }) }),
  deletePersonaRule: (ruleId) => api.fetch(`/personas/rules/${ruleId}`, { method: 'DELETE' }),
  getPersonaMemories: (jid) => api.fetch(`/personas/memories/${encodeURIComponent(jid)}`),
  addPersonaMemory: (id, data) => api.fetch(`/personas/${id}/memories`, { method: 'POST', body: JSON.stringify(data) }),
  deletePersonaMemory: (id) => api.fetch(`/personas/memories/${id}`, { method: 'DELETE' }),
  getPersonaAnalytics: (jid) => api.fetch(`/personas/analytics/${encodeURIComponent(jid)}`),
  getPersonaEvents: (jid) => api.fetch(`/personas/events/${encodeURIComponent(jid)}`)
};

// Login Component
function Login({ onLogin }) {
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  
  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    
    try {
      const result = await api.login(username, password);
      
      if (result.success) {
        localStorage.setItem('token', result.data.token);
        onLogin(result.data);
      } else {
        setError(result.error || 'Login failed');
      }
    } catch (err) {
      setError('Login failed: ' + err.message);
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-100">
      <div className="bg-white p-8 rounded-xl shadow-lg w-full max-w-md">
        <h1 className="text-2xl font-bold text-gray-800 mb-6 text-center">WhatsApp AI Agent</h1>
        <h2 className="text-lg text-gray-600 mb-6 text-center">Admin Dashboard</h2>
        
        {error && (
          <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">{error}</div>
        )}
        
        <form onSubmit={handleSubmit}>
          <div className="mb-4">
            <label className="block text-gray-700 text-sm font-bold mb-2">Username</label>
            <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} 
              className="w-full px-3 py-2 border border-gray-300 rounded-lg" placeholder="user" required />
          </div>
          <div className="mb-6">
            <label className="block text-gray-700 text-sm font-bold mb-2">Password</label>
            <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} 
              className="w-full px-3 py-2 border border-gray-300 rounded-lg" placeholder="password" required />
          </div>
          <button type="submit" disabled={loading} 
            className="w-full bg-blue-600 text-white font-bold py-2 px-4 rounded-lg hover:bg-blue-700 disabled:opacity-50">
            {loading ? 'Logging in...' : 'Login'}
          </button>
        </form>
      </div>
    </div>
  );
}

// Status Bar
function StatusBar({ status, user, onLogout, onReconnect, onLogoutBot }) {
  return (
    <div className="bg-white border-b px-6 py-3 flex items-center justify-between">
      <div className="flex items-center space-x-4">
        <h1 className="text-xl font-bold text-gray-800">WhatsApp AI Agent</h1>
        <div className="flex items-center space-x-2">
          <span className={`px-3 py-1 rounded-full text-sm font-medium ${
            status.connected ? 'bg-green-100 text-green-800' : status.hasQR ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800'
          }`}>
            {status.connected ? '🟢 Connected' : status.hasQR ? '🟡 QR Required' : '🔴 Disconnected'}
          </span>
          
          {!status.connected && (
            <button 
              onClick={onReconnect}
              className="px-3 py-1 bg-blue-600 text-white text-xs font-bold rounded hover:bg-blue-700 transition"
            >
              🔄 Reconnect
            </button>
          )}
          
          {status.connected && (
            <button 
              onClick={onLogoutBot}
              className="px-3 py-1 bg-gray-200 text-gray-700 text-xs font-bold rounded hover:bg-gray-300 transition"
            >
              🚪 Logout Bot
            </button>
          )}
        </div>
      </div>
      <div className="flex items-center space-x-4">
        <span className="text-sm text-gray-500">Logged in as <strong>{user?.username}</strong></span>
        <button onClick={onLogout} className="text-sm text-red-600 hover:text-red-800">Exit</button>
      </div>
    </div>
  );
}

// QR Modal Component
function QRModal({ qrCode, onClose }) {
  const qrRef = React.useRef(null);

  React.useEffect(() => {
    if (qrCode && qrRef.current) {
      qrRef.current.innerHTML = '';
      new QRCode(qrRef.current, {
        text: qrCode,
        width: 256,
        height: 256,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
      });
    }
  }, [qrCode]);

  return (
    <div className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-[100] p-4">
      <div className="bg-white rounded-2xl p-8 max-w-sm w-full text-center">
        <h3 className="text-2xl font-bold text-gray-900 mb-2">Scan QR Code</h3>
        <p className="text-gray-600 mb-6 text-sm">Open WhatsApp on your phone and scan this code to link your account.</p>
        
        <div className="bg-gray-50 p-4 rounded-xl inline-block mb-6 shadow-inner">
          <div ref={qrRef} className="mx-auto"></div>
        </div>
        
        <div className="space-y-3">
          <p className="text-xs text-gray-400">The code will update automatically. Scan it within 40 seconds.</p>
          <button 
            onClick={onClose}
            className="w-full py-3 bg-gray-100 text-gray-700 font-bold rounded-xl hover:bg-gray-200 transition"
          >
            Close
          </button>
        </div>
      </div>
    </div>
  );
}

// Sidebar
function Sidebar({ activeTab, setActiveTab, hasQR }) {
  const tabs = [
    { id: 'chats', label: '💬 Chats' },
    { id: 'contacts', label: '👥 Contacts' },
    { id: 'campaigns', label: '📢 Campaigns' },
    { id: 'analytics', label: '📊 Analytics' },
    { id: 'personas', label: '🎭 AI Personas' }
  ];
  
  return (
    <div className="w-64 bg-gray-900 text-white flex flex-col">
      <div className="p-4">
        {tabs.map(tab => (
          <button key={tab.id} onClick={() => setActiveTab(tab.id)} 
            className={`w-full text-left px-4 py-3 rounded-lg mb-2 ${activeTab === tab.id ? 'bg-blue-600' : 'hover:bg-gray-800'}`}>
            {tab.label}
          </button>
        ))}
      </div>
      
      {hasQR && (
        <div className="mt-auto p-4 bg-yellow-600">
          <p className="text-sm font-medium mb-2">⚠️ Scan QR Code</p>
          <p className="text-xs">WhatsApp needs authentication</p>
        </div>
      )}
    </div>
  );
}

// Lead Score Badge
function LeadScoreBadge({ score, stage }) {
  const getColor = () => {
    if (stage === 'hot' || score >= 0.7) return 'bg-red-500';
    if (stage === 'warm' || score >= 0.4) return 'bg-yellow-500';
    return 'bg-gray-400';
  };
  
  return (
    <div className="flex items-center space-x-2">
      <div className={`w-3 h-3 rounded-full ${getColor()}`}></div>
      <span className="text-sm font-medium">{stage?.toUpperCase()} ({(score * 100).toFixed(0)}%)</span>
    </div>
  );
}

// Intent Badge
function IntentBadge({ intent }) {
  if (!intent) return null;
  const colors = {
    greeting: 'bg-blue-100 text-blue-800',
    pricing: 'bg-green-100 text-green-800',
    demo: 'bg-purple-100 text-purple-800',
    buying: 'bg-red-100 text-red-800',
    objection: 'bg-orange-100 text-orange-800',
    support: 'bg-gray-100 text-gray-800'
  };
  return (
    <span className={`px-2 py-1 rounded text-xs font-medium ${colors[intent] || colors.support}`}>{intent}</span>
  );
}

// Chat List
function ChatList({ chats, selectedChat, onSelect, hotLeadsMode }) {
  const displayChats = hotLeadsMode ? chats.filter(c => (c.conversion_score || 0) > 0.6) : chats;
  
  return (
    <div className="w-80 bg-white border-r flex flex-col h-full">
      <div className="p-4 border-b">
        <div className="flex space-x-2 mb-3">
          <button onClick={() => onSelect(null, false)} 
            className={`flex-1 py-2 px-3 rounded-lg text-sm font-medium ${!hotLeadsMode ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700'}`}>
            All Chats
          </button>
          <button onClick={() => onSelect(null, true)} 
            className={`flex-1 py-2 px-3 rounded-lg text-sm font-medium ${hotLeadsMode ? 'bg-red-600 text-white' : 'bg-gray-100 text-gray-700'}`}>
            Hot Leads
          </button>
        </div>
      </div>
      
      <div className="flex-1 overflow-y-auto">
        {displayChats.map(chat => (
          <div key={chat.user_id} onClick={() => onSelect(chat.user_id, false)} 
            className={`p-4 border-b cursor-pointer hover:bg-gray-50 ${selectedChat === chat.user_id ? 'bg-blue-50 border-blue-200' : ''}`}>
            <div className="flex justify-between items-start mb-1">
              <h3 className="font-semibold text-gray-800 truncate">{chat.name || chat.user_id.split('@')[0]}</h3>
              <LeadScoreBadge score={chat.conversion_score || 0} stage={chat.stage} />
            </div>
            <p className="text-sm text-gray-500 truncate mb-2">{chat.last_message}</p>
            <div className="flex justify-between items-center">
              <div className="flex items-center gap-1">
                <IntentBadge intent={chat.current_intent} />
                {chat.persona && <span className="text-xs bg-purple-100 text-purple-700 px-1.5 py-0.5 rounded">{chat.persona.icon} {chat.persona.name}</span>}
              </div>
              <span className="text-xs text-gray-400">{new Date(chat.last_message_time).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// Chat Window
function ChatWindow({ userId, messages, memory, onSend }) {
  const [input, setInput] = React.useState('');
  const messagesEndRef = React.useRef(null);
  const [chatPersona, setChatPersona] = React.useState(null);
  const [allPersonas, setAllPersonas] = React.useState([]);
  
  React.useEffect(() => {
    if (userId) {
      loadContactPersona();
    }
    api.getPersonas().then(r => { if (r.success) setAllPersonas(r.data || []); }).catch(() => {});
  }, [userId]);

  const loadContactPersona = async () => {
    try {
      const r = await api.getContactPersona(userId);
      if (r.success) setChatPersona(r.data);
    } catch (e) {}
  };

  const handlePersonaChange = async (e) => {
    const newPersonaId = parseInt(e.target.value);
    if (!newPersonaId || !userId) return;
    try {
      await api.assignPersona(userId, newPersonaId);
      await loadContactPersona();
    } catch (err) {
      alert('Failed to change persona: ' + err.message);
    }
  };
  
  React.useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);
  
  const handleSend = (e) => {
    e.preventDefault();
    if (!input.trim()) return;
    onSend(input);
    setInput('');
  };
  
  return (
    <div className="flex-1 flex flex-col bg-gray-50">
      <div className="bg-white border-b px-6 py-4">
        <div className="flex justify-between items-center">
          <div>
            <h2 className="text-lg font-bold text-gray-800">{memory?.profile?.name || userId.split('@')[0]}</h2>
            <div className="flex items-center space-x-3 mt-1">
              <LeadScoreBadge score={memory?.sales_intelligence?.conversion_score || 0} stage={memory?.sales_intelligence?.stage} />
              <IntentBadge intent={memory?.intent_engine?.current_intent} />
            </div>
          </div>

          <div className="flex items-center space-x-2 bg-purple-50 p-2 rounded-xl border border-purple-100 shadow-sm">
            <span className="text-xs text-purple-700 font-bold flex items-center gap-1">
              🎭 AI Persona:
            </span>
            <select
              value={chatPersona?.prompt_id || chatPersona?.id || ''}
              onChange={handlePersonaChange}
              className="bg-white text-purple-900 border border-purple-300 rounded-lg px-3 py-1 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-purple-500 cursor-pointer"
            >
              <option value="" disabled>Select Persona...</option>
              {allPersonas.map(p => (
                <option key={p.id} value={p.id}>
                  {p.icon} {p.name} ({p.category})
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>
      
      <div className="flex-1 overflow-y-auto p-6 space-y-4">
        {messages?.map((msg, i) => (
          <div key={i} className={`flex ${msg.is_from_bot ? 'justify-end' : 'justify-start'}`}>
            <div className={`max-w-md px-4 py-3 rounded-2xl ${msg.is_from_bot ? 'bg-blue-600 text-white' : 'bg-white border'}`}>
              <p className="text-sm">{msg.content}</p>
              <span className={`text-xs mt-1 block ${msg.is_from_bot ? 'text-blue-200' : 'text-gray-400'}`}>
                {new Date(msg.timestamp).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
              </span>
            </div>
          </div>
        ))}
        <div ref={messagesEndRef} />
      </div>
      
      <form onSubmit={handleSend} className="bg-white border-t p-4">
        <div className="flex space-x-3">
          <input type="text" value={input} onChange={(e) => setInput(e.target.value)} 
            placeholder="Type a message..." className="flex-1 px-4 py-3 border rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500" />
          <button type="submit" className="px-6 py-3 bg-blue-600 text-white rounded-xl font-medium hover:bg-blue-700">Send</button>
        </div>
      </form>
    </div>
  );
}

// Contacts Page
function ContactsPage({ onStartChat }) {
  const [contacts, setContacts] = React.useState([]);
  const [showAdd, setShowAdd] = React.useState(false);
  const [showImport, setShowImport] = React.useState(false);
  const [newContact, setNewContact] = React.useState({ phone: '', name: '', tags: '' });
  const [importResult, setImportResult] = React.useState(null);
  
  React.useEffect(() => {
    loadContacts();
  }, []);
  
  const loadContacts = async () => {
    const result = await api.getContacts();
    if (result.success) setContacts(result.data);
  };
  
  const handleAdd = async (e) => {
    e.preventDefault();
    const result = await api.createContact(newContact);
    if (result.success) {
      setShowAdd(false);
      setNewContact({ phone: '', name: '', tags: '' });
      loadContacts();
    }
  };
  
  const handleDelete = async (id) => {
    if (!confirm('Delete?')) return;
    await api.deleteContact(id);
    loadContacts();
  };
  
  const handleImport = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('file', e.target.file.files[0]);
    const result = await api.importContacts(formData);
    setImportResult(result.data);
    setTimeout(() => { setShowImport(false); setImportResult(null); loadContacts(); }, 2000);
  };
  
  return (
    <div className="p-6 flex-1 overflow-y-auto">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold">Contacts ({contacts.length})</h2>
        <div className="space-x-2">
          <button onClick={() => setShowImport(true)} className="bg-green-600 text-white px-4 py-2 rounded-lg">📥 Import</button>
          <button onClick={() => setShowAdd(true)} className="bg-blue-600 text-white px-4 py-2 rounded-lg">+ Add</button>
        </div>
      </div>
      
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-100">
            <tr>
              <th className="px-4 py-3 text-left">Phone</th>
              <th className="px-4 py-3 text-left">Name</th>
              <th className="px-4 py-3 text-left">Tags</th>
              <th className="px-4 py-3 text-left">Replies</th>
              <th className="px-4 py-3 text-left">Action</th>
            </tr>
          </thead>
          <tbody>
            {contacts.map(c => (
              <tr key={c.id} className="border-b hover:bg-gray-50">
                <td className="px-4 py-3 font-medium text-gray-800">{c.phone}</td>
                <td className="px-4 py-3">{c.name || '-'}</td>
                <td className="px-4 py-3">
                  <span className="bg-gray-100 text-gray-700 text-xs px-2 py-1 rounded">{c.tags || 'none'}</span>
                </td>
                <td className="px-4 py-3">{c.reply_count || 0}</td>
                <td className="px-4 py-3">
                  <div className="flex items-center space-x-2">
                    <button 
                      onClick={() => onStartChat && onStartChat(c.phone)}
                      className="bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold px-3 py-1.5 rounded-lg flex items-center gap-1 transition shadow-sm"
                    >
                      💬 Chat
                    </button>
                    <button 
                      onClick={() => handleDelete(c.id)} 
                      className="text-red-500 hover:text-red-700 text-xs font-medium px-2 py-1"
                    >
                      Delete
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      
      {showAdd && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white p-6 rounded-xl w-96">
            <h3 className="text-xl font-bold mb-4">Add Contact</h3>
            <form onSubmit={handleAdd}>
              <input type="text" placeholder="Phone" value={newContact.phone} 
                onChange={e => setNewContact({...newContact, phone: e.target.value})} 
                className="w-full border px-3 py-2 rounded mb-2" required />
              <input type="text" placeholder="Name" value={newContact.name} 
                onChange={e => setNewContact({...newContact, name: e.target.value})} 
                className="w-full border px-3 py-2 rounded mb-2" />
              <input type="text" placeholder="Tags" value={newContact.tags} 
                onChange={e => setNewContact({...newContact, tags: e.target.value})} 
                className="w-full border px-3 py-2 rounded mb-4" />
              <div className="flex justify-end gap-2">
                <button type="button" onClick={() => setShowAdd(false)} className="px-4 py-2 text-gray-600">Cancel</button>
                <button type="submit" className="bg-blue-600 text-white px-4 py-2 rounded">Add</button>
              </div>
            </form>
          </div>
        </div>
      )}
      
      {showImport && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white p-6 rounded-xl w-96">
            <h3 className="text-xl font-bold mb-4">Import Contacts</h3>
            {importResult ? (
              <div className="text-center">
                <p className="text-green-600 font-bold">Imported: {importResult.imported}</p>
                <p className="text-gray-600">Duplicates: {importResult.duplicates}</p>
              </div>
            ) : (
              <form onSubmit={handleImport}>
                <input type="file" name="file" accept=".csv,.xlsx" required className="w-full mb-4" />
                <div className="flex justify-end gap-2">
                  <button type="button" onClick={() => setShowImport(false)} className="px-4 py-2 text-gray-600">Cancel</button>
                  <button type="submit" className="bg-green-600 text-white px-4 py-2 rounded">Import</button>
                </div>
              </form>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

// Campaigns Page
function CampaignsPage() {
  const [campaigns, setCampaigns] = React.useState([]);
  const [showCreate, setShowCreate] = React.useState(false);
  const [newCampaign, setNewCampaign] = React.useState({
    name: '', description: '', message_template: '', target_tags: '', media_url: '',
    business_hours_only: true, messages_per_hour: 30, min_delay_seconds: 30, max_delay_seconds: 120, use_content_variation: true
  });
  const [selectedMedia, setSelectedMedia] = React.useState(null);
  
  React.useEffect(() => {
    loadCampaigns();
    const interval = setInterval(loadCampaigns, 5000);
    return () => clearInterval(interval);
  }, []);
  
  const loadCampaigns = async () => {
    const result = await api.getCampaigns();
    if (result.success) setCampaigns(result.data);
  };
  
  const handleCreate = async (e) => {
    e.preventDefault();
    
    // Create form data for media upload
    const formData = new FormData();
    formData.append('name', newCampaign.name);
    formData.append('description', newCampaign.description);
    formData.append('message_template', newCampaign.message_template);
    formData.append('target_tags', newCampaign.target_tags);
    formData.append('business_hours_only', newCampaign.business_hours_only);
    formData.append('messages_per_hour', newCampaign.messages_per_hour);
    formData.append('min_delay_seconds', newCampaign.min_delay_seconds);
    formData.append('max_delay_seconds', newCampaign.max_delay_seconds);
    formData.append('use_content_variation', newCampaign.use_content_variation);
    if (selectedMedia) {
      formData.append('media', selectedMedia);
    }
    
    const result = await api.createCampaignWithMedia(formData);
    if (result.success) {
      await api.addRecipients(result.data.id, newCampaign.target_tags);
      setShowCreate(false);
      setNewCampaign({ name: '', description: '', message_template: '', target_tags: '', media_url: '', business_hours_only: true, messages_per_hour: 30, min_delay_seconds: 30, max_delay_seconds: 120, use_content_variation: true });
      setSelectedMedia(null);
      loadCampaigns();
    }
  };
  
  const getStatusColor = (status) => {
    const colors = { running: 'bg-green-100 text-green-800', paused: 'bg-yellow-100 text-yellow-800', completed: 'bg-blue-100 text-blue-800', draft: 'bg-gray-100 text-gray-800' };
    return colors[status] || colors.draft;
  };
  
  return (
    <div className="p-6 flex-1 overflow-y-auto">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold">Campaigns</h2>
        <button onClick={() => setShowCreate(true)} className="bg-purple-600 text-white px-4 py-2 rounded-lg">+ Create</button>
      </div>
      
      <div className="space-y-4">
        {campaigns.map(c => (
          <div key={c.id} className="bg-white p-6 rounded-lg shadow">
            <div className="flex justify-between items-start">
              <div>
                <h3 className="text-lg font-bold">{c.name}</h3>
                <p className="text-gray-600 text-sm">{c.description}</p>
              </div>
              <span className={`px-3 py-1 rounded-full text-sm font-medium ${getStatusColor(c.status)}`}>{c.status}</span>
            </div>
            
            {c.stats && (
              <div className="grid grid-cols-4 gap-4 my-4 bg-gray-50 p-3 rounded">
                <div className="text-center"><p className="text-2xl font-bold">{c.stats.total}</p><p className="text-xs text-gray-500">Total</p></div>
                <div className="text-center"><p className="text-2xl font-bold text-blue-600">{c.stats.sent}</p><p className="text-xs text-gray-500">Sent</p></div>
                <div className="text-center"><p className="text-2xl font-bold text-green-600">{c.stats.replied}</p><p className="text-xs text-gray-500">Replied</p></div>
                <div className="text-center"><p className="text-2xl font-bold text-gray-400">{c.stats.pending}</p><p className="text-xs text-gray-500">Pending</p></div>
              </div>
            )}
            
            <div className="text-sm text-gray-500 mb-4">
              📊 {c.messages_per_hour}/hour | ⏱️ {c.min_delay_seconds}-{c.max_delay_seconds}s | 
              🔄 {c.use_content_variation ? 'Variation ON' : 'OFF'} | 
              🏢 {c.business_hours_only ? 'Business Hours' : 'Any Time'}
            </div>
            
            <div className="flex gap-2">
              {c.status === 'draft' || c.status === 'paused' ? (
                <button onClick={() => api.startCampaign(c.id).then(loadCampaigns)} className="bg-green-600 text-white px-4 py-2 rounded">▶ Start</button>
              ) : c.status === 'running' ? (
                <button onClick={() => api.pauseCampaign(c.id).then(loadCampaigns)} className="bg-yellow-600 text-white px-4 py-2 rounded">⏸ Pause</button>
              ) : null}
              <button onClick={() => api.deleteCampaign(c.id).then(loadCampaigns)} className="bg-red-600 text-white px-4 py-2 rounded">Delete</button>
            </div>
          </div>
        ))}
      </div>
      
      {showCreate && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 overflow-y-auto">
          <div className="bg-white p-6 rounded-xl w-full max-w-2xl my-8">
            <h3 className="text-xl font-bold mb-4">Create Campaign</h3>
            <form onSubmit={handleCreate}>
              <div className="grid grid-cols-2 gap-4">
                <div className="col-span-2">
                  <label className="block text-sm font-bold mb-2">Name *</label>
                  <input type="text" value={newCampaign.name} onChange={e => setNewCampaign({...newCampaign, name: e.target.value})} className="w-full border px-3 py-2 rounded-lg" required />
                </div>
                <div className="col-span-2">
                  <label className="block text-sm font-bold mb-2">Message Template *</label>
                  <textarea value={newCampaign.message_template} onChange={e => setNewCampaign({...newCampaign, message_template: e.target.value})} className="w-full border px-3 py-2 rounded-lg h-24" placeholder="Hi, check out our offer..." required />
                </div>
                <div className="col-span-2">
                  <label className="block text-sm font-bold mb-2">Media File (Image/Video)</label>
                  <input type="file" accept="image/*,video/*" onChange={e => setSelectedMedia(e.target.files[0])} className="w-full border px-3 py-2 rounded-lg" />
                  {selectedMedia && <p className="text-sm text-green-600 mt-1">📎 {selectedMedia.name}</p>}
                </div>
                <div>
                  <label className="block text-sm font-bold mb-2">Target Tags</label>
                  <input type="text" value={newCampaign.target_tags} onChange={e => setNewCampaign({...newCampaign, target_tags: e.target.value})} className="w-full border px-3 py-2 rounded-lg" placeholder="customer, vip" />
                </div>
                <div>
                  <label className="block text-sm font-bold mb-2">Messages/Hour</label>
                  <input type="number" min="1" max="60" value={newCampaign.messages_per_hour} onChange={e => setNewCampaign({...newCampaign, messages_per_hour: parseInt(e.target.value)})} className="w-full border px-3 py-2 rounded-lg" />
                </div>
                <div>
                  <label className="block text-sm font-bold mb-2">Min Delay (sec)</label>
                  <input type="number" min="10" value={newCampaign.min_delay_seconds} onChange={e => setNewCampaign({...newCampaign, min_delay_seconds: parseInt(e.target.value)})} className="w-full border px-3 py-2 rounded-lg" />
                </div>
                <div>
                  <label className="block text-sm font-bold mb-2">Max Delay (sec)</label>
                  <input type="number" min="20" value={newCampaign.max_delay_seconds} onChange={e => setNewCampaign({...newCampaign, max_delay_seconds: parseInt(e.target.value)})} className="w-full border px-3 py-2 rounded-lg" />
                </div>
                <div className="col-span-2 flex gap-4">
                  <label className="flex items-center"><input type="checkbox" checked={newCampaign.business_hours_only} onChange={e => setNewCampaign({...newCampaign, business_hours_only: e.target.checked})} className="mr-2" /> Business Hours Only</label>
                  <label className="flex items-center"><input type="checkbox" checked={newCampaign.use_content_variation} onChange={e => setNewCampaign({...newCampaign, use_content_variation: e.target.checked})} className="mr-2" /> Anti-Ban Variation</label>
                </div>
              </div>
              <div className="flex justify-end gap-2 mt-6">
                <button type="button" onClick={() => setShowCreate(false)} className="px-4 py-2 text-gray-600">Cancel</button>
                <button type="submit" className="bg-purple-600 text-white px-4 py-2 rounded-lg">Create</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

// Analytics Panel
function AnalyticsPanel({ analytics }) {
  if (!analytics) return <div className="p-8">Loading...</div>;
  
  // Handle error case
  if (analytics.error) {
    return (
      <div className="p-6">
        <h2 className="text-2xl font-bold mb-6">Analytics</h2>
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
          Error loading analytics: {analytics.error}
        </div>
      </div>
    );
  }
  
  const { overview, stageDistribution } = analytics;
  
  return (
    <div className="p-6">
      <h2 className="text-2xl font-bold mb-6">Analytics</h2>
      <div className="grid grid-cols-4 gap-4 mb-6">
        <div className="bg-blue-50 rounded-lg p-4">
          <p className="text-sm text-gray-500">Total Users</p>
          <p className="text-2xl font-bold text-blue-600">{overview?.totalUsers || 0}</p>
        </div>
        <div className="bg-red-50 rounded-lg p-4">
          <p className="text-sm text-gray-500">Hot Leads</p>
          <p className="text-2xl font-bold text-red-600">{overview?.hotLeads || 0}</p>
        </div>
        <div className="bg-green-50 rounded-lg p-4">
          <p className="text-sm text-gray-500">Avg Score</p>
          <p className="text-2xl font-bold text-green-600">{overview?.avgConversionScore ? parseFloat(overview.avgConversionScore).toFixed(1) : '0.0'}%</p>
        </div>
        <div className="bg-purple-50 rounded-lg p-4">
          <p className="text-sm text-gray-500">Today's Messages</p>
          <p className="text-2xl font-bold text-purple-600">{overview?.todayMessages || 0}</p>
        </div>
      </div>
      
      <div className="bg-white rounded-lg shadow p-6">
        <h3 className="font-bold mb-4">Stage Distribution</h3>
        <div className="space-y-3">
          {Object.entries(stageDistribution || {}).map(([stage, count]) => (
            <div key={stage} className="flex items-center">
              <span className="w-20 capitalize">{stage}</span>
              <div className="flex-1 bg-gray-200 rounded-full h-4 mx-3">
                <div className={`h-4 rounded-full ${stage === 'hot' ? 'bg-red-500' : stage === 'warm' ? 'bg-yellow-500' : 'bg-gray-400'}`} 
                  style={{width: `${Math.max(5, (count / (overview?.totalUsers || 1)) * 100)}%`}} />
              </div>
              <span className="w-8">{count}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// AI Persona Engine
function PersonasPage() {
  const [personas, setPersonas] = React.useState([]);
  const [selectedPersona, setSelectedPersona] = React.useState(null);
  const [editMode, setEditMode] = React.useState(false);
  const [editData, setEditData] = React.useState({});
  const [showCreate, setShowCreate] = React.useState(false);
  const [newPersona, setNewPersona] = React.useState({ name: '', category: 'custom', icon: '🤖', description: '', system_prompt: '', temperature: 0.7 });
  const [showSimulator, setShowSimulator] = React.useState(false);
  const [testMessage, setTestMessage] = React.useState('');
  const [testResult, setTestResult] = React.useState(null);
  const [testLoading, setTestLoading] = React.useState(false);
  const [newRule, setNewRule] = React.useState('');
  const [activeSection, setActiveSection] = React.useState('prompt');
  
  React.useEffect(() => { loadPersonas(); }, []);
  
  const loadPersonas = async () => {
    try {
      const result = await api.getPersonas();
      if (result.success) setPersonas(result.data || []);
    } catch (e) { console.error('Failed to load personas:', e); }
  };
  
  const handleSelect = (persona) => {
    setSelectedPersona(persona);
    setEditData({ ...persona });
    setEditMode(false);
    setActiveSection('prompt');
  };
  
  const handleSave = async () => {
    try {
      await api.updatePersona(editData.id, {
        name: editData.name,
        description: editData.description,
        system_prompt: editData.system_prompt,
        temperature: editData.temperature,
        settings: {
          professionalism: editData.professionalism,
          humour: editData.humour,
          empathy: editData.empathy,
          emoji_level: editData.emoji_level,
          reply_length: editData.reply_length,
          creativity: editData.creativity,
          sales_focus: editData.sales_focus,
          confidence: editData.confidence,
          friendliness: editData.friendliness,
          assertiveness: editData.assertiveness
        }
      });
      setEditMode(false);
      loadPersonas();
    } catch (e) { alert('Save failed: ' + e.message); }
  };
  
  const handleCreate = async (e) => {
    e.preventDefault();
    try {
      await api.createPersona(newPersona);
      setShowCreate(false);
      setNewPersona({ name: '', category: 'custom', icon: '🤖', description: '', system_prompt: '', temperature: 0.7 });
      loadPersonas();
    } catch (e) { alert('Create failed: ' + e.message); }
  };
  
  const handleDelete = async (id) => {
    if (!confirm('Delete this persona?')) return;
    try {
      await api.deletePersona(id);
      if (selectedPersona?.id === id) setSelectedPersona(null);
      loadPersonas();
    } catch (e) { alert('Delete failed: ' + e.message); }
  };
  
  const handleTest = async () => {
    if (!testMessage.trim() || !selectedPersona) return;
    setTestLoading(true);
    try {
      const result = await api.testPersona(selectedPersona.id, testMessage);
      if (result.success) setTestResult(result.data);
    } catch (e) { setTestResult({ reply: 'Error: ' + e.message }); }
    setTestLoading(false);
  };
  
  const handleAddRule = async () => {
    if (!newRule.trim() || !selectedPersona) return;
    try {
      await api.addPersonaRule(selectedPersona.id, newRule, 5);
      setNewRule('');
      loadPersonas();
      // Refresh selected
      const result = await api.getPersona(selectedPersona.id);
      if (result.success) { setSelectedPersona(result.data); setEditData(result.data); }
    } catch (e) { alert('Failed to add rule'); }
  };
  
  const handleDeleteRule = async (ruleId) => {
    try {
      await api.deletePersonaRule(ruleId);
      loadPersonas();
      const result = await api.getPersona(selectedPersona.id);
      if (result.success) { setSelectedPersona(result.data); setEditData(result.data); }
    } catch (e) { alert('Failed to delete rule'); }
  };
  
  const sliderConfig = [
    { key: 'professionalism', label: '💼 Professionalism', color: '#3B82F6' },
    { key: 'humour', label: '😂 Humour', color: '#F59E0B' },
    { key: 'empathy', label: '💗 Empathy', color: '#EC4899' },
    { key: 'emoji_level', label: '😊 Emoji Level', color: '#8B5CF6' },
    { key: 'reply_length', label: '📝 Reply Length', color: '#10B981' },
    { key: 'creativity', label: '🎨 Creativity', color: '#6366F1' },
    { key: 'sales_focus', label: '💰 Sales Focus', color: '#EF4444' },
    { key: 'confidence', label: '💪 Confidence', color: '#F97316' },
    { key: 'friendliness', label: '🤗 Friendliness', color: '#14B8A6' },
    { key: 'assertiveness', label: '🎯 Assertiveness', color: '#8B5CF6' }
  ];
  
  const getCategoryColor = (cat) => {
    const colors = { personal: 'bg-pink-100 text-pink-800', business: 'bg-blue-100 text-blue-800', custom: 'bg-purple-100 text-purple-800', default: 'bg-gray-100 text-gray-800' };
    return colors[cat] || colors.custom;
  };
  
  return (
    <div className="flex-1 flex h-full overflow-hidden">
      {/* Persona List */}
      <div className="w-72 bg-white border-r flex flex-col">
        <div className="p-4 border-b">
          <div className="flex justify-between items-center mb-3">
            <h2 className="text-lg font-bold text-gray-800">🎭 AI Personas</h2>
            <button onClick={() => setShowCreate(true)} className="bg-blue-600 text-white px-3 py-1.5 rounded-lg text-sm font-medium hover:bg-blue-700">+ New</button>
          </div>
          <div className="flex gap-1">
            {['all', 'business', 'personal', 'custom'].map(f => (
              <button key={f} className="text-xs px-2 py-1 rounded capitalize bg-gray-100 hover:bg-gray-200 text-gray-700">{f}</button>
            ))}
          </div>
        </div>
        <div className="flex-1 overflow-y-auto">
          {personas.map(p => (
            <div key={p.id} onClick={() => handleSelect(p)}
              className={`p-3 border-b cursor-pointer hover:bg-gray-50 transition ${selectedPersona?.id === p.id ? 'bg-blue-50 border-l-4 border-l-blue-600' : ''}`}>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <span className="text-xl">{p.icon}</span>
                  <div>
                    <h3 className="font-semibold text-sm text-gray-800">{p.name}</h3>
                    <span className={`text-xs px-1.5 py-0.5 rounded ${getCategoryColor(p.category)}`}>{p.category}</span>
                  </div>
                </div>
                {p.is_builtin ? <span className="text-xs text-gray-400">Built-in</span> : null}
              </div>
            </div>
          ))}
        </div>
      </div>
      
      {/* Persona Detail */}
      {selectedPersona ? (
        <div className="flex-1 flex flex-col overflow-hidden">
          {/* Header */}
          <div className="bg-white border-b px-6 py-4">
            <div className="flex justify-between items-center">
              <div className="flex items-center gap-3">
                <span className="text-3xl">{selectedPersona.icon}</span>
                <div>
                  <h2 className="text-xl font-bold text-gray-800">{selectedPersona.name}</h2>
                  <p className="text-sm text-gray-500">{selectedPersona.description || 'No description'}</p>
                </div>
                <span className={`text-xs px-2 py-1 rounded-full ${getCategoryColor(selectedPersona.category)}`}>{selectedPersona.category}</span>
              </div>
              <div className="flex gap-2">
                <button onClick={() => setShowSimulator(true)} className="bg-green-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-green-700">🧪 Test</button>
                {editMode ? (
                  <>
                    <button onClick={handleSave} className="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-medium">💾 Save</button>
                    <button onClick={() => { setEditMode(false); setEditData({...selectedPersona}); }} className="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg text-sm">Cancel</button>
                  </>
                ) : (
                  <button onClick={() => setEditMode(true)} className="bg-yellow-500 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-yellow-600">✏️ Edit</button>
                )}
                {!selectedPersona.is_builtin && (
                  <button onClick={() => handleDelete(selectedPersona.id)} className="bg-red-500 text-white px-3 py-2 rounded-lg text-sm hover:bg-red-600">🗑️</button>
                )}
              </div>
            </div>
            {/* Section Tabs */}
            <div className="flex gap-2 mt-3">
              {[{id:'prompt',label:'📝 Prompt'},{id:'sliders',label:'🎚️ Sliders'},{id:'rules',label:'📋 Rules'},{id:'analytics',label:'📊 Analytics'}].map(s => (
                <button key={s.id} onClick={() => setActiveSection(s.id)}
                  className={`px-4 py-2 rounded-lg text-sm font-medium transition ${activeSection === s.id ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}>
                  {s.label}
                </button>
              ))}
            </div>
          </div>
          
          {/* Content */}
          <div className="flex-1 overflow-y-auto p-6 bg-gray-50">
            {/* Prompt Section */}
            {activeSection === 'prompt' && (
              <div className="space-y-4">
                <div className="bg-white rounded-xl p-6 shadow-sm">
                  <h3 className="font-bold text-gray-800 mb-3">System Prompt</h3>
                  {editMode ? (
                    <textarea value={editData.system_prompt || ''} onChange={e => setEditData({...editData, system_prompt: e.target.value})}
                      className="w-full h-48 border rounded-lg p-4 text-sm font-mono resize-y focus:ring-2 focus:ring-blue-500 focus:outline-none" />
                  ) : (
                    <div className="bg-gray-50 rounded-lg p-4 text-sm text-gray-700 whitespace-pre-wrap font-mono">{selectedPersona.system_prompt}</div>
                  )}
                </div>
                <div className="bg-white rounded-xl p-6 shadow-sm">
                  <h3 className="font-bold text-gray-800 mb-3">Settings</h3>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm text-gray-600">Temperature</label>
                      {editMode ? (
                        <input type="number" step="0.1" min="0" max="2" value={editData.temperature || 0.7}
                          onChange={e => setEditData({...editData, temperature: parseFloat(e.target.value)})}
                          className="w-full border rounded px-3 py-2 text-sm" />
                      ) : (
                        <p className="text-lg font-bold text-blue-600">{selectedPersona.temperature}</p>
                      )}
                    </div>
                    <div>
                      <label className="text-sm text-gray-600">Version</label>
                      <p className="text-lg font-bold text-gray-800">v{selectedPersona.version || 1}</p>
                    </div>
                  </div>
                </div>
              </div>
            )}
            
            {/* Sliders Section */}
            {activeSection === 'sliders' && (
              <div className="bg-white rounded-xl p-6 shadow-sm">
                <h3 className="font-bold text-gray-800 mb-4">🎚️ Behavior Sliders</h3>
                <div className="space-y-5">
                  {sliderConfig.map(s => (
                    <div key={s.key}>
                      <div className="flex justify-between items-center mb-1">
                        <label className="text-sm font-medium text-gray-700">{s.label}</label>
                        <span className="text-sm font-bold" style={{color: s.color}}>{editMode ? (editData[s.key] || 50) : (selectedPersona[s.key] || 50)}%</span>
                      </div>
                      <div className="relative">
                        <input type="range" min="0" max="100" 
                          value={editMode ? (editData[s.key] || 50) : (selectedPersona[s.key] || 50)}
                          onChange={e => editMode && setEditData({...editData, [s.key]: parseInt(e.target.value)})}
                          disabled={!editMode}
                          className="w-full h-2 rounded-lg appearance-none cursor-pointer"
                          style={{background: `linear-gradient(to right, ${s.color} ${editMode ? (editData[s.key] || 50) : (selectedPersona[s.key] || 50)}%, #E5E7EB ${editMode ? (editData[s.key] || 50) : (selectedPersona[s.key] || 50)}%)`}} />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
            
            {/* Rules Section */}
            {activeSection === 'rules' && (
              <div className="space-y-4">
                <div className="bg-white rounded-xl p-6 shadow-sm">
                  <h3 className="font-bold text-gray-800 mb-4">📋 Rules ({selectedPersona.rules?.length || 0})</h3>
                  <div className="space-y-2 mb-4">
                    {(selectedPersona.rules || []).map(rule => (
                      <div key={rule.id} className="flex items-center justify-between bg-gray-50 rounded-lg px-4 py-3">
                        <div className="flex items-center gap-2">
                          <span className="text-green-500">✅</span>
                          <span className="text-sm text-gray-700">{rule.rule_text}</span>
                        </div>
                        <button onClick={() => handleDeleteRule(rule.id)} className="text-red-400 hover:text-red-600 text-sm">✕</button>
                      </div>
                    ))}
                    {(!selectedPersona.rules || selectedPersona.rules.length === 0) && (
                      <p className="text-gray-400 text-sm text-center py-4">No rules defined yet</p>
                    )}
                  </div>
                  <div className="flex gap-2">
                    <input type="text" value={newRule} onChange={e => setNewRule(e.target.value)}
                      placeholder="Add a new rule..." className="flex-1 border rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                      onKeyDown={e => e.key === 'Enter' && handleAddRule()} />
                    <button onClick={handleAddRule} className="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-blue-700">+ Add</button>
                  </div>
                </div>
              </div>
            )}
            
            {/* Analytics Section */}
            {activeSection === 'analytics' && (
              <div className="bg-white rounded-xl p-6 shadow-sm">
                <h3 className="font-bold text-gray-800 mb-4">📊 Persona Overview</h3>
                <div className="grid grid-cols-3 gap-4">
                  <div className="bg-blue-50 rounded-xl p-4 text-center">
                    <p className="text-2xl font-bold text-blue-600">{selectedPersona.version || 1}</p>
                    <p className="text-xs text-gray-500">Version</p>
                  </div>
                  <div className="bg-green-50 rounded-xl p-4 text-center">
                    <p className="text-2xl font-bold text-green-600">{selectedPersona.rules?.length || 0}</p>
                    <p className="text-xs text-gray-500">Rules</p>
                  </div>
                  <div className="bg-purple-50 rounded-xl p-4 text-center">
                    <p className="text-2xl font-bold text-purple-600">{selectedPersona.temperature || 0.7}</p>
                    <p className="text-xs text-gray-500">Temperature</p>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      ) : (
        <div className="flex-1 flex items-center justify-center bg-gray-50">
          <div className="text-center">
            <p className="text-6xl mb-4">🎭</p>
            <h3 className="text-xl font-bold text-gray-700 mb-2">AI Persona Engine</h3>
            <p className="text-gray-500">Select a persona to configure or create a new one</p>
          </div>
        </div>
      )}
      
      {/* Create Modal */}
      {showCreate && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white p-6 rounded-xl w-[500px] max-h-[90vh] overflow-y-auto">
            <h3 className="text-xl font-bold mb-4">🎭 Create New Persona</h3>
            <form onSubmit={handleCreate}>
              <div className="space-y-3">
                <div className="flex gap-3">
                  <div className="w-20">
                    <label className="text-sm text-gray-600">Icon</label>
                    <input type="text" value={newPersona.icon} onChange={e => setNewPersona({...newPersona, icon: e.target.value})}
                      className="w-full border px-3 py-2 rounded text-2xl text-center" />
                  </div>
                  <div className="flex-1">
                    <label className="text-sm text-gray-600">Name</label>
                    <input type="text" value={newPersona.name} onChange={e => setNewPersona({...newPersona, name: e.target.value})}
                      className="w-full border px-3 py-2 rounded" placeholder="e.g., Coach" required />
                  </div>
                </div>
                <div>
                  <label className="text-sm text-gray-600">Category</label>
                  <select value={newPersona.category} onChange={e => setNewPersona({...newPersona, category: e.target.value})}
                    className="w-full border px-3 py-2 rounded">
                    <option value="personal">Personal</option>
                    <option value="business">Business</option>
                    <option value="custom">Custom</option>
                  </select>
                </div>
                <div>
                  <label className="text-sm text-gray-600">Description</label>
                  <input type="text" value={newPersona.description} onChange={e => setNewPersona({...newPersona, description: e.target.value})}
                    className="w-full border px-3 py-2 rounded" placeholder="Brief description..." />
                </div>
                <div>
                  <label className="text-sm text-gray-600">System Prompt</label>
                  <textarea value={newPersona.system_prompt} onChange={e => setNewPersona({...newPersona, system_prompt: e.target.value})}
                    className="w-full border px-3 py-2 rounded h-32 text-sm font-mono" placeholder="Define the AI personality..." required />
                </div>
                <div>
                  <label className="text-sm text-gray-600">Temperature ({newPersona.temperature})</label>
                  <input type="range" min="0" max="2" step="0.1" value={newPersona.temperature}
                    onChange={e => setNewPersona({...newPersona, temperature: parseFloat(e.target.value)})}
                    className="w-full" />
                </div>
              </div>
              <div className="flex justify-end gap-2 mt-4">
                <button type="button" onClick={() => setShowCreate(false)} className="px-4 py-2 text-gray-600">Cancel</button>
                <button type="submit" className="bg-blue-600 text-white px-4 py-2 rounded-lg font-medium">Create</button>
              </div>
            </form>
          </div>
        </div>
      )}
      
      {/* Simulator Modal */}
      {showSimulator && selectedPersona && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white p-6 rounded-xl w-[550px] max-h-[80vh] overflow-y-auto">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-xl font-bold">🧪 Persona Simulator</h3>
              <button onClick={() => { setShowSimulator(false); setTestResult(null); setTestMessage(''); }} className="text-gray-400 hover:text-gray-600 text-xl">✕</button>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 mb-4">
              <p className="text-sm"><strong>{selectedPersona.icon} {selectedPersona.name}</strong> — Temperature: {selectedPersona.temperature}</p>
            </div>
            <div className="flex gap-2 mb-4">
              <input type="text" value={testMessage} onChange={e => setTestMessage(e.target.value)}
                placeholder="Type a test message..." className="flex-1 border rounded-lg px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                onKeyDown={e => e.key === 'Enter' && handleTest()} />
              <button onClick={handleTest} disabled={testLoading}
                className="bg-green-600 text-white px-4 py-3 rounded-lg text-sm font-medium hover:bg-green-700 disabled:opacity-50">
                {testLoading ? '⏳' : '▶️ Send'}
              </button>
            </div>
            {testResult && (
              <div className="space-y-3">
                <div className="bg-blue-50 rounded-lg p-4">
                  <p className="text-sm font-medium text-blue-800 mb-1">🤖 AI Response ({testResult.persona_used})</p>
                  <p className="text-sm text-gray-800">{testResult.reply}</p>
                </div>
                {testResult.system_prompt_preview && (
                  <details className="bg-gray-50 rounded-lg p-3">
                    <summary className="text-xs text-gray-500 cursor-pointer">View Synthesized Prompt</summary>
                    <pre className="text-xs text-gray-600 mt-2 whitespace-pre-wrap">{testResult.system_prompt_preview}</pre>
                  </details>
                )}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

// Main App
function App() {
  const [user, setUser] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [chats, setChats] = React.useState([]);
  const [selectedChat, setSelectedChat] = React.useState(null);
  const [chatData, setChatData] = React.useState(null);
  const [status, setStatus] = React.useState({ connected: false });
  const [analytics, setAnalytics] = React.useState(null);
  const [activeTab, setActiveTab] = React.useState('chats');
  const [hotLeadsMode, setHotLeadsMode] = React.useState(false);
  const [showQRModal, setShowQRModal] = React.useState(false);
  
  // Update modal visibility based on status
  React.useEffect(() => {
    if (status.hasQR) {
      setShowQRModal(true);
    } else if (status.connected) {
      setShowQRModal(false);
    }
  }, [status.hasQR, status.connected]);
  
  // Check auth on mount
  React.useEffect(() => {
    const token = localStorage.getItem('token');
    const savedUsername = localStorage.getItem('username');
    if (token) {
      setUser({ username: savedUsername || 'admin' });
    }
    setLoading(false);
  }, []);
  
  // Load data when authenticated
  React.useEffect(() => {
    if (!user) return;
    
    const loadData = async () => {
      const [chatsRes, statusRes, analyticsRes] = await Promise.all([
        api.getChats(), api.getStatus(), api.getAnalytics()
      ]);
      if (chatsRes.success) setChats(chatsRes.data || []);
      if (statusRes.success) setStatus(statusRes.data || {});
      if (analyticsRes.success) setAnalytics(analyticsRes.data || null);
    };
    
    loadData();
    const interval = setInterval(loadData, 5000);
    return () => clearInterval(interval);
  }, [user]);
  
  // Load chat data
  React.useEffect(() => {
    if (!selectedChat) return;
    api.getChat(selectedChat).then(result => {
      if (result.success) setChatData(result.data);
    });
  }, [selectedChat]);
  
  const handleLogin = (userData) => {
    localStorage.setItem('username', userData.username);
    setUser({ username: userData.username });
  };
  
  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('username');
    setUser(null);
    setChats([]);
    setSelectedChat(null);
  };
  
  const handleSendMessage = async (text) => {
    if (!selectedChat) return;
    await api.sendMessage(selectedChat, text);
    const result = await api.getChat(selectedChat);
    if (result.success) setChatData(result.data);
  };
  
  const handleSelectChat = (userId, hotMode) => {
    setHotLeadsMode(hotMode);
    if (userId) setSelectedChat(userId);
  };

  const handleStartChatFromContact = (phone) => {
    let raw = String(phone || '').trim();
    if (raw.endsWith('@lid')) {
      setSelectedChat(raw);
      setActiveTab('chats');
      return;
    }
    let digits = raw.split('@')[0].replace(/[^0-9]/g, '');
    if (digits.startsWith('0') && digits.length === 11) {
      digits = digits.substring(1);
    }
    if (digits.length === 10) {
      digits = '91' + digits;
    }
    const jid = `${digits}@s.whatsapp.net`;
    setSelectedChat(jid);
    setActiveTab('chats');
  };

  const handleReconnect = async () => {
    try {
      await api.reconnect();
    } catch (e) {
      alert('Reconnect failed: ' + e.message);
    }
  };

  const handleLogoutBot = async () => {
    if (!confirm('Are you sure you want to log out of WhatsApp? This will clear your session.')) return;
    try {
      await api.logoutBot();
    } catch (e) {
      alert('Logout failed: ' + e.message);
    }
  };
  
  if (loading) return <div className="p-8">Loading...</div>;
  
  if (!user) {
    return <Login onLogin={handleLogin} />;
  }
  
  return (
    <div className="h-screen flex flex-col">
      <StatusBar 
        status={status} 
        user={user} 
        onLogout={handleLogout} 
        onReconnect={handleReconnect}
        onLogoutBot={handleLogoutBot}
      />
      {showQRModal && status.qrCode && (
        <QRModal qrCode={status.qrCode} onClose={() => setShowQRModal(false)} />
      )}
      <div className="flex-1 flex overflow-hidden">
        <Sidebar activeTab={activeTab} setActiveTab={setActiveTab} hasQR={status.hasQR} />
        <div className="flex-1 flex overflow-hidden">
          {activeTab === 'chats' && (
            <>
              <ChatList chats={chats} selectedChat={selectedChat} onSelect={handleSelectChat} hotLeadsMode={hotLeadsMode} />
              {selectedChat && chatData ? (
                <ChatWindow userId={selectedChat} messages={chatData.messages} memory={chatData.memory} onSend={handleSendMessage} />
              ) : (
                <div className="flex-1 flex items-center justify-center bg-gray-50">
                  <p className="text-gray-500">Select a chat</p>
                </div>
              )}
            </>
          )}
          {activeTab === 'contacts' && <ContactsPage onStartChat={handleStartChatFromContact} />}
          {activeTab === 'campaigns' && <CampaignsPage />}
          {activeTab === 'analytics' && <AnalyticsPanel analytics={analytics} />}
          {activeTab === 'personas' && <PersonasPage />}
        </div>
      </div>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);