/* global React */

// ============================================================
// KNOWLEDGE BASE — artículos que SOF.IA consulta
// ============================================================
const KB_ARTICLES = [
  {
    code: "KB-HP-M404-008",
    title: "Reemplazo del rodillo de arrastre · bandeja 2",
    category: "Mantenimiento HW",
    models: ["HP LaserJet Pro M404dn", "HP LaserJet Pro M404n", "HP LaserJet Pro M404dw"],
    brand: "HP",
    faultType: "Atasco / arrastre",
    uses: 142,
    successRate: 0.94,
    updated: "2026-04-18",
    author: "Eddy R. Marroquín",
    steps: [
      "Apagar la impresora y desconectar del tomacorriente. Esperar 5 min para que el fusor enfríe.",
      "Retirar bandeja 2 completa y bloquear puerta posterior.",
      "Localizar el rodillo de arrastre (ref. RM2-5397-000CN) en la pared inferior del compartimento.",
      "Desenganchar el clip lateral con la herramienta plástica · NO usar destornillador metálico.",
      "Deslizar el rodillo gastado y reemplazar con el nuevo. Verificar que el resorte de tensión asiente.",
      "Imprimir página de prueba desde la bandeja 2. Validar que no se atasque.",
      "Registrar el cambio en el historial del equipo con la fecha y serie del repuesto.",
    ],
    parts: [
      { ref: "RM2-5397-000CN", name: "Rodillo de arrastre HP M404", stock: 12 },
      { ref: "RM2-5421-000CN", name: "Separador (recomendado cambiar junto)", stock: 8 },
    ],
  },
  {
    code: "KB-HP-M404-003",
    title: "Diagnóstico de atascos por bandeja",
    category: "Diagnóstico",
    models: ["HP LaserJet Pro M404dn", "HP LaserJet Pro M428fdw"],
    brand: "HP",
    faultType: "Atasco",
    uses: 89,
    successRate: 0.87,
    updated: "2026-03-02",
  },
  {
    code: "KB-CAN-IR2630-014",
    title: "Códigos de error E000 / E007 en imageRUNNER 2630i",
    category: "Diagnóstico",
    models: ["Canon imageRUNNER 2630i", "Canon imageRUNNER 2625i"],
    brand: "Canon",
    faultType: "Fusor / temperatura",
    uses: 64,
    successRate: 0.78,
    updated: "2026-02-22",
  },
  {
    code: "KB-HP-M428-021",
    title: "Líneas verticales en impresión · tambor de imagen",
    category: "Calidad",
    models: ["HP LaserJet M428fdw", "HP LaserJet M428dw", "HP LaserJet M404dn"],
    brand: "HP",
    faultType: "Calidad impresión",
    uses: 117,
    successRate: 0.91,
    updated: "2026-05-08",
  },
  {
    code: "KB-GEN-014",
    title: "Política de visitas bajo contrato MANT",
    category: "Operación",
    models: ["Todos"],
    brand: "—",
    faultType: "Política",
    uses: 203,
    successRate: 1.0,
    updated: "2026-01-15",
  },
  {
    code: "KB-HP-WIFI-002",
    title: "Configuración WiFi · HP LaserJet M111w",
    category: "Conectividad",
    models: ["HP LaserJet M111w", "HP LaserJet M110we"],
    brand: "HP",
    faultType: "Conectividad",
    uses: 78,
    successRate: 0.96,
    updated: "2026-05-19",
  },
  {
    code: "KB-HP-TONER-005",
    title: "Sustitución de cartucho amarillo · Color LaserJet M283",
    category: "Mantenimiento HW",
    models: ["HP Color LaserJet M283fdw", "HP Color LaserJet M255dw"],
    brand: "HP",
    faultType: "Consumibles",
    uses: 56,
    successRate: 0.99,
    updated: "2026-04-30",
  },
  {
    code: "KB-CAN-LBP-007",
    title: "Calibración de color en LBP6230",
    category: "Calidad",
    models: ["Canon LBP6230dw"],
    brand: "Canon",
    faultType: "Calidad impresión",
    uses: 22,
    successRate: 0.71,
    updated: "2026-01-04",
  },
];

const KB_SUGGESTIONS = [
  {
    title: "Error 49.4C02 en HP M428fdw",
    cases: 7,
    period: "últimos 14 días",
    detail: "SOF.IA detectó 7 casos resueltos manualmente con el mismo procedimiento. Recomienda crear un artículo formal."
  },
  {
    title: "Resolución de ‘serie no aparece’ con cliente al contado",
    cases: 5,
    period: "últimos 30 días",
    detail: "Patrón frecuente. Operadores resuelven buscando por NIT como fallback. Vale formalizarlo."
  },
];

