"use client";

import { useCallback, useEffect, useState } from "react";
import { DEFAULT_CATEGORIES, STORAGE_KEYS } from "@/lib/constants";
import type { MenuCategory } from "@/lib/types";

export function useSidebarOrder() {
  const [categories, setCategoriesState] = useState<MenuCategory[]>(DEFAULT_CATEGORIES);

  useEffect(() => {
    const stored = localStorage.getItem(STORAGE_KEYS.SIDEBAR_ORDER);
    if (stored) {
      try {
        const ids: string[] = JSON.parse(stored);
        const ordered = ids
          .map((id) => DEFAULT_CATEGORIES.find((c) => c.id === id))
          .filter((c): c is MenuCategory => c != null);
        // Append any new categories not in stored order
        const missing = DEFAULT_CATEGORIES.filter(
          (c) => !ids.includes(c.id)
        );
        setCategoriesState([...ordered, ...missing]);
      } catch {
        setCategoriesState(DEFAULT_CATEGORIES);
      }
    }
  }, []);

  const setCategories = useCallback((newCategories: MenuCategory[]) => {
    setCategoriesState(newCategories);
    localStorage.setItem(
      STORAGE_KEYS.SIDEBAR_ORDER,
      JSON.stringify(newCategories.map((c) => c.id))
    );
  }, []);

  return [categories, setCategories] as const;
}
