/* MIRAI — Datos mock del dashboard de clientes (modo lectura)
 *
 * Todo lo simulado vive acá para que reemplazarlo por una API real sea simple:
 * cada getX(filters) sería luego un fetch al backend con los mismos parámetros.
 * Los componentes NO hardcodean valores: leen siempre desde estas funciones.
 */

// ============ CONFIG DE ESTADOS ============
// key -> { label, cls } — cls define el color suave de la pastilla (ver dashboard.css)
const DASH_STATUS = {
  waiting:    { label: "Esperando broker",   cls: "is-waiting" },   // amarillo suave
  qualified:  { label: "Calificado",         cls: "is-qualified" }, // verde suave
  emma:       { label: "Resuelto por Emma",  cls: "is-emma" },      // azul suave
  talking:    { label: "En conversación",    cls: "is-talking" },   // celeste/gris azulado
  unresolved: { label: "No resuelto",        cls: "is-unresolved" },// rojo suave
  manual:     { label: "Resuelto manualmente", cls: "is-manual" },  // gris suave
};

// ============ OPCIONES DE FILTROS ============
const DASH_PERIODS = [
  { key: "hoy",  label: "Hoy" },
  { key: "7d",   label: "Últimos 7 días" },
  { key: "30d",  label: "Últimos 30 días" },
  { key: "mes",  label: "Este mes" },
];
const DASH_CHANNELS = [
  { key: "all",       label: "Todos los canales" },
  { key: "whatsapp",  label: "WhatsApp" },
  { key: "instagram", label: "Instagram" },
];

// Factores deterministas para que los filtros muevan los datos de forma coherente.
const PERIOD_FACTOR  = { hoy: 0.05, "7d": 0.25, "30d": 1, mes: 0.82 };
const CHANNEL_FACTOR = { all: 1, whatsapp: 0.68, instagram: 0.32 };

function fmt(n) { return Math.round(n).toLocaleString("es-AR"); }
function factor(f) { return (PERIOD_FACTOR[f.period] || 1) * (CHANNEL_FACTOR[f.channel] || 1); }

// ============ TARJETAS DE MÉTRICAS ============
function dashGetMetrics(f) {
  const k = factor(f);
  const channelBest = f.channel === "instagram" ? "Instagram" : "WhatsApp";
  const channelRate = f.channel === "instagram" ? "41,2% calificación" : "48,6% calificación";
  const cmp = !!f.compare;
  return [
    { label: "Consultas recibidas", value: fmt(1842 * k), delta: "↑ 18,4%", dir: "up", note: "vs. período anterior" },
    { label: "Leads calificados",   value: fmt(824 * k),  delta: "↑ 12,1%", dir: "up", note: "vs. período anterior" },
    { label: "Tiempo medio de respuesta", value: (f.period === "hoy" ? 38 : 43) + " s", delta: cmp ? "↓ 6,5%" : null, dir: "down-good", note: "Emma" },
    { label: "Fuera de horario",    value: (f.channel === "instagram" ? 44 : 38) + "%", delta: cmp ? "↑ 2,1%" : null, dir: "up-bad", note: "consultas recibidas" },
    { label: "Mejor canal",         value: channelBest, note: channelRate },
  ];
}

// ============ SERIE TEMPORAL (gráfico de líneas) ============
const SERIES_30D = {
  labels: ["22 Abr", "26 Abr", "30 Abr", "4 May", "8 May", "12 May", "16 May", "20 May"],
  // 15 puntos (dominio 0–100), patrón con altibajos para que se vea orgánico
  consultas: [54, 62, 48, 71, 58, 66, 52, 60, 78, 64, 56, 70, 82, 68, 66],
  leads:     [24, 30, 22, 33, 27, 31, 25, 28, 36, 30, 26, 33, 40, 31, 30],
};
const SERIES_7D = {
  labels: ["Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"],
  consultas: [58, 72, 64, 80, 76, 48, 40],
  leads:     [26, 33, 29, 37, 35, 22, 18],
};
const SERIES_HOY = {
  labels: ["08", "10", "12", "14", "16", "18", "20", "22"],
  consultas: [22, 48, 66, 72, 58, 80, 64, 38],
  leads:     [10, 22, 30, 33, 26, 37, 29, 17],
};