// ============================================================
// REGLAS MCP — lenguaje natural → comportamiento de SOF.IA
// ============================================================
const MCP_RULES = [
  {
    id: "R-001",
    text: "Si entra un HP sin serie, escala directo a Dispatcher.",
    author: "Alejandra Carrillo",
    created: "2026-04-12",
    triggers: 34,
    active: true,
    category: "Triage",
  },
  {
    id: "R-002",
    text: "Tickets de arrendamiento → área de Conectividad automáticamente.",
    author: "Sistema · regla base",
    created: "2026-01-10",
    triggers: 218,
    active: true,
    category: "Routing",
  },
  {
    id: "R-003",
    text: "Si el contrato no está grabado o vencido, notificar al operador antes de proponer visita.",
    author: "Alejandra Carrillo",
    created: "2026-03-28",
    triggers: 47,
    active: true,
    category: "Validación",
  },
  {
    id: "R-004",
    text: "Cliente facturado o solicitud de cotización → marcar ‘fuera de alcance fase 1’, no escalar.",
    author: "Marcos R. (Optipixel)",
    created: "2026-02-05",
    triggers: 91,
    active: true,
    category: "Triage",
  },
  {
    id: "R-005",
    text: "Si la falla amerita visita, ofrecer ventana matutina por defecto entre 9 y 12.",
    author: "Alejandra Carrillo",
    created: "2026-05-02",
    triggers: 62,
    active: true,
    category: "Agenda",
  },
  {
    id: "R-006",
    text: "Atascos repetidos del mismo equipo (>2 en 30 días) → escalar a Taller para revisión completa.",
    author: "Eddy R. Marroquín",
    created: "2026-05-18",
    triggers: 4,
    active: false,
    category: "Mantenimiento",
  },
];

// ============================================================
// MCP COPILOT — sample queries (precanned for demo)
// ============================================================
const MCP_THREAD = [
  {
    role: "user",
    text: "Buenos días SOF.IA, ¿cuántos tickets de atascos de papel hubo esta semana?",
    time: "10:14",
  },
  {
    role: "sofia",
    time: "10:14",
    text: "Esta semana se registraron **38 tickets** por atascos de papel. Distribución diaria:",
    sources: ["tickets", "kb"],
    widget: {
      kind: "bars",
      title: "Tickets de atasco · últimos 7 días",
      data: [
        { label: "L", value: 4 },
        { label: "M", value: 7 },
        { label: "M", value: 5 },
        { label: "J", value: 9 },
        { label: "V", value: 6 },
        { label: "S", value: 3 },
        { label: "D", value: 4 },
      ],
      note: "Promedio diario 5.4 · pico el jueves coincide con corte de fin de mes en 4 clientes corporativos.",
    },
  },
  {
    role: "user",
    text: "Dame el desglose de escalamientos por motivo del último mes",
    time: "10:16",
  },
  {
    role: "sofia",
    time: "10:16",
    text: "En los últimos 30 días hubo **127 escalamientos**. Los motivos se reparten así:",
    sources: ["tickets"],
    widget: {
      kind: "table",
      title: "Escalamientos por motivo",
      cols: ["Motivo", "Tickets", "% del total"],
      rows: [
        ["Serie no aparece / al contado", "41", "32.3%"],
        ["Falla amerita visita técnica", "33", "26.0%"],
        ["Cliente no puede dar la serie", "18", "14.2%"],
        ["Equipo retirado, robado o no se encuentra", "12", "9.4%"],
        ["Contrato no grabado/actualizado", "11", "8.7%"],
        ["Da IP / chasis / tóner en vez de serie", "8", "6.3%"],
        ["Pide búsqueda por NIT / nombre", "4", "3.1%"],
      ],
      note: "La principal causa sigue siendo identificación del equipo. Una regla de fallback por NIT podría capturar ~36 tickets/mes.",
    },
  },
  {
    role: "user",
    text: "¿Qué modelo de impresora genera más tickets?",
    time: "10:19",
  },
  {
    role: "sofia",
    time: "10:19",
    text: "Ranking de modelos por volumen de tickets este mes:",
    sources: ["tickets", "equipos"],
    widget: {
      kind: "rank",
      data: [
        { name: "HP LaserJet Pro M404dn", count: 87, pct: 22 },
        { name: "HP LaserJet M428fdw", count: 64, pct: 16 },
        { name: "Canon imageRUNNER 2630i", count: 41, pct: 10 },
        { name: "HP Color LaserJet M283fdw", count: 33, pct: 8 },
        { name: "HP OfficeJet Pro 9015e", count: 28, pct: 7 },
      ],
      note: "El M404dn concentra atascos de bandeja 2 (KB-HP-M404-008). El M428fdw tiene patrón de líneas verticales — vale revisar el lote.",
    },
  },
];

