/* global React */
// =======================================================================
// BlazeConnector Admin v3 — Mock data
// Realistic Dominican ISP tenants + messages/logs/queues/alerts/audit
// =======================================================================

const TENANTS = [
  { id: 'tnt_01HV3', uuid: '8f4a2c9e-b1d3-4e87-a5f2-9c8b3d7a1e42', name: 'TeleCaribe',          slug: 'telecaribe',     plan: 'Enterprise', status: 'active',     modules: ['mensajeria','billing','pagos','automation'], region: 'Santo Domingo', subs: 18420, lastActive: '2026-05-26T17:42:18Z', channels: ['whatsapp','telegram','chatwoot'], billing: 'mikrowisp', pagos: ['cardnet','azul'],     errorRate: 0.4,  msgs24h: 8412 },
  { id: 'tnt_02KW9', uuid: '2d1f6a83-7e9c-4b21-9f0a-1d8e4c7b6f95', name: 'AltaVelocidad RD',    slug: 'altavel-rd',     plan: 'Pro',        status: 'active',     modules: ['mensajeria','billing','pagos'],              region: 'Santiago',      subs: 9840,  lastActive: '2026-05-26T17:44:02Z', channels: ['whatsapp','chatwoot'],           billing: 'wisphub',    pagos: ['cardnet'],            errorRate: 1.2,  msgs24h: 4112 },
  { id: 'tnt_03LM7', uuid: '5a9c8e21-3f4d-4a7b-b8e3-2c1f9a6d8e07', name: 'WispNorte',           slug: 'wispnorte',      plan: 'Pro',        status: 'active',     modules: ['mensajeria','billing'],                      region: 'Puerto Plata',  subs: 3120,  lastActive: '2026-05-26T17:39:55Z', channels: ['whatsapp'],                       billing: 'mikrowisp',  pagos: ['azul'],               errorRate: 0.1,  msgs24h: 1284 },
  { id: 'tnt_04QZ2', uuid: '7b3e9d12-8a5c-4f63-91d8-6e2a4b7c9f01', name: 'CibaoNet',            slug: 'cibaonet',       plan: 'Enterprise', status: 'active',     modules: ['mensajeria','billing','pagos','automation'], region: 'La Vega',       subs: 12760, lastActive: '2026-05-26T17:44:11Z', channels: ['whatsapp','telegram','chatwoot'], billing: 'wisphub',   pagos: ['cardnet','paypal'],   errorRate: 0.7,  msgs24h: 6203 },
  { id: 'tnt_05RT4', uuid: '9c2a4f81-5e7b-4d92-a3f1-8b6c1d7e9f04', name: 'OcoaConnect',         slug: 'ocoaconnect',    plan: 'Starter',    status: 'suspended',  modules: ['mensajeria'],                                region: 'Ocoa',          subs: 412,   lastActive: '2026-05-21T11:08:22Z', channels: ['whatsapp'],                       billing: 'oficable',   pagos: [],                     errorRate: 4.8,  msgs24h: 0 },
  { id: 'tnt_06DV1', uuid: '4d8b3e57-1c9a-4f26-8d5e-7b2f1a9c4e08', name: 'DR Fibra',            slug: 'dr-fibra',       plan: 'Pro',        status: 'active',     modules: ['mensajeria','billing','pagos'],              region: 'San Cristóbal', subs: 5630,  lastActive: '2026-05-26T17:43:48Z', channels: ['whatsapp','chatwoot'],           billing: 'domiisp',    pagos: ['cardnet'],            errorRate: 0.9,  msgs24h: 2891 },
  { id: 'tnt_07HY8', uuid: '6f1d8a93-4b2e-4c81-9a6f-3d7e2b1c4f95', name: 'MaoNet',              slug: 'maonet',         plan: 'Starter',    status: 'active',     modules: ['mensajeria'],                                region: 'Mao',           subs: 1840,  lastActive: '2026-05-26T17:32:14Z', channels: ['whatsapp'],                       billing: 'smartolt',   pagos: [],                     errorRate: 0.3,  msgs24h: 982 },
  { id: 'tnt_08PN6', uuid: '8a4c2d61-9e3f-4b78-a1c5-2f9d8e6b1a04', name: 'Punta Cana Fiber',    slug: 'pc-fiber',       plan: 'Enterprise', status: 'active',     modules: ['mensajeria','billing','pagos','automation'], region: 'Punta Cana',    subs: 14290, lastActive: '2026-05-26T17:43:59Z', channels: ['whatsapp','telegram','chatwoot'], billing: 'wisphub',   pagos: ['cardnet','azul','paypal'], errorRate: 0.5, msgs24h: 7146 },
  { id: 'tnt_09SB3', uuid: '1e7f9d24-6c3b-4a85-9f1d-8b4e2c7a3f60', name: 'Sabaneta Telecom',    slug: 'sabaneta-tc',    plan: 'Pro',        status: 'active',     modules: ['mensajeria','billing','pagos'],              region: 'Sabaneta',      subs: 2104,  lastActive: '2026-05-26T17:41:02Z', channels: ['whatsapp','chatwoot'],           billing: 'mikrowisp',  pagos: ['azul'],               errorRate: 1.4,  msgs24h: 1421 },
  { id: 'tnt_10AZ5', uuid: '3c9e1f48-7d2b-4a63-8e5f-1a6c4b8d2f97', name: 'Azua Wireless',       slug: 'azua-wireless',  plan: 'Starter',    status: 'inactive',   modules: ['mensajeria'],                                region: 'Azua',          subs: 718,   lastActive: '2026-04-29T08:14:31Z', channels: ['whatsapp'],                       billing: 'oficable',   pagos: [],                     errorRate: 0,    msgs24h: 0 },
  { id: 'tnt_11BV2', uuid: '5b2f7a91-8c4e-4d36-91a8-6f3e1c9b4d05', name: 'BávaroLink',          slug: 'bavarolink',     plan: 'Pro',        status: 'active',     modules: ['mensajeria','billing','pagos'],              region: 'Bávaro',        subs: 4218,  lastActive: '2026-05-26T17:44:01Z', channels: ['whatsapp','telegram'],            billing: 'wisphub',    pagos: ['cardnet'],            errorRate: 0.6,  msgs24h: 2104 },
  { id: 'tnt_12HG9', uuid: '7d4a9c12-3e6b-4f81-a2d5-9b1f8e2c7a04', name: 'Higüey Conecta',      slug: 'higuey-conecta', plan: 'Starter',    status: 'active',     modules: ['mensajeria','billing'],                      region: 'Higüey',        subs: 1502,  lastActive: '2026-05-26T17:38:42Z', channels: ['whatsapp'],                       billing: 'mikrowisp',  pagos: ['azul'],               errorRate: 0.2,  msgs24h: 814 }
];

