// Home layout preference — "cockpit" (the bento home, default) or "classic"
// (the original HomeDashboard). Stored in localStorage; a custom event keeps
// every listener (the <Home/> wrapper, the TopBar toggle) in sync within this
// tab, and the native storage event syncs other open tabs.

export type HomeLayout = "cockpit" | "classic";

export const HOME_LAYOUT_KEY = "mm-home-layout";
export const DEFAULT_HOME_LAYOUT: HomeLayout = "cockpit";

const CHANGE_EVENT = "mm-home-layout-change";

// In-memory fallback so the toggle still works this session when localStorage
// is unavailable (private mode).
let memoryLayout: HomeLayout | null = null;

export function readHomeLayout(): HomeLayout {
  try {
    const saved = localStorage.getItem(HOME_LAYOUT_KEY);
    if (saved === "classic" || saved === "cockpit") return saved;
  } catch { /* private mode: fall through */ }
  return memoryLayout ?? DEFAULT_HOME_LAYOUT;
}

export function setHomeLayout(layout: HomeLayout): void {
  memoryLayout = layout;
  try {
    localStorage.setItem(HOME_LAYOUT_KEY, layout);
  } catch { /* private mode: memory fallback carries the session */ }
  window.dispatchEvent(new Event(CHANGE_EVENT));
}

export function subscribeHomeLayout(onChange: () => void): () => void {
  window.addEventListener(CHANGE_EVENT, onChange);
  window.addEventListener("storage", onChange);
  return () => {
    window.removeEventListener(CHANGE_EVENT, onChange);
    window.removeEventListener("storage", onChange);
  };
}