const MCP_QUICK = [
  "Tickets por canal hoy",
  "Tasa de resolución autónoma · semana",
  "Top 5 KB más usadas",
  "Equipos con >2 fallas en 30 días",
  "SLA en riesgo ahora",
];

// ============================================================
// LIFECYCLE — fases por las que pasa un ticket
// ============================================================
const PHASES = [
  { id: "recepcion",  label: "Recepción",          color: "#6B7280" },
  { id: "validacion", label: "Validación",         color: "#1E6FE3" },
  { id: "diagnostico",label: "Diagnóstico",        color: "#8E44AD" },
  { id: "accion",     label: "En curso",           color: "#B88500" },
  { id: "escalado",   label: "Escalado",           color: "#D7263D" },
  { id: "resuelto",   label: "Resuelto",           color: "#16A06B" },
];

// Sub-phases for the detailed bar
const SUB_PHASES = [
  "Recepción",
  "Validación de serie",
  "Validación de cliente",
  "Indagación de falla",
  "Ticket creado",
  "Visita propuesta",
  "Confirmada",
  "Resuelta",
];

// Extended ticket list with phase, owner area, attachments, etc.
const LIFECYCLE_TICKETS = [
  // ============ RECEPCION ============
  { id:"CNL-2845", channel:"whatsapp", customer:"Ana Patricia López",   company:"Café Quetzalito",            printer:"HP DeskJet 2755e",          phase:"recepcion",  sub:"Recepción", owner:"sofia", handler:"SOF.IA",       age:"00:00:18", slaPct:2, urgent:false },
  { id:"CNL-2844", channel:"call",     customer:"Diego Castillo",       company:"Construcciones Castillo",     printer:"HP LaserJet Pro M404n",      phase:"recepcion",  sub:"Recepción", owner:"sofia", handler:"SOF.IA",       age:"00:00:32", slaPct:3, urgent:false },
  { id:"CNL-2843", channel:"email",    customer:"Marisela Pinzón",      company:"Bufete Pinzón & Asoc.",       printer:"Canon imageRUNNER 2625i",    phase:"recepcion",  sub:"Recepción", owner:"sofia", handler:"SOF.IA",       age:"00:01:02", slaPct:5, urgent:false },
  { id:"CNL-2842", channel:"web",      customer:"Estuardo Ramírez",     company:"Imprenta Galaxia",            printer:"HP LaserJet M428fdw",        phase:"recepcion",  sub:"Recepción", owner:"sofia", handler:"SOF.IA",       age:"00:01:44", slaPct:6, urgent:false },

  // ============ VALIDACION ============
  { id:"CNL-2841", channel:"whatsapp", customer:"María F. Soto",        company:"Distribuidora El Quetzal",    printer:"HP LaserJet Pro M404dn",     phase:"accion",     sub:"Visita confirmada", owner:"sofia",   handler:"SOF.IA",   age:"00:03:42", slaPct:18, urgent:false },
  { id:"CNL-2840", channel:"call",     customer:"Roberto Cifuentes",    company:"Constructora Cifuentes",      printer:"Canon imageRUNNER 2630i",    phase:"escalado",   sub:"Esperando Dispatcher", owner:"dispatch", handler:"Dispatcher", age:"00:01:08", slaPct:8, urgent:true },
  { id:"CNL-2839", channel:"web",      customer:"Luis Pérez",           company:"Imprenta Color GT",           printer:"HP LaserJet M428fdw",        phase:"diagnostico",sub:"Indagación de falla", owner:"sofia", handler:"SOF.IA",  age:"00:06:21", slaPct:24, urgent:false },
  { id:"CNL-2838", channel:"web",      customer:"Andrea Molina",        company:"Grupo Techo",                 printer:"HP Color LaserJet M283fdw",  phase:"validacion", sub:"Validación de cliente", owner:"sofia", handler:"SOF.IA", age:"00:11:55", slaPct:31, urgent:false },
  { id:"CNL-2837", channel:"call",     customer:"Industrias Polar",     company:"Industrias Polar CA",         printer:"Canon LBP6230dw",            phase:"escalado",   sub:"En Conectividad", owner:"conectividad", handler:"Conectividad", age:"00:18:02", slaPct:62, urgent:true },
  { id:"CNL-2836", channel:"email",    customer:"Karla Estrada",        company:"Notaría Estrada & Asoc.",     printer:"HP OfficeJet Pro 9015e",     phase:"accion",     sub:"Visita propuesta", owner:"sofia",   handler:"SOF.IA",   age:"00:24:11", slaPct:42, urgent:false },
  { id:"CNL-2835", channel:"whatsapp", customer:"José Alvarado",        company:"Ferretería Alvarado",         printer:"HP LaserJet M111w",          phase:"resuelto",   sub:"Resuelto · KB", owner:"sofia",   handler:"SOF.IA",    age:"00:08:42", slaPct:100, urgent:false },
  { id:"CNL-2834", channel:"call",     customer:"Helena Castañeda",     company:"Clínicas Vida Nueva",         printer:"HP LaserJet Pro M428",       phase:"escalado",   sub:"En Taller", owner:"taller",   handler:"Taller",        age:"00:14:30", slaPct:71, urgent:false },
  { id:"CNL-2833", channel:"whatsapp", customer:"Eva Maldonado",        company:"Mueblería del Centro",        printer:"HP LaserJet Pro M404n",      phase:"validacion", sub:"Validación de serie", owner:"sofia", handler:"SOF.IA", age:"00:02:21", slaPct:11, urgent:false },
  { id:"CNL-2832", channel:"email",    customer:"Pablo Recinos",        company:"Auditores Recinos",           printer:"Canon imageRUNNER 2625i",    phase:"validacion", sub:"Validación de serie", owner:"sofia", handler:"SOF.IA", age:"00:04:18", slaPct:14, urgent:false },
  { id:"CNL-2831", channel:"web",      customer:"Cristina Vela",        company:"Colegio San Pedro",           printer:"HP LaserJet M428dw",         phase:"diagnostico",sub:"Indagación de falla", owner:"sofia", handler:"SOF.IA", age:"00:09:11", slaPct:38, urgent:false },
  { id:"CNL-2830", channel:"whatsapp", customer:"Karen Avilés",         company:"Florería Tulipán",            printer:"HP DeskJet 2755e",           phase:"resuelto",   sub:"Resuelto · auto", owner:"sofia",   handler:"SOF.IA",   age:"00:02:31", slaPct:100, urgent:false },
  { id:"CNL-2829", channel:"call",     customer:"Mario Ovalle",         company:"Importadora Sol",             printer:"HP LaserJet Pro M404dn",     phase:"accion",     sub:"Visita confirmada", owner:"sofia",   handler:"SOF.IA",   age:"00:31:02", slaPct:55, urgent:false },
  { id:"CNL-2828", channel:"web",      customer:"Boutique Vera",        company:"Boutique Vera",               printer:"Canon LBP6230dw",            phase:"resuelto",   sub:"Resuelto · auto", owner:"sofia",   handler:"SOF.IA",   age:"00:06:14", slaPct:100, urgent:false },
  { id:"CNL-2827", channel:"email",    customer:"Sergio Funes",         company:"Funes & Cía.",                printer:"HP LaserJet M428fdw",        phase:"validacion", sub:"Validación de cliente", owner:"sofia", handler:"SOF.IA", age:"00:02:48", slaPct:11, urgent:false },
  { id:"CNL-2826", channel:"call",     customer:"Hugo Méndez",          company:"Distribuciones HM",           printer:"HP Color LaserJet M283fdw",  phase:"resuelto",   sub:"Resuelto · auto", owner:"sofia",   handler:"SOF.IA",   age:"00:05:02", slaPct:100, urgent:false },
  { id:"CNL-2825", channel:"whatsapp", customer:"Andrea Pérez",         company:"Estética Andrea",             printer:"HP LaserJet M111w",          phase:"resuelto",   sub:"Resuelto · auto", owner:"sofia",   handler:"SOF.IA",   age:"00:03:18", slaPct:100, urgent:false },

  // ============ MAS DIAGNOSTICO ============
  { id:"CNL-2824", channel:"email",    customer:"Hotel Casa Blanca",    company:"Hotel Casa Blanca Antigua",   printer:"HP LaserJet Pro M404dn",     phase:"diagnostico",sub:"Esperando foto display", owner:"sofia", handler:"SOF.IA", age:"01:12:04", slaPct:48, urgent:false },
  { id:"CNL-2823", channel:"call",     customer:"Tienda La Aurora",     company:"Tienda La Aurora",            printer:"HP LaserJet Pro M404n",      phase:"diagnostico",sub:"Indagación de falla", owner:"sofia", handler:"SOF.IA", age:"01:30:11", slaPct:55, urgent:false },
  { id:"CNL-2822", channel:"whatsapp", customer:"Ferretería El Sol",    company:"Ferretería El Sol",           printer:"HP LaserJet M111w",          phase:"escalado",   sub:"En Dispatcher", owner:"dispatch",  handler:"Dispatcher",  age:"00:11:40", slaPct:38, urgent:true },
  { id:"CNL-2821", channel:"call",     customer:"Rest. Doña Luisa",     company:"Restaurante Doña Luisa",      printer:"Canon imageRUNNER 2625i",    phase:"escalado",   sub:"En Dispatcher", owner:"dispatch",  handler:"Dispatcher",  age:"00:27:30", slaPct:61, urgent:true },

  // ============ MAS ACCION (en curso) ============
  { id:"CNL-2820", channel:"whatsapp", customer:"Carlos Aguilar",       company:"Carrocería Aguilar",          printer:"HP LaserJet Pro M404dn",     phase:"resuelto",   sub:"Resuelto · visita", owner:"sofia",   handler:"SOF.IA",   age:"02:08:11", slaPct:100, urgent:false },
  { id:"CNL-2819", channel:"email",    customer:"Verónica Rojas",       company:"Universidad del Valle",       printer:"HP Color LaserJet M283fdw",  phase:"accion",     sub:"Visita propuesta", owner:"sofia", handler:"SOF.IA",  age:"00:38:14", slaPct:44, urgent:false },
  { id:"CNL-2818", channel:"call",     customer:"Sandra Villatoro",     company:"Clínica Villatoro",           printer:"Canon imageRUNNER 2625i",    phase:"escalado",   sub:"En Taller", owner:"taller",  handler:"Taller",       age:"00:42:18", slaPct:78, urgent:false },
  { id:"CNL-2817", channel:"whatsapp", customer:"Farmacia Vida",        company:"Farmacia Vida",               printer:"HP LaserJet M111w",          phase:"accion",     sub:"Visita confirmada", owner:"sofia", handler:"SOF.IA", age:"00:46:02", slaPct:52, urgent:false },
  { id:"CNL-2816", channel:"web",      customer:"Lucía Marroquín",      company:"Editorial Páginas",           printer:"HP LaserJet M428fdw",        phase:"escalado",   sub:"En Taller", owner:"taller",  handler:"Taller",       age:"00:54:21", slaPct:81, urgent:false },
  { id:"CNL-2815", channel:"call",     customer:"Hotel del Lago",       company:"Hotel del Lago Atitlán",      printer:"HP Color LaserJet M283fdw",  phase:"accion",     sub:"Visita propuesta", owner:"sofia", handler:"SOF.IA",  age:"01:08:00", slaPct:67, urgent:false },
  { id:"CNL-2814", channel:"whatsapp", customer:"Ricardo Solís",        company:"Cafetería La Plaza",          printer:"HP LaserJet Pro M404n",      phase:"resuelto",   sub:"Resuelto · auto", owner:"sofia",   handler:"SOF.IA",   age:"04:55:00", slaPct:100, urgent:false },
  { id:"CNL-2813", channel:"call",     customer:"Cementos Progreso",    company:"Cementos Progreso (planta 2)",printer:"HP LaserJet Pro M404dn",     phase:"accion",     sub:"Visita confirmada", owner:"sofia", handler:"SOF.IA", age:"00:22:11", slaPct:34, urgent:false },
  { id:"CNL-2812", channel:"email",    customer:"Yésica Tobar",         company:"Asoc. Mujeres Activas",       printer:"HP LaserJet Pro M404dn",     phase:"resuelto",   sub:"Resuelto · KB", owner:"sofia",   handler:"SOF.IA",   age:"05:11:04", slaPct:100, urgent:false },
  { id:"CNL-2811", channel:"whatsapp", customer:"Inmobiliaria Vista",   company:"Inmobiliaria Vista Hermosa",  printer:"HP LaserJet Pro M404n",      phase:"diagnostico",sub:"Cruce con historial", owner:"sofia", handler:"SOF.IA", age:"00:18:22", slaPct:41, urgent:false },
  { id:"CNL-2810", channel:"call",     customer:"Banca Crédito GT",     company:"Banca Crédito GT (Mixco)",    printer:"Canon imageRUNNER 2630i",    phase:"resuelto",   sub:"Resuelto · auto", owner:"sofia",   handler:"SOF.IA",   age:"06:42:00", slaPct:100, urgent:false },
  { id:"CNL-2809", channel:"web",      customer:"Bufete Solórzano",     company:"Solórzano & Asoc.",           printer:"HP OfficeJet Pro 9015e",     phase:"validacion", sub:"Validación de cliente", owner:"sofia", handler:"SOF.IA", age:"00:08:32", slaPct:21, urgent:false },
  { id:"CNL-2808", channel:"email",    customer:"Café León",            company:"Café León (sucursal Zona 1)", printer:"HP DeskJet 4155e",           phase:"validacion", sub:"Validación de serie", owner:"sofia", handler:"SOF.IA", age:"00:04:11", slaPct:14, urgent:false },
  { id:"CNL-2807", channel:"whatsapp", customer:"Joyería La Roca",      company:"Joyería La Roca",             printer:"HP LaserJet M111w",          phase:"accion",     sub:"Visita propuesta", owner:"sofia", handler:"SOF.IA",  age:"00:52:08", slaPct:58, urgent:false },
  { id:"CNL-2806", channel:"call",     customer:"Pollo Campero",        company:"Pollo Campero (zona 11)",     printer:"HP Color LaserJet M283fdw",  phase:"escalado",   sub:"En Conectividad", owner:"conectividad", handler:"Conectividad", age:"00:38:44", slaPct:74, urgent:false },
  { id:"CNL-2805", channel:"web",      customer:"Cervecería CA",        company:"Cervecería Centroamericana",  printer:"HP LaserJet M428fdw",        phase:"diagnostico",sub:"Indagación de falla", owner:"sofia", handler:"SOF.IA", age:"00:15:21", slaPct:36, urgent:false },
  { id:"CNL-2804", channel:"whatsapp", customer:"Iván Aragón",          company:"Repuestos Cardenal",          printer:"HP LaserJet Pro M404dn",     phase:"resuelto",   sub:"Resuelto · auto", owner:"sofia",   handler:"SOF.IA",   age:"03:42:00", slaPct:100, urgent:false },
  { id:"CNL-2803", channel:"email",    customer:"Cooperativa Salcajá",  company:"Cooperativa Salcajá",         printer:"Canon imageRUNNER 2625i",    phase:"accion",     sub:"En Taller", owner:"taller",   handler:"Taller",       age:"01:14:00", slaPct:79, urgent:false },
  { id:"CNL-2802", channel:"call",     customer:"Empacadora Toledo",    company:"Empacadora Toledo",           printer:"Canon LBP6230dw",            phase:"escalado",   sub:"Esperando Dispatcher", owner:"dispatch", handler:"Dispatcher", age:"00:18:00", slaPct:42, urgent:false },
  { id:"CNL-2801", channel:"whatsapp", customer:"Fernanda Aguilar",     company:"Importaciones Wong",          printer:"HP LaserJet Pro M404n",      phase:"validacion", sub:"Validación de contrato", owner:"sofia", handler:"SOF.IA", age:"00:06:14", slaPct:18, urgent:false },
  { id:"CNL-2800", channel:"web",      customer:"Fundación Casa Niño",  company:"Fundación Casa del Niño",     printer:"HP LaserJet M111w",          phase:"resuelto",   sub:"Resuelto · auto", owner:"sofia",   handler:"SOF.IA",   age:"08:14:00", slaPct:100, urgent:false },
  { id:"CNL-2799", channel:"email",    customer:"Beatriz Solórzano",    company:"Solórzano & Asoc.",           printer:"HP OfficeJet Pro 9015e",     phase:"resuelto",   sub:"Resuelto · KB", owner:"sofia",   handler:"SOF.IA",    age:"09:30:00", slaPct:100, urgent:false },
  { id:"CNL-2798", channel:"whatsapp", customer:"Otto Pérez",           company:"Asesores Quetzal",            printer:"HP LaserJet M111w",          phase:"resuelto",   sub:"Resuelto · auto", owner:"sofia",   handler:"SOF.IA",   age:"11:08:00", slaPct:100, urgent:false },
  { id:"CNL-2797", channel:"call",     customer:"Cámara de Comercio",   company:"Cámara de Comercio (zona 4)", printer:"Canon imageRUNNER 2625i",    phase:"resuelto",   sub:"Resuelto · visita", owner:"sofia",   handler:"SOF.IA",   age:"12:24:00", slaPct:100, urgent:false },
];

