/** Per-café branding — synced with API CafeThemeDto / Core Branding.CafeTheme */

import { normalizeMenuTexture } from "@/lib/qr-menu-texture";

export type CafeThemeCustomColors = {
  primary?: string | null;
  secondary?: string | null;
  accent?: string | null;
  background?: string | null;
  surface?: string | null;
  text?: string | null;
  textMuted?: string | null;
  destructive?: string | null;
  success?: string | null;
};

export type CafeTheme = {
  paletteId: string;
  panelStyle: string;
  menuStyle: string;
  menuTexture: string;
  density: string;
  radius: string;
  custom?: CafeThemeCustomColors | null;
};

export type CafeThemePalette = {
  id: string;
  primary: string;
  primaryForeground: string;
  secondary: string;
  accent: string;
  background: string;
  surface: string;
  text: string;
  textMuted: string;
  destructive: string;
  success: string;
};

export const DEFAULT_CAFE_THEME: CafeTheme = {
  paletteId: "meezi-green",
  panelStyle: "modern",
  menuStyle: "cards",
  menuTexture: "none",
  density: "comfortable",
  radius: "md",
  custom: null,
};

export const CAFE_THEME_PALETTES: CafeThemePalette[] = [
  {
    id: "meezi-green",
    primary: "#0F6E56",
    primaryForeground: "#FFFFFF",
    secondary: "#E1F5EE",
    accent: "#BA7517",
    background: "#F5F5F4",
    surface: "#FFFFFF",
    text: "#1C1917",
    textMuted: "#78716C",
    destructive: "#A32D2D",
    success: "#0F6E56",
  },
  {
    id: "ocean-blue",
    primary: "#0C447C",
    primaryForeground: "#FFFFFF",
    secondary: "#E0F0FA",
    accent: "#0891B2",
    background: "#F0F9FF",
    surface: "#FFFFFF",
    text: "#0F172A",
    textMuted: "#64748B",
    destructive: "#B91C1C",
    success: "#059669",
  },
  {
    id: "royal-purple",
    primary: "#5B21B6",
    primaryForeground: "#FFFFFF",
    secondary: "#EDE9FE",
    accent: "#A855F7",
    background: "#FAF5FF",
    surface: "#FFFFFF",
    text: "#1E1B4B",
    textMuted: "#6B7280",
    destructive: "#DC2626",
    success: "#7C3AED",
  },
  {
    id: "sunset-orange",
    primary: "#C2410C",
    primaryForeground: "#FFFFFF",
    secondary: "#FFEDD5",
    accent: "#EA580C",
    background: "#FFF7ED",
    surface: "#FFFFFF",
    text: "#431407",
    textMuted: "#9A3412",
    destructive: "#991B1B",
    success: "#15803D",
  },
  {
    id: "rose-blush",
    primary: "#BE123C",
    primaryForeground: "#FFFFFF",
    secondary: "#FFE4E6",
    accent: "#DB2777",
    background: "#FFF1F2",
    surface: "#FFFFFF",
    text: "#4C0519",
    textMuted: "#9F1239",
    destructive: "#9F1239",
    success: "#059669",
  },
  {
    id: "charcoal-gold",
    primary: "#292524",
    primaryForeground: "#FEF3C7",
    secondary: "#E7E5E4",
    accent: "#CA8A04",
    background: "#F5F5F4",
    surface: "#FFFFFF",
    text: "#1C1917",
    textMuted: "#57534E",
    destructive: "#B91C1C",
    success: "#15803D",
  },
  {
    id: "espresso",
    primary: "#44403C",
    primaryForeground: "#FAFAF9",
    secondary: "#E7E5E4",
    accent: "#92400E",
    background: "#FAF8F5",
    surface: "#FFFFFF",
    text: "#292524",
    textMuted: "#78716C",
    destructive: "#991B1B",
    success: "#166534",
  },
  {
    id: "forest",
    primary: "#166534",
    primaryForeground: "#FFFFFF",
    secondary: "#DCFCE7",
    accent: "#65A30D",
    background: "#F0FDF4",
    surface: "#FFFFFF",
    text: "#14532D",
    textMuted: "#4B5563",
    destructive: "#DC2626",
    success: "#15803D",
  },
  {
    id: "midnight",
    primary: "#1E3A5F",
    primaryForeground: "#F8FAFC",
    secondary: "#E2E8F0",
    accent: "#38BDF8",
    background: "#F1F5F9",
    surface: "#FFFFFF",
    text: "#0F172A",
    textMuted: "#64748B",
    destructive: "#EF4444",
    success: "#22C55E",
  },
  {
    id: "coral",
    primary: "#E11D48",
    primaryForeground: "#FFFFFF",
    secondary: "#FFE4E6",
    accent: "#FB7185",
    background: "#FFF1F2",
    surface: "#FFFFFF",
    text: "#881337",
    textMuted: "#9F1239",
    destructive: "#B91C1C",
    success: "#059669",
  },
  {
    id: "gold-luxury",
    primary: "#854D0E",
    primaryForeground: "#FFFBEB",
    secondary: "#FEF3C7",
    accent: "#D97706",
    background: "#FFFBEB",
    surface: "#FFFFFF",
    text: "#422006",
    textMuted: "#78716C",
    destructive: "#991B1B",
    success: "#166534",
  },
  {
    id: "mint-fresh",
    primary: "#0D9488",
    primaryForeground: "#FFFFFF",
    secondary: "#CCFBF1",
    accent: "#2DD4BF",
    background: "#F0FDFA",
    surface: "#FFFFFF",
    text: "#134E4A",
    textMuted: "#5EEAD4",
    destructive: "#DC2626",
    success: "#0D9488",
  },
  {
    id: "wine-bar",
    primary: "#7F1D1D",
    primaryForeground: "#FEF2F2",
    secondary: "#FEE2E2",
    accent: "#B45309",
    background: "#FEF2F2",
    surface: "#FFFFFF",
    text: "#450A0A",
    textMuted: "#991B1B",
    destructive: "#991B1B",
    success: "#166534",
  },
  {
    id: "slate-modern",
    primary: "#334155",
    primaryForeground: "#F8FAFC",
    secondary: "#F1F5F9",
    accent: "#0EA5E9",
    background: "#F8FAFC",
    surface: "#FFFFFF",
    text: "#0F172A",
    textMuted: "#64748B",
    destructive: "#EF4444",
    success: "#10B981",
  },
  {
    id: "cherry",
    primary: "#9F1239",
    primaryForeground: "#FFFFFF",
    secondary: "#FECDD3",
    accent: "#F43F5E",
    background: "#FFF1F2",
    surface: "#FFFFFF",
    text: "#4C0519",
    textMuted: "#BE123C",
    destructive: "#881337",
    success: "#059669",
  },
  {
    id: "teal-wave",
    primary: "#0F766E",
    primaryForeground: "#FFFFFF",
    secondary: "#CCFBF1",
    accent: "#14B8A6",
    background: "#F0FDFA",
    surface: "#FFFFFF",
    text: "#134E4A",
    textMuted: "#5F6B6B",
    destructive: "#DC2626",
    success: "#0F766E",
  },
  {
    id: "sand-cafe",
    primary: "#A16207",
    primaryForeground: "#FFFBEB",
    secondary: "#FEF3C7",
    accent: "#D97706",
    background: "#FAFAF9",
    surface: "#FFFFFF",
    text: "#44403C",
    textMuted: "#A8A29E",
    destructive: "#B91C1C",
    success: "#15803D",
  },
];

