// Inbox v2 — literal WhatsTeam spec. No invented labels, real tabs/status/copy.

// ===== i18n =====
const _lang = (() => {
  try {
    const q = new URLSearchParams(window.location.search).get('lang');
    const l = (q || (navigator.language||'en').slice(0,2)).toLowerCase();
    return ['en','es','pt','it','fr','de'].includes(l) ? l : 'en';
  } catch (e) { return 'en'; }
})();
const I18N = {
  en: {
    dashboard:'Dashboard', chats:'Chats', campaigns:'Campaigns', contacts:'Contacts', flows:'Automation Flows', analytics:'Analytics', files:'Files', developers:'Developers', settings:'Settings', help:'Help Center', searchTitle:'Search (SHIFT + F)', activity:'Activity', quick:'Quick Actions',
    inbox:'Inbox', views:'Views', departments:'Departments', labels:'Labels',
    allChats:'All Chats', unread:'Unread', pending:'Pending', assignedToMe:'Assigned to Me', unassigned:'Unassigned', mentions:'Mentions', scheduled:'Scheduled', starred:'Starred', groups:'Groups', channels:'Channels',
    archived:'Archived', blocked:'Blocked', trash:'Trash',
    search:'Search', typing:'Agent is typing…',
    clickEdit:'Click to edit contact',
    banner:'This chat was automatically assigned to you by the system',
    assignedSys:'Assigned to Alex Morgan', missedCall:'You had a missed call at 10:29',
    privateNote:'Private note',
    reply:'Reply', note:'Note', templates:'Templates', quickReplies:'Quick Replies',
    phReply:'Type your message here…', phNote:'Create a private note that only your team can see',
    emoji:'Emoji', bold:'Bold', italic:'Italic', quote:'Quote', strike:'Strikethrough',
    media:'Image / video', contact:'Contact', document:'Document', location:'Location',
    recordAudio:'Record audio', predictReply:'Predict reply', scheduleMsg:'Schedule message delivery', signature:'Message signature',
    toSend:'to send', send:'Send',
    customerProfile:'Customer Profile', edit:'Edit', information:'Information',
    lastMessage:'Last Message', chatType:'Chat type', personal:'Personal', country:'Country', languages:'Languages', english:'English', currency:'Currency', localTime:'Local time', status:'Status', active:'active',
    assignedTo:'Assigned to', assigned:'Assigned', auto:'Auto', department:'Department', firstMessage:'First message',
    notes:'Notes', notesPh:'Private notes about this contact', lastUpdateBy:'Last update by',
    createLabel:'Create label', closePanel:'Close info panel', aiCopilot:'AI Copilot',
    allNumbers:'All Numbers', combinedView:'Combined view', unreadTotal:'unread total',
    connectNumber:'Connect new number', manageNumbers:'Manage numbers',
    numbers:'Numbers', esc:'Esc'
  },
  es: {
    dashboard:'Panel', chats:'Chats', campaigns:'Campañas', contacts:'Contactos', flows:'Flujos de automatización', analytics:'Analítica', files:'Archivos', developers:'Desarrolladores', settings:'Ajustes', help:'Centro de ayuda', searchTitle:'Buscar (MAYÚS + F)', activity:'Actividad', quick:'Acciones rápidas',
    inbox:'Bandeja', views:'Vistas', departments:'Departamentos', labels:'Etiquetas',
    allChats:'Todos los chats', unread:'Sin leer', pending:'Pendientes', assignedToMe:'Asignados a mí', unassigned:'Sin asignar', mentions:'Menciones', scheduled:'Programados', starred:'Destacados', groups:'Grupos', channels:'Canales',
    archived:'Archivados', blocked:'Bloqueados', trash:'Papelera',
    search:'Buscar', typing:'El agente está escribiendo…',
    clickEdit:'Click para editar contacto',
    banner:'Este chat se te asignó automáticamente por el sistema',
    assignedSys:'Asignado a Alex Morgan', missedCall:'Tienes una llamada perdida a las 10:29',
    privateNote:'Nota privada',
    reply:'Responder', note:'Nota', templates:'Plantillas', quickReplies:'Respuestas rápidas',
    phReply:'Escribe tu mensaje aquí…', phNote:'Crea una nota privada que solo vea tu equipo',
    emoji:'Emoji', bold:'Negrita', italic:'Cursiva', quote:'Cita', strike:'Tachado',
    media:'Imagen / vídeo', contact:'Contacto', document:'Documento', location:'Ubicación',
    recordAudio:'Grabar audio', predictReply:'Predecir respuesta', scheduleMsg:'Programar envío', signature:'Firma',
    toSend:'para enviar', send:'Enviar',
    customerProfile:'Perfil del cliente', edit:'Editar', information:'Información',
    lastMessage:'Último mensaje', chatType:'Tipo de chat', personal:'Personal', country:'País', languages:'Idiomas', english:'Inglés', currency:'Moneda', localTime:'Hora local', status:'Estado', active:'activo',
    assignedTo:'Asignado a', assigned:'Asignado', auto:'Auto', department:'Departamento', firstMessage:'Primer mensaje',
    notes:'Notas', notesPh:'Notas privadas sobre este contacto', lastUpdateBy:'Última actualización por',
    createLabel:'Crear etiqueta', closePanel:'Cerrar panel', aiCopilot:'Copiloto IA',
    allNumbers:'Todos los números', combinedView:'Vista combinada', unreadTotal:'sin leer en total',
    connectNumber:'Conectar nuevo número', manageNumbers:'Gestionar números',
    numbers:'Números', esc:'Esc'
  },
  pt: {
    dashboard:'Painel', chats:'Conversas', campaigns:'Campanhas', contacts:'Contactos', flows:'Fluxos de automação', analytics:'Analytics', files:'Ficheiros', developers:'Programadores', settings:'Definições', help:'Centro de ajuda', searchTitle:'Pesquisar (SHIFT + F)', activity:'Atividade', quick:'Ações rápidas',
    inbox:'Caixa de entrada', views:'Vistas', departments:'Departamentos', labels:'Etiquetas',
    allChats:'Todas as conversas', unread:'Não lidas', pending:'Pendentes', assignedToMe:'Atribuídas a mim', unassigned:'Por atribuir', mentions:'Menções', scheduled:'Agendadas', starred:'Destacadas', groups:'Grupos', channels:'Canais',
    archived:'Arquivadas', blocked:'Bloqueadas', trash:'Lixo',
    search:'Pesquisar', typing:'O agente está a escrever…',
    clickEdit:'Clique para editar contacto',
    banner:'Esta conversa foi atribuída automaticamente pelo sistema',
    assignedSys:'Atribuída a Alex Morgan', missedCall:'Teve uma chamada perdida às 10:29',
    privateNote:'Nota privada',
    reply:'Responder', note:'Nota', templates:'Modelos', quickReplies:'Respostas rápidas',
    phReply:'Escreva a sua mensagem aqui…', phNote:'Crie uma nota privada que só a sua equipa vê',
    emoji:'Emoji', bold:'Negrito', italic:'Itálico', quote:'Citação', strike:'Rasurado',
    media:'Imagem / vídeo', contact:'Contacto', document:'Documento', location:'Localização',
    recordAudio:'Gravar áudio', predictReply:'Prever resposta', scheduleMsg:'Agendar envio', signature:'Assinatura',
    toSend:'para enviar', send:'Enviar',
    customerProfile:'Perfil do cliente', edit:'Editar', information:'Informação',
    lastMessage:'Última mensagem', chatType:'Tipo de conversa', personal:'Pessoal', country:'País', languages:'Idiomas', english:'Inglês', currency:'Moeda', localTime:'Hora local', status:'Estado', active:'ativo',
    assignedTo:'Atribuída a', assigned:'Atribuída', auto:'Auto', department:'Departamento', firstMessage:'Primeira mensagem',
    notes:'Notas', notesPh:'Notas privadas sobre este contacto', lastUpdateBy:'Última atualização por',
    createLabel:'Criar etiqueta', closePanel:'Fechar painel', aiCopilot:'Copiloto IA',
    allNumbers:'Todos os números', combinedView:'Vista combinada', unreadTotal:'não lidas no total',
    connectNumber:'Ligar novo número', manageNumbers:'Gerir números',
    numbers:'Números', esc:'Esc'
  },
  it: {
    dashboard:'Dashboard', chats:'Chat', campaigns:'Campagne', contacts:'Contatti', flows:'Flussi di automazione', analytics:'Analytics', files:'File', developers:'Sviluppatori', settings:'Impostazioni', help:'Centro assistenza', searchTitle:'Cerca (MAIUSC + F)', activity:'Attività', quick:'Azioni rapide',
    inbox:'Posta in arrivo', views:'Viste', departments:'Reparti', labels:'Etichette',
    allChats:'Tutte le chat', unread:'Non lette', pending:'In attesa', assignedToMe:'Assegnate a me', unassigned:'Non assegnate', mentions:'Menzioni', scheduled:'Programmate', starred:'Preferite', groups:'Gruppi', channels:'Canali',
    archived:'Archiviate', blocked:'Bloccate', trash:'Cestino',
    search:'Cerca', typing:'L\u2019agente sta scrivendo…',
    clickEdit:'Clicca per modificare contatto',
    banner:'Questa chat è stata assegnata automaticamente dal sistema',
    assignedSys:'Assegnata ad Alex Morgan', missedCall:'Hai una chiamata persa alle 10:29',
    privateNote:'Nota privata',
    reply:'Rispondi', note:'Nota', templates:'Modelli', quickReplies:'Risposte rapide',
    phReply:'Scrivi il tuo messaggio qui…', phNote:'Crea una nota privata visibile solo al tuo team',
    emoji:'Emoji', bold:'Grassetto', italic:'Corsivo', quote:'Citazione', strike:'Barrato',
    media:'Immagine / video', contact:'Contatto', document:'Documento', location:'Posizione',
    recordAudio:'Registra audio', predictReply:'Prevedi risposta', scheduleMsg:'Pianifica invio', signature:'Firma',
    toSend:'per inviare', send:'Invia',
    customerProfile:'Profilo cliente', edit:'Modifica', information:'Informazioni',
    lastMessage:'Ultimo messaggio', chatType:'Tipo di chat', personal:'Personale', country:'Paese', languages:'Lingue', english:'Inglese', currency:'Valuta', localTime:'Ora locale', status:'Stato', active:'attivo',
    assignedTo:'Assegnata a', assigned:'Assegnata', auto:'Auto', department:'Reparto', firstMessage:'Primo messaggio',
    notes:'Note', notesPh:'Note private su questo contatto', lastUpdateBy:'Ultimo aggiornamento di',
    createLabel:'Crea etichetta', closePanel:'Chiudi pannello', aiCopilot:'Copilota AI',
    allNumbers:'Tutti i numeri', combinedView:'Vista combinata', unreadTotal:'non lette totali',
    connectNumber:'Collega nuovo numero', manageNumbers:'Gestisci numeri',
    numbers:'Numeri', esc:'Esc'
  },
  fr: {
    dashboard:'Tableau de bord', chats:'Chats', campaigns:'Campagnes', contacts:'Contacts', flows:'Flux d\u2019automatisation', analytics:'Analytique', files:'Fichiers', developers:'Développeurs', settings:'Paramètres', help:'Centre d\u2019aide', searchTitle:'Rechercher (MAJ + F)', activity:'Activité', quick:'Actions rapides',
    inbox:'Boîte de réception', views:'Vues', departments:'Départements', labels:'Étiquettes',
    allChats:'Toutes les discussions', unread:'Non lues', pending:'En attente', assignedToMe:'Attribuées à moi', unassigned:'Non attribuées', mentions:'Mentions', scheduled:'Programmées', starred:'Favoris', groups:'Groupes', channels:'Canaux',
    archived:'Archivées', blocked:'Bloquées', trash:'Corbeille',
    search:'Rechercher', typing:'L\u2019agent est en train d\u2019écrire…',
    clickEdit:'Cliquer pour modifier le contact',
    banner:'Cette conversation vous a été attribuée automatiquement',
    assignedSys:'Attribuée à Alex Morgan', missedCall:'Appel manqué à 10 h 29',
    privateNote:'Note privée',
    reply:'Répondre', note:'Note', templates:'Modèles', quickReplies:'Réponses rapides',
    phReply:'Tapez votre message ici…', phNote:'Créer une note privée visible uniquement par votre équipe',
    emoji:'Emoji', bold:'Gras', italic:'Italique', quote:'Citation', strike:'Barré',
    media:'Image / vidéo', contact:'Contact', document:'Document', location:'Localisation',
    recordAudio:'Enregistrer audio', predictReply:'Prédire la réponse', scheduleMsg:'Programmer l\u2019envoi', signature:'Signature',
    toSend:'pour envoyer', send:'Envoyer',
    customerProfile:'Profil client', edit:'Modifier', information:'Informations',
    lastMessage:'Dernier message', chatType:'Type de chat', personal:'Personnel', country:'Pays', languages:'Langues', english:'Anglais', currency:'Devise', localTime:'Heure locale', status:'Statut', active:'actif',
    assignedTo:'Attribué à', assigned:'Attribué', auto:'Auto', department:'Département', firstMessage:'Premier message',
    notes:'Notes', notesPh:'Notes privées sur ce contact', lastUpdateBy:'Dernière mise à jour par',
    createLabel:'Créer une étiquette', closePanel:'Fermer le panneau', aiCopilot:'Copilote IA',
    allNumbers:'Tous les numéros', combinedView:'Vue combinée', unreadTotal:'non lus au total',
    connectNumber:'Connecter un nouveau numéro', manageNumbers:'Gérer les numéros',
    numbers:'Numéros', esc:'Échap'
  },
  de: {
    dashboard:'Dashboard', chats:'Chats', campaigns:'Kampagnen', contacts:'Kontakte', flows:'Automatisierungs-Flows', analytics:'Analytics', files:'Dateien', developers:'Entwickler', settings:'Einstellungen', help:'Hilfe-Center', searchTitle:'Suchen (UMSCHALT + F)', activity:'Aktivität', quick:'Schnellaktionen',
    inbox:'Posteingang', views:'Ansichten', departments:'Abteilungen', labels:'Labels',
    allChats:'Alle Chats', unread:'Ungelesen', pending:'Ausstehend', assignedToMe:'Mir zugewiesen', unassigned:'Nicht zugewiesen', mentions:'Erwähnungen', scheduled:'Geplant', starred:'Favoriten', groups:'Gruppen', channels:'Kanäle',
    archived:'Archiviert', blocked:'Blockiert', trash:'Papierkorb',
    search:'Suchen', typing:'Agent schreibt…',
    clickEdit:'Klicken, um Kontakt zu bearbeiten',
    banner:'Dieser Chat wurde automatisch vom System zugewiesen',
    assignedSys:'Alex Morgan zugewiesen', missedCall:'Sie haben um 10:29 einen Anruf verpasst',
    privateNote:'Private Notiz',
    reply:'Antworten', note:'Notiz', templates:'Vorlagen', quickReplies:'Schnellantworten',
    phReply:'Nachricht hier eingeben…', phNote:'Private Notiz erstellen, die nur Ihr Team sieht',
    emoji:'Emoji', bold:'Fett', italic:'Kursiv', quote:'Zitat', strike:'Durchgestrichen',
    media:'Bild / Video', contact:'Kontakt', document:'Dokument', location:'Standort',
    recordAudio:'Audio aufnehmen', predictReply:'Antwort vorhersagen', scheduleMsg:'Versand planen', signature:'Signatur',
    toSend:'zum Senden', send:'Senden',
    customerProfile:'Kundenprofil', edit:'Bearbeiten', information:'Informationen',
    lastMessage:'Letzte Nachricht', chatType:'Chat-Typ', personal:'Persönlich', country:'Land', languages:'Sprachen', english:'Englisch', currency:'Währung', localTime:'Ortszeit', status:'Status', active:'aktiv',
    assignedTo:'Zugewiesen an', assigned:'Zugewiesen', auto:'Auto', department:'Abteilung', firstMessage:'Erste Nachricht',
    notes:'Notizen', notesPh:'Private Notizen zu diesem Kontakt', lastUpdateBy:'Letzte Aktualisierung von',
    createLabel:'Label erstellen', closePanel:'Panel schließen', aiCopilot:'AI-Copilot',
    allNumbers:'Alle Nummern', combinedView:'Kombinierte Ansicht', unreadTotal:'ungelesen insgesamt',
    connectNumber:'Neue Nummer verbinden', manageNumbers:'Nummern verwalten',
    numbers:'Nummern', esc:'Esc'
  }
};
const T = (k) => (I18N[_lang] && I18N[_lang][k]) || I18N.en[k] || k;

