import {
  layoutPreference,
  parseStoredDashboardLayout,
  type DashboardLayout,
  type StoredDashboardLayout,
} from "./dashboard-layout";

/**
 * Host-owned preference store. WordPress saves this in user meta.
 * The record is the compact layout preference, with no analytics values.
 */
export type DashboardLayoutStore = {
  load: () => Promise<StoredDashboardLayout | null>;
  save: (layout: StoredDashboardLayout) => Promise<void>;
  reset: () => Promise<void>;
};

/** One dashboard block for one authorized viewer on one site. Empty when the scope is incomplete. */
export function dashboardLayoutKey(site: string, userId: string, instance: string): string {
  const cleanSite = site.toLowerCase().replace(/[^a-z0-9.-]/g, "").slice(0, 80);
  const cleanUser = /^\d+$/.test(userId) ? userId : "";
  const cleanInstance = /^[A-Za-z0-9_-]{6,40}$/.test(instance) ? instance : "";
  if (!cleanSite || !cleanUser || cleanUser === "0" || !cleanInstance) return "";
  return `causewise-dashboard-layout:${cleanSite}:${cleanUser}:${cleanInstance}`;
}

export function readDashboardLayout(storage: Storage | null | undefined, key: string): StoredDashboardLayout | null {
  if (!storage || !key) return null;
  try {
    const raw = storage.getItem(key);
    if (!raw) return null;
    return parseStoredDashboardLayout(raw);
  } catch {
    return null;
  }
}

export function writeDashboardLayout(storage: Storage | null | undefined, key: string, layout: DashboardLayout): boolean {
  if (!storage || !key) return false;
  try {
    storage.setItem(key, JSON.stringify(layoutPreference(layout)));
    return true;
  } catch {
    return false;
  }
}

export function clearDashboardLayout(storage: Storage | null | undefined, key: string): void {
  if (!storage || !key) return;
  try {
    storage.removeItem(key);
  } catch {
    /* The layout stays on screen for this visit. */
  }
}
