// data.jsx — Mock data for Capivara's Fishing ERP
// All shared via window globals so other script tags can use it.

const STORE_INFO = {
  name: "Capivara's Fishing",
  razao: "CAPIVARA'S FISHING COMERCIO DE ARTIGOS DE PESCA LTDA",
  cnpj: "48.221.456/0001-09",
  ie: "395.482.119.118",
  endereco: "Av. Beira-Rio, 1842 — Centro",
  cidade: "Ponta Grossa / PR",
  cep: "84010-001",
  fone: "(42) 3521-8800",
  email: "loja@capivarasfishing.com.br",
};

// Categories
const CATS = [
  { id: "iscas",      name: "Iscas",            icon: "🎣" },
  { id: "varas",      name: "Varas",            icon: "🎏" },
  { id: "moli",       name: "Molinetes & Carret.", icon: "⚙️" },
  { id: "linhas",     name: "Linhas",           icon: "🧵" },
  { id: "anz",        name: "Anzóis",           icon: "🪝" },
  { id: "acess",      name: "Acessórios",       icon: "🧰" },
  { id: "embarc",     name: "Embarcações",      icon: "🛥️" },
  { id: "motor",      name: "Motores",          icon: "🔩" },
  { id: "vest",       name: "Vestuário",        icon: "🧢" },
];

// Marketplaces and which products are listed where
const MARKETPLACES = [
  { id: "loja",   name: "Loja Física",      color: "#4A5D3A", connected: true,  orders_today: 14, last_sync: "agora" },
  { id: "ml",     name: "Mercado Livre",    color: "#F7C530", connected: true,  orders_today: 8,  last_sync: "1 min" },
  { id: "shopee", name: "Shopee",           color: "#EE4D2D", connected: true,  orders_today: 5,  last_sync: "2 min" },
  { id: "amazon", name: "Amazon",           color: "#232F3E", connected: false, orders_today: 0,  last_sync: "—" },
  { id: "magalu", name: "Magalu",           color: "#0086FF", connected: true,  orders_today: 2,  last_sync: "4 min" },
];

