/**
 * Patrón de estilo de los Goal Fighters (chibi 2.5D).
 *
 * Un luchador se describe con un `FighterLook`: datos planos, serializables a
 * JSON, sin funciones ni objetos de canvas. El renderizador (`chibi.ts`) solo
 * lee este objeto, así que un futuro EDITOR DE PERSONAJES puede:
 *   1. listar las opciones de cada pieza con `LOOK_OPTIONS`,
 *   2. construir/modificar un look y validarlo con `sanitizeLook`,
 *   3. guardarlo (localStorage / servidor) tal cual, y
 *   4. dibujarlo con `drawLookPreview` sin tocar el motor.
 *
 * Las 8 figuras del roster salen de `characters.ts` mediante `lookFromCharacter`,
 * de modo que el roster actual y los personajes del editor usan exactamente el
 * mismo camino de dibujo.
 */
import type {
  Accessory,
  BrowStyle,
  Character,
  CharacterId,
  EyeStyle,
  HeadShape,
  MouthStyle,
} from "./characters.ts";
import { CHARACTERS, getCharacter } from "./characters.ts";

/** Complexión: cambia ancho de torso y grosor de brazos y piernas. */
export type Build = "slim" | "regular" | "stocky";
/** Estampado de la camiseta. */
export type KitPattern = "plain" | "stripes" | "hoops" | "sash" | "split" | "chevron";
/** Peinado base (va debajo del accesorio). */
export type HairStyle = "none" | "short" | "spiky" | "curly" | "bob" | "swoop";

export type FighterLook = {
  build: Build;
  /** Tamaño relativo de la cabeza (chibi): 0.9 – 1.15. */
  headScale: number;
  head: HeadShape;
  skin: string;
  hair: { style: HairStyle; color: string };
  face: { eyes: EyeStyle; brows: BrowStyle; mouth: MouthStyle; blush: boolean };
  accessory: Accessory;
  kit: {
    pattern: KitPattern;
    /** Color principal de la camiseta. */
    primary: string;
    /** Color del estampado. */
    secondary: string;
    shorts: string;
    socks: string;
    /** Dorsal visible en el pecho (0 = sin número). */
    number: number;
  };
  boots: { color: string; sole: string };
  /** Color de acento (cargas, destellos, detalles). */
  accent: string;
};

/** Opciones de cada pieza: la base de un editor de personajes. */
export const LOOK_OPTIONS = {
  build: ["slim", "regular", "stocky"] as const satisfies readonly Build[],
  head: ["round", "bean", "wide", "pear", "square", "oval", "dome", "diamond"] as const satisfies readonly HeadShape[],
  hair: ["none", "short", "spiky", "curly", "bob", "swoop"] as const satisfies readonly HairStyle[],
  eyes: ["wide", "happy", "sleepy", "sharp", "dot", "wink", "round"] as const satisfies readonly EyeStyle[],
  brows: ["thick", "arched", "angry", "flat", "thin", "worried"] as const satisfies readonly BrowStyle[],
  mouth: ["grin", "smile", "open", "tongue", "grit", "smirk", "o", "wide", "subtle"] as const satisfies readonly MouthStyle[],
  accessory: [
    "mohawk",
    "beanie",
    "topknot",
    "catears",
    "helmet",
    "glasses",
    "visor",
    "headband",
  ] as const satisfies readonly Accessory[],
  pattern: ["plain", "stripes", "hoops", "sash", "split", "chevron"] as const satisfies readonly KitPattern[],
  /** Tonos de piel sugeridos para el selector del editor. */
  skin: ["#ffe0c8", "#f6c9a0", "#f0b47d", "#d58d63", "#a86a45", "#7a4a2f", "#9cd66d", "#b9a4ff"] as const,
} as const;

/** Parámetros de complexión que usa el renderizador. */
export const BUILD_SPEC: Record<Build, { torsoW: number; limb: number; shoulder: number }> = {
  slim: { torsoW: 11, limb: 4.2, shoulder: 8.5 },
  regular: { torsoW: 12.5, limb: 4.8, shoulder: 9.5 },
  stocky: { torsoW: 14.5, limb: 5.8, shoulder: 11 },
};

