// Mock data for Blueways platform

const NOW = new Date('2026-05-01T11:42:00');

const TICKETS = [
  { id: 'T-2841', lead: 'Marta Cifuentes',  channel: 'whatsapp', dir: 'in',  type: 'Comprador',  state: 'active',     last: '2 min',  agent: 'AG-WA-01', vip: true,  property: 'REF-MAD-1029', phone: '+34 612 04 89 31', preview: 'Sí, me interesa la zona de Chamberí, 3 dormitorios…' },
  { id: 'T-2840', lead: 'Hugo Bensaude',    channel: 'phone',    dir: 'in',  type: 'Inversor',   state: 'in_call',    last: 'en curso', agent: 'AG-VOZ-02', vip: false, property: '—',           phone: '+33 6 47 21 09 14', preview: 'Llamada en curso · 02:14' },
  { id: 'T-2839', lead: 'Carolina Aguirre', channel: 'email',    dir: 'in',  type: 'Comprador',  state: 'qualified',  last: '14 min', agent: 'AG-MAIL-01', vip: false, property: 'REF-BCN-0314', phone: '+34 658 12 04 70', preview: 'Adjunto la documentación de financiación…' },
  { id: 'T-2838', lead: 'Pavel Krastev',    channel: 'whatsapp', dir: 'out', type: 'Postventa',  state: 'escalated',  last: '21 min', agent: 'AG-WA-02', vip: false, property: 'REF-MLG-0822', phone: '+359 89 632 41 09', preview: '↗ Escalado a Lucía R. — espera tasación' },
  { id: 'T-2837', lead: 'Júlia Romaní',     channel: 'phone',    dir: 'out', type: 'Inversor',   state: 'active',     last: '24 min', agent: 'AG-VOZ-03', vip: true,  property: 'REF-IBZ-0044', phone: '+34 671 99 02 18', preview: 'Outbound · cualificación parcial · 65%' },
  { id: 'T-2836', lead: 'Aleksei Volkov',   channel: 'email',    dir: 'in',  type: 'Comprador',  state: 'active',     last: '38 min', agent: 'AG-MAIL-01', vip: false, property: 'REF-MAD-0918', phone: '—',                preview: 'Quería confirmar visita el sábado a las 11h.' },
  { id: 'T-2835', lead: 'Pilar Estévez',    channel: 'whatsapp', dir: 'in',  type: 'Comprador',  state: 'qualified',  last: '47 min', agent: 'AG-WA-01', vip: false, property: 'REF-VAL-0277', phone: '+34 633 18 27 09', preview: 'Perfecto, espero el informe entonces.' },
  { id: 'T-2834', lead: 'Marc Soler',       channel: 'whatsapp', dir: 'in',  type: 'Descartado', state: 'discarded',  last: '1 h',    agent: 'AG-WA-01', vip: false, property: '—',            phone: '+34 692 47 11 03', preview: 'No me cuadra el presupuesto, gracias.' },
  { id: 'T-2833', lead: 'Yusuf Demir',      channel: 'phone',    dir: 'in',  type: 'Comprador',  state: 'active',     last: '1 h 8',  agent: 'AG-VOZ-01', vip: false, property: 'REF-MAD-0445', phone: '+90 532 19 84 02', preview: 'Llamada · escuchar grabación' },
  { id: 'T-2832', lead: 'Greta Lindqvist',  channel: 'email',    dir: 'in',  type: 'Inversor',   state: 'qualified',  last: '1 h 22', agent: 'AG-MAIL-01', vip: true,  property: 'REF-MLG-0917', phone: '—',                preview: 'Confirmando interés en la cartera completa.' },
  { id: 'T-2831', lead: 'Ramón Ortega',     channel: 'whatsapp', dir: 'in',  type: 'Comprador',  state: 'closed',     last: '2 h',    agent: 'AG-WA-01', vip: false, property: 'REF-SEV-0118', phone: '+34 615 03 19 22', preview: 'Cerrado-ganado · firma 12 de mayo.' },
  { id: 'T-2830', lead: 'Sandra Méndez',    channel: 'whatsapp', dir: 'in',  type: 'Comprador',  state: 'active',     last: '2 h 14', agent: 'AG-WA-01', vip: false, property: 'REF-BCN-1144', phone: '+34 661 88 02 41', preview: 'Estoy revisando las opciones que enviaste.' },
];

const ALERTS = [
  { kind: 'vip',     title: 'Lead VIP sin atender',     desc: 'Marta Cifuentes — 2 min desde su último mensaje.', sev: 'amber', lead: 'T-2841' },
  { kind: 'esc',     title: '3 escalados sin respuesta humana', desc: 'Más de 15 min de espera promedio.', sev: 'red' },
  { kind: 'channel', title: 'WhatsApp · plantilla pendiente',   desc: '«visita_propuesta» en revisión por Meta.', sev: 'amber' },
];

const KPIS = [
  { label: 'Leads activos',        value: 87,   delta: '+12 vs. ayer', dir: 'up'   },
  { label: 'Cualificados hoy',     value: 23,   delta: '+4 vs. ayer',  dir: 'up'   },
  { label: 'Escalados pendientes', value: 3,    delta: '−2 vs. ayer',  dir: 'down' },
  { label: 'Tasa respuesta IA',    value: '94%', delta: '+1.2 pp',     dir: 'up'   },
];