export const CAFE_PANEL_STYLES = [
  "flat",
  "modern",
  "glass",
  "minimal",
  "bold",
  "soft",
  "elevated",
  "outline",
] as const;

export const CAFE_MENU_STYLES = [
  "cards",
  "compact",
  "grid",
  "list",
  "magazine",
  "classic",
] as const;

export {
  CAFE_MENU_TEXTURES,
  normalizeMenuTexture,
  qrMenuTextureShellProps,
  type CafeMenuTexture,
} from "./qr-menu-texture";

export const CAFE_THEME_DENSITIES = ["compact", "comfortable", "spacious"] as const;
export const CAFE_THEME_RADIUS = ["none", "sm", "md", "lg", "full"] as const;

const paletteById = new Map(CAFE_THEME_PALETTES.map((p) => [p.id, p]));

export function getThemePalette(id: string): CafeThemePalette {
  return paletteById.get(id) ?? CAFE_THEME_PALETTES[0];
}

export function resolveThemeColors(theme: CafeTheme): CafeThemePalette {
  const base = getThemePalette(theme.paletteId);
  const c = theme.custom;
  if (!c) return base;
  return {
    ...base,
    primary: c.primary ?? base.primary,
    secondary: c.secondary ?? base.secondary,
    accent: c.accent ?? base.accent,
    background: c.background ?? base.background,
    surface: c.surface ?? base.surface,
    text: c.text ?? base.text,
    textMuted: c.textMuted ?? base.textMuted,
    destructive: c.destructive ?? base.destructive,
    success: c.success ?? base.success,
  };
}

function hexToHslChannels(hex: string): string {
  const raw = hex.replace("#", "");
  const r = parseInt(raw.slice(0, 2), 16) / 255;
  const g = parseInt(raw.slice(2, 4), 16) / 255;
  const b = parseInt(raw.slice(4, 6), 16) / 255;
  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  let h = 0;
  let s = 0;
  const l = (max + min) / 2;
  if (max !== min) {
    const d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    switch (max) {
      case r:
        h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
        break;
      case g:
        h = ((b - r) / d + 2) / 6;
        break;
      default:
        h = ((r - g) / d + 4) / 6;
    }
  }
  return `${Math.round(h * 360)} ${Math.round(s * 100)}% ${Math.round(l * 100)}%`;
}