// ============================================================
// EQUIPMENT HISTORY — for the focused case
// ============================================================
const EQUIPMENT_HISTORY = {
  "VNB3K12089": {
    model: "HP LaserJet Pro M404dn",
    installed: "2023-08-15",
    counter: 91420,
    counterUnits: "impresiones",
    avgMonthly: 4280,
    pastTickets: [
      { id:"CNL-1842", date:"2025-12-04", channel:"whatsapp", issue:"Toner agotado (cartucho 58A)", solver:"SOF.IA · auto", duration:"4 min" },
      { id:"CNL-1611", date:"2025-10-19", channel:"call",     issue:"Configuración duplex bandeja 1", solver:"SOF.IA · auto", duration:"2 min" },
      { id:"CNL-1098", date:"2025-06-30", channel:"email",    issue:"Visita preventiva semestral", solver:"Eddy R. Marroquín", duration:"on-site" },
      { id:"CNL-0721", date:"2024-12-12", channel:"whatsapp", issue:"Atasco bandeja 2 (¡mismo síntoma!)", solver:"Dispatcher", duration:"on-site" },
    ],
    alerts: [
      "Reincidencia: este es el 2.º atasco de bandeja 2 en 18 meses.",
      "Contador supera el umbral típico de fallo del rodillo (~80k impresiones).",
    ],
  }
};