/** Detalles del patrón por figura del roster (lo que `Character` no trae). */
const ROSTER_EXTRAS: Record<
  CharacterId,
  { build: Build; hair: HairStyle; pattern: KitPattern; number: number; blush: boolean; headScale: number }
> = {
  tizo: { build: "regular", hair: "none", pattern: "sash", number: 9, blush: false, headScale: 1 },
  lumi: { build: "slim", hair: "bob", pattern: "hoops", number: 7, blush: true, headScale: 1.04 },
  mango: { build: "stocky", hair: "short", pattern: "split", number: 4, blush: false, headScale: 0.98 },
  kiwi: { build: "slim", hair: "none", pattern: "chevron", number: 11, blush: true, headScale: 0.94 },
  coco: { build: "stocky", hair: "none", pattern: "stripes", number: 5, blush: false, headScale: 0.97 },
  nube: { build: "slim", hair: "curly", pattern: "plain", number: 3, blush: true, headScale: 1.05 },
  bombo: { build: "stocky", hair: "none", pattern: "hoops", number: 1, blush: false, headScale: 1 },
  pico: { build: "regular", hair: "swoop", pattern: "stripes", number: 10, blush: false, headScale: 1 },
};

/** Convierte una figura del roster al patrón de estilo. */
export function lookFromCharacter(ch: Character): FighterLook {
  const extra = ROSTER_EXTRAS[ch.id] ?? ROSTER_EXTRAS.tizo;
  return {
    build: extra.build,
    headScale: extra.headScale,
    head: ch.head,
    skin: ch.skin,
    hair: { style: extra.hair, color: ch.hair },
    face: { eyes: ch.eyes, brows: ch.brows, mouth: ch.mouth, blush: extra.blush },
    accessory: ch.accessory,
    kit: {
      pattern: extra.pattern,
      primary: ch.shirt,
      secondary: ch.shirtLight,
      shorts: ch.shorts,
      socks: ch.accent,
      number: extra.number,
    },
    boots: { color: ch.boots, sole: ch.soles },
    accent: ch.accent,
  };
}

const HEX = /^#[0-9a-f]{6}$/i;

function pick<T extends string>(value: unknown, options: readonly T[], fallback: T): T {
  return typeof value === "string" && (options as readonly string[]).includes(value) ? (value as T) : fallback;
}

function color(value: unknown, fallback: string): string {
  return typeof value === "string" && HEX.test(value) ? value.toLowerCase() : fallback;
}

/**
 * Valida un look que viene de fuera (editor, localStorage, red): cualquier
 * campo inválido cae al valor de `base`. Nunca lanza.
 */
export function sanitizeLook(input: unknown, base: FighterLook = lookFromCharacter(CHARACTERS[0])): FighterLook {
  const o = (input && typeof input === "object" ? input : {}) as Record<string, unknown>;
  const hair = (o.hair && typeof o.hair === "object" ? o.hair : {}) as Record<string, unknown>;
  const face = (o.face && typeof o.face === "object" ? o.face : {}) as Record<string, unknown>;
  const kit = (o.kit && typeof o.kit === "object" ? o.kit : {}) as Record<string, unknown>;
  const boots = (o.boots && typeof o.boots === "object" ? o.boots : {}) as Record<string, unknown>;
  const headScale = typeof o.headScale === "number" && Number.isFinite(o.headScale) ? o.headScale : base.headScale;
  const num = typeof kit.number === "number" && Number.isFinite(kit.number) ? Math.round(kit.number) : base.kit.number;
  return {
    build: pick(o.build, LOOK_OPTIONS.build, base.build),
    headScale: Math.max(0.9, Math.min(1.15, headScale)),
    head: pick(o.head, LOOK_OPTIONS.head, base.head),
    skin: color(o.skin, base.skin),
    hair: { style: pick(hair.style, LOOK_OPTIONS.hair, base.hair.style), color: color(hair.color, base.hair.color) },
    face: {
      eyes: pick(face.eyes, LOOK_OPTIONS.eyes, base.face.eyes),
      brows: pick(face.brows, LOOK_OPTIONS.brows, base.face.brows),
      mouth: pick(face.mouth, LOOK_OPTIONS.mouth, base.face.mouth),
      blush: typeof face.blush === "boolean" ? face.blush : base.face.blush,
    },
    accessory: pick(o.accessory, LOOK_OPTIONS.accessory, base.accessory),
    kit: {
      pattern: pick(kit.pattern, LOOK_OPTIONS.pattern, base.kit.pattern),
      primary: color(kit.primary, base.kit.primary),
      secondary: color(kit.secondary, base.kit.secondary),
      shorts: color(kit.shorts, base.kit.shorts),
      socks: color(kit.socks, base.kit.socks),
      number: Math.max(0, Math.min(99, num)),
    },
    boots: { color: color(boots.color, base.boots.color), sole: color(boots.sole, base.boots.sole) },
    accent: color(o.accent, base.accent),
  };
}