const RADIUS_MAP: Record<string, string> = {
  none: "0px",
  sm: "0.375rem",
  md: "0.75rem",
  lg: "1rem",
  full: "1.25rem",
};

const OVERRIDE_STYLE_ID = "meezi-cafe-theme-overrides";

function injectBrandOverrides(primaryHex: string, secondaryHex: string): void {
  let el = document.getElementById(OVERRIDE_STYLE_ID) as HTMLStyleElement | null;
  if (!el) {
    el = document.createElement("style");
    el.id = OVERRIDE_STYLE_ID;
    document.head.appendChild(el);
  }
  el.textContent = `
    html[data-cafe-theme] .bg-\\[\\#0F6E56\\],
    html[data-cafe-theme] .hover\\:bg-\\[\\#0c5a46\\]:hover,
    html[data-cafe-theme] .bg-\\[\\#0c5a46\\] {
      background-color: ${primaryHex} !important;
    }
    html[data-cafe-theme] .text-\\[\\#0F6E56\\],
    html[data-cafe-theme] .hover\\:text-\\[\\#0F6E56\\]:hover {
      color: ${primaryHex} !important;
    }
    html[data-cafe-theme] .border-\\[\\#0F6E56\\],
    html[data-cafe-theme] .hover\\:border-\\[\\#0F6E56\\]\\/40:hover,
    html[data-cafe-theme] .ring-\\[\\#0F6E56\\]\\/30 {
      border-color: color-mix(in srgb, ${primaryHex} 40%, transparent) !important;
    }
    html[data-cafe-theme] .bg-\\[\\#E1F5EE\\] {
      background-color: ${secondaryHex} !important;
    }
  `;
}

export function applyCafeTheme(theme: CafeTheme): void {
  if (typeof document === "undefined") return;
  const colors = resolveThemeColors(theme);
  const root = document.documentElement;

  root.dataset.cafeTheme = "true";
  root.dataset.panelStyle = theme.panelStyle;
  root.dataset.menuStyle = theme.menuStyle;
  root.dataset.density = theme.density;

  const set = (name: string, hex: string) => root.style.setProperty(name, hexToHslChannels(hex));

  set("--primary", colors.primary);
  set("--primary-foreground", colors.primaryForeground);
  set("--secondary", colors.secondary);
  set("--secondary-foreground", colors.text);
  set("--accent", colors.secondary);
  set("--accent-foreground", colors.primary);
  set("--background", colors.background);
  set("--foreground", colors.text);
  set("--card", colors.surface);
  set("--card-foreground", colors.text);
  set("--muted", colors.background);
  set("--muted-foreground", colors.textMuted);
  set("--destructive", colors.destructive);
  set("--ring", colors.primary);
  set("--meezi-green", colors.primary);
  set("--meezi-green-tint", colors.secondary);
  set("--meezi-amber", colors.accent);
  set("--meezi-danger", colors.destructive);

  root.style.setProperty("--radius", RADIUS_MAP[theme.radius] ?? RADIUS_MAP.md);
  root.style.setProperty("--brand-primary-hex", colors.primary);
  root.style.setProperty("--brand-secondary-hex", colors.secondary);
  root.style.setProperty("--brand-accent-hex", colors.accent);

  injectBrandOverrides(colors.primary, colors.secondary);
}

export function normalizeCafeTheme(input?: Partial<CafeTheme> | null): CafeTheme {
  if (!input) return { ...DEFAULT_CAFE_THEME };
  return {
    paletteId: paletteById.has(input.paletteId ?? "") ? input.paletteId! : DEFAULT_CAFE_THEME.paletteId,
    panelStyle: CAFE_PANEL_STYLES.includes(input.panelStyle as (typeof CAFE_PANEL_STYLES)[number])
      ? input.panelStyle!
      : DEFAULT_CAFE_THEME.panelStyle,
    menuStyle: CAFE_MENU_STYLES.includes(input.menuStyle as (typeof CAFE_MENU_STYLES)[number])
      ? input.menuStyle!
      : DEFAULT_CAFE_THEME.menuStyle,
    menuTexture: normalizeMenuTexture(input.menuTexture ?? DEFAULT_CAFE_THEME.menuTexture),
    density: CAFE_THEME_DENSITIES.includes(input.density as (typeof CAFE_THEME_DENSITIES)[number])
      ? input.density!
      : DEFAULT_CAFE_THEME.density,
    radius: CAFE_THEME_RADIUS.includes(input.radius as (typeof CAFE_THEME_RADIUS)[number])
      ? input.radius!
      : DEFAULT_CAFE_THEME.radius,
    custom: input.custom ?? null,
  };
}