// ============================================================
// ATTACHMENTS — del cliente
// ============================================================
const ATTACHMENTS_2841 = [
  { kind:"image", label:"Foto del display de error", source:"whatsapp", time:"10:43", size:"0.8 MB" },
  { kind:"image", label:"Foto del papel atascado",   source:"whatsapp", time:"10:44", size:"1.2 MB" },
  { kind:"audio", label:"Nota de voz · síntoma",     source:"whatsapp", time:"10:43", size:"0:14" },
];

// ============================================================
// SLA timing for case 2841
// ============================================================
const SLA_2841 = {
  target: "4 horas a primera respuesta · 24 h a resolución",
  segments: [
    { phase: "Recepción",          duration: "0:00:03", status: "ok" },
    { phase: "Validación serie",   duration: "0:00:11", status: "ok" },
    { phase: "Validación cliente", duration: "0:00:02", status: "ok" },
    { phase: "Indagación falla",   duration: "0:02:24", status: "ok" },
    { phase: "Ticket creado",      duration: "0:00:02", status: "ok" },
    { phase: "Visita propuesta",   duration: "0:00:34", status: "ok" },
    { phase: "Confirmada",         duration: "0:00:26", status: "ok" },
  ],
  totalCapture: "0:03:42",
  slaStatus: "a-tiempo",
};

