/* lib.jsx — dados, comissões, fetch real + fallback de demonstração */

const BRL = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' });
const formatBRL = (v) => BRL.format(Number(v) || 0);
const formatPct = (r) => `${(Number(r) * 100).toFixed(Number(r) * 100 % 1 === 0 ? 0 : 1)}%`;

function titleCase(s) {
  return String(s || '')
    .trim()
    .split(/\s+/)
    .map((w) => (w.length > 2 ? w[0].toUpperCase() + w.slice(1) : w))
    .join(' ');
}

/* ---- Tabela de comissão Mercado Livre por categoria ---- */
const ML_COMMISSION = {
  MLB1051: 0.03, // Celulares
  MLB1648: 0.03, // Eletrônicos
  MLB1649: 0.04, // Informática
  MLB1574: 0.05, // Eletrodomésticos
  MLB9:    0.08, // Casa e Decoração
  MLB1430: 0.12, // Moda e Vestuário
  MLB1246: 0.10, // Beleza e Cuidado Pessoal
  MLB1276: 0.09, // Esportes e Fitness
  MLB5726: 0.08, // Brinquedos
  MLB1039: 0.07, // Ferramentas
  MLB1193: 0.06, // Livros / Mídia
};
const ML_CATEGORY_LABEL = {
  MLB1051: 'Celulares', MLB1648: 'Eletrônicos', MLB1649: 'Informática',
  MLB1574: 'Eletrodomésticos', MLB9: 'Casa e Decoração', MLB1430: 'Moda',
  MLB1246: 'Beleza', MLB1276: 'Esportes', MLB5726: 'Brinquedos',
  MLB1039: 'Ferramentas', MLB1193: 'Livros / Mídia',
};
const mlRate = (catId) => (ML_COMMISSION[catId] != null ? ML_COMMISSION[catId] : 0.05);
const mlCategoryLabel = (catId) => ML_CATEGORY_LABEL[catId] || 'Outras categorias';

/* ---- Fetch real: Mercado Livre (público; token opcional) ---- */
async function searchMercadoLivre(term, token) {
  const url = `https://api.mercadolibre.com/sites/MLB/search?q=${encodeURIComponent(term)}&limit=20`;
  const headers = {};
  if (token) headers.Authorization = 'Bearer ' + token;
  const res = await fetch(url, { headers });
  if (!res.ok) throw new Error(`ML_HTTP_${res.status}`);
  const data = await res.json();
  return (data.results || []).map((r) => {
    const rate = mlRate(r.category_id);
    return {
      id: 'ml-' + r.id,
      platform: 'ml',
      title: r.title,
      price: r.price,
      rate,
      commission: r.price * rate,
      image: (r.thumbnail || '').replace('http://', 'https://') || null,
      link: r.permalink,
      category: r.category_id,
      categoryLabel: mlCategoryLabel(r.category_id),
      demo: false,
    };
  });
}

/* ---- Fetch real: Shopee Afiliados (GraphQL, requer Bearer token) ---- */
async function searchShopee(term, token) {
  if (!token) throw new Error('NO_TOKEN');
  const query = `query { productOfferV2(listType: 0 sortType: 2 page: 1 limit: 20 keyword: "${term.replace(/"/g, '\\"')}") { nodes { itemId shopId productName priceMin commissionRate commission productLink imageUrl offerLink } } }`;
  const res = await fetch('https://open-api.affiliate.shopee.com.br/graphql', {
    method: 'POST',
    headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query }),
  });
  if (!res.ok) throw new Error(`SHOPEE_HTTP_${res.status}`);
  const data = await res.json();
  const nodes = (data && data.data && data.data.productOfferV2 && data.data.productOfferV2.nodes) || [];
  return nodes.map((n) => {
    const price = parseFloat(n.priceMin);
    const rate = parseFloat(n.commissionRate);
    return {
      id: 'sp-' + n.itemId,
      platform: 'shopee',
      title: n.productName,
      price,
      rate,
      commission: n.commission != null ? parseFloat(n.commission) : price * rate,
      image: n.imageUrl || null,
      link: n.offerLink || n.productLink,
      demo: false,
    };
  });
}