// Agentes IA — sin nombres humanos ni de empresa.
//   mode: 'respond'  → Solo responde (inbound, atiende lo que llega)
//   mode: 'initiate' → Inicia conversación y responde (outbound + recepción)
//   channel: 'phone' | 'whatsapp' | 'email'
const AGENTS = [
  // Solo responde
  { id: 'AG-WA-INB-01',   name: 'Recepción WhatsApp',          channel: 'whatsapp', mode: 'respond',  state: 'active', convs: 412, qual: '38%', avg: '3m 42s' },
  { id: 'AG-VOZ-INB-01',  name: 'Recepción telefónica',        channel: 'phone',    mode: 'respond',  state: 'active', convs: 198, qual: '31%', avg: '4m 12s' },
  { id: 'AG-MAIL-INB-01', name: 'Bandeja de entrada Email',    channel: 'email',    mode: 'respond',  state: 'active', convs: 144, qual: '42%', avg: '—'      },
  // Inicia conversación y responde
  { id: 'AG-WA-OUT-01',   name: 'Captación WhatsApp',          channel: 'whatsapp', mode: 'initiate', state: 'active', convs: 521, qual: '18%', avg: '2m 09s' },
  { id: 'AG-VOZ-OUT-01',  name: 'Llamada saliente comercial',  channel: 'phone',    mode: 'initiate', state: 'paused', convs: 312, qual: '22%', avg: '3m 14s' },
  { id: 'AG-MAIL-OUT-01', name: 'Email saliente nurturing',    channel: 'email',    mode: 'initiate', state: 'active', convs: 167, qual: '29%', avg: '—'      },
];

const LEADS = [
  { id: 'L-04219', name: 'Marta Cifuentes',  email: 'marta.cifuentes@gmail.com', phone: '+34 612 04 89 31', channel: 'whatsapp', type: 'Comprador', state: 'qualified', budget: '450–600k €', zone: 'Chamberí, Madrid', owner: 'Lucía R.',   first: 'Hoy 10:14',  ref: 'REF-MAD-1029', vip: true  },
  { id: 'L-04218', name: 'Hugo Bensaude',    email: 'hugo.b@protonmail.com',     phone: '+33 6 47 21 09 14', channel: 'phone',    type: 'Inversor',  state: 'active',    budget: '1.2–2 M €',   zone: 'Costa Brava',     owner: 'Lucía R.',   first: 'Hoy 11:02',  ref: '—',            vip: false },
  { id: 'L-04217', name: 'Carolina Aguirre', email: 'carolina@aguirre-co.es',    phone: '+34 658 12 04 70', channel: 'email',    type: 'Comprador', state: 'qualified', budget: '320–400k €',  zone: 'Eixample, BCN',   owner: 'Diego P.',   first: 'Hoy 09:48',  ref: 'REF-BCN-0314', vip: false },
  { id: 'L-04216', name: 'Pavel Krastev',    email: 'p.krastev@volna.bg',        phone: '+359 89 632 41 09', channel: 'whatsapp', type: 'Postventa', state: 'escalated', budget: '—',           zone: 'Marbella',        owner: 'Lucía R.',   first: 'Ayer 17:31', ref: 'REF-MLG-0822', vip: false },
  { id: 'L-04215', name: 'Júlia Romaní',     email: 'julia@romanigroup.com',     phone: '+34 671 99 02 18', channel: 'phone',    type: 'Inversor',  state: 'active',    budget: '800k–1.5 M €', zone: 'Ibiza',          owner: 'Sara M.',    first: 'Ayer 16:12', ref: 'REF-IBZ-0044', vip: true  },
  { id: 'L-04214', name: 'Aleksei Volkov',   email: 'a.volkov@yandex.ru',        phone: '—',                channel: 'email',    type: 'Comprador', state: 'active',    budget: '500–700k €',  zone: 'Salamanca, MAD',  owner: 'Diego P.',   first: 'Ayer 14:02', ref: 'REF-MAD-0918', vip: false },
  { id: 'L-04213', name: 'Pilar Estévez',    email: 'p.estevez@gmail.com',       phone: '+34 633 18 27 09', channel: 'whatsapp', type: 'Comprador', state: 'qualified', budget: '180–240k €',  zone: 'Valencia centro', owner: 'Sara M.',    first: 'Ayer 12:18', ref: 'REF-VAL-0277', vip: false },
  { id: 'L-04212', name: 'Marc Soler',       email: 'msoler@gmx.es',             phone: '+34 692 47 11 03', channel: 'whatsapp', type: 'Descartado',state: 'discarded', budget: '120–140k €',  zone: 'BCN área',        owner: '—',          first: '29 abr',     ref: '—',            vip: false },
  { id: 'L-04211', name: 'Greta Lindqvist',  email: 'greta@lindqvist.se',        phone: '—',                channel: 'email',    type: 'Inversor',  state: 'qualified', budget: '2–4 M €',     zone: 'Costa del Sol',   owner: 'Lucía R.',   first: '29 abr',     ref: 'REF-MLG-0917', vip: true  },
  { id: 'L-04210', name: 'Yusuf Demir',      email: 'yusuf@demir.tr',            phone: '+90 532 19 84 02', channel: 'phone',    type: 'Comprador', state: 'active',    budget: '600–900k €',  zone: 'Madrid centro',   owner: 'Diego P.',   first: '28 abr',     ref: 'REF-MAD-0445', vip: false },
  { id: 'L-04209', name: 'Ramón Ortega',     email: 'r.ortega@telefonica.es',    phone: '+34 615 03 19 22', channel: 'whatsapp', type: 'Comprador', state: 'closed_won',budget: '210k €',      zone: 'Sevilla este',    owner: 'Sara M.',    first: '27 abr',     ref: 'REF-SEV-0118', vip: false },
];