// ============================================================
// AUDIT TRAIL — para el ticket focal
// ============================================================
const AUDIT_2841 = [
  { actor: "sofia",  action: "Recibió mensaje entrante",     time: "10:42:18", note: "vía WhatsApp · +502 5512 0481" },
  { actor: "sofia",  action: "Clasificó · falla HW · atasco", time: "10:42:19", note: "confianza 0.94" },
  { actor: "sofia",  action: "Validó serie en BD",            time: "10:43:07", note: "VNB3K12089 · match exacto" },
  { actor: "sofia",  action: "Cruzó historial del equipo",    time: "10:45:16", note: "contador 91,420 · alerta reincidencia" },
  { actor: "sofia",  action: "Consultó KB",                   time: "10:45:14", note: "KB-HP-M404-008 · score 0.91" },
  { actor: "sofia",  action: "Reservó slot técnico",          time: "10:45:58", note: "Eddy R. Marroquín · zona 11" },
  { actor: "sofia",  action: "Creó ticket #CNL-2841",         time: "10:45:59", note: "auto" },
  { actor: "sofia",  action: "Envió correo de confirmación",  time: "10:46:00", note: "3 destinatarios" },
];

// ============================================================
// PER-CHANNEL CASES (so click any ticket shows correct render)
// ============================================================

