import { IMAGE_MANIFEST } from "./images";
import type { AttrValue, Category, Product } from "./types";

export const BRANDS = ["nordik", "luma", "vento", "oca", "pulsar", "atlas"];
export const cap = (x: string) => (x ? x[0]!.toUpperCase() + x.slice(1) : "");

const CAT_OF: Record<string, Category> = {
  "p-phone": "Celulares", "p-laptop": "Informática", "p-kb": "Informática",
  "p-shirt": "Moda", "p-shoe": "Moda", "p-bag": "Moda",
  "p-hp": "Áudio", "p-watch": "Áudio", "p-spk": "Áudio",
  "p-coffee": "Casa", "p-lamp": "Casa", "p-bot": "Casa",
};

type Base = Omit<Product, "brand" | "cat" | "attrs">;
/** Catálogo de demonstração. Troque por chamadas à API mantendo o tipo Product. */
export const BASE: Base[] = [
  { id: 1, title: "Fone de ouvido Bluetooth over-ear com cancelamento de ruído", priceCents: 24990, originalPriceCents: 32990, installments: 10, rating: 4.7, reviews: 1284, freeShipping: true, eta: "chega amanhã", verified: true, badge: "Oferta", art: "p-hp" },
  { id: 2, title: "Smartwatch com GPS, monitor de sono e tela AMOLED", priceCents: 38900, installments: 12, rating: 4.5, reviews: 642, freeShipping: true, eta: "chega em 2 dias", verified: true, art: "p-watch" },
  { id: 3, title: "Smartphone 6,7 pol. 256 GB 5G com câmera tripla", priceCents: 189900, originalPriceCents: 229900, installments: 12, rating: 4.6, reviews: 3412, freeShipping: true, eta: "chega amanhã", verified: true, badge: "Mais vendido", art: "p-phone" },
  { id: 4, title: "Notebook 14 pol., 16 GB de RAM e SSD de 512 GB", priceCents: 329900, originalPriceCents: 379900, installments: 12, rating: 4.6, reviews: 905, freeShipping: true, eta: "chega em 3 dias", verified: true, art: "p-laptop" },
  { id: 5, title: "Tênis de corrida leve com amortecimento responsivo", priceCents: 21990, installments: 8, rating: 4.4, reviews: 512, freeShipping: true, eta: "chega em 3 a 5 dias", art: "p-shoe" },
  { id: 6, title: "Camiseta básica de algodão premium, corte regular", priceCents: 7990, originalPriceCents: 9990, installments: 3, rating: 4.5, reviews: 2210, freeShipping: false, verified: true, art: "p-shirt" },
  { id: 7, title: "Cafeteira elétrica programável 1,2 L com jarra térmica", priceCents: 18990, originalPriceCents: 22990, installments: 6, rating: 4.8, reviews: 3011, freeShipping: true, eta: "chega amanhã", verified: true, badge: "Mais vendido", art: "p-coffee" },
  { id: 8, title: "Mochila impermeável para notebook de até 15,6 pol.", priceCents: 12990, installments: 4, rating: 4.3, reviews: 218, freeShipping: false, art: "p-bag" },
  { id: 9, title: "Teclado mecânico compacto sem fio, switch silencioso", priceCents: 29990, originalPriceCents: 34990, installments: 10, rating: 4.6, reviews: 907, freeShipping: true, eta: "chega em 2 dias", verified: true, art: "p-kb" },
  { id: 10, title: "Garrafa térmica de aço inox 750 ml, mantém 12 h", priceCents: 7990, installments: 2, rating: 4.9, reviews: 4120, freeShipping: true, eta: "chega amanhã", verified: true, badge: "Mais vendido", art: "p-bot" },
  { id: 11, title: "Caixa de som Bluetooth portátil à prova d'água", priceCents: 15990, originalPriceCents: 19990, installments: 6, rating: 4.5, reviews: 733, freeShipping: true, eta: "chega em 2 dias", verified: true, badge: "Oferta", art: "p-spk" },
  { id: 12, title: "Luminária de mesa LED com carregador sem fio", priceCents: 9990, originalPriceCents: 13990, installments: 3, rating: 4.2, reviews: 89, freeShipping: false, art: "p-lamp" },
];

