/**
 * BrandPack: marca conmutable en 1 click (presets + active).
 */
import fs from "fs";
import path from "path";

const REQUIRED = ["id", "name", "tagline", "primary", "accent", "bg", "fg", "logo"] as const;

export interface BrandPack {
  id: string;
  name: string;
  tagline: string;
  logo: string;
  favicon?: string;
  primary: string;
  accent: string;
  bg: string;
  fg: string;
  muted?: string;
  font_display?: string;
  font_body?: string;
  pwa_name?: string;
  theme_color?: string;
  legal_name?: string;
  domain_hint?: string;
}

function brandRoot(): string {
  return path.join(process.cwd(), "data", "brand");
}

function presetsDir(): string {
  const d = path.join(brandRoot(), "presets");
  if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true });
  return d;
}

function activePath(): string {
  return path.join(brandRoot(), "active.json");
}

function defaultPack(): BrandPack {
  return {
    id: "captajaus",
    name: "CaptaJaus",
    tagline: "Captación inteligente de inmuebles en Llíria y Valencia",
    logo: "/icons/icon-512.png",
    favicon: "/icons/favicon-32.png",
    primary: "#0b4f6c",
    accent: "#01baef",
    bg: "#f0f7fa",
    fg: "#0a1f2e",
    muted: "#5a7280",
    font_display: '"Segoe UI", system-ui, sans-serif',
    font_body: '"Segoe UI", system-ui, sans-serif',
    pwa_name: "CaptaJaus",
    theme_color: "#0b4f6c",
    legal_name: "CaptaJaus",
    domain_hint: "captajaus.local",
  };
}

export function listPresets(): BrandPack[] {
  const out: BrandPack[] = [];
  for (const file of fs.readdirSync(presetsDir()).filter((f) => f.endsWith(".json")).sort()) {
    try {
      const data = JSON.parse(fs.readFileSync(path.join(presetsDir(), file), "utf8")) as BrandPack;
      if (data?.id) out.push(data);
    } catch {
      /* skip corrupt preset */
    }
  }
  if (out.length === 0) {
    const pack = defaultPack();
    savePreset(pack);
    out.push(pack);
  }
  return out;
}

export function getPreset(presetId: string): BrandPack | null {
  const p = path.join(presetsDir(), `${presetId}.json`);
  if (!fs.existsSync(p)) return null;
  return JSON.parse(fs.readFileSync(p, "utf8")) as BrandPack;
}

export function savePreset(pack: BrandPack): BrandPack {
  const pid = String(pack.id || "").trim();
  if (!pid) throw new Error("preset id requerido");
  for (const k of REQUIRED) {
    if (!(k in pack)) throw new Error(`falta campo ${k}`);
  }
  const file = path.join(presetsDir(), `${pid}.json`);
  fs.writeFileSync(file, JSON.stringify(pack, null, 2), "utf8");
  return pack;
}

export function getActive(): BrandPack {
  const p = activePath();
  if (fs.existsSync(p)) {
    try {
      const data = JSON.parse(fs.readFileSync(p, "utf8")) as BrandPack;
      if (data?.id) return data;
    } catch {
      /* fall through */
    }
  }
  const pack = getPreset("captajaus") || defaultPack();
  if (!getPreset("captajaus")) savePreset(pack);
  setActive(String(pack.id));
  return pack;
}

export function setActive(presetId: string): BrandPack {
  const pack = getPreset(presetId);
  if (!pack) throw new Error(`preset ${presetId} no encontrado`);
  const root = brandRoot();
  if (!fs.existsSync(root)) fs.mkdirSync(root, { recursive: true });
  fs.writeFileSync(activePath(), JSON.stringify(pack, null, 2), "utf8");
  return pack;
}

export function cssVariables(pack?: BrandPack | null): string {
  const p = pack || getActive();
  return (
    ":root{" +
    `--brand-primary:${p.primary || "#0b4f6c"};` +
    `--brand-accent:${p.accent || "#01baef"};` +
    `--brand-bg:${p.bg || "#f0f7fa"};` +
    `--brand-fg:${p.fg || "#0a1f2e"};` +
    `--brand-muted:${p.muted || "#5a7280"};` +
    `--brand-font-display:${p.font_display || "system-ui"};` +
    `--brand-font-body:${p.font_body || "system-ui"};` +
    "}"
  );
}