const TRANSCRIPT = [
  { t: '11:38:02', who: 'agent', text: 'Buenos días, soy Aitana de Inmobiliaria Blueways. ¿Hablo con Marta Cifuentes?' },
  { t: '11:38:09', who: 'lead',  text: 'Sí, soy yo, hola Aitana.' },
  { t: '11:38:15', who: 'agent', text: 'Encantada. Vi que dejaste tu contacto interesada en una vivienda en la zona de Chamberí. ¿Sigues buscando activamente?' },
  { t: '11:38:32', who: 'lead',  text: 'Sí, sí, llevamos dos meses mirando. Buscamos algo de tres dormitorios, exterior, y a ser posible con plaza de garaje.' },
  { t: '11:38:51', who: 'agent', text: 'Perfecto. ¿En qué horquilla de presupuesto os movéis para tener claras las opciones que mejor encajan?' },
  { t: '11:39:03', who: 'lead',  text: 'Hasta unos 600.000, dependiendo del estado. Podemos llegar a 650 si es para entrar a vivir.' },
  { t: '11:39:18', who: 'agent', text: 'Anotado. ¿La compra sería con financiación bancaria o disponéis del importe completo?' },
  { t: '11:39:31', who: 'lead',  text: 'Con hipoteca, ya tenemos preaprobación de ING al 80%.' },
  { t: '11:39:42', who: 'agent', text: '¡Genial, eso agiliza muchísimo! Voy a registrar tus criterios y pasaré tu caso a Lucía, nuestra comercial de la zona Centro. ¿Te parece si te llama esta tarde sobre las 17h?' },
  { t: '11:40:01', who: 'lead',  text: 'Perfecto, esta tarde mejor a partir de las seis si puede ser.' },
  { t: '11:40:08', who: 'agent', text: 'Sin problema, así queda. Te confirmo todo por WhatsApp en cuanto Lucía revise tu ficha. ¡Hasta pronto, Marta!' },
];

