// Small client-side cache of the merchant's branding so the correct name, logo
// and colours render on the very first paint after a refresh — no flash of the
// default "Partner Nook" / navy before the API responds.

export type Brand = {
  logoUrl: string | null;
  name: string;
  brandColor?: string | null;
  brandSecondaryColor?: string | null;
};

const KEY = "mn_brand";
// Our own brand — the fallback whenever a merchant hasn't set theirs, and what
// the marketing site always wears (there is no merchant context there).
export const DEFAULT_BRAND: Brand = {
  logoUrl: "/trackopia-icon.svg",
  name: "Trackopia",
  brandColor: "#1a3c6e",
  brandSecondaryColor: "#E0A82E",
};

export function readBrand(): Brand {
  if (typeof window === "undefined") return DEFAULT_BRAND;
  try {
    const cached = JSON.parse(localStorage.getItem(KEY) || "null");
    return cached ? { ...DEFAULT_BRAND, ...cached } : DEFAULT_BRAND;
  } catch {
    return DEFAULT_BRAND;
  }
}

export function writeBrand(b: Brand) {
  if (typeof window === "undefined") return;
  try {
    localStorage.setItem(KEY, JSON.stringify(b));
  } catch {
    /* ignore quota / privacy-mode errors */
  }
}

export function applyBrandVars(b: Brand) {
  if (typeof document === "undefined") return;
  const root = document.documentElement;
  if (b.brandColor) {
    root.style.setProperty("--brand", b.brandColor);
    // --brand-50 is a *tint* used behind icons and selected rows, so derive it
    // from the brand colour. (It used to be set to the secondary colour, which
    // painted every tile in a solid accent.)
    root.style.setProperty("--brand-50", `color-mix(in srgb, ${b.brandColor} 12%, white)`);
  }
  if (b.brandSecondaryColor) root.style.setProperty("--brand-accent", b.brandSecondaryColor);
}

// Runs before paint (injected in the root layout) to set colours from cache.
export const BRAND_PRELOAD = `try{var b=JSON.parse(localStorage.getItem('${KEY}')||'null');if(b){var r=document.documentElement;if(b.brandColor){r.style.setProperty('--brand',b.brandColor);r.style.setProperty('--brand-50','color-mix(in srgb, '+b.brandColor+' 12%, white)');}if(b.brandSecondaryColor)r.style.setProperty('--brand-accent',b.brandSecondaryColor);}}catch(e){}`;