/* ---- Gerador de demonstração (determinístico por termo) ---- */
function hashStr(s) {
  let h = 1779033703 ^ s.length;
  for (let i = 0; i < s.length; i++) {
    h = Math.imul(h ^ s.charCodeAt(i), 3432918353);
    h = (h << 13) | (h >>> 19);
  }
  return h >>> 0;
}
function mulberry32(a) {
  return function () {
    a |= 0; a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

const DEMO_CATS = [
  { id: 'MLB1051', label: 'Celulares', range: [699, 5200] },
  { id: 'MLB1649', label: 'Informática', range: [89, 3400] },
  { id: 'MLB1574', label: 'Eletrodomésticos', range: [159, 2400] },
  { id: 'MLB9', label: 'Casa e Decoração', range: [29, 690] },
  { id: 'MLB1430', label: 'Moda', range: [39, 380] },
  { id: 'MLB1246', label: 'Beleza', range: [19, 320] },
  { id: 'MLB1276', label: 'Esportes', range: [49, 980] },
  { id: 'MLB5726', label: 'Brinquedos', range: [29, 420] },
  { id: 'MLB1039', label: 'Ferramentas', range: [39, 880] },
  { id: 'MLB1193', label: 'Livros / Mídia', range: [18, 140] },
];

function demoResults(term, only) {
  const rng = mulberry32(hashStr((term || 'produto').toLowerCase()));
  const pick = (arr) => arr[Math.floor(rng() * arr.length)];
  const rnd = (a, b) => a + rng() * (b - a);
  const PRE = ['Kit', 'Original', 'Pro', 'Premium', 'Smart', 'Ultra', 'Combo', 'Novo', 'Top', 'Master'];
  const SUF = ['2025', 'Importado', 'com NF', 'Original', 'Edição Especial', 'Pronta Entrega', 'com Garantia', 'Lacrado', 'Promoção', 'Frete Grátis'];
  const t = titleCase(term || 'produto');
  const items = [];
  for (let i = 0; i < 18; i++) {
    const cat = DEMO_CATS[Math.floor(rng() * DEMO_CATS.length)];
    const price = Math.round(rnd(cat.range[0], cat.range[1]) * 100) / 100;
    const platform = rng() < 0.5 ? 'ml' : 'shopee';
    if (only && platform !== only) continue;
    const name = `${pick(PRE)} ${t} ${pick(SUF)}`;
    const rate = platform === 'ml' ? mlRate(cat.id) : Math.round(rnd(0.06, 0.2) * 100) / 100;
    const commission = Math.round(price * rate * 100) / 100;
    items.push({
      id: `demo-${platform}-${i}`,
      platform,
      title: name,
      price,
      rate,
      commission,
      image: null,
      link: '#',
      category: cat.id,
      categoryLabel: cat.label,
      demo: true,
    });
  }
  // garante pelo menos alguns itens quando filtrado por plataforma
  if (only && items.length < 6) {
    for (let i = items.length; i < 8; i++) {
      const cat = DEMO_CATS[Math.floor(rng() * DEMO_CATS.length)];
      const price = Math.round(rnd(cat.range[0], cat.range[1]) * 100) / 100;
      const rate = only === 'ml' ? mlRate(cat.id) : Math.round(rnd(0.06, 0.2) * 100) / 100;
      items.push({
        id: `demo-${only}-x${i}`, platform: only, title: `${pick(PRE)} ${t} ${pick(SUF)}`,
        price, rate, commission: Math.round(price * rate * 100) / 100, image: null,
        link: '#', category: cat.id, categoryLabel: cat.label, demo: true,
      });
    }
  }
  return items;
}

/* ---- Dados de demonstração do Dashboard de Ganhos ---- */
function demoEarnings(seed = 'achamais') {
  const rng = mulberry32(hashStr(seed));
  const rnd = (a, b) => a + rng() * (b - a);
  const MES = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];

  // série diária (últimos 30 dias)
  const series = [];
  let base = rnd(40, 90);
  for (let i = 0; i < 30; i++) {
    base += rnd(-18, 22);
    base = Math.max(12, Math.min(230, base));
    const weekendBoost = (i % 7 === 5 || i % 7 === 6) ? rnd(1.1, 1.5) : 1;
    series.push(Math.round(base * weekendBoost));
  }
  const total = series.reduce((a, b) => a + b, 0);

  const clicks = Math.round(rnd(2600, 4200));
  const conversions = Math.round(clicks * rnd(0.03, 0.06));
  const avgTicket = total / Math.max(1, conversions);
  const mlShare = rnd(0.52, 0.66);

  // série mensal (6 meses) para mini-tendência
  const now = 5; // Jun
  const months = [];
  let m = total * rnd(0.55, 0.7);
  for (let i = 5; i >= 0; i--) {
    m *= rnd(0.86, 1.18);
    months.unshift({ label: MES[(now - i + 12) % 12], value: Math.round(m) });
  }
  months[months.length - 1].value = total;

  const PRODS = [
    { title: 'Fone Bluetooth TWS Pro', platform: 'ml', cat: 'Eletrônicos' },
    { title: 'Air Fryer 5L Digital', platform: 'shopee', cat: 'Eletrodomésticos' },
    { title: 'Smartwatch Series 9', platform: 'ml', cat: 'Eletrônicos' },
    { title: 'Kit Skincare Facial', platform: 'shopee', cat: 'Beleza' },
    { title: 'Tênis de Corrida Ultra', platform: 'ml', cat: 'Esportes' },
    { title: 'Luminária LED de Mesa', platform: 'shopee', cat: 'Casa e Decoração' },
  ];
  const topProducts = PRODS.map((p, i) => {
    const sales = Math.round(rnd(8, 70) - i * 4);
    const comm = Math.round(rnd(90, 520) - i * 30);
    return { ...p, sales: Math.max(3, sales), commission: Math.max(28, comm) };
  }).sort((a, b) => b.commission - a.commission);

  return {
    total,
    clicks,
    conversions,
    convRate: conversions / Math.max(1, clicks),
    avgTicket,
    series,
    months,
    platforms: { ml: mlShare, shopee: 1 - mlShare },
    platformValues: { ml: Math.round(total * mlShare), shopee: Math.round(total * (1 - mlShare)) },
    topProducts,
    deltas: { total: rnd(0.08, 0.24), clicks: rnd(-0.05, 0.18), conversions: rnd(0.04, 0.2), avgTicket: rnd(-0.03, 0.12) },
  };
}

/* ---- Trends: produtos mais vendidos agora (demonstração determinística) ---- */
function demoTrends(category, period) {
  const rng = mulberry32(hashStr('trends-' + (category || 'all') + '-' + (period || '24h')));
  const rnd = (a, b) => a + rng() * (b - a);
  const CATALOG = [
    { title: 'Fone Bluetooth TWS Pro 5.3', cat: 'Eletrônicos', catId: 'MLB1648', base: 159 },
    { title: 'Air Fryer 5L Digital Inox', cat: 'Eletrodomésticos', catId: 'MLB1574', base: 329 },
    { title: 'Smartwatch Série 9 GPS', cat: 'Eletrônicos', catId: 'MLB1648', base: 289 },
    { title: 'Kit Skincare Vitamina C', cat: 'Beleza', catId: 'MLB1246', base: 119 },
    { title: 'Tênis de Corrida UltraBoost', cat: 'Esportes', catId: 'MLB1276', base: 349 },
    { title: 'Luminária LED Articulada', cat: 'Casa', catId: 'MLB9', base: 89 },
    { title: 'Caixa de Som Portátil 30W', cat: 'Eletrônicos', catId: 'MLB1648', base: 199 },
    { title: 'Conjunto de Panelas Antiaderente', cat: 'Casa', catId: 'MLB9', base: 259 },
    { title: 'Perfume Importado 100ml', cat: 'Beleza', catId: 'MLB1246', base: 239 },
    { title: 'Mochila Notebook Antifurto', cat: 'Moda', catId: 'MLB1430', base: 149 },
    { title: 'Webcam Full HD 1080p', cat: 'Informática', catId: 'MLB1649', base: 129 },
    { title: 'Garrafa Térmica Inox 1L', cat: 'Esportes', catId: 'MLB1276', base: 79 },
    { title: 'Teclado Mecânico RGB', cat: 'Informática', catId: 'MLB1649', base: 219 },
    { title: 'Organizador de Maquiagem Acrílico', cat: 'Casa', catId: 'MLB9', base: 69 },
    { title: 'Whey Protein 900g', cat: 'Esportes', catId: 'MLB1276', base: 139 },
    { title: 'Câmera de Segurança Wi-Fi', cat: 'Eletrônicos', catId: 'MLB1648', base: 169 },
  ];
  let list = CATALOG.map((p, i) => {
    const platform = rng() < 0.5 ? 'ml' : 'shopee';
    const price = Math.round(p.base * rnd(0.85, 1.15) * 100) / 100;
    const rate = platform === 'ml' ? mlRate(p.catId) : Math.round(rnd(0.08, 0.2) * 100) / 100;
    const sales = Math.round(rnd(120, 4200));
    const heat = Math.round(rnd(8, 96));
    const trend = Math.round(rnd(-12, 145));
    return {
      id: `trend-${i}`, rank: 0, title: p.title, category: p.cat, platform,
      price, rate, commission: Math.round(price * rate * 100) / 100,
      sales, heat, trend, demo: true, link: '#',
    };
  });
  if (category && category !== 'all') list = list.filter((p) => p.category === category);
  list.sort((a, b) => b.sales - a.sales);
  list.forEach((p, i) => (p.rank = i + 1));
  return list;
}

Object.assign(window, {
  formatBRL, formatPct, titleCase,
  ML_COMMISSION, ML_CATEGORY_LABEL, mlRate, mlCategoryLabel,
  searchMercadoLivre, searchShopee, demoResults, demoEarnings, demoTrends,
});