const pick = <T,>(a: T[], h: number) => a[h % a.length]!;
export function attrsFor(art: string, cat: Category, id: number): Record<string, AttrValue> {
  const h = id;
  if (cat === "Celulares") return { ram: pick([6, 8, 12], h), storage: pick([128, 256, 512], h + 1), tela: pick([6.1, 6.5, 6.7], h), g5: h % 4 !== 0 };
  if (cat === "Informática")
    return art === "p-kb" ? { conect: pick(["Bluetooth", "USB", "Wi-Fi"], h) }
      : { ram: pick([8, 16, 32], h), storage: pick([256, 512, 1024], h + 1), tela: pick([14, 15.6], h) };
  if (cat === "Moda") return { tamanho: pick(["P", "M", "G", "GG"], h), cor: pick(["Preto", "Branco", "Verde", "Cinza"], h + 2), genero: pick(["Unissex", "Feminino", "Masculino"], h) };
  if (cat === "Áudio") return { conect: pick(["Bluetooth", "Cabo"], h), resist: pick(["À prova d'água", "Padrão"], h + 1) };
  return { voltagem: pick(["Bivolt", "110V", "220V"], h), material: pick(["Aço inox", "Plástico", "Vidro", "Alumínio"], h + 1) };
}

function build(): Product[] {
  const out: Product[] = [];
  const mk = (b: Base, brand: string, over: Partial<Product> = {}): Product => {
    const cat = CAT_OF[b.art]!;
    const p = { ...b, ...over, brand, cat } as Product;
    p.attrs = attrsFor(p.art, cat, p.id);
    // Foto real, se houver: por id do produto ou pelo código da ilustração (variantes reaproveitam a foto).
    const img = IMAGE_MANIFEST[String(p.id)] ?? IMAGE_MANIFEST[p.art];
    if (img && !p.imageUrl) { p.imageUrl = img.src; p.imageSrcSet = img.srcSet; }
    return p;
  };
  BASE.forEach((b, i) => out.push(mk(b, BRANDS[i % 6]!)));
  let id = 13;
  BASE.forEach((b, i) => [0, 1].forEach((k) => {
    const m = k ? 1.14 : 0.82, brand = BRANDS[(i + k * 2 + 1) % 6]!;
    out.push(mk(b, brand, {
      id: id++, title: `${cap(brand)} ${b.title}`,
      priceCents: Math.round((b.priceCents * m) / 10) * 10,
      originalPriceCents: b.originalPriceCents ? Math.round((b.originalPriceCents * m) / 10) * 10 : undefined,
      rating: Math.min(5, Math.max(3.8, +(b.rating + (k ? -0.2 : 0.1)).toFixed(1))),
      reviews: Math.round(b.reviews * (k ? 0.4 : 0.7)), badge: "",
      freeShipping: k ? !b.freeShipping : b.freeShipping, verified: k ? !b.verified : b.verified,
      eta: b.eta ?? "chega em 3 a 5 dias",
    }));
  }));
  return out;
}
export const PRODUCTS: Product[] = build();
export const HOME_PRODUCTS = PRODUCTS.slice(0, 12);
export const getProduct = (id: number | string) => PRODUCTS.find((p) => p.id === Number(id));

export const SCHEMA: Record<string, [key: string, label: string, unit: string][]> = {
  Celulares: [["ram", "Memória RAM", " GB"], ["storage", "Armazenamento", " GB"], ["tela", "Tela", " pol."], ["g5", "5G", ""]],
  Informática: [["ram", "Memória RAM", " GB"], ["storage", "Armazenamento", " GB"], ["tela", "Tela", " pol."], ["conect", "Conectividade", ""]],
  Moda: [["tamanho", "Tamanho", ""], ["cor", "Cor", ""], ["genero", "Gênero", ""]],
  Áudio: [["conect", "Conectividade", ""], ["resist", "Resistência", ""]],
  Casa: [["voltagem", "Voltagem", ""], ["material", "Material", ""]],
};
export const ATTR_LABEL: Record<string, [string, string]> = {};
Object.values(SCHEMA).flat().forEach(([k, l, u]) => { ATTR_LABEL[k] = [l, u]; });
export const fmtAttr = (v: string, unit: string) => (v === "true" ? "Sim" : v === "false" ? "Não" : v + unit);