/* ------------------------------------------------------------------ */
/* Paleta derivada: sombras y luces del cel-shading, calculadas una vez. */
/* ------------------------------------------------------------------ */

/** Color de la tinta del sombreado: violeta oscuro, más vivo que el negro. */
const SHADE_INK = [42, 22, 52] as const;

function parseHex(hex: string): [number, number, number] {
  const h = HEX.test(hex) ? hex.slice(1) : "888888";
  return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];
}

function toHex(r: number, g: number, b: number): string {
  const c = (v: number) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, "0");
  return `#${c(r)}${c(g)}${c(b)}`;
}

/** Mezcla hacia la tinta de sombra (k 0..1). */
export function shadeHex(hex: string, k: number): string {
  const [r, g, b] = parseHex(hex);
  return toHex(r + (SHADE_INK[0] - r) * k, g + (SHADE_INK[1] - g) * k, b + (SHADE_INK[2] - b) * k);
}

/** Mezcla hacia blanco cálido (k 0..1). */
export function lightHex(hex: string, k: number): string {
  const [r, g, b] = parseHex(hex);
  return toHex(r + (255 - r) * k, g + (250 - g) * k, b + (236 - b) * k);
}

/** Look + todos los tonos que el render necesita, precalculados. */
export type LookPalette = {
  look: FighterLook;
  skin: string;
  skinShade: string;
  skinBack: string;
  skinLight: string;
  shirt: string;
  shirtShade: string;
  shirtBack: string;
  shirtLight: string;
  pattern: string;
  shorts: string;
  shortsShade: string;
  shortsBack: string;
  socks: string;
  socksBack: string;
  boot: string;
  bootShade: string;
  bootBack: string;
  bootLight: string;
  sole: string;
  hair: string;
  hairShade: string;
  hairLight: string;
  accent: string;
  blush: string;
  spec: (typeof BUILD_SPEC)[Build];
};

export function paletteOf(look: FighterLook): LookPalette {
  return {
    look,
    skin: look.skin,
    skinShade: shadeHex(look.skin, 0.3),
    skinBack: shadeHex(look.skin, 0.22),
    skinLight: lightHex(look.skin, 0.45),
    shirt: look.kit.primary,
    shirtShade: shadeHex(look.kit.primary, 0.32),
    shirtBack: shadeHex(look.kit.primary, 0.25),
    shirtLight: lightHex(look.kit.primary, 0.4),
    pattern: look.kit.secondary,
    shorts: look.kit.shorts,
    shortsShade: shadeHex(look.kit.shorts, 0.35),
    shortsBack: shadeHex(look.kit.shorts, 0.25),
    socks: look.kit.socks,
    socksBack: shadeHex(look.kit.socks, 0.25),
    boot: look.boots.color,
    bootShade: shadeHex(look.boots.color, 0.32),
    bootBack: shadeHex(look.boots.color, 0.24),
    bootLight: lightHex(look.boots.color, 0.6),
    sole: look.boots.sole,
    hair: look.hair.color,
    hairShade: shadeHex(look.hair.color, 0.35),
    hairLight: lightHex(look.hair.color, 0.35),
    accent: look.accent,
    blush: "rgba(255, 96, 110, 0.32)",
    spec: BUILD_SPEC[look.build],
  };
}

const paletteCache = new Map<CharacterId, LookPalette>();

/** Paleta de una figura del roster (cacheada: el render no recalcula colores). */
export function paletteForCharacter(id: CharacterId): LookPalette {
  let p = paletteCache.get(id);
  if (!p) {
    p = paletteOf(lookFromCharacter(getCharacter(id)));
    paletteCache.set(id, p);
  }
  return p;
}
