import { createStore } from "./createStore";

const STORAGE_KEY = "dailymeals.layout";

export type LayoutId = "sidebar" | "topnav" | "compact" | "wide";

const VALID: LayoutId[] = ["sidebar", "topnav", "compact", "wide"];

function loadLayout(): LayoutId {
  const stored = localStorage.getItem(STORAGE_KEY);
  const id = VALID.includes(stored as LayoutId) ? (stored as LayoutId) : "sidebar";
  document.documentElement.dataset.layout = id;
  return id;
}

interface LayoutState {
  layout: LayoutId;
}

export const layoutStore = createStore<LayoutState>({ layout: loadLayout() });

export function setLayout(id: LayoutId): void {
  layoutStore.setState({ layout: id });
  localStorage.setItem(STORAGE_KEY, id);
  document.documentElement.dataset.layout = id;
}

export function useLayout() {
  const layout = layoutStore.useStore((s) => s.layout);
  return { layout, setLayout };
}