const CHANNEL_LABEL = {
  whatsapp: 'WhatsApp',
  telegram: 'Telegram',
  chatwoot: 'Chatwoot',
  messenger: 'Messenger',
  instagram: 'Instagram',
  sms: 'SMS',
  email: 'Email'
};
const CHANNEL_LETTER = { whatsapp: 'W', telegram: 'T', chatwoot: 'C', messenger: 'M', instagram: 'I', sms: 'S', email: 'E' };

const PROVIDERS_ISP = [
  { id: 'mikrowisp',  name: 'Mikrowisp',  category: 'Billing/OSS', vendor: 'Mikrowisp',  status: 'healthy',  latency: 142, tenants: 4, version: 'v6.7.3',  apiBase: 'https://api.mikrowisp.com/api/v1' },
  { id: 'wisphub',    name: 'WispHub',    category: 'Billing/OSS', vendor: 'WispHub',    status: 'healthy',  latency: 218, tenants: 4, version: 'v2.4.0',  apiBase: 'https://api.wisphub.net/api/v1' },
  { id: 'domiisp',    name: 'DomiISP',    category: 'Billing/OSS', vendor: 'DomiISP',    status: 'degraded', latency: 612, tenants: 1, version: 'v3.1.8',  apiBase: 'https://app.domiisp.com/api' },
  { id: 'oficable',   name: 'Oficable',   category: 'Billing/OSS', vendor: 'Oficable',   status: 'healthy',  latency: 184, tenants: 2, version: 'v1.9.4',  apiBase: 'https://api.oficable.com.do/v1' },
  { id: 'smartolt',   name: 'SmartOLT',   category: 'Billing/OSS', vendor: 'SmartOLT',   status: 'healthy',  latency: 96,  tenants: 1, version: 'v23.10',  apiBase: 'https://api.smartolt.com/v1' }
];