// Products — mix of small (iscas, anzóis) → big (barcos, motores)
const PRODUCTS = [
  { id: "P001", sku: "ISC-RPL-001", barcode: "7891000010012", name: "Isca Artificial Plug Raptor 9cm Verde",     cat: "iscas",   price: 49.90,   cost: 22.00,  stock: 38, min: 10, mp: ["loja","ml","shopee","magalu"] },
  { id: "P002", sku: "ISC-JIG-014", barcode: "7891000010029", name: "Jig Head 7g 4/0 (cartela c/ 5)",            cat: "iscas",   price: 24.90,   cost: 11.50,  stock: 84, min: 20, mp: ["loja","ml","shopee"] },
  { id: "P003", sku: "ISC-SIL-022", barcode: "7891000010036", name: "Isca Soft Shad 12cm Pumpkinseed",            cat: "iscas",   price: 18.50,   cost: 7.20,   stock: 6,  min: 15, mp: ["loja","ml","shopee","magalu"] },
  { id: "P004", sku: "VRA-FBR-301", barcode: "7891000010043", name: "Vara Pesca Brava 1.80m Ação Média",          cat: "varas",   price: 219.00,  cost: 110.00, stock: 12, min: 4,  mp: ["loja","ml","magalu"] },
  { id: "P005", sku: "VRA-CRB-410", barcode: "7891000010050", name: "Vara Carbono Pro 2.10m 8-17lb",              cat: "varas",   price: 489.00,  cost: 235.00, stock: 5,  min: 3,  mp: ["loja","ml"] },
  { id: "P006", sku: "VRA-TEL-205", barcode: "7891000010067", name: "Vara Telescópica Iniciante 2.40m",           cat: "varas",   price: 119.90,  cost: 52.00,  stock: 24, min: 6,  mp: ["loja","ml","shopee","magalu"] },
  { id: "P007", sku: "MOL-2500-AL", barcode: "7891000010074", name: "Molinete Pantaneiro 2500 5+1 Rolamentos",     cat: "moli",    price: 359.00,  cost: 178.00, stock: 9,  min: 3,  mp: ["loja","ml","magalu"] },
  { id: "P008", sku: "MOL-4000-PR", barcode: "7891000010081", name: "Molinete Pro Series 4000 9+1",                cat: "moli",    price: 599.00,  cost: 295.00, stock: 4,  min: 2,  mp: ["loja","ml"] },
  { id: "P009", sku: "MOL-CAR-150", barcode: "7891000010098", name: "Carretilha Perfil Baixo 150 RH",              cat: "moli",    price: 549.00,  cost: 270.00, stock: 7,  min: 3,  mp: ["loja","ml","shopee"] },
  { id: "P010", sku: "LIN-MUL-040", barcode: "7891000010104", name: "Linha Multifilamento 0.40mm 300m Verde",     cat: "linhas",  price: 89.90,   cost: 38.00,  stock: 42, min: 10, mp: ["loja","ml","shopee","magalu"] },
  { id: "P011", sku: "LIN-MON-035", barcode: "7891000010111", name: "Linha Monofilamento 0.35mm 100m",            cat: "linhas",  price: 24.90,   cost: 9.50,   stock: 0,  min: 20, mp: ["loja","ml","shopee","magalu"] },
  { id: "P012", sku: "ANZ-MUS-040", barcode: "7891000010128", name: "Anzol Mustad 4/0 (cartela c/ 10)",            cat: "anz",     price: 14.90,   cost: 5.20,   stock: 156, min: 30, mp: ["loja","ml","shopee","magalu"] },
  { id: "P013", sku: "ANZ-OWN-010", barcode: "7891000010135", name: "Anzol Owner 1/0 Tripli (3 unid.)",            cat: "anz",     price: 22.90,   cost: 9.80,   stock: 88, min: 25, mp: ["loja","ml","shopee"] },
  { id: "P014", sku: "ACE-CAI-PXG", barcode: "7891000010142", name: "Caixa Estojo Tackle 4 Bandejas",              cat: "acess",   price: 89.00,   cost: 38.00,  stock: 18, min: 5,  mp: ["loja","ml","shopee","magalu"] },
  { id: "P015", sku: "ACE-ALI-200", barcode: "7891000010159", name: "Alicate Manuseio Inox 23cm",                   cat: "acess",   price: 79.90,   cost: 32.00,  stock: 22, min: 6,  mp: ["loja","ml","magalu"] },
  { id: "P016", sku: "ACE-PUC-001", barcode: "7891000010166", name: "Puçá de Mão Cabo Alumínio 50cm",              cat: "acess",   price: 59.90,   cost: 24.00,  stock: 14, min: 5,  mp: ["loja","ml","shopee"] },
  { id: "P017", sku: "ACE-COL-040", barcode: "7891000010173", name: "Colete Salva-Vidas Adulto 40-90kg (Hom.)",    cat: "acess",   price: 149.90,  cost: 62.00,  stock: 11, min: 4,  mp: ["loja","ml","magalu"] },
  { id: "P018", sku: "EMB-CAI-450", barcode: "7891000010180", name: "Barco Alumínio Caiaque 4.50m",                cat: "embarc",  price: 8990.00, cost: 5200.00, stock: 2, min: 1,  mp: ["loja"] },
  { id: "P019", sku: "EMB-BOT-300", barcode: "7891000010197", name: "Bote Inflável 3.00m c/ Remos",                cat: "embarc",  price: 2390.00, cost: 1280.00, stock: 3, min: 1,  mp: ["loja","ml"] },
  { id: "P020", sku: "MOT-POP-15H", barcode: "7891000010203", name: "Motor de Popa 15HP 2 Tempos",                 cat: "motor",   price: 14990.00, cost: 9200.00, stock: 1, min: 1, mp: ["loja"] },
  { id: "P021", sku: "MOT-ELE-046", barcode: "7891000010210", name: "Motor Elétrico 46 lbs 12V",                    cat: "motor",   price: 2890.00, cost: 1620.00, stock: 4, min: 1,  mp: ["loja","ml"] },
  { id: "P022", sku: "VES-CAM-PMG", barcode: "7891000010227", name: "Camiseta UV 50+ Manga Longa Verde Musgo",     cat: "vest",    price: 89.90,   cost: 32.00,  stock: 36, min: 8,  mp: ["loja","ml","shopee","magalu"] },
  { id: "P023", sku: "VES-BON-001", barcode: "7891000010234", name: "Boné Trucker Capivara's Verde/Laranja",       cat: "vest",    price: 59.90,   cost: 18.00,  stock: 47, min: 10, mp: ["loja","ml","shopee","magalu"] },
  { id: "P024", sku: "ISC-COL-006", barcode: "7891000010241", name: "Colher Rotativa #4 Dourada",                   cat: "iscas",   price: 32.90,   cost: 13.00,  stock: 28, min: 8,  mp: ["loja","ml","shopee"] },
];