// 2836 — Email case · Karla Estrada · OfficeJet
const CASE_EMAIL = {
  id: "CNL-2836",
  channel: "email",
  customer: "Karla Estrada",
  customerSub: "kestrada@notariaestrada.com.gt",
  company: "Notaría Estrada & Asoc.",
  printer: "HP OfficeJet Pro 9015e",
  serial: "TH1B9011XK",
  contract: "MANT-2024-217 · vigente",
  state: "auto",
  startedAt: "10:18",
  duration: "8 min 24 s",
  emailThread: [
    {
      from: "kestrada@notariaestrada.com.gt",
      fromName: "Karla Estrada",
      to: "soporte@canella.gt",
      subject: "Falla intermitente · OfficeJet de la notaría",
      time: "Hoy · 10:18",
      body: `Buen día,

La impresora multifuncional que tenemos en la notaría está fallando de forma intermitente desde el lunes. A veces imprime sin problemas y a veces da un error rojo y se reinicia sola.

Necesito apoyo lo antes posible porque tenemos audiencia el jueves y debemos imprimir mucha documentación.

Adjunto fotos del display cuando da el error.

Saludos,
Lic. Karla Estrada
Notaría Estrada & Asoc.
NIT 2873041-2`,
      direction: "in",
      hasAttachments: true,
    },
    {
      from: "sofia@canella.gt",
      fromName: "SOF.IA · Soporte Canella",
      to: "kestrada@notariaestrada.com.gt",
      subject: "Re: Falla intermitente · OfficeJet de la notaría · Ticket #CNL-2836",
      time: "Hoy · 10:24",
      body: `Estimada Licda. Estrada,

Recibimos su reporte y abrimos el ticket #CNL-2836. Identificamos su equipo:

  Serie:        TH1B9011XK
  Modelo:       HP OfficeJet Pro 9015e
  Cliente:      Notaría Estrada & Asoc. (NIT 2873041-2)
  Contrato:     MANT-2024-217 · vigente

A partir de la foto del display el error corresponde al código E-002, asociado al cabezal de impresión. Este es un fallo que generalmente requiere visita técnica para limpieza profunda del cabezal o sustitución.

Dada la urgencia mencionada (audiencia del jueves), le propongo una visita mañana miércoles 28/05 entre 9:00 y 12:00.

¿Le funciona ese horario? Confirme respondiendo SÍ a este correo y queda agendado.

Atentamente,
SOF.IA`,
      direction: "out",
    },
    {
      from: "kestrada@notariaestrada.com.gt",
      fromName: "Karla Estrada",
      to: "soporte@canella.gt",
      subject: "Re: Re: Falla intermitente · Ticket #CNL-2836",
      time: "Hoy · 10:26",
      body: "Sí confirmo, mañana entre 9 y 12 está bien. Gracias.",
      direction: "in",
    },
    {
      from: "sofia@canella.gt",
      fromName: "SOF.IA · Soporte Canella",
      to: "kestrada@notariaestrada.com.gt; despacho@canella.gt",
      cc: "tecnicos.zona10@canella.gt",
      subject: "Confirmación · Visita técnica #CNL-2836 · Notaría Estrada",
      time: "Hoy · 10:26",
      direction: "out",
      isFormal: true,
      body: `Estimada Licda. Estrada,

Confirmamos la apertura y agenda de su ticket de servicio:

  # Ticket:        CNL-2836
  Serie equipo:    TH1B9011XK (HP OfficeJet Pro 9015e)
  Cliente:         Notaría Estrada & Asoc.  ·  NIT 2873041-2
  Contrato:        MANT-2024-217  ·  Vigente
  Motivo:          Diagnóstico cabezal — error E-002
  Diagnóstico:     Falla intermitente cabezal de impresión

Visita programada
  Fecha:           Miércoles 28 de mayo de 2026
  Ventana:         09:00 – 12:00 hrs
  Dirección:       12 Avenida 6-25 zona 10, edificio Real Reforma, oficina 401
  Técnico asign.:  Walter A. Galindo  ·  DPI 1998 47820 0101
  Vehículo:        Pickup Hyundai H100 blanco  ·  Placas P-301BVN

El técnico le confirmará 30 minutos antes del arribo.

Atentamente,
SOF.IA · Soporte Canella
(generado automáticamente · 27/05/2026 10:26)`,
    },
  ],
};