// ===== Industry verticals =====
const _vertical = (() => {
  try {
    const v = new URLSearchParams(window.location.search).get('vertical');
    return ['service','ecom','dental','msp','hospitality','default'].includes(v) ? v : 'default';
  } catch (e) { return 'default'; }
})();

const VERTICALS = {
  default: {
    chatList: [
      { id:'m1', name:'Marcus Johnson', initials:'MJ', avBg:'#f59e0b', time:'2m ago', tick:'read', typing:false, preview:'Could you confirm the correct webhook URL for production?', unread:2, state:'active-s', stateIco:'fa-user', flags:['pin'], labels:[{n:'Label name',c:'#3b82f6'}], active:true },
      { id:'m2', name:'Sarah Chen', initials:'SC', avBg:'#ec4899', time:'12m ago', tick:'delivered', typing:true, preview:null, unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[] },
      { id:'m3', name:'Emily Rodriguez', initials:'ER', avBg:'#3b82f6', time:'24m ago', tick:null, typing:false, preview:{type:'mtype',text:'Audio (4:32)',icon:'fa-microphone'}, unread:1, state:'pending', stateIco:'fa-clock', flags:[], labels:[{n:'Label name',c:'#8b5cf6'}] },
      { id:'m4', name:'David Park', initials:'DP', avBg:'#64748b', time:'43m ago', tick:'sent', typing:false, preview:{type:'mtype',text:'Template message'}, unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[] },
      { id:'m5', name:'Lisa Anderson', initials:'LA', avBg:'#06b6d4', time:'1h ago', tick:'read', typing:false, preview:{type:'mtype',text:'Image'}, unread:0, state:'resolved', stateIco:'fa-check-circle', flags:[], labels:[] },
      { id:'m6', name:'Support Group', initials:'SG', avBg:'#22c55e', time:'2h ago', tick:null, typing:false, preview:'James: Perfect, appreciate the quick response!', unread:5, state:'active-s', stateIco:'fa-users', flags:['mute'], labels:[{n:'Label name',c:'#22c55e'}] },
      { id:'m7', name:'+34 642 659 656', initials:'?', avBg:'#94a3b8', time:'3h ago', tick:null, typing:false, preview:{type:'mtype',text:'Contact card (2)'}, unread:0, state:'pending', stateIco:'fa-clock', flags:[], labels:[] },
      { id:'m8', name:'Marcus Johnson', initials:'MJ', avBg:'#f59e0b', time:'3h ago', tick:'read', typing:false, preview:{type:'mtype',text:'List message'}, unread:0, state:'resolved', stateIco:'fa-check-circle', flags:[], labels:[] },
      { id:'m9', name:'David Park', initials:'DP', avBg:'#64748b', time:'1d ago', tick:'err', typing:false, preview:'The dashboard is loading very slowly today…', unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[] }
    ],
    departments: [
      { id:'d1', name:'Support',    rgb:'34,197,94',   icon:'fa-headset',             count:14 },
      { id:'d2', name:'Sales',      rgb:'59,130,246',  icon:'fa-handshake',           count:6 },
      { id:'d3', name:'Billing',    rgb:'139,92,246',  icon:'fa-file-invoice-dollar', count:2 }
    ],
    labels: [
      { id:'l1', name:'Label name', rgb:'234,179,8',   count:7 },
      { id:'l2', name:'Label name', rgb:'239,68,68',   count:3 },
      { id:'l3', name:'Label name', rgb:'16,185,129',  count:11 }
    ],
    active: { initials:'MJ', avBg:'#f59e0b', name:'Marcus Johnson', phone:'+1 555 064 3210', flag:'🇺🇸', country:'United States', languages:'English', currency:'USD', department:'Support', deptColor:'#22c55e', deptIcon:'fa-headset' },
    thread: [
      { t:'in',  text:'I need help with setting up the new API integration. The documentation mentions webhook endpoints, but I\u2019m not sure which URL to use for production.', time:'10:28' },
      { t:'in',  text:'Could you confirm the correct webhook URL for the production environment?', time:'10:28' },
      { t:'sys', kind:'missedCall' },
      { t:'out', textHtml:'Hi Marcus — for production, use <b>https://api.yourcompany.com/webhooks/v2</b>. Authenticate with your production API key from the dashboard settings.', time:'10:30', tick:'✓✓' },
      { t:'note', text:'FYI customer is on the Enterprise plan — should route via the priority queue.', time:'10:30' },
      { t:'in',  quote:{ qa:'Alex Morgan', text:'Hi Marcus — for production, use https://api…' }, text:'Also, what\u2019s the timeout for the handler?', time:'10:31', reactions:'👍 2' },
      { t:'audio', dur:'1:24', time:'10:32', tick:'✓✓' },
      { t:'in',  text:'Thank you! That solved my issue completely.', time:'10:34' }
    ]
  },
  service: {
    chatList: [
      { id:'s1', name:'Maria García', initials:'MG', avBg:'#ef4444', time:'2m ago', tick:null,       typing:false, preview:'What time will the technician arrive? Water is still leaking 😰', unread:3, state:'active-s', stateIco:'fa-user', flags:['pin'], labels:[{n:'URGENT',c:'#ef4444'}], active:true },
      { id:'s2', name:'Tom Wilson',   initials:'TW', avBg:'#f59e0b', time:'9m ago', tick:'delivered', typing:true,  preview:null, unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[{n:'Quote sent',c:'#3b82f6'}] },
      { id:'s3', name:'Oakwood HOA',  initials:'OH', avBg:'#22c55e', time:'18m ago', tick:null,      typing:false, preview:'Can you confirm tomorrow at 9am for the AC service?', unread:1, state:'pending', stateIco:'fa-clock', flags:[], labels:[{n:'Recurring',c:'#8b5cf6'}] },
      { id:'s4', name:'Jennifer Park',initials:'JP', avBg:'#3b82f6', time:'32m ago', tick:'sent',    typing:false, preview:{type:'mtype',text:'Photo'}, unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[] },
      { id:'s5', name:'Davis Family', initials:'DF', avBg:'#06b6d4', time:'1h ago',  tick:'read',    typing:false, preview:'Tech arrived, everything fixed. Thank you!', unread:0, state:'resolved', stateIco:'fa-check-circle', flags:[], labels:[] },
      { id:'s6', name:'Apt 4B - Ruiz',initials:'AR', avBg:'#64748b', time:'2h ago',  tick:'read',    typing:false, preview:'Estimate approved, when can you start?', unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[{n:'Quote sent',c:'#3b82f6'}] },
      { id:'s7', name:'El Sol Restaurant', initials:'ES', avBg:'#f97316', time:'3h ago', tick:null, typing:false, preview:'Walk-in freezer alarm — urgent!', unread:2, state:'pending', stateIco:'fa-clock', flags:[], labels:[{n:'URGENT',c:'#ef4444'}] },
      { id:'s8', name:'Westfield Mall',initials:'WM', avBg:'#8b5cf6', time:'5h ago',  tick:'read',   typing:false, preview:{type:'mtype',text:'Invoice #2891'}, unread:0, state:'resolved', stateIco:'fa-check-circle', flags:[], labels:[] },
      { id:'s9', name:'+1 415 555 0199', initials:'?', avBg:'#94a3b8', time:'1d ago', tick:null,     typing:false, preview:'New lead — kitchen remodel', unread:0, state:'pending', stateIco:'fa-clock', flags:[], labels:[] }
    ],
    departments: [
      { id:'d1', name:'Dispatch',   rgb:'239,68,68',   icon:'fa-truck',           count:9 },
      { id:'d2', name:'Estimates',  rgb:'59,130,246',  icon:'fa-file-invoice',    count:5 },
      { id:'d3', name:'Billing',    rgb:'139,92,246',  icon:'fa-dollar-sign',     count:2 }
    ],
    labels: [
      { id:'l1', name:'URGENT',      rgb:'239,68,68',  count:4 },
      { id:'l2', name:'Quote sent',  rgb:'59,130,246', count:11 },
      { id:'l3', name:'Recurring',   rgb:'139,92,246', count:7 }
    ],
    active: { initials:'MG', avBg:'#ef4444', name:'Maria García', phone:'+1 415 555 0142', flag:'🇺🇸', country:'Oakland, CA', languages:'English · Spanish', currency:'USD', department:'Dispatch', deptColor:'#ef4444', deptIcon:'fa-truck' },
    thread: [
      { t:'in',  text:'Hola, my kitchen sink is leaking really bad. Water under the cabinet. 😰', time:'10:24' },
      { t:'in',  text:'I shut off the valve but it\u2019s still dripping. Is someone coming today??', time:'10:25' },
      { t:'sys', kind:'missedCall' },
      { t:'out', textHtml:'Hi Maria — I\u2019ve dispatched <b>Carlos</b> to your address. ETA <b>35–45 min</b>. He\u2019ll call before arrival.', time:'10:28', tick:'✓✓' },
      { t:'note', text:'Recurring customer — last service Oct 14. On priority tier. Dog friendly 🐕.', time:'10:29' },
      { t:'in',  text:'🙏 Thank you so much. Same technician that came last time?', time:'10:30', reactions:'❤️ 1' },
      { t:'out', textHtml:'Yes, same one 👍 He has the access code from last visit.', time:'10:31', tick:'✓✓' },
      { t:'in',  text:'Perfect. I\u2019ll be waiting at the door.', time:'10:32' }
    ]
  },
  ecom: {
    chatList: [
      { id:'e1', name:'Sarah Chen',    initials:'SC', avBg:'#ec4899', time:'3m ago', tick:'read', typing:false, preview:'Where is my order #4872? Tracking shows delivered but nothing arrived', unread:2, state:'active-s', stateIco:'fa-user', flags:['pin'], labels:[{n:'Order issue',c:'#ef4444'},{n:'VIP',c:'#eab308'}], active:true },
      { id:'e2', name:'Emma Davis',    initials:'ED', avBg:'#8b5cf6', time:'11m ago', tick:'delivered', typing:true, preview:null, unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[{n:'Return',c:'#f59e0b'}] },
      { id:'e3', name:'Marcus Thompson', initials:'MT', avBg:'#22c55e', time:'22m ago', tick:null, typing:false, preview:'Do you have size M in green? Saw the preorder page', unread:1, state:'pending', stateIco:'fa-clock', flags:[], labels:[{n:'Pre-order',c:'#3b82f6'}] },
      { id:'e4', name:'Priya Patel',   initials:'PP', avBg:'#f59e0b', time:'40m ago', tick:'read', typing:false, preview:{type:'mtype',text:'Image'}, unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[{n:'Order issue',c:'#ef4444'}] },
      { id:'e5', name:'James O\u2019Brien', initials:'JO', avBg:'#06b6d4', time:'1h ago', tick:'read', typing:false, preview:'Got the refund, thanks!', unread:0, state:'resolved', stateIco:'fa-check-circle', flags:[], labels:[] },
      { id:'e6', name:'Lisa Rodríguez',initials:'LR', avBg:'#ef4444', time:'2h ago',  tick:'read',   typing:false, preview:'Can I change the shipping address for order #4850?', unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[] },
      { id:'e7', name:'Hannah Müller', initials:'HM', avBg:'#64748b', time:'3h ago',  tick:null,     typing:false, preview:'Will this ship to Berlin?', unread:2, state:'pending', stateIco:'fa-clock', flags:[], labels:[{n:'International',c:'#8b5cf6'}] },
      { id:'e8', name:'David Kim',     initials:'DK', avBg:'#3b82f6', time:'5h ago',  tick:'read',   typing:false, preview:{type:'mtype',text:'Order #4812'}, unread:0, state:'resolved', stateIco:'fa-check-circle', flags:[], labels:[] },
      { id:'e9', name:'+34 699 123 456', initials:'?', avBg:'#94a3b8', time:'1d ago', tick:null,     typing:false, preview:'Hola, is the discount code still valid?', unread:0, state:'pending', stateIco:'fa-clock', flags:[], labels:[] }
    ],
    departments: [
      { id:'d1', name:'Support',    rgb:'34,197,94',   icon:'fa-headset',     count:18 },
      { id:'d2', name:'Shipping',   rgb:'59,130,246',  icon:'fa-shipping-fast', count:7 },
      { id:'d3', name:'Returns',    rgb:'239,68,68',   icon:'fa-undo',        count:4 }
    ],
    labels: [
      { id:'l1', name:'Order issue', rgb:'239,68,68',  count:6 },
      { id:'l2', name:'VIP',         rgb:'234,179,8',  count:12 },
      { id:'l3', name:'Pre-order',   rgb:'59,130,246', count:9 }
    ],
    active: { initials:'SC', avBg:'#ec4899', name:'Sarah Chen', phone:'+1 213 555 0188', flag:'🇺🇸', country:'Los Angeles, CA', languages:'English', currency:'USD', department:'Support', deptColor:'#22c55e', deptIcon:'fa-headset' },
    thread: [
      { t:'in',  text:'Hi! I ordered #4872 last Monday and the tracking says it was delivered yesterday but my package is not here 😩', time:'10:22' },
      { t:'in',  text:'I\u2019ve checked with neighbors too. Can you help?', time:'10:22' },
      { t:'out', textHtml:'Hi Sarah — I see order <b>#4872</b> ($189.50, 3 items) with UPS, marked delivered 11:42am. Let me open a trace with the carrier right now.', time:'10:24', tick:'✓✓' },
      { t:'note', text:'VIP customer — LTV $4,120. Priority handling, approve replacement if UPS can\u2019t locate in 24h.', time:'10:25' },
      { t:'in',  text:'Thank you 🙏 I really need those earrings for Friday', time:'10:26', reactions:'👍 1' },
      { t:'out', textHtml:'Totally understand. If UPS doesn\u2019t resolve today I\u2019ll ship a replacement <b>overnight at no cost</b>. You\u2019ll have it before Friday.', time:'10:27', tick:'✓✓' },
      { t:'in',  text:'You\u2019re the best 💚', time:'10:28' }
    ]
  },
  dental: {
    chatList: [
      { id:'d1', name:'Rodríguez Family',initials:'RF', avBg:'#3b82f6', time:'4m ago', tick:'read', typing:false, preview:'Confirming Tuesday 2pm cleaning with Dr. Smith for Emma', unread:1, state:'active-s', stateIco:'fa-user', flags:['pin'], labels:[{n:'Dr. Smith',c:'#3b82f6'},{n:'Hygiene',c:'#06b6d4'}], active:true },
      { id:'d2', name:'Robert Johnson',  initials:'RJ', avBg:'#ef4444', time:'14m ago', tick:null,  typing:true, preview:null, unread:0, state:'pending', stateIco:'fa-clock', flags:[], labels:[{n:'Emergency',c:'#ef4444'}] },
      { id:'d3', name:'Emily Patel',     initials:'EP', avBg:'#22c55e', time:'28m ago', tick:'delivered', typing:false, preview:'Need to reschedule my crown appointment', unread:2, state:'active-s', stateIco:'fa-user', flags:[], labels:[{n:'Dr. Johnson',c:'#22c55e'}] },
      { id:'d4', name:'David Kim',       initials:'DK', avBg:'#64748b', time:'45m ago', tick:'read', typing:false, preview:'Question about insurance coverage for implants', unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[{n:'Billing',c:'#8b5cf6'}] },
      { id:'d5', name:'Martha Williams', initials:'MW', avBg:'#f59e0b', time:'1h ago',  tick:'read', typing:false, preview:'Tooth pain getting worse since yesterday 😣', unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[{n:'Emergency',c:'#ef4444'}] },
      { id:'d6', name:'Thomas Anderson', initials:'TA', avBg:'#ec4899', time:'2h ago',  tick:'read', typing:false, preview:'Thanks for the reminder! See you tomorrow 10am', unread:0, state:'resolved', stateIco:'fa-check-circle', flags:[], labels:[] },
      { id:'d7', name:'Olivia Brown',    initials:'OB', avBg:'#8b5cf6', time:'4h ago',  tick:null,  typing:false, preview:'Reminder: cleaning Friday 3pm', unread:0, state:'pending', stateIco:'fa-clock', flags:[], labels:[{n:'Hygiene',c:'#06b6d4'}] },
      { id:'d8', name:'James Carter',    initials:'JC', avBg:'#06b6d4', time:'6h ago',  tick:'read', typing:false, preview:{type:'mtype',text:'X-ray image'}, unread:0, state:'resolved', stateIco:'fa-check-circle', flags:[], labels:[] },
      { id:'d9', name:'Ana Fernández',   initials:'AF', avBg:'#f97316', time:'1d ago',  tick:'read', typing:false, preview:'Gracias por la cita de ayer', unread:0, state:'resolved', stateIco:'fa-check-circle', flags:[], labels:[] }
    ],
    departments: [
      { id:'d1', name:'Reception',     rgb:'34,197,94',   icon:'fa-user-nurse',    count:12 },
      { id:'d2', name:'Dr. Smith',     rgb:'59,130,246',  icon:'fa-tooth',         count:6 },
      { id:'d3', name:'Dr. Johnson',   rgb:'34,197,94',   icon:'fa-tooth',         count:5 }
    ],
    labels: [
      { id:'l1', name:'Emergency',  rgb:'239,68,68',  count:3 },
      { id:'l2', name:'Hygiene',    rgb:'6,182,212',  count:14 },
      { id:'l3', name:'Billing',    rgb:'139,92,246', count:4 }
    ],
    active: { initials:'RF', avBg:'#3b82f6', name:'Rodríguez Family', phone:'+1 646 555 0137', flag:'🇺🇸', country:'Brooklyn, NY', languages:'English · Spanish', currency:'USD', department:'Dr. Smith', deptColor:'#3b82f6', deptIcon:'fa-tooth' },
    thread: [
      { t:'in',  text:'Hi, this is Carmen Rodríguez — confirming Emma\u2019s cleaning Tuesday at 2pm with Dr. Smith', time:'10:20' },
      { t:'out', textHtml:'Hi Carmen — confirmed ✅ <b>Emma, Tuesday Nov 5, 2:00 PM with Dr. Smith</b>. We\u2019ll see you then.', time:'10:21', tick:'✓✓' },
      { t:'note', text:'Emma is 8yo, last visit 6mo ago, insurance: MetLife PPO covered. Parent prefers afternoon slots.', time:'10:22' },
      { t:'in',  text:'Thanks! And can I also book a cleaning for my son Diego? Same day if possible 🙏', time:'10:23', reactions:'👍 1' },
      { t:'out', textHtml:'Let me check… Dr. Smith has <b>3:00 PM</b> available right after Emma. Want me to book it?', time:'10:24', tick:'✓✓' },
      { t:'in',  text:'Yes please! Perfect', time:'10:25' },
      { t:'out', textHtml:'Booked ✅ Reminder will go out Monday. Parking validated as usual 🅿️', time:'10:26', tick:'✓✓' }
    ]
  },
  msp: {
    chatList: [
      { id:'p1', name:'Acme Corp - John',  initials:'AC', avBg:'#ef4444', time:'1m ago', tick:null, typing:false, preview:'Server down, production site throwing 500. Need help ASAP', unread:4, state:'active-s', stateIco:'fa-exclamation-triangle', flags:['pin'], labels:[{n:'P1 Critical',c:'#ef4444'}], active:true },
      { id:'p2', name:'TechFirm IT - Amy', initials:'TF', avBg:'#f59e0b', time:'8m ago', tick:'delivered', typing:true, preview:null, unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[{n:'P2 High',c:'#f59e0b'}] },
      { id:'p3', name:'Global Mfg - Karl', initials:'GM', avBg:'#3b82f6', time:'24m ago', tick:'read', typing:false, preview:'Can\u2019t login to VPN from home office', unread:1, state:'pending', stateIco:'fa-clock', flags:[], labels:[{n:'P3 Normal',c:'#3b82f6'}] },
      { id:'p4', name:'Smith & Co Law',    initials:'SC', avBg:'#8b5cf6', time:'41m ago', tick:'read', typing:false, preview:'Printer offline again in boardroom', unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[{n:'P3 Normal',c:'#3b82f6'}] },
      { id:'p5', name:'Harbor Logistics',  initials:'HL', avBg:'#22c55e', time:'1h ago',  tick:'read', typing:false, preview:'Onboard 2 new employees for Monday — accounts, email, laptop', unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[] },
      { id:'p6', name:'Green Dental PLLC', initials:'GD', avBg:'#06b6d4', time:'2h ago',  tick:'read', typing:false, preview:'All good now, thanks for the quick fix!', unread:0, state:'resolved', stateIco:'fa-check-circle', flags:[], labels:[] },
      { id:'p7', name:'BlueStone Realty',  initials:'BS', avBg:'#64748b', time:'3h ago',  tick:'delivered', typing:false, preview:'Invoice question on Oct statement', unread:0, state:'pending', stateIco:'fa-clock', flags:[], labels:[{n:'Billing',c:'#8b5cf6'}] },
      { id:'p8', name:'Alpha Finance',     initials:'AF', avBg:'#ec4899', time:'5h ago',  tick:'read', typing:false, preview:{type:'mtype',text:'Ticket #INC-4871 resolved'}, unread:0, state:'resolved', stateIco:'fa-check-circle', flags:[], labels:[] },
      { id:'p9', name:'Northline Clinics', initials:'NC', avBg:'#f97316', time:'1d ago',  tick:'read', typing:false, preview:'Monthly report received, thank you', unread:0, state:'resolved', stateIco:'fa-check-circle', flags:[], labels:[] }
    ],
    departments: [
      { id:'d1', name:'L1 Support',   rgb:'34,197,94',   icon:'fa-headset',      count:11 },
      { id:'d2', name:'L2 Support',   rgb:'59,130,246',  icon:'fa-user-shield',  count:5 },
      { id:'d3', name:'NOC',          rgb:'239,68,68',   icon:'fa-server',       count:2 }
    ],
    labels: [
      { id:'l1', name:'P1 Critical', rgb:'239,68,68',  count:1 },
      { id:'l2', name:'P2 High',     rgb:'245,158,11', count:3 },
      { id:'l3', name:'P3 Normal',   rgb:'59,130,246', count:8 }
    ],
    active: { initials:'AC', avBg:'#ef4444', name:'Acme Corp - John Miller', phone:'+1 212 555 0144', flag:'🇺🇸', country:'New York, NY', languages:'English', currency:'USD', department:'NOC', deptColor:'#ef4444', deptIcon:'fa-server' },
    thread: [
      { t:'in',  text:'Hey our production site is throwing 500 errors. This is a P1, can you jump on ASAP?', time:'10:19' },
      { t:'in',  text:'Sales team can\u2019t process orders. We\u2019re bleeding revenue every minute 🔥', time:'10:19' },
      { t:'out', textHtml:'John — opened <b>INC-4892</b> in ConnectWise, P1 escalation. NOC is on the bridge now. Checking DB + webserver health.', time:'10:20', tick:'✓✓' },
      { t:'note', text:'Contract SLA: P1 response 15min / resolution 4h. Account owner: Mike. Last outage Sep 12 was MySQL replication.', time:'10:21' },
      { t:'in',  text:'Thanks. Keep me posted every few min please', time:'10:22', reactions:'👍 1' },
      { t:'out', textHtml:'<b>Update:</b> MySQL primary at 98% CPU, failing over to replica now. ETA recovery 3–5 min.', time:'10:24', tick:'✓✓' },
      { t:'out', textHtml:'✅ Failover complete. Site is back. Root cause analysis + postmortem will be in your inbox by EOD.', time:'10:28', tick:'✓✓' },
      { t:'in',  text:'🙌 appreciate the speed. You guys are the reason I don\u2019t hire internal IT', time:'10:29' }
    ]
  },
  hospitality: {
    chatList: [
      { id:'h1', name:'Rodríguez Family', initials:'RF', avBg:'#3b82f6', time:'2m ago', tick:'read', typing:false, preview:'Confirming Tuesday 2pm check-in at Villa Marina', unread:1, state:'active-s', stateIco:'fa-user', flags:['pin'], labels:[{n:'Check-in today',c:'#22c55e'},{n:'Reception',c:'#3b82f6'}], active:true },
      { id:'h2', name:'Sophie Turner', initials:'ST', avBg:'#ec4899', time:'12m ago', tick:'delivered', typing:true, preview:null, unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[{n:'Reception',c:'#3b82f6'}] },
      { id:'h3', name:'Marco Rossi', initials:'MR', avBg:'#f59e0b', time:'24m ago', tick:null, typing:false, preview:'What\u2019s the wifi password?', unread:1, state:'pending', stateIco:'fa-clock', flags:[], labels:[{n:'FAQ',c:'#06b6d4'}] },
      { id:'h4', name:'Anna Schmidt', initials:'AS', avBg:'#ef4444', time:'1h ago', tick:null, typing:false, preview:'No hot water in apartment 3 🚿', unread:3, state:'active-s', stateIco:'fa-exclamation-triangle', flags:['pin'], labels:[{n:'Maintenance',c:'#f59e0b'},{n:'Urgent',c:'#ef4444'}] },
      { id:'h5', name:'Luis Mendez', initials:'LM', avBg:'#22c55e', time:'2h ago', tick:'read', typing:false, preview:'Late check-in, arriving at 11pm', unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[{n:'Reception',c:'#3b82f6'}] },
      { id:'h6', name:'Turno Cleaner', initials:'TC', avBg:'#8b5cf6', time:'3h ago', tick:'read', typing:false, preview:'Done with unit 5A, moving on to 3B', unread:0, state:'active-s', stateIco:'fa-user', flags:[], labels:[{n:'Housekeeping',c:'#f59e0b'}] },
      { id:'h7', name:'Hannah Weber', initials:'HW', avBg:'#06b6d4', time:'4h ago', tick:'read', typing:false, preview:{type:'mtype',text:'Photo — dirty linens'}, unread:0, state:'pending', stateIco:'fa-clock', flags:[], labels:[{n:'Housekeeping',c:'#f59e0b'}] },
      { id:'h8', name:'James O\u2019Connor', initials:'JO', avBg:'#64748b', time:'6h ago', tick:'read', typing:false, preview:'Thanks for the late checkout! 🙏', unread:0, state:'resolved', stateIco:'fa-check-circle', flags:[], labels:[] },
      { id:'h9', name:'+34 612 345 999', initials:'?', avBg:'#94a3b8', time:'1d ago', tick:null, typing:false, preview:'Do you have airport transfer?', unread:0, state:'pending', stateIco:'fa-clock', flags:[], labels:[{n:'FAQ',c:'#06b6d4'}] }
    ],
    departments: [
      { id:'d1', name:'Reception',       rgb:'59,130,246',  icon:'fa-concierge-bell', count:6 },
      { id:'d2', name:'Housekeeping',    rgb:'245,158,11',  icon:'fa-broom',          count:3 },
      { id:'d3', name:'Maintenance',     rgb:'239,68,68',   icon:'fa-tools',          count:2 },
      { id:'d4', name:'Guest Relations', rgb:'139,92,246',  icon:'fa-hands-helping',  count:4 }
    ],
    labels: [
      { id:'l1', name:'Check-in today', rgb:'34,197,94',   count:5 },
      { id:'l2', name:'Urgent',         rgb:'239,68,68',   count:2 },
      { id:'l3', name:'FAQ',            rgb:'6,182,212',   count:12 },
      { id:'l4', name:'Complaint',      rgb:'245,158,11',  count:1 }
    ],
    active: { initials:'RF', avBg:'#3b82f6', name:'Rodríguez Family', phone:'+34 612 345 678', flag:'🇪🇸', country:'Valencia, Spain', languages:'Spanish · English', currency:'EUR', department:'Reception', deptColor:'#3b82f6', deptIcon:'fa-concierge-bell' },
    profileLabels: [
      { name:'VIP',        color:'#eab308' },
      { name:'Returning',  color:'#22c55e' },
      { name:'Anniversary',color:'#ec4899' }
    ],
    profileNotes: '3rd stay with us. First visit Mar 2024. Prefers early coffee setup. Anniversary trip — add welcome prosecco 🥂',
    booking: {
      listing: 'Villa Marina',
      dates: 'Nov 5 – Nov 7 · 2 nights',
      guests: '4 guests',
      total: '€540',
      checkIn: 'Tue · 2:00 PM',
      checkOut: 'Thu · 11:00 AM'
    },
    thread: [
      { t:'in',  text:'Hi! Confirming check-in Tuesday at 2pm for our 2-night stay at Villa Marina 🏨', time:'10:28' },
      { t:'sys', text:'Auto-assigned to Maria (Front Desk) · Reception department' },
      { t:'out', textHtml:'Confirmed ✅ <b>Villa Marina · Nov 5, 2:00 PM check-in</b> with Maria (Front Desk). Parking is available — door code will be sent 2h before arrival.', time:'10:30', tick:'✓✓' },
      { t:'note', text:'Returning guest (3rd stay). Prefers early coffee setup. Mentioned anniversary trip — consider welcome note + prosecco.', time:'10:30' },
      { t:'in',  text:'Perfect! Any restaurant recs nearby? 🍽️', time:'10:32', reactions:'👍 1' },
      { t:'out', textHtml:'Absolutely — <b>La Marinera</b> (5 min walk, seafood) and <b>Casa Pepe</b> (tapas, 3 min). I\u2019ll book for you if you\u2019d like — Tuesday night, 2 people?', time:'10:33', tick:'✓✓' },
      { t:'in',  text:'Yes please, La Marinera 8pm 🙏', time:'10:34' },
      { t:'out', textHtml:'Booked ✅ La Marinera, Tuesday 8:00 PM for 2. Confirmation sent to your email. See you Tuesday, Carmen 🌊', time:'10:35', tick:'✓✓' }
    ]
  }
};