// Property-management tickets — tenant incidents (Step 1+ demo)
const PM_TICKETS = [
  { id: 'PM-1042', tenant: 'Lucía Marín',     unit: 'Apt 4B · Chamberí',     channel: 'whatsapp', state: 'open',        priority: 'high',   issue: 'Aire acondicionado averiado',  last: '8 min',  agent: 'AG-WA-INB-01',  property: 'REF-MAD-1029', phone: '+34 612 04 89 31', summary: 'El AC del salón no enfría desde anoche. Inquilina con bebé en casa.', category: 'HVAC',            subcategory: 'Split mural · 1×1',   component: 'Compresor unidad exterior', symptoms: ['No enfría','Ventilador interior OK','Split exterior sin arranque','Bebé en casa'],         urgencyReason: 'Persona vulnerable · ola de calor en Madrid', recommendedSpecialty: 'Técnico de climatización',   compatibleTeams: 4, confidence: 0.94 },
  { id: 'PM-1041', tenant: 'James Carter',    unit: 'Loft 2 · Malasaña',     channel: 'whatsapp', state: 'scheduled',   priority: 'medium', issue: 'Fuga en lavabo',               last: '34 min', agent: 'AG-WA-INB-01',  property: 'REF-MAD-0918', phone: '+44 7700 900142', summary: 'Goteo continuo. Técnico programado mañana 10:00.',                  category: 'Fontanería',      subcategory: 'Lavabo · sifón',      component: 'Llave de paso angular',     symptoms: ['Goteo continuo','Bandeja recogiendo agua','Llave angular cerrada por inquilino'],         urgencyReason: 'Sin riesgo de inundación · llave cortada',     recommendedSpecialty: 'Fontanero',                   compatibleTeams: 6, confidence: 0.91 },
  { id: 'PM-1040', tenant: 'Helena Vidal',    unit: 'Apt 1A · Salamanca',    channel: 'email',    state: 'open',        priority: 'low',    issue: 'Persiana del dormitorio',      last: '1 h 12', agent: 'AG-MAIL-INB-01', property: 'REF-MAD-0445', phone: '—',                summary: 'Persiana no sube del todo. Sin urgencia.',                          category: 'Carpintería',     subcategory: 'Persiana enrollable', component: 'Cinta · mecanismo recogedor', symptoms: ['Persiana atascada','Sube parcial','Sin afectación seguridad'],                            urgencyReason: 'Bajo impacto · inquilina indica sin prisa',    recommendedSpecialty: 'Carpintero',                  compatibleTeams: 3, confidence: 0.86 },
  { id: 'PM-1039', tenant: 'Tomás Ferré',     unit: 'Apt 3C · Gràcia',       channel: 'phone',    state: 'resolved',    priority: 'high',   issue: 'Sin agua caliente',            last: '2 h',    agent: 'AG-VOZ-INB-01',  property: 'REF-BCN-0314', phone: '+34 633 18 27 09', summary: 'Termo cambiado. Inquilino confirma agua caliente.',                 category: 'Fontanería',      subcategory: 'Termo eléctrico',     component: 'Resistencia · termostato',  symptoms: ['Agua fría','Termo no calienta','Diferencial saltado en cuadro'],                            urgencyReason: 'Resuelto · termo reemplazado',                 recommendedSpecialty: 'Fontanero + electricista',    compatibleTeams: 5, confidence: 0.96 },
  { id: 'PM-1038', tenant: 'Sofía Aragón',    unit: 'Apt 7D · Eixample',     channel: 'whatsapp', state: 'in_progress', priority: 'medium', issue: 'Electrodoméstico (horno)',     last: '3 h',    agent: 'AG-WA-INB-01',  property: 'REF-BCN-1144', phone: '+34 671 99 02 18', summary: 'Horno no enciende. Técnico en camino, llegada estimada 14:30.',     category: 'Electrodoméstico',subcategory: 'Horno empotrado',     component: 'Fusible térmico · placa',   symptoms: ['No enciende','Enchufe con corriente confirmado','Sin display ni piloto'],                  urgencyReason: 'Inquilina trabaja desde casa · usa cocina',    recommendedSpecialty: 'SAT electrodoméstico',        compatibleTeams: 2, confidence: 0.88 },
  { id: 'PM-1037', tenant: 'Greta Lindqvist', unit: 'Villa M3 · Marbella',   channel: 'email',    state: 'follow_up',   priority: 'low',    issue: 'Mantenimiento jardín',         last: '5 h',    agent: 'AG-MAIL-INB-01', property: 'REF-MLG-0917', phone: '—',                summary: 'Solicita poda trimestral. Encuesta de satisfacción enviada.',       category: 'Exterior',        subcategory: 'Jardinería',          component: 'Setos · árboles ornamentales', symptoms: ['Solicitud programada','Sin urgencia','Cliente premium'],                                    urgencyReason: 'Mantenimiento programado · sin avería',        recommendedSpecialty: 'Jardinero',                   compatibleTeams: 2, confidence: 0.99 },
  { id: 'PM-1036', tenant: 'Nour El-Sayed',   unit: 'Estudio 5 · Lavapiés',  channel: 'whatsapp', state: 'open',        priority: 'high',   issue: 'Cerradura bloqueada',          last: '6 h',    agent: 'AG-WA-INB-01',  property: 'REF-MAD-0822', phone: '+34 692 47 11 03', summary: 'No puede entrar al piso. Cerrajero contactado.',                    category: 'Seguridad',       subcategory: 'Cerradura · bombín',  component: 'Bombín cilindro europeo',   symptoms: ['Llave gira en vacío','Inquilino fuera del piso','Acceso bloqueado'],                       urgencyReason: 'Acceso a vivienda bloqueado',                   recommendedSpecialty: 'Cerrajero 24h',               compatibleTeams: 3, confidence: 0.92 },
  { id: 'PM-1035', tenant: 'Pavel Krastev',   unit: 'Apt 6F · Castellana',   channel: 'phone',    state: 'escalated',   priority: 'high',   issue: 'Plaga · cucarachas',           last: '8 h',    agent: 'AG-VOZ-INB-01',  property: 'REF-MAD-1101', phone: '+359 89 632 41 09', summary: 'Tercera incidencia este mes. Derivado a supervisor.',               category: 'Sanidad',         subcategory: 'Plaga · insectos',    component: 'Zona cocina y baño',        symptoms: ['Avistamientos múltiples','Tercera incidencia en 4 semanas','Posible foco no resuelto'],   urgencyReason: 'Reincidencia · riesgo sanitario',               recommendedSpecialty: 'DDD certificada',             compatibleTeams: 2, confidence: 0.87 },
];

// Category → icon + color tokens for the identification UI
const PM_CATEGORIES = {
  'HVAC':            { icon: 'Sparkle',        color: '#0891B2', bg: '#CFFAFE' },
  'Fontanería':      { icon: 'Refresh',        color: '#2563EB', bg: '#DBEAFE' },
  'Electricidad':    { icon: 'AlertTriangle',  color: '#D97706', bg: '#FEF3C7' },
  'Electrodoméstico':{ icon: 'Settings',       color: '#7C3AED', bg: '#EDE9FE' },
  'Carpintería':     { icon: 'Tag',            color: '#92400E', bg: '#FEF3C7' },
  'Seguridad':       { icon: 'Lock',           color: '#DC2626', bg: '#FEE2E2' },
  'Sanidad':         { icon: 'AlertTriangle',  color: '#16A34A', bg: '#DCFCE7' },
  'Exterior':        { icon: 'Star',           color: '#65A30D', bg: '#ECFCCB' },
};