// 2838 — Web chat · Andrea Molina · toner amarillo
const CASE_WEB = {
  id: "CNL-2838",
  channel: "web",
  customer: "Andrea Molina",
  customerSub: "andrea.molina@grupotecho.gt · widget web canella.gt",
  company: "Grupo Techo",
  printer: "HP Color LaserJet M283fdw",
  serial: "CNF9X22033",
  contract: "MANT-2024-301 · vigente",
  state: "progress",
  duration: "12 min",
  conversation: [
    { dir:"in", text:"Hola, mi impresora dice que ya no tiene tóner amarillo. ¿Cómo lo solicito?", time:"09:48" },
    { dir:"out", text:"Hola Andrea, soy SOF.IA. Te ayudo con el repuesto. ¿Me confirmas la serie del equipo? Aparece en la pantalla en Configuración → Acerca de.", time:"09:48" },
    { dir:"in", text:"CNF9X22033", time:"09:49" },
    { dir:"out", text:"Perfecto. HP Color LaserJet M283fdw de Grupo Techo, bajo contrato MANT-2024-301. Cubre consumibles. Te despacho el cartucho ref. W2112A (amarillo) hoy mismo a la dirección registrada. ¿Sigue siendo 13 Calle 1-22 zona 10?", time:"09:49" },
    { dir:"in", text:"sí, esa", time:"09:50" },
    { dir:"out", text:"Listo. Despacho confirmado para llegar en las próximas 4 horas. Te llegará confirmación por correo. ¿Algo más?", time:"09:50" },
  ],
};

// 2834 — Call · Helena · serie ilegible (escalated, en taller)
const CASE_HELENA = {
  id: "CNL-2834",
  channel: "call",
  customer: "Helena Castañeda",
  customerSub: "+502 5790 2200",
  company: "Clínicas Vida Nueva",
  printer: "HP LaserJet Pro M428",
  serialAttempted: "CNB8H4XXXX (ilegible)",
  state: "escalated",
  reason: "cliente-no-serie",
};

Object.assign(window, {
  KB_ARTICLES, KB_SUGGESTIONS,
  MCP_RULES, MCP_THREAD, MCP_QUICK,
  PHASES, SUB_PHASES, LIFECYCLE_TICKETS,
  EQUIPMENT_HISTORY, ATTACHMENTS_2841, SLA_2841, AUDIT_2841,
  CASE_EMAIL, CASE_WEB, CASE_HELENA,
});