const V = VERTICALS[_vertical] || VERTICALS.default;
const CHAT_LIST = V.chatList;

// Filter sidebar data — literal spec values
const VIEWS = [
  { k:'all',        label:T('allChats'),      icon:'fa-inbox',        count:null },
  { k:'unread',     label:T('unread'),        icon:'fa-envelope',     count:8, unread:true },
  { k:'pending',    label:T('pending'),       icon:'fa-clock',        count:3, unread:true },
  { k:'mine',       label:T('assignedToMe'),  icon:'fa-user-check',   count:6, unread:true },
  { k:'unassigned', label:T('unassigned'),    icon:'fa-user-slash',   count:12 },
  { k:'mentions',   label:T('mentions'),      icon:'fa-at',           count:2, unread:true },
  { k:'scheduled',  label:T('scheduled'),     icon:'fa-calendar-alt', count:4 },
  { k:'starred',    label:T('starred'),       icon:'fa-star',         count:null },
  { k:'groups',     label:T('groups'),        icon:'fa-user-friends', count:1, unread:true },
  { k:'channels',   label:T('channels'),      icon:'fa-house-user',   count:null },
];

// Departments + labels are now sourced from the active vertical (V)
const DEPARTMENTS = V.departments;
const LABELS = V.labels;

// Team members available for assignment
const TEAM_MEMBERS = [
  { id:'u1', name:'Alex Morgan',  initials:'AM', color:'#8b5cf6' },
  { id:'u2', name:'Sarah Kim',    initials:'SK', color:'#ec4899' },
  { id:'u3', name:'David Park',   initials:'DP', color:'#64748b' },
  { id:'u4', name:'Maria García', initials:'MG', color:'#ef4444' }
];