const PM_TRANSCRIPTS = {
  'PM-1042': [
    { t: '09:42', who: 'lead',  text: 'Hola, buenos días. Soy Lucía del 4B. Tengo el aire acondicionado del salón estropeado desde anoche.' },
    { t: '09:42', who: 'agent', text: 'Hola Lucía, soy el asistente de Ementil. Lamento la incidencia. ¿Puedes contarme qué hace exactamente el equipo? ¿Enciende pero no enfría, o no responde?' },
    { t: '09:43', who: 'lead',  text: 'Enciende, el ventilador funciona, pero el aire sale a temperatura ambiente. No enfría nada.' },
    { t: '09:43', who: 'agent', text: 'Entendido. ¿Has notado algún ruido inusual, goteo, o el split exterior funciona?' },
    { t: '09:44', who: 'lead',  text: 'El de fuera no oigo que arranque. Y tengo un bebé en casa, hace mucho calor.' },
    { t: '09:44', who: 'agent', text: 'Te marco como prioridad alta. Reviso disponibilidad del técnico de climatización ahora mismo.' },
    { t: '09:45', who: 'agent', text: 'Tengo a Climatec disponible mañana a las 10:30, o un técnico externo hoy entre 17:00 y 19:00 (coste adicional 45 €). ¿Qué opción prefieres?' },
    { t: '09:46', who: 'lead',  text: 'Hoy mismo por favor, aunque haya coste. Necesitamos resolverlo cuanto antes.' },
    { t: '09:46', who: 'agent', text: 'Perfecto. Acabo de generar la orden #PM-1042 y notificar a ServiClima. Recibirás un WhatsApp con datos del técnico (nombre, foto, matrícula) 30 min antes de la visita.' },
  ],
  'PM-1041': [
    { t: 'Ayer 18:20', who: 'lead',  text: 'Hi, there is a constant drip under the bathroom sink. Tray is filling up fast.' },
    { t: 'Ayer 18:21', who: 'agent', text: 'Hi James, sorry to hear that. Could you close the angle valve under the sink for now? It will stop the flow until the plumber arrives.' },
    { t: 'Ayer 18:22', who: 'lead',  text: 'Done, water has stopped. Thank you.' },
    { t: 'Ayer 18:23', who: 'agent', text: 'I have booked Fontanería Madrid Centro for tomorrow between 10:00 and 11:00. You will receive a follow-up message tomorrow morning with the technician\u2019s details.' },
  ],
  'PM-1038': [
    { t: '08:14', who: 'lead',  text: 'Buenos días, el horno de la cocina no enciende. Ayer funcionaba sin problema.' },
    { t: '08:15', who: 'agent', text: 'Hola Sofía, lo siento. ¿Llega corriente al enchufe? Si tienes otro electrodoméstico cerca puedes probar y confirmarme.' },
    { t: '08:18', who: 'lead',  text: 'Probé la tostadora en el mismo enchufe y va perfectamente. El horno no responde ni en frío ni en programa.' },
    { t: '08:18', who: 'agent', text: 'Anotado. Te he asignado al técnico Electrodom IB. Llegada estimada hoy 14:00-14:30. Te avisamos 30 min antes.' },
  ],
  'PM-1039': [
    { t: '16:02', who: 'agent', text: 'Llamada saliente · Blueways. Buenas tardes, ¿hablo con Tomás Ferré?' },
    { t: '16:02', who: 'lead',  text: 'Sí, soy yo. ¿Qué tal?' },
    { t: '16:02', who: 'agent', text: 'Llamamos por la incidencia de agua caliente del Apt 3C. ¿Confirmas que el técnico de fontanería ha cambiado el termo y todo funciona correctamente?' },
    { t: '16:03', who: 'lead',  text: 'Sí, ha venido Marta esta mañana. Cambió el termo y ahora hay agua caliente sin problemas.' },
    { t: '16:03', who: 'agent', text: 'Perfecto. Marcamos la incidencia como resuelta. Te enviaremos una breve encuesta de satisfacción por WhatsApp en 24 horas. ¿Algo más en lo que podamos ayudarte?' },
    { t: '16:04', who: 'lead',  text: 'No, todo correcto. Gracias.' },
    { t: '16:04', who: 'agent', text: 'A ti, Tomás. Que tengas buen día.' },
  ],
  'PM-1035': [
    { t: '14:10', who: 'lead',  text: 'Llamada entrante · inquilino. Buenas tardes, llamo por la plaga de cucarachas en el Apt 6F. Es la tercera vez este mes.' },
    { t: '14:10', who: 'agent', text: 'Buenas tardes, lamento mucho la situación. Voy a registrar la incidencia con prioridad alta y derivarla a supervisor para escalado inmediato. ¿Has notado los avistamientos en zonas concretas?' },
    { t: '14:11', who: 'lead',  text: 'Sobre todo en la cocina y el baño. El último tratamiento DDD no ha funcionado, sigue habiendo.' },
    { t: '14:11', who: 'agent', text: 'Anotado. Te paso con el supervisor de operaciones, Pablo Vidal, en menos de 15 minutos. Mientras tanto, abrimos ticket #PM-1035 con histórico completo y revisaremos cambio de proveedor DDD.' },
    { t: '14:12', who: 'lead',  text: 'De acuerdo, espero su llamada.' },
    { t: '14:12', who: 'agent', text: 'Quedamos así. Gracias por avisar.' },
  ],
};

const REPORT = {
  generated: 'Hoy 11:40',
  type: 'Comprador particular · alta intención',
  budget: '450.000 – 650.000 €',
  zone: 'Chamberí, Madrid',
  rooms: '3 dormitorios + plaza garaje',
  financing: 'Hipoteca preaprobada — ING — 80% LTV',
  next: 'Llamada de Lucía R. hoy a las 18:00. Adjuntar 3 referencias en Chamberí (REF-MAD-1029, 1031, 1044).',
  score: 92,
};