function dashGetSeries(f) {
  const base = f.period === "hoy" ? SERIES_HOY : f.period === "7d" ? SERIES_7D : SERIES_30D;
  const cf = CHANNEL_FACTOR[f.channel] || 1;
  const scale = (arr) => arr.map((v) => Math.round(v * (0.55 + 0.45 * cf)));
  return {
    labels: base.labels,
    consultas: scale(base.consultas),
    leads: scale(base.leads),
  };
}

// ============ DONA (resultado de las consultas) ============
function dashGetResults(f) {
  // Colores alineados con las pastillas de estado (ver dashboard.css .dash-tag).
  return [
    { label: "Resueltas por Emma",   value: 45, color: "#16A34A" },
    { label: "Derivadas correctamente", value: 25, color: "#2563EB" },
    { label: "En conversación",      value: 15, color: "#0EA5E9" },
    { label: "No resueltas",         value: 10, color: "#DC2626" },
    { label: "Resueltas manualmente", value: 5, color: "#6B7280" },
  ];
}

// ============ CANALES ============
function dashGetChannels(f) {
  const k = factor(f);
  const waCount = Math.round(1256 * (PERIOD_FACTOR[f.period] || 1) * (f.channel === "instagram" ? 0 : 1));
  const igCount = Math.round(586 * (PERIOD_FACTOR[f.period] || 1) * (f.channel === "whatsapp" ? 0 : 1));
  if (f.channel === "whatsapp") return [{ key: "whatsapp", label: "WhatsApp", pct: 100, count: waCount }];
  if (f.channel === "instagram") return [{ key: "instagram", label: "Instagram", pct: 100, count: igCount }];
  return [
    { key: "whatsapp", label: "WhatsApp", pct: 68, count: waCount },
    { key: "instagram", label: "Instagram", pct: 32, count: igCount },
  ];
}