const PROVIDERS_PAY = [
  { id: 'cardnet',    name: 'CardNET',    category: 'Pagos', vendor: 'CardNET',    status: 'healthy',  latency: 412, tenants: 6, version: 'PSP v2', currency: 'DOP', authMode: 'OAuth2'  },
  { id: 'azul',       name: 'Azul',       category: 'Pagos', vendor: 'Banco Popular Azul', status: 'healthy', latency: 380, tenants: 5, version: 'WS v3.1', currency: 'DOP', authMode: 'API Key' },
  { id: 'paypal',     name: 'PayPal',     category: 'Pagos', vendor: 'PayPal',     status: 'healthy',  latency: 528, tenants: 2, version: 'REST v2', currency: 'USD', authMode: 'OAuth2' },
  { id: 'cybersource',name: 'CyberSource',category: 'Pagos', vendor: 'CyberSource', status: 'down',    latency: null, tenants: 1, version: 'REST v2', currency: 'USD', authMode: 'HMAC' }
];

const QUEUES = [
  { name: 'critical',  active: 12,  pending: 4,    retry: 0,   archived: 0,   failed: 0,   completed: 2841,  throughputPerMin: 84,  p95: 142,  workers: 6,  weight: 6 },
  { name: 'messaging', active: 184, pending: 612,  retry: 38,  archived: 14,  failed: 12,  completed: 84219, throughputPerMin: 1240, p95: 318, workers: 24, weight: 4 },
  { name: 'webhooks',  active: 42,  pending: 184,  retry: 22,  archived: 6,   failed: 4,   completed: 18420, throughputPerMin: 412, p95: 612,  workers: 12, weight: 3 },
  { name: 'default',   active: 8,   pending: 24,   retry: 2,   archived: 1,   failed: 1,   completed: 9214,  throughputPerMin: 84,  p95: 480,  workers: 4,  weight: 2 },
  { name: 'low',       active: 2,   pending: 142,  retry: 0,   archived: 28,  failed: 0,   completed: 4128,  throughputPerMin: 24,  p95: 1840, workers: 2,  weight: 1 }
];

const SERVICES = ['msgr.dispatch', 'msgr.inbound', 'msgr.webhook', 'billing.sync', 'pagos.callback', 'pagos.process', 'auth.session', 'audit.writer', 'sse.broker', 'wabacloud.proxy', 'telegram.bot', 'chatwoot.bridge', 'mikrowisp.adapter', 'wisphub.adapter', 'sched.cron'];

const TRACE_PREFIX = () => Math.random().toString(16).slice(2, 10) + Math.random().toString(16).slice(2, 10);