const CHANNELS_DATA = [
  { id: 'phone-blueways',  type: 'phone',    name: 'Telefonía Blueways',     stack: 'Vapi · Twilio · ElevenLabs · Deepgram', number: '+34 91 198 04 12', state: 'active',  detail: '23.418 min este mes',   error: null },
  { id: 'wa-blueways',     type: 'whatsapp', name: 'WhatsApp Blueways',      stack: 'Meta WhatsApp Business API',          number: '+34 612 11 02 00', state: 'active',  detail: '14 plantillas aprobadas', error: null },
  { id: 'mail-blueways',   type: 'email',    name: 'Email Blueways',          stack: 'IMAP · SMTP — Gmail Workspace',       number: 'leads@blueways.es',    state: 'active',  detail: 'Hilo activo en 38 leads', error: null },
  { id: 'phone-trenca', type: 'phone',    name: 'Telefonía Trencadís', stack: 'Vapi · Twilio · ElevenLabs · Deepgram', number: '+34 93 220 81 71', state: 'error',   detail: 'Saliente — error de SIP', error: 'TWILIO 32208 · trunk timeout' },
  { id: 'wa-trenca',    type: 'whatsapp', name: 'WhatsApp Trencadís',  stack: 'Meta WhatsApp Business API',          number: '+34 671 03 88 19', state: 'pending', detail: 'Verificación Meta — paso 2/3', error: null },
  { id: 'crm-inmovilla',type: 'crm',      name: 'Inmovilla',           stack: 'API REST · sync bidireccional',       number: 'tenant.inmovilla.com', state: 'active', detail: 'Sincronizado hace 1 min', error: null },
  { id: 'crm-casafari', type: 'crm',      name: 'Casafari',            stack: 'API REST · solo lectura',             number: '—',                  state: 'inactive', detail: 'No conectado',         error: null },
];

const INVOICES = [
  { n: 'INV-2026-04', period: 'Abril 2026', fixed: 690, variable: 1247.31, total: 1937.31, state: 'paid',    issued: '01 may 2026' },
  { n: 'INV-2026-03', period: 'Marzo 2026', fixed: 690, variable: 982.04,  total: 1672.04, state: 'paid',    issued: '01 abr 2026' },
  { n: 'INV-2026-02', period: 'Febrero',    fixed: 690, variable: 871.18,  total: 1561.18, state: 'paid',    issued: '01 mar 2026' },
  { n: 'INV-2026-01', period: 'Enero',      fixed: 690, variable: 1102.55, total: 1792.55, state: 'paid',    issued: '01 feb 2026' },
  { n: 'INV-2025-12', period: 'Diciembre',  fixed: 690, variable: 1488.72, total: 2178.72, state: 'paid',    issued: '01 ene 2026' },
];

const VARIABLE_BREAKDOWN = [
  { provider: 'Vapi',       desc: 'Orquestación de llamadas',    minutes: 8412, unit: '0.0420', total: 353.30 },
  { provider: 'Twilio',     desc: 'Provisión de números + PSTN', minutes: 8412, unit: '0.0185', total: 155.62 },
  { provider: 'ElevenLabs', desc: 'TTS — voz IA',                minutes: 8412, unit: '0.0610', total: 513.13 },
  { provider: 'Deepgram',   desc: 'STT — transcripción',         minutes: 8412, unit: '0.0140', total: 117.77 },
  { provider: 'LLM (GPT)',  desc: 'Razonamiento conversacional', minutes: 8412, unit: '0.0128', total: 107.49 },
];

const TEAM = [
  { name: 'Adrián Núñez',   email: 'adrian@blueways.es',  role: 'Administrador', last: 'Activo ahora',  initials: 'AN', color: '#1554F0' },
  { name: 'Lucía Romero',   email: 'lucia@blueways.es',   role: 'Comercial',     last: 'Hace 4 min',    initials: 'LR', color: '#0D9488' },
  { name: 'Diego Pintor',   email: 'diego@blueways.es',   role: 'Comercial',     last: 'Hace 18 min',   initials: 'DP', color: '#7C3AED' },
  { name: 'Sara Martínez',  email: 'sara@blueways.es',    role: 'Supervisor',    last: 'Hoy 09:42',     initials: 'SM', color: '#D97706' },
  { name: 'Pablo Vidal',    email: 'pablo@blueways.es',   role: 'Comercial',     last: 'Ayer',          initials: 'PV', color: '#DC2626' },
];