// Clients
const CLIENTS = [
  { id: "C001", nome: "João Carvalho da Silva",       cpf: "324.118.902-77", fone: "(67) 99182-4400", email: "joao.carvalho@gmail.com",  compras: 23, ticket: 187.40, ultima: "Hoje, 11:42" },
  { id: "C002", nome: "Marina Soares Pacheco",        cpf: "812.445.119-30", fone: "(67) 99204-7711", email: "marina.sp@hotmail.com",    compras: 14, ticket: 312.10, ultima: "Ontem"      },
  { id: "C003", nome: "Renato Oliveira Júnior",       cpf: "291.077.452-19", fone: "(11) 98832-1029", email: "renato.jr@outlook.com",    compras: 41, ticket: 89.30,  ultima: "Há 3 dias"  },
  { id: "C004", nome: "Fernando Bittencourt Lopes",   cpf: "445.882.110-44", fone: "(67) 99100-2233", email: "fb.lopes@gmail.com",       compras: 8,  ticket: 1290.00, ultima: "Há 1 semana" },
  { id: "C005", nome: "Aline Tavares de Souza",       cpf: "112.998.044-82", fone: "(31) 99771-8800", email: "aline.ts@yahoo.com.br",    compras: 6,  ticket: 145.20, ultima: "Há 2 semanas" },
  { id: "C006", nome: "Carlos Eduardo Mendes",        cpf: "778.221.330-15", fone: "(67) 99055-9912", email: "ce.mendes@gmail.com",      compras: 67, ticket: 78.50,  ultima: "Hoje, 10:11" },
  { id: "C007", nome: "Patricia Honorato",            cpf: "509.334.871-22", fone: "(47) 99230-1144", email: "pati.h@gmail.com",         compras: 3,  ticket: 8990.00, ultima: "Há 1 mês"   },
  { id: "C008", nome: "Wesley Marques Pereira",       cpf: "201.778.005-44", fone: "(67) 99811-0023", email: "wesley.mp@outlook.com",    compras: 19, ticket: 222.40, ultima: "Ontem"      },
];

// Users — 5 roles: admin (master), ceo, gerente, caixa, vendedor
const USERS = [
  { id: "U001", nome: "Você (Admin Master)",     email: "admin@capivarasfishing.com.br",        role: "admin",    ativo: true,  pdvs: ["PDV01","PDV02"], ultimo: "Online agora" },
  { id: "U002", nome: "Netto (CEO)",              email: "netto@capivarasfishing.com.br",        role: "ceo",      ativo: true,  pdvs: ["PDV01","PDV02"], ultimo: "Online agora" },
  { id: "U003", nome: "Ays (CEO)",                email: "ays@capivarasfishing.com.br",          role: "ceo",      ativo: true,  pdvs: ["PDV01","PDV02"], ultimo: "Há 12 min" },
  { id: "U004B",nome: "Daniela Maranhão",         email: "dani.gerente@capivarasfishing.com.br", role: "gerente",  ativo: true,  pdvs: ["PDV01","PDV02"], ultimo: "Online agora" },
  { id: "U007", nome: "Carla Tristão (Caixa)",    email: "carla.caixa@capivarasfishing.com.br",  role: "caixa",    ativo: true,  pdvs: ["PDV01"],         ultimo: "Online agora" },
  { id: "U004", nome: "Pedro Henrique Costa",     email: "pedro.h@capivarasfishing.com.br",     role: "vendedor", ativo: true,  pdvs: ["PDV01"],         ultimo: "Online agora" },
  { id: "U005", nome: "Larissa Furtado",          email: "larissa.f@capivarasfishing.com.br",   role: "vendedor", ativo: true,  pdvs: ["PDV02"],         ultimo: "Há 5 min" },
  { id: "U006", nome: "Bruno Tatuí",              email: "bruno.t@capivarasfishing.com.br",     role: "vendedor", ativo: false, pdvs: ["PDV01"],         ultimo: "Há 3 dias" },
];

// Permission matrix by role.
// Keys are screen ids (matching the router in app.jsx).
const ROLE_LABEL = {
  admin:    "Admin Master",
  ceo:      "CEO",
  gerente:  "Gerente",
  caixa:    "Caixa",
  vendedor: "Vendedor(a)",
};