// ============ CONSULTAS (tabla + detalle) ============
const DASH_CONSULTATIONS = [
  {
    id: "c1",
    name: "Juan García",
    channel: "whatsapp",
    intent: "Comprar",
    zone: "Nordelta",
    budget: "USD 250.000",
    status: "waiting",
    dateLabel: "Hoy, 11:42",
    dayOffset: 0,
    detail: {
      contact: "+54 9 11 2866 1164",
      propertyType: "Departamento",
      ambientes: "3 ambientes",
      payment: "Ahorros",
      features: "Balcón, cochera",
      entryTime: "Hoy, 11:42",
      derivTime: "Hoy, 11:47",
      summary: "Juan busca comprar un departamento de tres ambientes en Nordelta. Cuenta con un presupuesto aproximado de USD 250.000 y pagaría con ahorros. Prefiere una propiedad con balcón y cochera. El diagnóstico fue completado y el caso está esperando el contacto de un broker.",
      conversation: [
        { from: "lead", time: "11:42", text: "Hola, vi una publicación de un depto en Nordelta. Sigue disponible?" },
        { from: "emma", time: "11:42", text: "¡Hola Juan! Soy Emma, asistente de la inmobiliaria. Te ayudo con gusto. ¿Buscás para comprar o alquilar?" },
        { from: "lead", time: "11:43", text: "Para comprar. Busco 3 ambientes." },
        { from: "emma", time: "11:43", text: "Perfecto. ¿Tenés un presupuesto aproximado en mente?" },
        { from: "lead", time: "11:44", text: "Alrededor de 250 mil dólares, con ahorros." },
        { from: "emma", time: "11:45", text: "Genial. ¿Alguna preferencia como balcón o cochera?" },
        { from: "lead", time: "11:46", text: "Sí, balcón y cochera idealmente." },
        { from: "emma", time: "11:47", text: "Excelente, ya tomé todos los datos. Un broker se va a contactar a la brevedad para mostrarte opciones. ¡Gracias Juan!" },
      ],
    },
  },
  {
    id: "c2",
    name: "Martina Pérez",
    channel: "instagram",
    intent: "Alquilar",
    zone: "Tigre",
    budget: "USD 1.200",
    status: "qualified",
    dateLabel: "Hoy, 10:18",
    dayOffset: 0,
    detail: {
      contact: "@martina.perez",
      propertyType: "Departamento",
      ambientes: "2 ambientes",
      payment: "Mensual",
      features: "Amoblado, pet friendly",
      entryTime: "Hoy, 10:18",
      derivTime: "Hoy, 10:25",
      summary: "Martina busca alquilar un departamento de dos ambientes en Tigre por hasta USD 1.200 mensuales. Necesita que sea amoblado y que acepte mascotas. El lead fue calificado correctamente y derivado para coordinar una visita.",
      conversation: [
        { from: "lead", time: "10:18", text: "Hola! Tienen deptos en alquiler en Tigre?" },
        { from: "emma", time: "10:18", text: "¡Hola Martina! Sí, tenemos varias opciones. ¿De cuántos ambientes lo buscás?" },
        { from: "lead", time: "10:19", text: "2 ambientes, amoblado. Tengo un gato 🐱" },
        { from: "emma", time: "10:20", text: "Perfecto, marco que necesitás pet friendly. ¿Qué presupuesto mensual manejás?" },
        { from: "lead", time: "10:22", text: "Hasta 1200 usd" },
        { from: "emma", time: "10:25", text: "Genial, tengo opciones que encajan. Te derivo con un asesor para coordinar la visita. ¡Gracias!" },
      ],
    },
  },
  {
    id: "c3",
    name: "Pedro López",
    channel: "whatsapp",
    intent: "Propiedad específica",
    zone: "Benavídez",
    budget: "—",
    status: "emma",
    dateLabel: "Hoy, 09:36",
    dayOffset: 0,
    detail: {
      contact: "+54 9 11 5544 3322",
      propertyType: "Casa",
      ambientes: "—",
      payment: "—",
      features: "Consulta puntual",
      entryTime: "Hoy, 09:36",
      derivTime: "—",
      summary: "Pedro consultó por una propiedad específica publicada en Benavídez. Emma le brindó la información de disponibilidad y características, y la consulta quedó resuelta automáticamente sin necesidad de derivación.",
      conversation: [
        { from: "lead", time: "09:36", text: "Buenas, la casa del código BNV-204 sigue disponible?" },
        { from: "emma", time: "09:36", text: "¡Hola Pedro! Déjame verificar… Sí, la propiedad BNV-204 está disponible." },
        { from: "lead", time: "09:37", text: "Cuántos m2 tiene?" },
        { from: "emma", time: "09:37", text: "Tiene 220 m² cubiertos sobre un lote de 600 m², con 4 ambientes y jardín. ¿Querés que te pase más fotos por mail?" },
        { from: "lead", time: "09:38", text: "No por ahora, gracias!" },
        { from: "emma", time: "09:38", text: "¡Genial! Cualquier cosa quedo a disposición. 😊" },
      ],
    },
  },
  {
    id: "c4",
    name: "Lucía Fernández",
    channel: "instagram",
    intent: "Tasar",
    zone: "San Isidro",
    budget: "—",
    status: "talking",
    dateLabel: "Ayer, 23:47",
    dayOffset: 1,
    detail: {
      contact: "@luciafer",
      propertyType: "Casa",
      ambientes: "5 ambientes",
      payment: "—",
      features: "Tasación de venta",
      entryTime: "Ayer, 23:47",
      derivTime: "—",
      summary: "Lucía quiere tasar una casa de cinco ambientes en San Isidro para una eventual venta. Emma está relevando los datos de la propiedad para preparar la tasación. La conversación sigue en curso.",
      conversation: [
        { from: "lead", time: "23:47", text: "Hola, hacen tasaciones? Quiero vender mi casa en San Isidro" },
        { from: "emma", time: "23:47", text: "¡Hola Lucía! Sí, realizamos tasaciones sin cargo. ¿Cuántos ambientes tiene la propiedad?" },
        { from: "lead", time: "23:48", text: "5 ambientes, con pileta" },
        { from: "emma", time: "23:49", text: "Perfecto. ¿Me pasás la dirección aproximada para estimar el valor de zona?" },
      ],
    },
  },
];

function dashGetConsultations(f) {
  return DASH_CONSULTATIONS.filter((c) => {
    if (f.channel !== "all" && c.channel !== f.channel) return false;
    if (f.period === "hoy" && c.dayOffset > 0) return false;
    return true;
  });
}