function randomFrom(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
function randHex(n) { return Array.from({ length: n }, () => Math.floor(Math.random() * 16).toString(16)).join(''); }

const ERROR_TEMPLATES = [
  { svc: 'msgr.dispatch',     level: 'error', msg: 'whatsapp cloud api: rate_limit_exceeded for phone_number_id=104982304', code: '131056' },
  { svc: 'msgr.dispatch',     level: 'error', msg: 'meta graph: 24h customer service window expired — template required', code: '131047' },
  { svc: 'msgr.webhook',      level: 'warn',  msg: 'signature mismatch on inbound webhook — discarding', code: 'WHK_SIG_BAD' },
  { svc: 'pagos.callback',    level: 'error', msg: 'cardnet ipn: invalid currency code "DPP" — expected DOP', code: 'PAY_CUR_002' },
  { svc: 'pagos.process',     level: 'warn',  msg: 'azul: 3DS step-up required — flow paused at challenge', code: 'AZL_3DS_01' },
  { svc: 'billing.sync',      level: 'error', msg: 'wisphub: 503 service unavailable — backoff 30s', code: 'WHB_503' },
  { svc: 'billing.sync',      level: 'warn',  msg: 'mikrowisp: invoice 84219 marked paid in source — local diff resolved', code: null },
  { svc: 'wabacloud.proxy',   level: 'info',  msg: 'template "factura_lista_ES" SYNCED → 1 tenant', code: null },
  { svc: 'wabacloud.proxy',   level: 'error', msg: 'template "promo_oferta_mayo" REJECTED → reason: promotional category violation', code: 'TPL_REJ_PR' },
  { svc: 'sse.broker',        level: 'info',  msg: 'client reconnected — channel=ops.dashboard sid=87a3', code: null },
  { svc: 'auth.session',      level: 'warn',  msg: 'api key tnt_07HY8/key_AHmK9 used after expiration warning', code: null },
  { svc: 'chatwoot.bridge',   level: 'error', msg: 'chatwoot: contact merge failed — duplicate phone E.164=+18095551842', code: 'CWB_MRG' },
  { svc: 'telegram.bot',      level: 'info',  msg: 'incoming command /factura from chat=−1001984... → routed', code: null },
  { svc: 'sched.cron',        level: 'info',  msg: 'cron: daily.invoice.notify completed — 4128 messages dispatched in 142s', code: null },
  { svc: 'msgr.inbound',      level: 'info',  msg: 'received message_status=delivered for wamid=wamid.HBgL...', code: null },
  { svc: 'msgr.inbound',      level: 'debug', msg: 'normalizing inbound payload v=3.0 schema=meta', code: null },
  { svc: 'mikrowisp.adapter', level: 'error', msg: 'unexpected json at /clientes/listar — got html (login page)', code: 'MKW_AUTH' },
  { svc: 'audit.writer',      level: 'info',  msg: 'audit.event persisted actor=user_84 tenant=tnt_04QZ2', code: null }
];

function genLogs(n = 80) {
  const out = [];
  const now = Date.now();
  for (let i = 0; i < n; i++) {
    const tpl = randomFrom(ERROR_TEMPLATES);
    const tnt = randomFrom(TENANTS);
    out.push({
      id: 'log_' + randHex(10),
      ts: new Date(now - i * (Math.random() * 4000 + 700)).toISOString(),
      level: tpl.level,
      svc: tpl.svc,
      tenant: tnt.id,
      tenantName: tnt.name,
      msg: tpl.msg,
      code: tpl.code,
      trace_id: TRACE_PREFIX(),
      span_id: randHex(8),
      attrs: {
        env: 'production',
        region: 'sdq-1',
        host: 'connector-worker-' + (Math.floor(Math.random() * 6) + 1),
        request_id: 'req_' + randHex(12),
        user_agent: tpl.svc.includes('webhook') ? 'facebookplatform/1.0' : 'BlazeConnector/3.4.2 (go1.22)'
      }
    });
  }
  return out;
}

const MSG_STATES = [
  { v: 'delivered', tone: 'success', wt: 50 },
  { v: 'sent',      tone: 'info',    wt: 20 },
  { v: 'read',      tone: 'success', wt: 15 },
  { v: 'queued',    tone: 'warn',    wt: 7 },
  { v: 'failed',    tone: 'danger',  wt: 5 },
  { v: 'expired',   tone: 'neutral', wt: 3 }
];
const MSG_DIRECTIONS = ['outbound', 'inbound'];
const MSG_TYPES = ['template', 'text', 'media', 'button_reply'];
const TEMPLATES = [
  { name: 'factura_lista_ES',         category: 'UTILITY',        lang: 'es', status: 'APPROVED' },
  { name: 'pago_recibido_ES',         category: 'UTILITY',        lang: 'es', status: 'APPROVED' },
  { name: 'corte_servicio_aviso_ES',  category: 'UTILITY',        lang: 'es', status: 'APPROVED' },
  { name: 'reactivacion_post_pago_ES',category: 'UTILITY',        lang: 'es', status: 'APPROVED' },
  { name: 'soporte_tecnico_ack_ES',   category: 'UTILITY',        lang: 'es', status: 'APPROVED' },
  { name: 'recordatorio_pago_ES',     category: 'UTILITY',        lang: 'es', status: 'APPROVED' },
  { name: 'bienvenida_cliente_ES',    category: 'MARKETING',      lang: 'es', status: 'APPROVED' },
  { name: 'encuesta_satisfaccion_ES', category: 'MARKETING',      lang: 'es', status: 'PENDING' },
  { name: 'promo_oferta_mayo',        category: 'MARKETING',      lang: 'es', status: 'REJECTED' },
  { name: 'otp_verificacion_ES',      category: 'AUTHENTICATION', lang: 'es', status: 'APPROVED' }
];

function weightedPick(opts) {
  const total = opts.reduce((a, o) => a + o.wt, 0);
  let r = Math.random() * total;
  for (const o of opts) { r -= o.wt; if (r <= 0) return o; }
  return opts[0];
}

const DR_NAMES = ['María Hernández', 'Juan Peña', 'Yarisbel Rodríguez', 'Eduardo Báez', 'Laura Mejía', 'Carlos Ureña', 'Ana Núñez', 'Pedro Almonte', 'Rosa Fernández', 'José Pichardo', 'Patricia Disla', 'Ramón Valdez', 'Sandra Ovalles', 'Luis Encarnación', 'Mónica Lebrón', 'Iván Polanco', 'Diana Montás', 'Wilkin Tejada', 'Yokasta Cabrera', 'Franklin Reyes', 'Jenny Sosa', 'Manuel Brito', 'Karla Bonilla', 'Héctor Florián'];

function genMessages(n = 60) {
  const now = Date.now();
  const out = [];
  for (let i = 0; i < n; i++) {
    const tnt = randomFrom(TENANTS.filter(t => t.status === 'active'));
    const ch = randomFrom(tnt.channels);
    const st = weightedPick(MSG_STATES);
    const dir = randomFrom(MSG_DIRECTIONS);
    const tpl = randomFrom(TEMPLATES);
    const to = '+18' + (Math.floor(Math.random() * 90000000) + 10000000).toString();
    const retries = st.v === 'failed' ? Math.floor(Math.random() * 3) + 1 : (st.v === 'queued' ? Math.floor(Math.random() * 2) : 0);
    out.push({
      id: 'msg_' + randHex(12),
      ts: new Date(now - i * (Math.random() * 60000 + 3000)).toISOString(),
      tenant: tnt.id, tenantName: tnt.name,
      channel: ch,
      direction: dir,
      type: randomFrom(MSG_TYPES),
      template: dir === 'outbound' ? tpl.name : null,
      to: dir === 'outbound' ? to : null,
      from: dir === 'inbound' ? to : null,
      contactName: randomFrom(DR_NAMES),
      status: st.v, tone: st.tone,
      provider: ch === 'whatsapp' ? 'meta_cloud' : ch,
      providerMessageId: 'wamid.HBgL' + randHex(20),
      retries,
      trace_id: TRACE_PREFIX(),
      latencyMs: Math.floor(Math.random() * 800) + 80,
      preview: dir === 'outbound'
        ? (tpl.name === 'factura_lista_ES'
            ? 'Su factura de mayo está lista. Monto: RD$1,250.00. Vence el 02/06.'
            : tpl.name === 'pago_recibido_ES'
              ? 'Confirmamos su pago de RD$1,250.00. ¡Gracias!'
              : tpl.name === 'corte_servicio_aviso_ES'
                ? 'Su servicio será suspendido en 24h por falta de pago.'
                : 'Mensaje plantilla ' + tpl.name)
        : randomFrom(['¿Pueden verificar mi factura?', 'No tengo internet desde ayer', 'Quiero pagar', 'Gracias', 'Necesito soporte técnico urgente', '/factura'])
    });
  }
  return out;
}

function makeSamplePayload(m) {
  return {
    messaging_product: 'whatsapp',
    to: m.to || m.from,
    type: m.type,
    template: m.template ? {
      name: m.template,
      language: { code: 'es' },
      components: [
        { type: 'body', parameters: [
          { type: 'text', text: m.contactName.split(' ')[0] },
          { type: 'currency', currency: { fallback_value: 'RD$1,250.00', code: 'DOP', amount_1000: 1250000 } },
          { type: 'date_time', date_time: { fallback_value: '02/06/2026' } }
        ] }
      ]
    } : undefined,
    metadata: {
      tenant_id: m.tenant,
      trace_id: m.trace_id,
      origin: 'connector.dispatcher.v3',
      attempts: m.retries + 1
    }
  };
}

const API_KEYS = [
  { id: 'key_AHmK9pQz', name: 'Production · WhatsApp dispatcher', tenant: 'tnt_01HV3', tenantName: 'TeleCaribe',       scopes: ['messages:write', 'messages:read', 'templates:read'], createdAt: '2025-11-04T13:24:18Z', lastUsed: '2026-05-26T17:42:11Z', lastIp: '186.46.12.84',  status: 'active', preview: 'bzc_live_••••••••AHmK9pQz' },
  { id: 'key_QnX4tB72', name: 'Billing sync · WispHub',            tenant: 'tnt_04QZ2', tenantName: 'CibaoNet',         scopes: ['billing:sync', 'tenants:read'],                       createdAt: '2025-09-12T10:08:00Z', lastUsed: '2026-05-26T17:30:00Z', lastIp: '190.166.4.218', status: 'active', preview: 'bzc_live_••••••••QnX4tB72' },
  { id: 'key_BvR2k1Pa', name: 'CardNET IPN ingest',                 tenant: 'tnt_08PN6', tenantName: 'Punta Cana Fiber', scopes: ['pagos:webhook'],                                       createdAt: '2026-01-22T09:42:11Z', lastUsed: '2026-05-26T17:43:00Z', lastIp: '200.88.50.144', status: 'active', preview: 'bzc_live_••••••••BvR2k1Pa' },
  { id: 'key_ZpL8m3Hc', name: 'Soporte read-only',                  tenant: 'tnt_02KW9', tenantName: 'AltaVelocidad RD', scopes: ['messages:read', 'tenants:read', 'logs:read'],         createdAt: '2026-03-04T14:15:42Z', lastUsed: '2026-05-25T22:08:14Z', lastIp: '152.166.18.42', status: 'active', preview: 'bzc_live_••••••••ZpL8m3Hc' },
  { id: 'key_TjW7q9Dx', name: 'Legacy migration',                   tenant: 'tnt_06DV1', tenantName: 'DR Fibra',         scopes: ['*'],                                                   createdAt: '2024-08-10T11:00:00Z', lastUsed: '2025-12-18T08:42:11Z', lastIp: '200.55.142.6',  status: 'revoked', preview: 'bzc_live_••••••••TjW7q9Dx' },
  { id: 'key_YcN5r2Ka', name: 'Webhooks · Chatwoot',                tenant: 'tnt_11BV2', tenantName: 'BávaroLink',       scopes: ['webhooks:write'],                                      createdAt: '2026-02-18T16:30:08Z', lastUsed: '2026-05-26T17:33:02Z', lastIp: '190.166.7.92',  status: 'active', preview: 'bzc_live_••••••••YcN5r2Ka' }
];

const ALERTS = [
  { id: 'alr_001', severity: 'critical', title: 'CyberSource gateway DOWN',                              source: 'pagos.cybersource', tenant: null,            fired: '2026-05-26T17:18:42Z', age: '26m',  ack: false, runbook: 'rb-pagos-cyb-001' },
  { id: 'alr_002', severity: 'warning',  title: 'Cola messaging — backlog > 600',                        source: 'queue.messaging',   tenant: null,            fired: '2026-05-26T17:32:08Z', age: '12m',  ack: false, runbook: 'rb-queue-mssg-002' },
  { id: 'alr_003', severity: 'warning',  title: 'DomiISP latencia p95 > 600ms (sostenido 5m)',           source: 'isp.domiisp',       tenant: 'tnt_06DV1',     fired: '2026-05-26T17:36:54Z', age: '7m',   ack: true,  runbook: 'rb-isp-domi-006' },
  { id: 'alr_004', severity: 'critical', title: 'OcoaConnect — error rate 4.8% últimas 15m',             source: 'tenant.errors',     tenant: 'tnt_05RT4',     fired: '2026-05-26T17:08:12Z', age: '36m',  ack: false, runbook: 'rb-tenant-err' },
  { id: 'alr_005', severity: 'info',     title: 'Template `promo_oferta_mayo` rechazada por Meta',       source: 'wabacloud',         tenant: 'tnt_02KW9',     fired: '2026-05-26T16:42:01Z', age: '1h 2m',ack: true,  runbook: null },
  { id: 'alr_006', severity: 'warning',  title: 'API key `key_TjW7q9Dx` revocada pero aún recibe tráfico',source: 'auth.audit',        tenant: 'tnt_06DV1',     fired: '2026-05-26T15:08:42Z', age: '2h 36m',ack: true, runbook: null }
];

const AUDIT_EVENTS = [
  { id: 'aud_001', ts: '2026-05-26T17:43:18Z', actor: { type: 'user', id: 'u_84', name: 'Yarisbel Rodríguez', role: 'operaciones' }, action: 'apikey.created',    target: 'key_AHmK9pQz', tenant: 'tnt_01HV3', meta: { scopes: ['messages:write','messages:read','templates:read'] } },
  { id: 'aud_002', ts: '2026-05-26T17:30:08Z', actor: { type: 'system', id: 'sys.scheduler', name: 'sched.cron' },                action: 'template.synced',   target: 'factura_lista_ES', tenant: 'tnt_04QZ2', meta: { previous: 'PENDING', current: 'APPROVED' } },
  { id: 'aud_003', ts: '2026-05-26T17:24:42Z', actor: { type: 'user', id: 'u_84', name: 'Yarisbel Rodríguez', role: 'operaciones' }, action: 'retry.executed',    target: 'msg_a8f3c2b1d4e6', tenant: 'tnt_04QZ2', meta: { reason: 'manual', previous_status: 'failed' } },
  { id: 'aud_004', ts: '2026-05-26T17:12:11Z', actor: { type: 'user', id: 'u_12', name: 'Eduardo Báez', role: 'superadmin' },     action: 'tenant.updated',    target: 'tnt_05RT4', tenant: 'tnt_05RT4', meta: { status: 'suspended', reason: 'pago vencido' } },
  { id: 'aud_005', ts: '2026-05-26T16:54:32Z', actor: { type: 'user', id: 'u_31', name: 'Laura Mejía', role: 'soporte' },         action: 'message.viewed',    target: 'msg_c3e9d2b1a4f8', tenant: 'tnt_08PN6', meta: { reason: 'soporte_lookup', ticket: 'BC-2843' } },
  { id: 'aud_006', ts: '2026-05-26T16:42:01Z', actor: { type: 'system', id: 'sys.wabacloud', name: 'wabacloud.proxy' },           action: 'template.rejected', target: 'promo_oferta_mayo', tenant: 'tnt_02KW9', meta: { reason: 'promotional_violation' } },
  { id: 'aud_007', ts: '2026-05-26T16:28:18Z', actor: { type: 'user', id: 'u_12', name: 'Eduardo Báez', role: 'superadmin' },     action: 'config.updated',    target: 'tnt_08PN6/pagos.cardnet', tenant: 'tnt_08PN6', meta: { field: 'webhook_url', from: '…/v2/callback', to: '…/v3/callback' } },
  { id: 'aud_008', ts: '2026-05-26T15:08:42Z', actor: { type: 'user', id: 'u_12', name: 'Eduardo Báez', role: 'superadmin' },     action: 'apikey.revoked',    target: 'key_TjW7q9Dx', tenant: 'tnt_06DV1', meta: { reason: 'legacy_cleanup' } },
  { id: 'aud_009', ts: '2026-05-26T14:42:14Z', actor: { type: 'user', id: 'u_84', name: 'Yarisbel Rodríguez', role: 'operaciones' }, action: 'tenant.created', target: 'tnt_12HG9', tenant: 'tnt_12HG9', meta: { plan: 'Starter', region: 'Higüey' } },
  { id: 'aud_010', ts: '2026-05-26T13:18:42Z', actor: { type: 'system', id: 'sys.audit', name: 'audit.writer' },                  action: 'config.updated',    target: 'global.feature.flags', tenant: null, meta: { flag: 'sse.bursts.coalesce', value: true } }
];

// Time-series for charts (synthetic but consistent shapes)
function genSeries(n, base, variance, trend = 0) {
  const out = [];
  for (let i = 0; i < n; i++) {
    const t = i / n;
    const v = base + Math.sin(i * 0.42) * variance * 0.4 + (Math.random() - 0.5) * variance + trend * t * base;
    out.push(Math.max(0, Math.round(v)));
  }
  return out;
}

const DASHBOARD_SERIES = {
  msgsPerMin:   genSeries(60, 1200, 220, 0.1),
  errorsPerMin: genSeries(60, 14,   8,  -0.2),
  latencyP95:   genSeries(60, 320,  80,  0),
  queueDepth:   genSeries(60, 720,  140, 0.05),
  workerActive: genSeries(60, 46,   6,   0),
  inbound:      genSeries(60, 280,  60,  0)
};

const CHANNEL_BREAKDOWN = [
  { ch: 'whatsapp', label: 'WhatsApp', count: 84219, pct: 78.4, color: '#25D366' },
  { ch: 'telegram', label: 'Telegram', count: 14802, pct: 13.8, color: '#2CA5E0' },
  { ch: 'chatwoot', label: 'Chatwoot', count: 6418,  pct: 6.0,  color: '#8C1F8C' },
  { ch: 'sms',      label: 'SMS',      count: 1942,  pct: 1.8,  color: '#F000D8' }
];

// expose globally for other Babel scripts
Object.assign(window, {
  TENANTS, CHANNEL_LABEL, CHANNEL_LETTER, PROVIDERS_ISP, PROVIDERS_PAY,
  QUEUES, SERVICES, ERROR_TEMPLATES, genLogs, genMessages, makeSamplePayload,
  API_KEYS, ALERTS, AUDIT_EVENTS, DASHBOARD_SERIES, CHANNEL_BREAKDOWN, TEMPLATES,
  randomFrom, randHex, TRACE_PREFIX, DR_NAMES
});