const PERMISSIONS = {
  // sidebar / nav access by role
  // null = no access; "full" = full; "readonly" = read-only (qty only, no $)
  vendedor: {
    pdv: "full",
    estoque: "readonly_qty",   // só quantidades, sem custo/preço de venda nem margem
  },
  caixa: {
    pdv: "full",
    vendas: "full",
    nf: "full",
    clientes: "full",
  },
  gerente: {
    dashboard: "full",
    pdv: "full",
    estoque: "full",
    vendas: "full",
    nf: "full",
    clientes: "full",
    compras: "full",
    fornecedores: "full",
    integracoes: "full",
    relatorios: "full",
    // SEM usuários, SEM financeiro
  },
  ceo: {
    dashboard: "full",
    pdv: "full",
    estoque: "full",
    vendas: "full",
    nf: "full",
    clientes: "full",
    compras: "full",
    fornecedores: "full",
    integracoes: "full",
    financeiro: "full",
    relatorios: "full",
    usuarios: "full",
    discovery: "full", // ferramenta interna DashM
  },
  admin: {
    dashboard: "full",
    pdv: "full",
    estoque: "full",
    vendas: "full",
    nf: "full",
    clientes: "full",
    compras: "full",
    fornecedores: "full",
    integracoes: "full",
    financeiro: "full",
    relatorios: "full",
    usuarios: "full",
    configuracoes: "full", // exclusivo do admin master
    discovery: "full",     // ferramenta interna DashM
  },
};

function can(user, screen) {
  if (!user) return false;
  return !!(PERMISSIONS[user.role] && PERMISSIONS[user.role][screen]);
}
function permLevel(user, screen) {
  return user && PERMISSIONS[user.role] ? PERMISSIONS[user.role][screen] : null;
}

// Suppliers
const SUPPLIERS = [
  { id: "F001", nome: "Marine Sports Distribuidora",  cnpj: "11.234.567/0001-22", contato: "(11) 3322-1100", ultimo: "12/05/2026" },
  { id: "F002", nome: "Albatroz Equipamentos LTDA",   cnpj: "07.882.119/0001-44", contato: "(11) 4422-3344", ultimo: "08/05/2026" },
  { id: "F003", nome: "Marurê Pesca Atacado",         cnpj: "33.291.882/0001-77", contato: "(42) 3521-9988", ultimo: "02/05/2026" },
  { id: "F004", nome: "Nautika Brasil",                cnpj: "55.118.330/0001-15", contato: "(11) 3030-4400", ultimo: "28/04/2026" },
];

// Sales (recent)
function makeRecentSales() {
  const sellers = ["Pedro H.", "Larissa F.", "Daniela M."];
  const channels = ["loja", "ml", "shopee", "magalu", "loja", "loja"];
  const out = [];
  let n = 1042;
  const now = new Date();
  for (let i = 0; i < 32; i++) {
    const ago = i * 17 + Math.floor(Math.random() * 30);
    const d = new Date(now.getTime() - ago * 60_000);
    const channel = channels[i % channels.length];
    const seller = sellers[i % sellers.length];
    const itemsCount = 1 + Math.floor(Math.random() * 4);
    const items = [];
    let total = 0;
    for (let j = 0; j < itemsCount; j++) {
      const p = PRODUCTS[(i * 3 + j * 7) % PRODUCTS.length];
      if (p.price > 1000 && Math.random() > 0.3) continue;
      const qty = 1 + Math.floor(Math.random() * 3);
      items.push({ pid: p.id, name: p.name, sku: p.sku, qty, price: p.price });
      total += p.price * qty;
    }
    if (!items.length) {
      const p = PRODUCTS[i % 10];
      items.push({ pid: p.id, name: p.name, sku: p.sku, qty: 1, price: p.price });
      total = p.price;
    }
    out.push({
      id: "V" + (n++).toString().padStart(5, "0"),
      data: d.toISOString(),
      total,
      items,
      cliente: i % 3 === 0 ? CLIENTS[i % CLIENTS.length].nome : "Consumidor Final",
      vendedor: seller,
      canal: channel,
      pagamento: ["pix","credito","debito","dinheiro"][i % 4],
      status: i === 0 ? "em_aberto" : (i % 9 === 0 ? "cancelada" : "finalizada"),
      nf: i % 9 !== 0 ? ("NFe " + (28910 - i).toString()) : null,
    });
  }
  return out;
}
const SALES = makeRecentSales();