// ============ ZONAS MÁS BUSCADAS ============
const DASH_ZONES = [
  { zone: "Nordelta", count: 642 },
  { zone: "Tigre", count: 398 },
  { zone: "San Isidro", count: 286 },
  { zone: "Benavídez", count: 216 },
  { zone: "Pacheco", count: 174 },
];
// Listado ampliado para el modal "Ver todas las zonas"
const DASH_ZONES_FULL = [
  ...DASH_ZONES,
  { zone: "Pilar", count: 178 },
  { zone: "Escobar", count: 142 },
  { zone: "Vicente López", count: 121 },
  { zone: "Núñez", count: 98 },
  { zone: "Belgrano", count: 87 },
  { zone: "Martínez", count: 76 },
];
function dashGetZones(f) {
  const cf = (PERIOD_FACTOR[f.period] || 1);
  return DASH_ZONES.map((z) => ({ ...z, count: Math.round(z.count * cf) }));
}

// ============ CONSULTAS NO RESUELTAS ============
const DASH_UNRESOLVED = [
  { reason: "No se encontró la propiedad", pct: 38, desc: "El cliente consultó por una propiedad que ya no estaba publicada o cuyo código no existe en el catálogo." },
  { reason: "Dirección insuficiente", pct: 24, desc: "Los datos de ubicación aportados no alcanzaron para identificar una zona o propiedad concreta." },
  { reason: "Error del CRM", pct: 18, desc: "Falla temporal al sincronizar con el CRM de la inmobiliaria al momento de la consulta." },
  { reason: "Error de interpretación", pct: 20, desc: "La intención del mensaje no pudo determinarse con confianza suficiente para avanzar." },
];
function dashGetUnresolved(f) { return DASH_UNRESOLVED; }

// ============ CONFIG POR CANAL (WhatsApp / Instagram) ============
// Paleta monocromática compartida para la dona (negro -> gris claro).
const RESULT_COLORS = ["#000000", "#555555", "#8a8a8a", "#bcbcbc", "#dcdcdc"];

const DASH_CHANNEL_CFG = {
  whatsapp: {
    key: "whatsapp",
    name: "WhatsApp",
    assistant: "Emma",
    subtitle: "Rendimiento de las consultas recibidas a través de WhatsApp",
    accent: "#1FA855",
    accentSoft: "rgba(37,211,102,0.14)",
    deltaCls: "is-wa",
    seriesAmp: 1,
    metricsBase: [
      { label: "Consultas recibidas", base: 1256, delta: "↑ 14,8%", dir: "up", note: "vs. período anterior", count: true },
      { label: "Leads calificados", base: 612, delta: "↑ 10,6%", dir: "up", note: "vs. período anterior", count: true },
      { label: "Esperando broker", base: 43, note: "requieren seguimiento", count: true },
      { label: "Tiempo medio de respuesta", value: "42 s", note: "Emma" },
      { label: "Fuera de horario", value: "38%", note: "consultas recibidas" },
      { label: "Tasa de resolución", value: "91%", note: "atención satisfactoria" },
    ],
    results: [["Resueltas por Emma", 48], ["Derivadas correctamente", 27], ["En conversación", 12], ["No resueltas", 8], ["Resueltas manualmente", 5]],
    intentions: [["Comprar", 42], ["Alquilar", 28], ["Propiedad específica", 17], ["Tasar", 8], ["Vender", 5]],
    recent: [
      { name: "Juan García", intent: "Comprar", zone: "Nordelta", status: "waiting", time: "Hoy, 11:42" },
      { name: "Pedro López", intent: "Propiedad específica", zone: "Benavídez", status: "emma", time: "Hoy, 09:36" },
      { name: "Diego Sosa", intent: "Comprar", zone: "Pilar", status: "qualified", time: "Hoy, 08:55" },
      { name: "Marcos Ruiz", intent: "Alquilar", zone: "Tigre", status: "talking", time: "Ayer, 21:10" },
    ],
    peakHours: [["09–11 h", 100], ["18–20 h", 86], ["12–14 h", 72], ["20–22 h", 58]],
    zones: [["Nordelta", 412], ["Tigre", 268], ["Benavídez", 154], ["Pilar", 121]],
    unresolved: [["No se encontró la propiedad", 40], ["Dirección insuficiente", 26], ["Error del CRM", 19], ["Error de interpretación", 15]],
  },
  instagram: {
    key: "instagram",
    name: "Instagram",
    assistant: "Envia",
    subtitle: "Rendimiento de las consultas recibidas a través de Instagram",
    accent: "#E1306C",
    accentSoft: "rgba(225,48,108,0.12)",
    gradient: "linear-gradient(90deg, #8134AF 0%, #C837AB 38%, #F35369 70%, #F58529 100%)",
    deltaCls: "is-ig",
    seriesAmp: 0.8,
    metricsBase: [
      { label: "Consultas recibidas", base: 986, delta: "↑ 12,3%", dir: "up", note: "vs. período anterior", count: true },
      { label: "Leads calificados", base: 482, delta: "↑ 8,7%", dir: "up", note: "vs. período anterior", count: true },
      { label: "Esperando broker", base: 31, note: "requieren seguimiento", count: true },
      { label: "Tiempo medio de respuesta", value: "58 s", note: "Envia" },
      { label: "Fuera de horario", value: "32%", note: "consultas recibidas" },
      { label: "Tasa de resolución", value: "89%", note: "atención satisfactoria" },
    ],
    results: [["Resueltas por Envia", 47], ["Derivadas correctamente", 28], ["En conversación", 13], ["No resueltas", 7], ["Resueltas manualmente", 5]],
    intentions: [["Comprar", 41], ["Alquilar", 27], ["Propiedad específica", 16], ["Tasar", 9], ["Vender", 7]],
    recent: [
      { name: "Martina Pérez", intent: "Alquilar", zone: "Tigre", status: "qualified", time: "Hoy, 10:18" },
      { name: "Sofía Díaz", intent: "Comprar", zone: "Nordelta", status: "waiting", time: "Hoy, 09:12" },
      { name: "Lucía Fernández", intent: "Tasar", zone: "San Isidro", status: "talking", time: "Ayer, 23:47" },
      { name: "Camila Vera", intent: "Vender", zone: "Escobar", status: "emma", time: "Ayer, 19:05" },
    ],
    peakHours: [["19–21 h", 100], ["13–15 h", 82], ["21–23 h", 74], ["10–12 h", 60]],
    zones: [["Tigre", 198], ["San Isidro", 142], ["Nordelta", 118], ["Escobar", 86]],
    unresolved: [["No se encontró la propiedad", 35], ["Error de interpretación", 27], ["Dirección insuficiente", 22], ["Error del CRM", 16]],
  },
};

