/**
 * Website side of the product catalogue (API reference: "How products work (website)").
 * Types of GET /public/products and /public/products/:slug, the catalogue's URL filters
 * and the display rules (prices in cents, variant matching). Used on the server and in
 * the browser.
 */
import type { Img, PublicLanguage } from "./content";

export type Money = { currency: string; unit: string };

/** A product card (list items and `related`). For on-request products `price` has no figures. */
export type ProductCard = {
  id: string;
  slug: string;
  type: "simple" | "variable";
  name: string;
  language?: string;
  shortDescription?: string | null;
  thumbnail: Img | null;
  category?: { slug: string; name: string } | null;
  defaultVariant?: { id: string; sku: string } | null;
  price: Money & { visibility: "show" | "on-request"; min?: number | null; max?: number | null; marketPrice?: number | null };
  variantCount?: number;
};

type Facet = { count: number };
export type ProductFacets = {
  categories: { slug: string; name: string; children: ({ slug: string; name: string } & Facet)[] }[];
  origin: ({ code: string; name: string } & Facet)[];
  farming: ({ value: "organic" | "conventional" } & Facet)[];
  volume: ({ value: string } & Facet)[];
  certifications: ({ slug: string; name: string } & Facet)[];
};

/** GET /public/products */
export type ProductList = {
  language?: PublicLanguage;
  items: ProductCard[];
  facets: ProductFacets;
  pagination: { page: number; limit: number; total: number; pages: number };
};

export type ProductVariant = {
  id: string;
  sku: string;
  /** { attributeSlug: valueSlug } */
  attributes: Record<string, string>;
  marketPrice?: number | null;
  sellingPrice?: number | null;
  dimensions: { length: number; width: number; height: number; unit: string } | null;
  weight: { value: number; unit: string } | null;
  image: Img | null;
  gallery: Img[];
};

/** GET /public/products/:slug */
export type ProductPageData = {
  id: string;
  slug: string;
  type: "simple" | "variable";
  language?: string;
  name: string;
  shortDescription?: string | null;
  description?: string | null;
  breadcrumb: { group: { slug: string; name: string } | null; category: { slug: string; name: string } | null };
  categories: { slug: string; name: string }[];
  certifications: { slug: string; name: string; logo: Img | null }[];
  origin: { code: string; name: string }[];
  farming: "organic" | "conventional";
  volumeMt: { min: number; max: number | null } | null;
  moq: { value: number; unit: string } | null;
  details: { label: string; text: string }[];
  thumbnail: Img | null;
  gallery: Img[];
  files: { label: string; url: string }[];
  currency: string;
  priceUnit: string;
  priceVisibility: "show" | "on-request";
  /** One select per attribute; values limited to what is on sale. Empty for a simple product. */
  attributes: { slug: string; name: string; values: { slug: string; label: string }[] }[];
  defaultVariantId: string | null;
  variants: ProductVariant[];
  seo: { title?: string | null; description?: string | null } | null;
  /** Up to 4 cards from the same category (not in the admin preview). */
  related?: ProductCard[];
};

/* ------------------------------------------------------------------ */
/* Filters ⇄ URL                                                       */
/* ------------------------------------------------------------------ */

export type CatalogFilters = {
  q: string;
  category: string[];
  origin: string[];
  farming: "" | "organic" | "conventional";
  volume: string;
  certification: string[];
  page: number;
};

export const NO_FILTERS: CatalogFilters = { q: "", category: [], origin: [], farming: "", volume: "", certification: [], page: 1 };
export const PAGE_SIZE = 12;

/** The fixed volume ranges (metric tonnes) and the label of each in the CMS catalog section. */
export const VOLUMES = [
  ["0-10", "upTo10"],
  ["10-50", "from10To50"],
  ["50-100", "from50To100"],
  ["100-500", "from100To500"],
  ["500-", "over500"],
] as const;

const list = (v: string | null) => (v ? v.split(",").map((s) => s.trim()).filter(Boolean).slice(0, 20) : []);

