import { createStore } from "./createStore";
import { THEME_PROPOSALS, type AppearanceId, type ThemeProposal } from "@/theme/appearance.config";

const STORAGE_KEY = "dailymeals.appearance";

function loadProposal(): ThemeProposal {
  const stored = localStorage.getItem(STORAGE_KEY) as AppearanceId | null;
  const found = THEME_PROPOSALS.find((p) => p.id === stored);
  return found ?? THEME_PROPOSALS[0];
}

function applyProposal(proposal: ThemeProposal): void {
  document.documentElement.dataset.colorTheme = proposal.colorTheme;
  document.documentElement.dataset.iconStyle = proposal.iconStyle;
}

const initial = loadProposal();
applyProposal(initial);

interface AppearanceState {
  proposal: ThemeProposal;
}

export const appearanceStore = createStore<AppearanceState>({ proposal: initial });

export function setAppearance(id: AppearanceId): void {
  const next = THEME_PROPOSALS.find((p) => p.id === id) ?? THEME_PROPOSALS[0];
  appearanceStore.setState({ proposal: next });
  localStorage.setItem(STORAGE_KEY, id);
  applyProposal(next);
}

export function useAppearance() {
  const proposal = appearanceStore.useStore((s) => s.proposal);
  return {
    proposal,
    setAppearance,
    proposals: THEME_PROPOSALS,
    iconStyle: proposal.iconStyle,
    strokeWidth: proposal.iconStyle === "bold" ? 2.5 : 2,
    useEmoji: proposal.iconStyle === "emoji",
  };
}

export function initAppearance(): void {
  applyProposal(appearanceStore.getState().proposal);
}