// Follow-ups per ticket — 3-step plan: T-3, T-1, T+1 (satisfaction)
const PM_FOLLOWUPS = {
  'PM-1041': {
    visitDate: '21 may 2026 · 10:00–11:00',
    technicianAssigned: { name:'Jorge Ramos', company:'Fontanería Madrid Centro', phone:'+34 633 11 02 88', rating: 4.9 },
    steps: [
      { stage:'T-3', label:'Recordatorio inicial',     when:'18 may · 09:00', channel:'whatsapp', state:'sent',     message:'Hi James, reminder that the plumber visit is scheduled for Thursday 21 May between 10:00 and 11:00. We will share the technician details 24h before. — Blueways Property Care', response:null, rating: null },
      { stage:'T-1', label:'Confirmación 24h',         when:'20 may · 10:00', channel:'whatsapp', state:'sent',     message:'Hi James, confirming Jorge Ramos (Fontanería MC) will visit tomorrow 10:00–11:00. Photo + ID attached. Estimated duration: 45 min. Reply STOP to cancel or RESCHEDULE for a new slot.', response:'OK, thanks!', rating: null },
      { stage:'T+1', label:'Encuesta de satisfacción', when:'22 may · 11:00', channel:'whatsapp', state:'pending',  message:'Hi James, how would you rate the visit yesterday? Reply with a number 1–5 and any comment you may have. Your feedback helps us improve. — Blueways', response:null, rating: null },
    ],
  },
  'PM-1038': {
    visitDate: 'Hoy · 14:00–14:30',
    technicianAssigned: { name:'Pere Llull', company:'Electrodom IB', phone:'+34 671 03 22 14', rating: 4.5 },
    steps: [
      { stage:'T-3', label:'Recordatorio inicial',     when:'—',             channel:'whatsapp', state:'skipped',   message:'(Servicio inmediato — sin ventana T-3)', response:null, rating: null },
      { stage:'T-1', label:'Confirmación 24h',         when:'Hoy · 08:30',  channel:'whatsapp', state:'sent',      message:'Sofía, confirmamos que Pere Llull (Electrodom IB) llegará hoy entre 14:00 y 14:30. Te avisará 30 min antes. Ref. PM-1038.', response:'Vale, gracias', rating: null },
      { stage:'T+1', label:'Encuesta de satisfacción', when:'Mañana · 10:00', channel:'whatsapp', state:'scheduled', message:'(Se enviará 24h después de la finalización del servicio)', response:null, rating: null },
    ],
  },
  'PM-1039': {
    visitDate: '18 may · 11:30',
    technicianAssigned: { name:'Marta Solé', company:'Plantilla Blueways', phone:'+34 615 00 12 05', rating: 4.8 },
    steps: [
      { stage:'T-3', label:'Recordatorio inicial',     when:'15 may · 09:00', channel:'whatsapp', state:'sent',      message:'Tomás, recordatorio: técnico de fontanería el martes 18 entre 11:30 y 12:30 para revisar el termo.', response:'Perfecto', rating: null },
      { stage:'T-1', label:'Confirmación 24h',         when:'17 may · 11:30', channel:'whatsapp', state:'sent',      message:'Marta Solé llegará mañana a las 11:30. Cualquier cambio, escríbenos.', response:'Ok', rating: null },
      { stage:'T+1', label:'Encuesta de satisfacción', when:'19 may · 11:30', channel:'whatsapp', state:'responded', message:'¿Cómo valoras la visita? Responde 1–5.', response:'5 — Resuelto en una visita, muy profesional. Gracias.', rating: 5 },
    ],
  },
  'PM-1037': {
    visitDate: '17 may · 09:00',
    technicianAssigned: { name:'Òscar Mata', company:'Jardinería Iberica', phone:'+34 952 88 10 22', rating: 4.5 },
    steps: [
      { stage:'T-3', label:'Recordatorio inicial',     when:'14 may · 10:00', channel:'email', state:'sent', message:'Estimada Sra. Lindqvist, le recordamos la cita de jardinería para el sábado 17 a las 09:00.', response:null, rating: null },
      { stage:'T-1', label:'Confirmación 24h',         when:'16 may · 09:00', channel:'email', state:'sent', message:'Òscar Mata llegará mañana a las 09:00 con el equipo de poda. Duración estimada: 3h.', response:'Confirmed', rating: null },
      { stage:'T+1', label:'Encuesta de satisfacción', when:'18 may · 10:00', channel:'email', state:'sent', message:'How would you rate the service? Reply with 1–5 stars and any comment.', response:'4 — Buen trabajo, pero llegó 25 min tarde.', rating: 4 },
    ],
  },
};

const TECHNICIANS = [
  { id: 'TEC-001', company: 'Climatec',        contact: 'Roberto Iglesias',  type: 'external', specialties: ['HVAC','Climatización'],            zone: 'Madrid centro',     rating: 4.8, completed: 142, slaMin: 35,  status: 'available', preferred: true,  phone: '+34 610 22 11 04', rate: '45 €/h' },
  { id: 'TEC-002', company: 'ServiClima 24h',  contact: 'María Cuevas',     type: 'external', specialties: ['HVAC','Electricidad'],             zone: 'Madrid sur',        rating: 4.6, completed: 87,  slaMin: 25,  status: 'available', preferred: false, phone: '+34 611 84 39 02', rate: '55 €/h · 24h' },
  { id: 'TEC-003', company: 'Fontanería Madrid Centro', contact: 'Jorge Ramos', type: 'external', specialties: ['Fontanería'],                   zone: 'Madrid centro',     rating: 4.9, completed: 201, slaMin: 45,  status: 'available', preferred: true,  phone: '+34 633 11 02 88', rate: '38 €/h' },
  { id: 'TEC-004', company: 'En plantilla',    contact: 'Carlos Vega',      type: 'internal', specialties: ['Fontanería','Carpintería'],        zone: 'Madrid · BCN',      rating: 4.7, completed: 318, slaMin: 60,  status: 'busy',      preferred: true,  phone: '+34 615 00 12 04', rate: '—' },
  { id: 'TEC-005', company: 'En plantilla',    contact: 'Marta Solé',       type: 'internal', specialties: ['Electricidad','Electrodoméstico'], zone: 'Barcelona área',    rating: 4.8, completed: 256, slaMin: 50,  status: 'available', preferred: true,  phone: '+34 615 00 12 05', rate: '—' },
  { id: 'TEC-006', company: 'Electrodom IB',   contact: 'Pere Llull',       type: 'external', specialties: ['Electrodoméstico'],                zone: 'Madrid · BCN · IB', rating: 4.5, completed: 64,  slaMin: 90,  status: 'available', preferred: false, phone: '+34 671 03 22 14', rate: '52 €/h' },
  { id: 'TEC-007', company: 'Cerrajeros Express 24h', contact: 'Andrés Páez', type:'external', specialties: ['Seguridad','Cerrajería'],         zone: 'Madrid 24h',        rating: 4.4, completed: 91,  slaMin: 30,  status: 'available', preferred: false, phone: '+34 600 99 04 18', rate: '80 €/visita' },
  { id: 'TEC-008', company: 'Carpintería Lo Real', contact: 'Vicente Ruiz', type: 'external', specialties: ['Carpintería'],                    zone: 'Madrid · Toledo',   rating: 4.6, completed: 38,  slaMin: 120, status: 'busy',      preferred: false, phone: '+34 691 47 11 20', rate: '42 €/h' },
  { id: 'TEC-009', company: 'DDD Sanitas',     contact: 'Isabel Roca',      type: 'external', specialties: ['Sanidad','Plagas'],                zone: 'Nacional',          rating: 4.7, completed: 22,  slaMin: 240, status: 'available', preferred: false, phone: '+34 902 18 33 04', rate: '180 €/visita' },
  { id: 'TEC-010', company: 'Jardinería Iberica',  contact: 'Òscar Mata',   type: 'external', specialties: ['Exterior','Jardinería'],          zone: 'Costa del Sol',     rating: 4.5, completed: 14,  slaMin: 480, status: 'available', preferred: false, phone: '+34 952 88 10 22', rate: '32 €/h' },
];

