import { apiUrl, adminApiUrl } from "@/lib/apiUrl";

export type SiteSettings = {
  header_layout: string;
  footer_layout: string;
};

export const SITE_SETTINGS_QUERY_KEY = ["site-settings"] as const;

/** Bumped when site settings are saved so all tabs/views refetch. */
export const SITE_SETTINGS_VERSION_KEY = "orion-site-settings-version";

export const SITE_SETTINGS_UPDATED_EVENT = "orion-site-settings-updated";

const DEFAULT_SETTINGS: SiteSettings = {
  header_layout: "default",
  footer_layout: "default",
};

export function normalizeSiteSettings(data: Partial<SiteSettings> | null | undefined): SiteSettings {
  return {
    header_layout: data?.header_layout?.trim() || DEFAULT_SETTINGS.header_layout,
    footer_layout: data?.footer_layout?.trim() || DEFAULT_SETTINGS.footer_layout,
  };
}

/** Public site settings fetch (authenticated site session). */
export async function fetchSiteSettings(): Promise<SiteSettings> {
  const res = await fetch(apiUrl("/api/site-settings"), { cache: "no-store" });
  if (!res.ok) throw new Error("Failed to load site settings");
  const data = (await res.json()) as Partial<SiteSettings>;
  return normalizeSiteSettings(data);
}

/** Admin dashboard fetch (Passport token). */
export async function fetchSiteSettingsAdmin(): Promise<SiteSettings> {
  const res = await fetch(adminApiUrl("/api/site-settings"), { cache: "no-store" });
  if (!res.ok) throw new Error("Failed to load site settings");
  const data = (await res.json()) as Partial<SiteSettings>;
  return normalizeSiteSettings(data);
}

/** Notify every open tab/view to reload site settings. */
export function notifySiteSettingsUpdated(): void {
  if (typeof window === "undefined") return;
  try {
    localStorage.setItem(SITE_SETTINGS_VERSION_KEY, String(Date.now()));
  } catch {
    // ignore storage errors
  }
  window.dispatchEvent(new Event(SITE_SETTINGS_UPDATED_EVENT));
}

export function readSiteSettingsVersion(): string | null {
  if (typeof window === "undefined") return null;
  try {
    return localStorage.getItem(SITE_SETTINGS_VERSION_KEY);
  } catch {
    return null;
  }
}