// WABA Message Templates (approved by Meta) — used to reinitiate a conversation outside the 24h window
const WABA_TEMPLATES = [
  {
    id: 't1',
    name: 'order_shipped',
    category: 'UTILITY',
    language: 'en_US',
    status: 'APPROVED',
    body: 'Hi {{1}}, your order #{{2}} has shipped and is on its way. Track it here: {{3}}'
  },
  {
    id: 't2',
    name: 'appointment_reminder',
    category: 'UTILITY',
    language: 'en_US',
    status: 'APPROVED',
    body: 'Hi {{1}}, this is a reminder of your appointment on {{2}} at {{3}}. Reply CONFIRM to confirm or CANCEL to reschedule.'
  },
  {
    id: 't3',
    name: 'welcome_new_customer',
    category: 'MARKETING',
    language: 'en_US',
    status: 'APPROVED',
    body: 'Welcome to WhatsTeam, {{1}}! We are thrilled to have you on board. Reply to this message if you need anything at all.'
  },
  {
    id: 't4',
    name: 'payment_confirmation',
    category: 'UTILITY',
    language: 'en_US',
    status: 'APPROVED',
    body: 'Hi {{1}}, we confirm we have received your payment of {{2}} for invoice {{3}}. Thanks!'
  },
  {
    id: 't5',
    name: 'abandoned_cart',
    category: 'MARKETING',
    language: 'en_US',
    status: 'APPROVED',
    body: 'Hey {{1}}, you left something in your cart. Complete your order in the next 24h and get 10% off with code BACK10.'
  },
  {
    id: 't6',
    name: 'feedback_request',
    category: 'MARKETING',
    language: 'en_US',
    status: 'APPROVED',
    body: 'Hi {{1}}, how did we do? Your feedback helps us improve. Reply with a score from 1 to 5 or leave a short comment.'
  },
  {
    id: 't7',
    name: 'authentication_code',
    category: 'AUTHENTICATION',
    language: 'en_US',
    status: 'APPROVED',
    body: 'Your WhatsTeam verification code is {{1}}. It expires in 10 minutes. Do not share this code with anyone.'
  },
  {
    id: 't8',
    name: 'out_of_stock_alert',
    category: 'UTILITY',
    language: 'en_US',
    status: 'APPROVED',
    body: 'Hi {{1}}, the item {{2}} you were interested in is back in stock. Tap here to order: {{3}}'
  }
];

