// ============ Mock data ============

// Deterministic pseudo-random for stable demo
function mulberry32(a) {
  return function() {
    let t = a += 0x6D2B79F5;
    t = Math.imul(t ^ t >>> 15, t | 1);
    t ^= t + Math.imul(t ^ t >>> 7, t | 61);
    return ((t ^ t >>> 14) >>> 0) / 4294967296;
  };
}

const TOP_TERMS_ES = [
  { term: "audífonos bluetooth", searches: 48210, ctr: 24.3, clicks: 11715, zero: 0.4, t: "up" },
  { term: "zapatos deportivos", searches: 36552, ctr: 31.7, clicks: 11587, zero: 0.2, t: "up" },
  { term: "laptop gamer",        searches: 29140, ctr: 18.9, clicks:  5507, zero: 1.1, t: "flat" },
  { term: "cafetera espresso",   searches: 24870, ctr: 22.1, clicks:  5496, zero: 0.6, t: "up" },
  { term: "iphone 16 pro",       searches: 22305, ctr: 42.5, clicks:  9480, zero: 0.1, t: "up" },
  { term: "silla gamer",         searches: 19788, ctr: 27.4, clicks:  5422, zero: 0.9, t: "flat" },
  { term: "aspiradora robot",    searches: 16440, ctr: 19.2, clicks:  3156, zero: 1.4, t: "down" },
  { term: "smart tv 55",         searches: 15022, ctr: 33.1, clicks:  4972, zero: 0.3, t: "up" },
  { term: "airfryer",            searches: 14410, ctr: 28.8, clicks:  4150, zero: 0.5, t: "up" },
  { term: "mochila escolar",     searches: 12990, ctr: 21.4, clicks:  2780, zero: 0.7, t: "flat" },
  { term: "reloj inteligente",   searches: 12110, ctr: 25.0, clicks:  3028, zero: 0.6, t: "up" },
  { term: "bicicleta eléctrica", searches: 10520, ctr: 17.1, clicks:  1799, zero: 1.6, t: "down" },
  { term: "perfume mujer",       searches:  9870, ctr: 30.5, clicks:  3010, zero: 0.3, t: "flat" },
  { term: "tenis nike",          searches:  9510, ctr: 36.2, clicks:  3443, zero: 0.2, t: "up" },
  { term: "monitor 27",          searches:  8944, ctr: 23.0, clicks:  2057, zero: 0.8, t: "flat" },
  { term: "teclado mecánico",    searches:  8410, ctr: 26.7, clicks:  2245, zero: 0.5, t: "up" },
  { term: "bocina bluetooth",    searches:  7988, ctr: 22.9, clicks:  1829, zero: 0.9, t: "flat" },
  { term: "cámara de seguridad", searches:  7412, ctr: 18.4, clicks:  1364, zero: 1.3, t: "down" },
  { term: "freidora de aire",    searches:  7125, ctr: 29.3, clicks:  2088, zero: 0.4, t: "up" },
  { term: "tablet android",      searches:  6840, ctr: 20.5, clicks:  1402, zero: 1.0, t: "flat" },
];

const ZERO_RESULT_TERMS = [
  { term: "manzana vision pro 2", count: 412, sessions: 318, first_seen: "hace 2 días" },
  { term: "ps6 consola",          count: 384, sessions: 290, first_seen: "hace 1 día"  },
  { term: "iphone 17",            count: 356, sessions: 271, first_seen: "hace 3 días" },
  { term: "lavadora samsugn",     count: 298, sessions: 224, first_seen: "hace 5 días" },  // typo
  { term: "audifons inalambricos",count: 251, sessions: 197, first_seen: "hace 1 día"  },  // typo
  { term: "celular xomi",         count: 209, sessions: 178, first_seen: "hace 4 días" },  // typo (xiaomi)
  { term: "kindel",               count: 187, sessions: 165, first_seen: "hace 2 días" },  // typo
  { term: "macbook air m5",       count: 162, sessions: 152, first_seen: "hace 1 día"  },
  { term: "ventilador torre recargable", count: 148, sessions: 140, first_seen: "hace 6 días" },
  { term: "carrito bebe todo terreno",   count: 133, sessions: 128, first_seen: "hace 3 días" },
];

// Time series — 24 hourly points
function genSeries(seed) {
  const rnd = mulberry32(seed);
  const out = [];
  for (let i = 0; i < 24; i++) {
    // diurnal pattern
    const base = 1800 + 1600 * Math.sin((i - 6) / 24 * Math.PI * 2) + 900;
    const noise = (rnd() - 0.5) * 600;
    out.push(Math.max(200, Math.round(base + noise)));
  }
  return out;
}

function genSeries7d(seed) {
  const rnd = mulberry32(seed);
  const out = [];
  for (let i = 0; i < 7; i++) {
    const base = 24000 + (i % 2 ? 4000 : -2000) + (rnd() - 0.5) * 5000;
    out.push(Math.max(10000, Math.round(base + i * 800)));
  }
  return out;
}