const DISPATCHES = [
  { id: 'D-2104', ticket: 'PM-1041', technician: 'Jorge Ramos · Fontanería MC',  channel: 'whatsapp', sentAt: 'Hoy 09:14', state: 'confirmed', eta: 'Mañana 10:00 – 11:00', tenant: 'James Carter', issue: 'Fuga en lavabo' },
  { id: 'D-2103', ticket: 'PM-1038', technician: 'Pere Llull · Electrodom IB',   channel: 'email',    sentAt: 'Hoy 08:48', state: 'confirmed', eta: 'Hoy 14:00 – 14:30',     tenant: 'Sofía Aragón', issue: 'Horno no enciende' },
  { id: 'D-2102', ticket: 'PM-1036', technician: 'Andrés Páez · Cerrajeros 24h', channel: 'phone',    sentAt: 'Hoy 06:18', state: 'confirmed', eta: 'Hoy 07:00',             tenant: 'Nour El-Sayed', issue: 'Cerradura bloqueada' },
  { id: 'D-2101', ticket: 'PM-1035', technician: 'Isabel Roca · DDD Sanitas',    channel: 'email',    sentAt: 'Ayer 18:02', state: 'declined',  eta: '—',                     tenant: 'Pavel Krastev', issue: 'Plaga reincidente' },
  { id: 'D-2100', ticket: 'PM-1040', technician: 'Vicente Ruiz · Carpintería',   channel: 'whatsapp', sentAt: 'Ayer 16:30', state: 'sent',     eta: 'Pendiente',             tenant: 'Helena Vidal', issue: 'Persiana atascada' },
];

// Operational insights — bottleneck detection (Step 5)
const INSIGHTS = [
  { id:'I1', sev:'high',   icon:'AlertTriangle', title:'Climatización · 8 dispatches sin confirmar > 30 min', desc:'Climatec y ServiClima 24h con tiempo medio de respuesta de 47 min hoy (SLA: 30 min). Posible saturación por ola de calor en Madrid.', metric:'+57% vs. SLA', actions:[{label:'Ver dispatches', go:'technicians'},{label:'Buscar alternativas', go:'technicians'}] },
  { id:'I2', sev:'high',   icon:'Refresh',       title:'Plagas · 3 reincidencias en 14 días · Apt 6F Castellana', desc:'Tercer aviso por cucarachas en la misma unidad. Tratamiento DDD anterior no resolutivo. Recomendación: cambio de proveedor o intervención estructural.', metric:'3 incidencias / 14 d', actions:[{label:'Ver historial ticket', go:'tickets'}] },
  { id:'I3', sev:'medium', icon:'Wrench',        title:'Técnica saturada · Marta Solé (plantilla)', desc:'12 tickets activos en cola (capacidad recomendada: 8). 4 tickets en \"En curso\" con > 90 min sobre estimado.', metric:'+50% capacidad', actions:[{label:'Reasignar 4 tickets', go:'tickets'}] },
  { id:'I4', sev:'medium', icon:'Mail',          title:'Email · tasa de respuesta de inquilino baja', desc:'Solo 41% de inquilinos responde por email vs. 86% por WhatsApp. 7 tickets sin avance en bandeja Email > 48h.', metric:'41% vs 86%', actions:[{label:'Migrar a WhatsApp', go:'channels'}] },
  { id:'I5', sev:'low',    icon:'Clock',         title:'Categoría Carpintería · tiempo medio +35% vs. mes anterior', desc:'Solo 1 carpintero externo activo (Vicente Ruiz). Subir capacidad o priorizar piezas en stock interno.', metric:'+35% lead time', actions:[{label:'Ver técnicos', go:'technicians'}] },
];

window.BW_DATA = { TICKETS, ALERTS, KPIS, AGENTS, LEADS, TRANSCRIPT, REPORT, CHANNELS_DATA, INVOICES, VARIABLE_BREAKDOWN, TEAM, NOW, PM_TICKETS, PM_TRANSCRIPTS, PM_CATEGORIES, PM_FOLLOWUPS, TECHNICIANS, DISPATCHES, INSIGHTS };