// Connected numbers (devices) — realistic enterprise placeholders
const DEFAULT_NUMBERS = [
  { id:'n1', phone:'+34 612 345 678',  name:'Support Team',  cc:'ES', flag:'🇪🇸', status:'connected',    unread:12 },
  { id:'n2', phone:'+1 555 064 3210',  name:'Sales US',      cc:'US', flag:'🇺🇸', status:'connected',    unread:3 },
  { id:'n3', phone:'+44 20 7946 0123', name:'Billing',       cc:'UK', flag:'🇬🇧', status:'connected',    unread:2 },
  { id:'n4', phone:'+49 30 1234 5678', name:'Marketing DE',  cc:'DE', flag:'🇩🇪', status:'syncing',      unread:0 },
  { id:'n5', phone:'+55 11 99876 5432',name:'Partner BR',    cc:'BR', flag:'🇧🇷', status:'disconnected', unread:0, muted:true },
];
const HOSPITALITY_NUMBERS = [
  { id:'n1', phone:'+1 (305) 555 0142', name:'Villa Marina Front Desk', cc:'US', flag:'🇺🇸', status:'connected', unread:12 },
  { id:'n2', phone:'+1 (786) 555 0199', name:'Housekeeping Dispatch',   cc:'US', flag:'🇺🇸', status:'connected', unread:3 },
  { id:'n3', phone:'+1 (954) 555 0177', name:'Guest Relations',         cc:'US', flag:'🇺🇸', status:'connected', unread:2 },
  { id:'n4', phone:'+34 612 345 678',   name:'Spain Concierge',         cc:'ES', flag:'🇪🇸', status:'syncing',      unread:0 },
  { id:'n5', phone:'+44 20 7946 0123',  name:'London Property',         cc:'UK', flag:'🇬🇧', status:'disconnected', unread:0, muted:true }
];
const NUMBERS = _vertical === 'hospitality' ? HOSPITALITY_NUMBERS : DEFAULT_NUMBERS;
const STATUS_LABEL = { connected:'Connected', syncing:'Syncing', disconnected:'Disconnected' };

const Tick = ({t}) => {
  if (!t) return null;
  if (t === 'sent') return <span className="tick">✓</span>;
  if (t === 'delivered') return <span className="tick">✓✓</span>;
  if (t === 'read') return <span className="tick read">✓✓</span>;
  if (t === 'err') return <span className="tick err"><i className="fas fa-redo"/></span>;
  if (t === 'pending') return <span className="tick"><i className="far fa-clock"/></span>;
  return null;
};

// Shared dropdown body for both the conv-header pill and the profile-panel row
const AssignMenu = ({ TEAM_MEMBERS, activeChat, assignTo, placement }) => (
  <div className={`v2-assign-pop v2-assign-pop--${placement}`} onClick={e=>e.stopPropagation()}>
    <div className="v2-assign-head">Assign to</div>
    {TEAM_MEMBERS.map(m => (
      <div
        key={m.id}
        className={`v2-assign-row ${activeChat.assigneeId===m.id?'active':''}`}
        onClick={()=>assignTo(m.id)}
      >
        <span className="av-xs" style={{background:m.color}}>{m.initials}</span>
        <span className="name">{m.name}</span>
        {activeChat.assigneeId===m.id && <i className="fas fa-check check"/>}
      </div>
    ))}
    <div className="v2-assign-sep"/>
    <div
      className={`v2-assign-row ${!activeChat.assigneeId?'active':''}`}
      onClick={()=>assignTo(null)}
    >
      <span className="av-xs v2-assign-empty"><i className="fas fa-user-slash"/></span>
      <span className="name">Unassigned</span>
      {!activeChat.assigneeId && <i className="fas fa-check check"/>}
    </div>
  </div>
);

// WABA Templates lateral panel — used to start/reinitiate conversations outside the 24h window
const CATEGORY_META = {
  ALL:           { label: 'All',            color: '#6b7280' },
  UTILITY:       { label: 'Utility',        color: '#3b82f6' },
  MARKETING:     { label: 'Marketing',      color: '#22c55e' },
  AUTHENTICATION:{ label: 'Authentication', color: '#f59e0b' }
};