// Day-by-day sales for charts (last 30 days)
function makeDailyChart() {
  const out = [];
  const today = new Date();
  for (let i = 29; i >= 0; i--) {
    const d = new Date(today);
    d.setDate(today.getDate() - i);
    const base = 2400;
    const wkBoost = (d.getDay() === 0 || d.getDay() === 6) ? 1.4 : 1.0;
    const noise = 0.7 + Math.random() * 0.6;
    out.push({
      date: d,
      total: Math.round(base * wkBoost * noise),
      sales: Math.round(18 * wkBoost * noise),
    });
  }
  return out;
}
const DAILY_CHART = makeDailyChart();

// Channel split
const CHANNEL_SPLIT = [
  { id: "loja",   label: "Loja Física",   pct: 58, value: 41280 },
  { id: "ml",     label: "Mercado Livre", pct: 22, value: 15660 },
  { id: "shopee", label: "Shopee",        pct: 11, value:  7830 },
  { id: "magalu", label: "Magalu",        pct:  6, value:  4270 },
  { id: "amazon", label: "Amazon",        pct:  3, value:  2135 },
];

// Top products this month
const TOP_PRODUCTS = [
  { id: "P012", qty: 318, rev: 4738.20 },
  { id: "P002", qty: 142, rev: 3535.80 },
  { id: "P010", qty: 78,  rev: 7012.20 },
  { id: "P023", qty: 64,  rev: 3833.60 },
  { id: "P001", qty: 52,  rev: 2594.80 },
  { id: "P022", qty: 41,  rev: 3685.90 },
];

// Cash session
const CASH_SESSION = {
  open: true,
  pdv: "PDV01",
  opened_at: "Hoje 07:42",
  opened_by: "Daniela Maranhão",
  initial: 200.00,
  sales: 1842.50,
  cash_in: 1240.30,
  cash_out: 80.00,   // sangria
  current: 200 + 1240.30 - 80,
};

// Marketplace orders awaiting fulfilment
const MP_ORDERS = [
  { id: "ML-87412", mp: "ml",     buyer: "Carlos Souza",        when: "Há 8 min",   total: 89.90,  status: "pago_aguardando" },
  { id: "ML-87410", mp: "ml",     buyer: "Renata Carvalho",     when: "Há 24 min",  total: 359.00, status: "etiqueta_pronta" },
  { id: "SH-22910", mp: "shopee", buyer: "Bruno Lima",          when: "Há 41 min",  total: 49.90,  status: "pago_aguardando" },
  { id: "MG-10044", mp: "magalu", buyer: "Patricia Honorato",   when: "Há 1h 12m",  total: 219.00, status: "pago_aguardando" },
  { id: "ML-87401", mp: "ml",     buyer: "Eduardo Tavares",     when: "Há 2h",      total: 24.90,  status: "enviado" },
  { id: "SH-22899", mp: "shopee", buyer: "Marcia Aparecida",    when: "Há 3h",      total: 119.90, status: "enviado" },
];

// Helpers
function brl(n) {
  return "R$ " + (n || 0).toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function brlShort(n) {
  if (n >= 1_000_000) return "R$ " + (n / 1_000_000).toFixed(1) + "M";
  if (n >= 1_000) return "R$ " + (n / 1_000).toFixed(1) + "k";
  return brl(n);
}
function dateBR(iso) {
  const d = new Date(iso);
  const dd = String(d.getDate()).padStart(2, "0");
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const yy = d.getFullYear();
  const hh = String(d.getHours()).padStart(2, "0");
  const mn = String(d.getMinutes()).padStart(2, "0");
  return `${dd}/${mm}/${yy} ${hh}:${mn}`;
}
function timeAgo(iso) {
  const d = new Date(iso);
  const diff = Math.floor((Date.now() - d.getTime()) / 60000);
  if (diff < 1) return "agora";
  if (diff < 60) return `há ${diff} min`;
  const h = Math.floor(diff / 60);
  if (h < 24) return `há ${h}h`;
  const days = Math.floor(h / 24);
  return `há ${days}d`;
}
function findProduct(id) { return PRODUCTS.find(p => p.id === id); }
function categoryById(id) { return CATS.find(c => c.id === id); }
function marketplaceById(id) { return MARKETPLACES.find(m => m.id === id); }

Object.assign(window, {
  STORE_INFO, CATS, MARKETPLACES, PRODUCTS, CLIENTS, USERS, SUPPLIERS,
  SALES, DAILY_CHART, CHANNEL_SPLIT, TOP_PRODUCTS, CASH_SESSION, MP_ORDERS,
  brl, brlShort, dateBR, timeAgo, findProduct, categoryById, marketplaceById,
  ROLE_LABEL, PERMISSIONS, can, permLevel,
});