/** Filters from the page URL (?q=&category=a,b&origin=IR,ES&farming=&volume=&certification=&page=). */
export function filtersFromSearch(search: string): CatalogFilters {
  const p = new URLSearchParams(search);
  const farming = p.get("farming");
  const page = Number(p.get("page"));
  return {
    q: (p.get("q") ?? "").slice(0, 80),
    category: list(p.get("category")),
    origin: list(p.get("origin")).map((c) => c.toUpperCase()),
    farming: farming === "organic" || farming === "conventional" ? farming : "",
    volume: VOLUMES.some(([v]) => v === p.get("volume")) ? p.get("volume")! : "",
    certification: list(p.get("certification")),
    page: Number.isInteger(page) && page > 1 ? page : 1,
  };
}

/**
 * Query string for both the page URL and the API (same parameter names). Search needs
 * 2+ characters, so a single character is left out.
 */
export function productQuery(f: CatalogFilters): string {
  const p = new URLSearchParams();
  const q = f.q.trim();
  if (q.length >= 2) p.set("q", q);
  if (f.category.length) p.set("category", f.category.join(","));
  if (f.origin.length) p.set("origin", f.origin.join(","));
  if (f.farming) p.set("farming", f.farming);
  if (f.volume) p.set("volume", f.volume);
  if (f.certification.length) p.set("certification", f.certification.join(","));
  if (f.page > 1) p.set("page", String(f.page));
  return p.toString();
}

export const hasFilters = (f: CatalogFilters) => productQuery({ ...f, page: 1 }) !== "";

/* ------------------------------------------------------------------ */
/* Display                                                             */
/* ------------------------------------------------------------------ */

const UNIT_LABEL: Record<string, string> = { kg: "kg", mt: "MT", pack: "pack", unit: "unit" };
export const unitLabel = (u: string) => UNIT_LABEL[u] ?? u;

/** Integer cents → "€480.00" in the visitor's locale. */
export function formatMoney(cents: number, currency: string, locale = "en"): string {
  try {
    return new Intl.NumberFormat(locale, { style: "currency", currency }).format(cents / 100);
  } catch {
    return `${(cents / 100).toFixed(2)} ${currency}`;
  }
}

/** Card price: one price when min = max, otherwise "From min"; null for on-request (show "Request a quote"). */
export function cardPrice(p: ProductCard["price"], locale = "en"): { text: string; market: string | null } | null {
  if (p.visibility === "on-request" || p.min == null) return null;
  const unit = ` / ${unitLabel(p.unit)}`;
  const text = p.max != null && p.max !== p.min ? `From ${formatMoney(p.min, p.currency, locale)}${unit}` : `${formatMoney(p.min, p.currency, locale)}${unit}`;
  const market = p.marketPrice != null && p.marketPrice > p.min ? formatMoney(p.marketPrice, p.currency, locale) : null;
  return { text, market };
}

/** "10–500 MT" ("500+ MT" without a maximum). */
export function volumeText(v: ProductPageData["volumeMt"]): string | null {
  if (!v) return null;
  return v.max == null ? `${v.min}+ MT` : `${v.min}–${v.max} MT`;
}

export const dimensionsText = (d: ProductVariant["dimensions"]) => (d ? `${d.length} × ${d.width} × ${d.height} ${d.unit}` : null);
export const weightText = (w: ProductVariant["weight"]) => (w ? `${w.value} ${w.unit}` : null);

/** "Iran & Spain", "Iran, Spain & India". */
export function joinNames(names: string[]): string {
  if (names.length <= 1) return names[0] ?? "";
  return `${names.slice(0, -1).join(", ")} & ${names[names.length - 1]}`;
}

/** The variant whose attributes match every picked value, if any. */
export function findVariant(variants: ProductVariant[], picked: Record<string, string>): ProductVariant | undefined {
  return variants.find((v) => Object.entries(picked).every(([a, val]) => v.attributes[a] === val));
}

/**
 * Whether choosing `value` for attribute `attr` (keeping the other picks) leads to a
 * variant on sale. Values that can't complete a combination are greyed out.
 */
export function isPossible(variants: ProductVariant[], picked: Record<string, string>, attr: string, value: string): boolean {
  const next = { ...picked, [attr]: value };
  return variants.some((v) => Object.entries(next).every(([a, val]) => v.attributes[a] === val));
}

/** Contact link used as "Request a quote" until the leads module exists. */
export const quoteHref = (slug: string, sku?: string | null) => `/contact?product=${encodeURIComponent(slug)}${sku ? `&sku=${encodeURIComponent(sku)}` : ""}`;

export const productHref = (slug: string) => `/products/${slug}`;