const TemplatesPanel = ({ templates, search, setSearch, category, setCategory, onClose, onSend, activeChat }) => {
  const filtered = templates.filter(t => {
    const matchCat = category === 'ALL' || t.category === category;
    const q = search.trim().toLowerCase();
    const matchQ = !q || t.name.toLowerCase().includes(q) || t.body.toLowerCase().includes(q);
    return matchCat && matchQ;
  });
  return (
    <div className="v2-tpl-panel" onClick={e => e.stopPropagation()}>
      <div className="v2-tpl-head">
        <div className="v2-tpl-title">
          <i className="fas fa-file-alt"/>
          <span>Message Templates</span>
          <span className="v2-tpl-count">{filtered.length}</span>
        </div>
        <button className="v2-icon-btn" onClick={onClose} title="Close">
          <i className="fas fa-times"/>
        </button>
      </div>
      <div className="v2-tpl-sub">Sending to <strong>{activeChat.name}</strong> · {activeChat.phone || '+1 234 567 890'}</div>
      <div className="v2-tpl-search">
        <i className="fas fa-search"/>
        <input
          type="text"
          placeholder="Search by name or content"
          value={search}
          onChange={e => setSearch(e.target.value)}
        />
      </div>
      <div className="v2-tpl-cats">
        {Object.entries(CATEGORY_META).map(([k, m]) => (
          <button
            key={k}
            className={`v2-tpl-cat ${category === k ? 'active' : ''}`}
            onClick={() => setCategory(k)}
            style={category === k ? { borderColor: m.color, color: m.color } : undefined}
          >
            {m.label}
          </button>
        ))}
      </div>
      <div className="v2-tpl-list">
        {filtered.length === 0 ? (
          <div className="v2-tpl-empty">
            <i className="fas fa-inbox"/>
            <div>No templates match your search</div>
          </div>
        ) : filtered.map(t => {
          const meta = CATEGORY_META[t.category] || CATEGORY_META.UTILITY;
          return (
            <div key={t.id} className="v2-tpl-card" onClick={() => onSend(t)}>
              <div className="v2-tpl-card-head">
                <span className="v2-tpl-name">{t.name}</span>
                <span className="v2-tpl-badge" style={{background: meta.color + '22', color: meta.color}}>
                  {meta.label}
                </span>
              </div>
              <div className="v2-tpl-body">{t.body}</div>
              <div className="v2-tpl-card-foot">
                <span className="v2-tpl-lang"><i className="fas fa-globe"/>{t.language}</span>
                <span className="v2-tpl-status"><i className="fas fa-check-circle"/>{t.status}</span>
                <span className="v2-tpl-send">Send <i className="fas fa-paper-plane"/></span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

const InboxV2 = () => {
  const [activeView, setActiveView] = React.useState('all');
  const [deptsOpen, setDeptsOpen] = React.useState(true);
  const [labelsOpen, setLabelsOpen] = React.useState(true);
  const [ctab, setCtab] = React.useState('reply');
  const [openAcc, setOpenAcc] = React.useState({info:true, labels:true, notes:true});
  const [activeNumId, setActiveNumId] = React.useState('n1');
  const [combinedView, setCombinedView] = React.useState(false);
  const [numPopOpen, setNumPopOpen] = React.useState(false);
  const [cmdkOpen, setCmdkOpen] = React.useState(false);
  const [composerMenuOpen, setComposerMenuOpen] = React.useState(false);
  const [tweaks, setTweaks] = React.useState({ showPopover:false, showCmdK:false, combined:false });
  const pillRef = React.useRef(null);

  // ===== Interactivity state (assign, select, filter, labels, templates) =====
  const initialActive = CHAT_LIST.find(c => c.active) || CHAT_LIST[0];
  const [chats, setChats] = React.useState(() =>
    CHAT_LIST.map((c) => ({
      ...c,
      assigneeId: (c.initials === '?' || c.stateIco === 'fa-users') ? null : 'u1',
      // Only the initially-active chat (Marcus) has the V.thread conversation.
      // All others start with no messages → triggers the "send a template to start" empty state.
      messages: c.id === initialActive.id ? V.thread.map(m => ({ ...m })) : []
    }))
  );
  const [selectedChatId, setSelectedChatId] = React.useState(initialActive.id);
  // assignSource: null = closed, 'head' = opened from conv header, 'profile' = opened from profile row
  const [assignSource, setAssignSource] = React.useState(null);
  const [labelPickerOpen, setLabelPickerOpen] = React.useState(false);
  const [templatesPanelOpen, setTemplatesPanelOpen] = React.useState(false);
  const [templateSearch, setTemplateSearch] = React.useState('');
  const [templateCategory, setTemplateCategory] = React.useState('ALL');

  const activeChat = chats.find(c => c.id === selectedChatId) || chats[0];
  const activeAssignee = TEAM_MEMBERS.find(m => m.id === activeChat.assigneeId) || null;

  const filteredChats = React.useMemo(() => {
    if (activeView === 'all') return chats;
    if (activeView === 'unread') return chats.filter(c => c.unread > 0);
    if (activeView === 'pending') return chats.filter(c => c.state === 'pending');
    if (activeView === 'mine') return chats.filter(c => c.assigneeId === 'u1');
    if (activeView === 'unassigned') return chats.filter(c => !c.assigneeId);
    if (activeView === 'starred') return chats.filter(c => c.flags && c.flags.includes('pin'));
    if (activeView === 'groups') return chats.filter(c => c.stateIco === 'fa-users');
    if (['channels','scheduled','archived','blocked','trash','mentions'].includes(activeView)) return [];
    if (activeView.startsWith('dept:')) return chats;
    if (activeView.startsWith('label:')) {
      const id = activeView.slice(6);
      const label = LABELS.find(l => l.id === id);
      if (!label) return chats;
      return chats.filter(c => c.labels.some(l => l.n === label.name));
    }
    return chats;
  }, [chats, activeView]);

  const assignTo = (userId) => {
    setChats(cs => cs.map(c => c.id === selectedChatId ? { ...c, assigneeId: userId } : c));
    setAssignSource(null);
  };

  const toggleLabel = (labelName, labelColor) => {
    setChats(cs => cs.map(c => {
      if (c.id !== selectedChatId) return c;
      const has = c.labels.some(l => l.n === labelName);
      return {
        ...c,
        labels: has ? c.labels.filter(l => l.n !== labelName) : [...c.labels, { n: labelName, c: labelColor }]
      };
    }));
  };

  const sendTemplate = (template) => {
    // Hydrate placeholders with plausible sample values so the demo doesn't show {{1}} {{2}}
    const firstName = (activeChat.name || '').split(' ')[0] || 'there';
    const hydrated = template.body
      .replace('{{1}}', firstName)
      .replace('{{2}}', template.name === 'payment_confirmation' ? '$129.00' : 'WT-' + Math.floor(1000 + Math.random() * 9000))
      .replace('{{3}}', 'https://whats.team/t/' + template.name);
    const now = new Date();
    const time = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    setChats(cs => cs.map(c => {
      if (c.id !== selectedChatId) return c;
      return {
        ...c,
        messages: [
          ...c.messages,
          { t: 'sys', text: 'Template sent · ' + template.name + ' (' + template.category + ')' },
          { t: 'out', text: hydrated, time, tick: 'delivered' }
        ]
      };
    }));
    setTemplatesPanelOpen(false);
  };

  // Close popovers with Escape
  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') { setAssignSource(null); setLabelPickerOpen(false); setTemplatesPanelOpen(false); } };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);

  // Tweak knobs: only open the popover/palette *when the knob is true* — don't force-close when false
  React.useEffect(() => { if (tweaks.showPopover) setNumPopOpen(true); }, [tweaks.showPopover]);
  React.useEffect(() => { if (tweaks.showCmdK) setCmdkOpen(true); }, [tweaks.showCmdK]);
  React.useEffect(() => { setCombinedView(tweaks.combined); }, [tweaks.combined]);

  // Global ⌘K
  React.useEffect(() => {
    const h = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') { e.preventDefault(); setCmdkOpen(v => !v); }
      if (e.key === 'Escape') { setCmdkOpen(false); setNumPopOpen(false); }
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);

  const activeNum = NUMBERS.find(n => n.id === activeNumId) || NUMBERS[0];
  const othersUnread = NUMBERS
    .filter(n => n.id !== activeNumId && !n.muted)
    .reduce((s,n) => s + n.unread, 0);

  return (
    <div className="v2-shell">
      <div className="v2-window">
        {/* ===== Col 1 — Nav Rail ===== */}
        <aside className="v2-rail">
          <div className="ws-av">AM<span className="status-dot"/></div>
          <button className="v2-rail-btn" title={T('dashboard')}><i className="fas fa-home"/></button>
          <button className="v2-rail-btn active" title={T('chats')}><i className="fas fa-comments"/><span className="badge-dot"/></button>
          <button className="v2-rail-btn" title={T('campaigns')}><i className="fas fa-bullhorn"/></button>
          <button className="v2-rail-btn" title={T('contacts')}><i className="fas fa-address-book"/></button>
          <button className="v2-rail-btn" title={T('flows')}><i className="fas fa-project-diagram"/></button>
          <button className="v2-rail-btn" title={T('analytics')}><i className="fas fa-chart-bar"/></button>
          <button className="v2-rail-btn" title={T('files')}><i className="fas fa-folder-open"/></button>
          <button className="v2-rail-btn" title={T('developers')}><i className="fas fa-code"/></button>
          <button className="v2-rail-btn" title={T('settings')}><i className="fas fa-cog"/></button>
          <button className="v2-rail-btn" title={T('help')}><i className="fas fa-question-circle"/></button>
          <div className="v2-rail-spacer"/>
          <button className="v2-rail-btn" title={T('searchTitle')}><i className="fas fa-search"/></button>
          <button className="v2-rail-btn" title={T('activity')}><i className="fas fa-bell"/><span className="badge-red">3</span></button>
          <button className="v2-rail-btn quick" title={T('quick')}><i className="fas fa-plus-circle"/></button>
        </aside>

        {/* ===== Col 2 — Filter Sidebar ===== */}
        <aside className="v2-filters">
          <div className="v2-filters-head">
            <div className="t">{T('inbox')}</div>
            <button className="new-chat" title="New chat"><i className="fas fa-plus"/></button>
          </div>
          <div className="v2-filters-scroll">
            {/* VIEWS */}
            <div className="v2-fsec">
              <div className="v2-fsec-head">
                <span>{T('views')}</span>
              </div>
              <div className="v2-fsec-body">
                {VIEWS.map(v => (
                  <div
                    key={v.k}
                    className={`v2-fitem ${activeView===v.k?'active':''} ${v.unread?'has-unread':''}`}
                    onClick={()=>setActiveView(v.k)}
                  >
                    <i className={`fas ${v.icon} fitem-ico`}/>
                    <span className="fitem-label">{v.label}</span>
                    {v.count != null && (
                      <span className="fitem-badge">{v.count>99?'99+':v.count}</span>
                    )}
                  </div>
                ))}
              </div>
            </div>

            {/* DEPARTMENTS */}
            <div className={`v2-fsec ${deptsOpen?'':'collapsed'}`}>
              <div className="v2-fsec-head" onClick={()=>setDeptsOpen(v=>!v)}>
                <span>{T('departments')}</span>
                <div className="right">
                  <i className="fas fa-chevron-down caret"/>
                </div>
              </div>
              <div className="v2-fsec-body">
                {DEPARTMENTS.map(d => (
                  <div
                    key={d.id}
                    className={`v2-fitem ${activeView===`dept:${d.id}`?'active':''}`}
                    onClick={()=>setActiveView(`dept:${d.id}`)}
                  >
                    <span className="fitem-dot" style={{background:`rgb(${d.rgb})`}}/>
                    <i className={`fas ${d.icon} fitem-ico`} style={{color:`rgb(${d.rgb})`}}/>
                    <span className="fitem-label">{d.name}</span>
                    <span className="fitem-badge">{d.count}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* LABELS */}
            <div className={`v2-fsec ${labelsOpen?'':'collapsed'}`}>
              <div className="v2-fsec-head">
                <span onClick={()=>setLabelsOpen(v=>!v)} style={{flex:1}}>{T('labels')}</span>
                <div className="right">
                  <button className="add" title={T('createLabel')} onClick={e=>e.stopPropagation()}><i className="fas fa-plus"/></button>
                  <i className="fas fa-chevron-down caret" onClick={()=>setLabelsOpen(v=>!v)}/>
                </div>
              </div>
              <div className="v2-fsec-body">
                {LABELS.map(l => (
                  <div
                    key={l.id}
                    className={`v2-fitem ${activeView===`label:${l.id}`?'active':''}`}
                    onClick={()=>setActiveView(`label:${l.id}`)}
                  >
                    <span className="fitem-dot" style={{background:`rgb(${l.rgb})`}}/>
                    <span className="fitem-label">{l.name}</span>
                    <span className="fitem-badge">{l.count}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Footer pinned */}
          <div className="v2-filters-footer">
            <div className={`v2-fitem ${activeView==='archived'?'active':''}`} onClick={()=>setActiveView('archived')}>
              <i className="fas fa-archive fitem-ico"/>
              <span className="fitem-label">{T('archived')}</span>
              <span className="fitem-badge">42</span>
            </div>
            <div className={`v2-fitem ${activeView==='blocked'?'active':''}`} onClick={()=>setActiveView('blocked')}>
              <i className="fas fa-ban fitem-ico"/>
              <span className="fitem-label">{T('blocked')}</span>
            </div>
            <div className={`v2-fitem ${activeView==='trash'?'active':''}`} onClick={()=>setActiveView('trash')}>
              <i className="fas fa-trash fitem-ico"/>
              <span className="fitem-label">{T('trash')}</span>
            </div>
          </div>
        </aside>

        {/* ===== Col 3 — Chat list ===== */}
        <section className="v2-list">
          {/* Active Number Pill (replaces workspace header) */}
          <div ref={pillRef} className={`v2-numpill ${numPopOpen?'open':''}`} onClick={()=>setNumPopOpen(v=>!v)}>
            {combinedView ? (
              <>
                <div className="np-av" style={{background:'#ecfdf5', color:'#059669'}}>
                  <i className="fas fa-layer-group" style={{fontSize:13}}/>
                </div>
                <div className="np-text">
                  <div className="np-phone">{T('allNumbers')}</div>
                  <div className="np-sub">{NUMBERS.length} numbers · <span className="unread-dot">{NUMBERS.reduce((s,n)=>s+n.unread,0)} unread</span></div>
                </div>
              </>
            ) : (
              <>
                <div className="np-av" style={{background:'#fef3c7', color:'#92400e'}}>
                  {activeNum.flag}
                  <span className={`status-dot ${activeNum.status}`}/>
                </div>
                <div className="np-text">
                  <div className="np-phone">{activeNum.phone}</div>
                  <div className="np-sub">{activeNum.name} · <span className="unread-dot">{activeNum.unread} unread</span></div>
                </div>
              </>
            )}
            <i className="fas fa-chevron-down np-caret"/>
            {othersUnread > 0 && !combinedView && (
              <span className="np-others" title={`${othersUnread} unread on other numbers`}>{othersUnread}</span>
            )}
            <span className="np-kbd">⌘K</span>
          </div>

          {/* Horizontal tabs removed — view filtering now lives in the Filter Sidebar (Section 2A) */}

          <div className="v2-filter-row">
            <span className="v2-filter-drop">{T('allChats')} <i className="fas fa-chevron-down"/></span>
            <span className="v2-filter-drop"><i className="fas fa-filter"/></span>
          </div>

          <div className="v2-search">
            <i className="fas fa-search"/>
            <span>{T('search')}</span>
            <span className="kbd">⇧ F</span>
          </div>

          <div className="v2-chats">
            {filteredChats.length === 0 && (
              <div className="v2-chats-empty">
                <i className="fas fa-inbox"/>
                <div className="t">No chats in this view</div>
                <div className="s">Try a different filter on the left.</div>
              </div>
            )}
            {filteredChats.map((c, idx) => {
              // Vary which number each chat belongs to when showing combined view
              const chatNum = NUMBERS[idx % NUMBERS.length];
              return (
              <div key={c.id} className={`v2-chat ${c.id===selectedChatId?'active':''}`} onClick={()=>setSelectedChatId(c.id)}>
                <div className="avwrap">
                  <div className="av" style={{background:c.avBg}}>{c.initials}</div>
                  <div className={`state-ico ${c.state}`}><i className={`fas ${c.stateIco}`}/></div>
                </div>
                <div className="body">
                  <div className="row1">
                    <span className="name">{c.name}</span>
                    <span className="flags">
                      {c.flags.includes('pin') && <i className="fas fa-thumbtack"/>}
                      {c.flags.includes('mute') && <i className="fas fa-volume-mute mute"/>}
                    </span>
                    {combinedView && (
                      <span className="numchip" title={`${chatNum.phone} · ${chatNum.name}`}>
                        <span className="nav">{chatNum.flag}</span>
                        {chatNum.cc}
                      </span>
                    )}
                    <span className="time">{c.time}</span>
                  </div>
                  <div className="row2">
                    <Tick t={c.tick}/>
                    <span className="preview">
                      {c.typing ? <span className="typing">{T('typing')}</span>
                       : typeof c.preview === 'string' ? c.preview
                       : c.preview?.type === 'mtype' ? <span className="mtype">{c.preview.icon && <i className={`fas ${c.preview.icon}`} style={{marginRight:4}}/>}{c.preview.text}</span>
                       : null}
                    </span>
                    {c.unread > 0 && <span className="unread">{c.unread>99?'99+':c.unread}</span>}
                  </div>
                  {c.labels.length > 0 && (
                    <div className="label-chips">
                      {c.labels.map((l,i) => (
                        <span key={i} className="v2-chip-label"><span className="dot" style={{background:l.c}}/>{l.n}</span>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            );})}
          </div>
        </section>

        {/* ===== Col 3 — Conversation pane ===== */}
        <section className="v2-conv">
          <div className="v2-conv-head">
            <div className="who">
              <div className="av" style={{background:activeChat.avBg}}>{activeChat.initials}</div>
              <div className="text">
                <div className="n">{activeChat.name}</div>
                <div className="sub">{T('clickEdit')}</div>
              </div>
            </div>
            <div className="acts">
              <div className="v2-head-assign-wrap">
                <button
                  type="button"
                  className="v2-head-assign"
                  onClick={(e)=>{ e.stopPropagation(); setAssignSource(s => s==='head' ? null : 'head'); }}
                  title={activeAssignee ? `Assigned to ${activeAssignee.name}` : 'Unassigned — click to assign'}
                >
                  {activeAssignee ? (
                    <>
                      <span className="av-xs" style={{background:activeAssignee.color}}>{activeAssignee.initials}</span>
                      <span className="label">{activeAssignee.name}</span>
                    </>
                  ) : (
                    <>
                      <span className="av-xs v2-assign-empty"><i className="fas fa-user-slash"/></span>
                      <span className="label muted">Assign</span>
                    </>
                  )}
                  <i className="fas fa-chevron-down caret"/>
                </button>
                {assignSource === 'head' && <AssignMenu TEAM_MEMBERS={TEAM_MEMBERS} activeChat={activeChat} assignTo={assignTo} placement="head"/>}
              </div>
              <button className="v2-icon-btn" title={T('aiCopilot')}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 2l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>
              </button>
              <button className="v2-btn-resolve split">
                <i className="fas fa-check-circle"/>Resolve chat
                <span className="v2-btn-resolve-caret"><i className="fas fa-chevron-down" style={{fontSize:9}}/></span>
              </button>
              <button className="v2-icon-btn" title={T('closePanel')}><i className="fas fa-columns"/></button>
            </div>
          </div>

          <div className="v2-banner">{T('banner')}</div>

          <div className="v2-stream">
            {activeChat.messages.length === 0 ? (
              <div className="v2-empty-thread">
                <div className="v2-empty-icon"><i className="fas fa-comment-slash"/></div>
                <div className="v2-empty-title">24h window closed</div>
                <div className="v2-empty-sub">
                  This customer hasn't messaged you in the last 24 hours.<br/>
                  To reinitiate the conversation, send an approved WABA template.
                </div>
                <button className="v2-empty-cta" onClick={() => setTemplatesPanelOpen(true)}>
                  <i className="fas fa-file-alt"/>Browse templates
                </button>
              </div>
            ) : (
              <>
                <div className="v2-sys"><i className="fas fa-user-plus"/>{T('assignedSys')}</div>
                {activeChat.messages.map((m, i) => {
              if (m.t === 'sys') {
                if (m.kind === 'missedCall') {
                  return <div key={i} className="v2-sys"><i className="fas fa-phone"/>{T('missedCall')}</div>;
                }
                return <div key={i} className="v2-sys">{m.text}</div>;
              }
              if (m.t === 'note') {
                return (
                  <div key={i} className="v2-msg out">
                    <div className="v2-bubble note">
                      <div className="note-label"><i className="fas fa-lock"/>{T('privateNote')}</div>
                      {m.text}
                      <div className="meta" style={{color:'#b45309'}}>{m.time}</div>
                    </div>
                  </div>
                );
              }
              if (m.t === 'audio') {
                return (
                  <div key={i} className="v2-msg out">
                    <div className="v2-bubble out">
                      <div className="audio-player">
                        <div className="play"><i className="fas fa-play"/></div>
                        <div className="bar"/>
                        <div className="dur">{m.dur}</div>
                      </div>
                      <div className="meta">{m.time} {m.tick && <span className="tick">{m.tick}</span>}</div>
                    </div>
                  </div>
                );
              }
              const isOut = m.t === 'out';
              return (
                <div key={i} className={`v2-msg ${isOut ? 'out' : 'in'}`}>
                  <div className={`v2-bubble ${isOut ? 'out' : ''}`}>
                    {m.quote && (
                      <div className="quote"><div className="qa">{m.quote.qa}</div>{m.quote.text}</div>
                    )}
                    {m.textHtml
                      ? <span dangerouslySetInnerHTML={{__html: m.textHtml}}/>
                      : m.text}
                    <div className="meta">{m.time}{isOut && m.tick && <> <span className="tick">{m.tick}</span></>}</div>
                  </div>
                  {m.reactions && (
                    <div className="v2-reactions">
                      <span className="v2-reaction">{m.reactions}</span>
                    </div>
                  )}
                </div>
              );
                })}
              </>
            )}
          </div>

          {/* Composer */}
          <div className="v2-composer">
            <div className="v2-composer-tabs">
              {[
                {k:'reply', l:T('reply')},
                {k:'note', l:T('note')},
                {k:'templates', l:T('templates')},
                {k:'quick', l:T('quickReplies')},
                {k:'scheduled', l:T('scheduled'), c:'9+'},
              ].map(t => (
                <div
                  key={t.k}
                  className={`v2-ctab ${ctab===t.k?'active':''}`}
                  onClick={() => {
                    setCtab(t.k);
                    if (t.k === 'templates') setTemplatesPanelOpen(true);
                  }}
                >
                  {t.l}{t.c && <span className="cc">{t.c}</span>}
                </div>
              ))}
            </div>

            <div className="v2-composer-box">
              <div className="v2-composer-input" contentEditable suppressContentEditableWarning data-placeholder={ctab==='note' ? T('phNote') : T('phReply')}/>
              <div className="v2-composer-actions">
                <div className="v2-composer-more">
                  <button
                    type="button"
                    className="v2-icon-btn"
                    title="+"
                    aria-expanded={composerMenuOpen}
                    onClick={() => setComposerMenuOpen(v => !v)}
                  >
                    <i className="fas fa-plus"/>
                  </button>
                  {composerMenuOpen && (
                    <div className="v2-composer-dropup" role="menu">
                      <button className="v2-dropup-item"><i className="far fa-grin"/><span>{T('emoji')}</span></button>
                      <button className="v2-dropup-item"><i className="fas fa-bold"/><span>{T('bold')}</span></button>
                      <button className="v2-dropup-item"><i className="fas fa-italic"/><span>{T('italic')}</span></button>
                      <button className="v2-dropup-item"><i className="fas fa-quote-right"/><span>{T('quote')}</span></button>
                      <button className="v2-dropup-item"><i className="fas fa-strikethrough"/><span>{T('strike')}</span></button>
                      <div className="v2-dropup-sep"/>
                      <button className="v2-dropup-item"><i className="fas fa-photo-video"/><span>{T('media')}</span></button>
                      <button className="v2-dropup-item"><i className="far fa-address-book"/><span>{T('contact')}</span></button>
                      <button className="v2-dropup-item"><i className="fas fa-file-pdf"/><span>{T('document')}</span></button>
                      <button className="v2-dropup-item"><i className="fas fa-map-marker-alt"/><span>{T('location')}</span></button>
                    </div>
                  )}
                </div>
                <button className="v2-icon-btn btn-record" title={T('recordAudio')}><i className="fas fa-microphone"/></button>
                <div className="spacer"/>
                <button className="ai-btn" title={T('predictReply')}>
                  <svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 2l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/></svg>
                  AI
                </button>
                <button className="v2-icon-btn" title={T('scheduleMsg')}><i className="fas fa-clock"/></button>
                <button className="v2-icon-btn" title={T('signature')}><i className="fas fa-signature"/></button>
                <span className="hint"><kbd>⌘</kbd>+Enter {T('toSend')}</span>
                <button className="send"><i className="fas fa-paper-plane"/>{T('send')}</button>
              </div>
            </div>
          </div>

          {/* Templates side panel — absolute-positioned overlay, does not shift layout */}
          {templatesPanelOpen && (
            <>
              <div className="v2-tpl-backdrop" onClick={() => setTemplatesPanelOpen(false)}/>
              <TemplatesPanel
                templates={WABA_TEMPLATES}
                search={templateSearch}
                setSearch={setTemplateSearch}
                category={templateCategory}
                setCategory={setTemplateCategory}
                onClose={() => setTemplatesPanelOpen(false)}
                onSend={sendTemplate}
                activeChat={activeChat}
              />
            </>
          )}
        </section>

        {/* ===== Col 4 — Customer Profile Panel ===== */}
        <aside className="v2-cp">
          <div className="v2-cp-head">
            <div className="t">{T('customerProfile')}</div>
            <button className="v2-icon-btn" title="Close info panel"><i className="fas fa-columns"/></button>
          </div>
          <div className="v2-cp-scroll">
            <div className="v2-cp-hero">
              <div className="av" style={{background:activeChat.avBg}}>{activeChat.initials}</div>
              <div className="n">{activeChat.name}</div>
              <div className="phone">{V.active.phone} <i className="fas fa-copy copy"/></div>
              <button className="edit-btn"><i className="fas fa-pen"/>{T('edit')} {activeChat.name}</button>
            </div>

            {/* Information accordion */}
            <div className={`v2-acc ${openAcc.info?'open':''}`}>
              <div className="v2-acc-head" onClick={()=>setOpenAcc(s=>({...s,info:!s.info}))}>
                <span className="t">{T('information')}</span>
                <i className="fas fa-chevron-right caret" style={{fontSize:10}}/>
              </div>
              <div className="v2-acc-body">
                <div className="v2-acc-row"><span className="k"><i className="fas fa-circle" style={{color:'#22c55e'}}/>{T('lastMessage')}</span><span className="v">2m ago</span></div>
                <div className="v2-acc-row"><span className="k"><i className="fas fa-user"/>{T('chatType')}</span><span className="v">{T('personal')}</span></div>
                <div className="v2-acc-row"><span className="k">{T('country')}</span><span className="v">{V.active.flag} {V.active.country}</span></div>
                <div className="v2-acc-row"><span className="k">{T('languages')}</span><span className="v">{V.active.languages}</span></div>
                <div className="v2-acc-row"><span className="k">{T('currency')}</span><span className="v">{V.active.currency}</span></div>
                <div className="v2-acc-row"><span className="k">{T('localTime')}</span><span className="v" style={{fontFamily:'var(--font-mono)'}}>10:34</span></div>
                <div className="v2-acc-row" style={{marginTop:8}}><span className="k"><i className="fas fa-user-clock" style={{color:'#3b82f6'}}/>{T('status')}</span><span className="v"><span className="tag active"><span className="dot" style={{background:'#3b82f6'}}/>{T('active')}</span></span></div>
                <div className="v2-acc-row"><span className="k">{T('assignedTo')}</span><span className="v">
                  <button
                    type="button"
                    className="v2-assign-trigger"
                    onClick={(e)=>{ e.stopPropagation(); setAssignSource(s => s==='profile' ? null : 'profile'); }}
                  >
                    {activeAssignee ? (
                      <>
                        <span className="av-xs" style={{background:activeAssignee.color}}>{activeAssignee.initials}</span>
                        {activeAssignee.name}
                      </>
                    ) : (
                      <>
                        <span className="av-xs v2-assign-empty"><i className="fas fa-user-slash"/></span>
                        Unassigned
                      </>
                    )}
                    <i className="fas fa-chevron-down" style={{fontSize:9,marginLeft:4,opacity:.5}}/>
                  </button>
                  {assignSource === 'profile' && <AssignMenu TEAM_MEMBERS={TEAM_MEMBERS} activeChat={activeChat} assignTo={assignTo} placement="profile"/>}
                </span></div>
                <div className="v2-acc-row"><span className="k"><i className="fas fa-random"/>{T('assigned')}</span><span className="v">{T('auto')} · 2m ago</span></div>
                <div className="v2-acc-row"><span className="k">{T('department')}</span><span className="v"><i className={`fas ${V.active.deptIcon}`} style={{color:V.active.deptColor}}/>{V.active.department}</span></div>
                <div className="v2-acc-row"><span className="k"><i className="fas fa-comment-alt"/>{T('firstMessage')}</span><span className="v">15 Jan 2026</span></div>
                <div className="v2-acc-row"><span className="k"><i className="fas fa-comment"/>{T('lastMessage')}</span><span className="v">2m ago</span></div>
              </div>
            </div>

            {/* Booking accordion (hospitality only) */}
            {V.booking && (
              <div className="v2-acc open">
                <div className="v2-acc-head">
                  <span className="t"><i className="fas fa-hotel" style={{marginRight:6,color:'#3b82f6'}}/>Booking</span>
                  <i className="fas fa-chevron-right caret" style={{fontSize:10}}/>
                </div>
                <div className="v2-acc-body">
                  <div className="v2-acc-row"><span className="k"><i className="fas fa-building" style={{color:'#3b82f6'}}/>Listing</span><span className="v">{V.booking.listing}</span></div>
                  <div className="v2-acc-row"><span className="k"><i className="fas fa-calendar-alt"/>Dates</span><span className="v">{V.booking.dates}</span></div>
                  <div className="v2-acc-row"><span className="k"><i className="fas fa-users"/>Guests</span><span className="v">{V.booking.guests}</span></div>
                  <div className="v2-acc-row"><span className="k"><i className="fas fa-euro-sign"/>Total</span><span className="v"><b>{V.booking.total}</b></span></div>
                  <div className="v2-acc-row"><span className="k"><i className="fas fa-sign-in-alt" style={{color:'#22c55e'}}/>Check-in</span><span className="v">{V.booking.checkIn}</span></div>
                  <div className="v2-acc-row"><span className="k"><i className="fas fa-sign-out-alt" style={{color:'#94a3b8'}}/>Check-out</span><span className="v">{V.booking.checkOut}</span></div>
                </div>
              </div>
            )}

            {/* Labels accordion */}
            <div className={`v2-acc ${openAcc.labels?'open':''}`}>
              <div className="v2-acc-head" onClick={()=>setOpenAcc(s=>({...s,labels:!s.labels}))}>
                <span className="t">{T('labels')}</span>
                <div style={{display:'flex',alignItems:'center',gap:8}}>
                  <button
                    className="v2-icon-btn"
                    style={{width:22,height:22}}
                    onClick={e=>{ e.stopPropagation(); setLabelPickerOpen(o=>!o); }}
                    title={T('createLabel')}
                  >
                    <i className="fas fa-plus-circle" style={{fontSize:11}}/>
                  </button>
                  <i className="fas fa-chevron-right caret" style={{fontSize:10}}/>
                </div>
              </div>
              <div className="v2-acc-body">
                <div className="v2-labels-list">
                  {activeChat.labels.length === 0 && !labelPickerOpen && (
                    <div className="v2-labels-empty">No labels yet — click + to add.</div>
                  )}
                  {activeChat.labels.map((lbl, i) => (
                    <span key={`${lbl.n}-${i}`} className="v2-label-chip removable">
                      <span className="dot" style={{background:lbl.c}}/>
                      {lbl.n}
                      <button
                        type="button"
                        className="v2-label-remove"
                        onClick={(e)=>{ e.stopPropagation(); toggleLabel(lbl.n, lbl.c); }}
                        title="Remove"
                      >
                        <i className="fas fa-times"/>
                      </button>
                    </span>
                  ))}
                </div>
                {labelPickerOpen && (
                  <div className="v2-label-picker" onClick={e=>e.stopPropagation()}>
                    <div className="v2-picker-head">Labels</div>
                    {LABELS.map(l => {
                      const color = `rgb(${l.rgb})`;
                      const checked = activeChat.labels.some(x => x.n === l.name);
                      return (
                        <div
                          key={l.id}
                          className={`v2-picker-row ${checked?'active':''}`}
                          onClick={()=>toggleLabel(l.name, color)}
                        >
                          <span className="dot" style={{background:color}}/>
                          <span className="name">{l.name}</span>
                          {checked && <i className="fas fa-check check"/>}
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </div>

            {/* Notes accordion */}
            <div className={`v2-acc ${openAcc.notes?'open':''}`}>
              <div className="v2-acc-head" onClick={()=>setOpenAcc(s=>({...s,notes:!s.notes}))}>
                <span className="t">{T('notes')}</span>
                <i className="fas fa-chevron-right caret" style={{fontSize:10}}/>
              </div>
              <div className="v2-acc-body">
                <textarea key={V.profileNotes || 'default-notes'} className="v2-notes-ta" placeholder={T('notesPh')} defaultValue={V.profileNotes || 'Enterprise plan. Prefers async comms. Timezone: ET.'}/>
                <div className="v2-notes-meta">{T('lastUpdateBy')} Alex Morgan 15m ago</div>
              </div>
            </div>
          </div>
        </aside>
      </div>

      {numPopOpen && (
        <NumbersPopover
          numbers={NUMBERS}
          activeId={activeNumId}
          combined={combinedView}
          anchorRect={pillRef.current?.getBoundingClientRect()}
          onPick={(id)=>{ if(id==='combined'){ setCombinedView(true); } else { setActiveNumId(id); setCombinedView(false); } setNumPopOpen(false); }}
          onClose={()=>setNumPopOpen(false)}
        />
      )}

      {cmdkOpen && <CommandPalette onClose={()=>setCmdkOpen(false)} numbers={NUMBERS} activeId={activeNumId} onPick={(id)=>{ if(id==='combined'){setCombinedView(true);} else {setActiveNumId(id); setCombinedView(false);} setCmdkOpen(false); }} />}

    </div>
  );
};

// ===== Numbers Popover =====
const NumbersPopover = ({ numbers, activeId, combined, onPick, onClose, anchorRect }) => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const h = (e) => {
      if (ref.current && !ref.current.contains(e.target) && !e.target.closest('.v2-numpill')) {
        onClose();
      }
    };
    const t = setTimeout(() => document.addEventListener('mousedown', h), 100);
    return () => { clearTimeout(t); document.removeEventListener('mousedown', h); };
  }, []);

  const style = anchorRect ? { top: anchorRect.bottom + 4, left: anchorRect.left } : {};

  return (
    <div className="v2-numpop" ref={ref} style={style} onClick={e=>e.stopPropagation()}>
      <div className="v2-numpop-head">
        <i className="fas fa-search"/>
        <input autoFocus placeholder="Search numbers…"/>
        <span className="kbd">⌘K</span>
      </div>
      <div className="v2-numpop-list">
        {numbers.map((n, i) => (
          <div
            key={n.id}
            className={`v2-numrow ${!combined && activeId===n.id?'active':''} ${n.muted?'muted':''}`}
            onClick={()=>onPick(n.id)}
          >
            <i className="fas fa-check check"/>
            <div className="av" style={{background:'#fef3c7'}}>
              {n.flag}
              <span className={`status-dot ${n.status}`}/>
            </div>
            <div className="meta">
              <div className="phone">
                {n.phone}
                {n.muted && <i className="fas fa-volume-mute mute-ico"/>}
              </div>
              <div className="sub">{n.name} · {STATUS_LABEL[n.status]}</div>
            </div>
            {n.unread > 0 && <span className="unread">{n.unread}</span>}
            <span className="kbd">⌘{i+1}</span>
          </div>
        ))}

        <div className={`v2-numrow special ${combined?'active':''}`} onClick={()=>onPick('combined')}>
          <i className="fas fa-check check"/>
          <div className="av"><i className="fas fa-layer-group" style={{fontSize:12}}/></div>
          <div className="meta">
            <div className="phone" style={{fontFamily:'inherit'}}>{T('allNumbers')}</div>
            <div className="sub">{T('combinedView')} · {numbers.reduce((s,n)=>s+n.unread,0)} {T('unreadTotal')}</div>
          </div>
          <span/>
          <span className="kbd">⌘0</span>
        </div>
      </div>
      <div className="v2-numpop-footer">
        <div className="v2-numrow-simple"><i className="fas fa-plus-circle"/><span>{T('connectNumber')}</span></div>
        <div className="v2-numrow-simple"><i className="fas fa-cog"/><span>{T('manageNumbers')}</span></div>
      </div>
    </div>
  );
};

// ===== Command Palette =====
const CommandPalette = ({ onClose, numbers, activeId, onPick }) => {
  const [sel, setSel] = React.useState(0);
  return (
    <div className="v2-cmdk-backdrop" onClick={onClose}>
      <div className="v2-cmdk" onClick={e=>e.stopPropagation()}>
        <div className="v2-cmdk-head">
          <i className="fas fa-search search"/>
          <input autoFocus placeholder="Type a command or search…"/>
          <span className="kbd">Esc</span>
        </div>
        <div className="v2-cmdk-body">
          <div className="v2-cmdk-cat-head">Numbers</div>
          {numbers.filter(n=>n.id!==activeId).slice(0,3).map((n,i)=>(
            <div key={n.id} className={`v2-cmdk-row ${sel===i?'sel':''}`} onMouseEnter={()=>setSel(i)} onClick={()=>onPick(n.id)}>
              <span className="ico">{n.flag}</span>
              <span className="label">Switch to <span className="phone">{n.phone}</span> <span className="dim">· {n.name}</span></span>
              <span className="kbd">⌘{numbers.findIndex(x=>x.id===n.id)+1}</span>
            </div>
          ))}
          <div className={`v2-cmdk-row ${sel===3?'sel':''}`} onMouseEnter={()=>setSel(3)} onClick={()=>onPick('combined')}>
            <i className="fas fa-layer-group ico" style={{color:'#059669'}}/>
            <span className="label">Switch to <span style={{fontWeight:500}}>All Numbers</span> <span className="dim">· combined view</span></span>
            <span className="kbd">⌘0</span>
          </div>

          <div className="v2-cmdk-cat-head">Chats</div>
          <div className="v2-cmdk-row"><i className="fas fa-comment ico"/><span className="label">Marcus Johnson <span className="dim">— 2m ago</span></span><span className="kbd">↵</span></div>
          <div className="v2-cmdk-row"><i className="fas fa-comment ico"/><span className="label">Sarah Chen <span className="dim">— 12m ago</span></span><span className="kbd">↵</span></div>

          <div className="v2-cmdk-cat-head">Actions</div>
          <div className="v2-cmdk-row"><i className="fas fa-check-circle ico" style={{color:'#22c55e'}}/><span className="label">Resolve current chat</span><span className="kbd">⌘⇧R</span></div>
          <div className="v2-cmdk-row"><i className="fas fa-paper-plane ico"/><span className="label">New message</span><span className="kbd">⌘N</span></div>
          <div className="v2-cmdk-row"><i className="fas fa-user ico"/><span className="label">Search contacts</span><span className="kbd">⇧F</span></div>
          <div className="v2-cmdk-row"><i className="fas fa-plus-circle ico"/><span className="label">Connect new number</span><span/></div>

          <div className="v2-cmdk-cat-head">Navigate</div>
          <div className="v2-cmdk-row"><i className="fas fa-home ico"/><span className="label">Go to Dashboard</span><span/></div>
          <div className="v2-cmdk-row"><i className="fas fa-chart-bar ico"/><span className="label">Go to Analytics</span><span/></div>
          <div className="v2-cmdk-row"><i className="fas fa-cog ico"/><span className="label">Go to Settings</span><span/></div>
        </div>
      </div>
    </div>
  );
};

window.InboxV2 = InboxV2;