DASH_CHANNEL_CFG.crm = {
  key: "crm", name: "CRM", assistant: "Emma",
  subtitle: "Gestiona y responde consultas desde la web en tiempo real con Emma",
  accent: "#C0003B", accentSoft: "rgba(192,0,59,0.1)",
  deltaCls: "is-crm", seriesAmp: 0.9,
  metricsBase: [], results: [], intentions: [], recent: [], peakHours: [], zones: [], unresolved: [],
};

function dashGetChannelCfg(ch) { return DASH_CHANNEL_CFG[ch]; }

function dashGetChannelMetrics(ch, f) {
  const cfg = DASH_CHANNEL_CFG[ch];
  const pf = PERIOD_FACTOR[f.period] || 1;
  return cfg.metricsBase.map((m) => ({
    label: m.label,
    value: m.count ? fmt(m.base * pf) : m.value,
    delta: m.delta || null,
    dir: m.dir || "up",
    note: m.note,
  }));
}

function dashGetChannelSeries(ch, f) {
  const base = f.period === "hoy" ? SERIES_HOY : f.period === "7d" ? SERIES_7D : SERIES_30D;
  const amp = DASH_CHANNEL_CFG[ch].seriesAmp;
  const s = (arr) => arr.map((v) => Math.round(v * amp));
  return { labels: base.labels, consultas: s(base.consultas), leads: s(base.leads) };
}

function dashGetChannelResults(ch) {
  return DASH_CHANNEL_CFG[ch].results.map((r, i) => ({ label: r[0], value: r[1], color: RESULT_COLORS[i] }));
}

Object.assign(window, {
  DASH_STATUS, DASH_PERIODS, DASH_CHANNELS, DASH_ZONES_FULL, DASH_UNRESOLVED, DASH_CHANNEL_CFG,
  dashGetMetrics, dashGetSeries, dashGetResults, dashGetChannels,
  dashGetConsultations, dashGetZones, dashGetUnresolved,
  dashGetChannelCfg, dashGetChannelMetrics, dashGetChannelSeries, dashGetChannelResults,
});