// Workflow runs
const RUNS = [
  { id: "run_8f3c02a1", started: "2026-04-22 18:04:12", duration: 342, records: 142_810, status: "running" },
  { id: "run_8f3bd74e", started: "2026-04-22 12:00:02", duration: 318, records: 141_992, status: "success" },
  { id: "run_8f3b9c01", started: "2026-04-22 06:00:05", duration: 301, records: 141_420, status: "success" },
  { id: "run_8f3b6a22", started: "2026-04-22 00:00:01", duration: 325, records: 140_988, status: "success" },
  { id: "run_8f3b3f10", started: "2026-04-21 18:00:04", duration: 512, records: 140_241, status: "failed" },
  { id: "run_8f3b0b77", started: "2026-04-21 12:00:03", duration: 298, records: 139_812, status: "success" },
  { id: "run_8f3ad810", started: "2026-04-21 06:00:06", duration: 307, records: 139_440, status: "success" },
  { id: "run_8f3aa522", started: "2026-04-21 00:00:02", duration: 312, records: 138_910, status: "success" },
  { id: "run_8f3a7211", started: "2026-04-20 18:00:03", duration: 294, records: 138_402, status: "success" },
  { id: "run_8f3a3f55", started: "2026-04-20 12:00:01", duration: 289, records: 137_950, status: "success" },
  { id: "run_8f3a0c30", started: "2026-04-20 06:00:04", duration: 305, records: 137_520, status: "success" },
  { id: "run_8f39d910", started: "2026-04-20 00:00:02", duration: 321, records: 137_080, status: "success" },
];

// Users
const USERS_INITIAL = [
  { id: 1, name: "María González",   email: "maria.gonzalez@amarello.com.mx", role: "Admin",    status: "active",   last: "hace 2 min"  },
  { id: 2, name: "Luis Hernández",   email: "luis.hernandez@amarello.com.mx", role: "Analyst",  status: "active",   last: "hace 14 min" },
  { id: 3, name: "Sofía Ramírez",    email: "sofia.ramirez@amarello.com.mx",  role: "Editor",   status: "active",   last: "hace 1 h"    },
  { id: 4, name: "Diego Torres",     email: "diego.torres@amarello.com.mx",   role: "Analyst",  status: "invited",  last: "—"           },
  { id: 5, name: "Camila Vargas",    email: "camila.vargas@amarello.com.mx",  role: "Viewer",   status: "active",   last: "hace 3 h"    },
  { id: 6, name: "Javier Medina",    email: "javier.medina@amarello.com.mx",  role: "Editor",   status: "suspended",last: "hace 12 d"   },
  { id: 7, name: "Laura Castillo",   email: "laura.castillo@amarello.com.mx", role: "Analyst",  status: "active",   last: "hace 4 h"    },
  { id: 8, name: "Andrés Peña",      email: "andres.pena@amarello.com.mx",    role: "Viewer",   status: "invited",  last: "—"           },
  { id: 9, name: "Valentina Ríos",   email: "valentina.rios@amarello.com.mx", role: "Admin",    status: "active",   last: "hace 8 min"  },
  { id:10, name: "Mateo Delgado",    email: "mateo.delgado@amarello.com.mx",  role: "Editor",   status: "active",   last: "hace 2 h"    },
  { id:11, name: "Renata Aguilar",   email: "renata.aguilar@amarello.com.mx", role: "Analyst",  status: "active",   last: "hace 1 d"    },
  { id:12, name: "Emilio Navarro",   email: "emilio.navarro@amarello.com.mx", role: "Viewer",   status: "active",   last: "hace 5 h"    },
];

const STEP_KEYS = ["s_setup", "s_ingest", "s_enhance", "s_vector", "s_confirm"];
const STEP_ICONS = ["check", "database", "sparkle", "cube", "rocket"];

// ============ API client ============
async function fetchStats(period) {
  return apiAuth(`/api/stats?period=${encodeURIComponent(period)}`);
}

function useStats(period) {
  return useApi(`/api/stats?period=${encodeURIComponent(period)}`, [period]);
}
function useTrends(period, limit) {
  const url = `/api/trends?period=${encodeURIComponent(period)}` + (limit ? `&limit=${limit}` : "");
  return useApi(url, [period, limit]);
}
function useApi(url, deps) {
  const [state, setState] = React.useState({ loading: !!url, data: null, error: null });
  React.useEffect(() => {
    if (!url) { setState({ loading: false, data: null, error: null }); return; }
    let cancelled = false;
    setState(s => ({ loading: true, data: s.data, error: null }));
    apiAuth(url)
      .then(data => { if (!cancelled) setState({ loading: false, data, error: null }); })
      .catch(err => { if (!cancelled) setState({ loading: false, data: null, error: err.message }); });
    return () => { cancelled = true; };
  }, deps); // eslint-disable-line
  return state;
}

Object.assign(window, {
  TOP_TERMS_ES, ZERO_RESULT_TERMS, genSeries, genSeries7d, RUNS, USERS_INITIAL,
  STEP_KEYS, STEP_ICONS, mulberry32, fetchStats, useStats, useTrends, useApi,
});
