'use client';

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from 'react';
import type { MenuCategory, MenuItem } from '@/domain/menu/entities';
import {
  allMenuItems as staticAllMenuItems,
  menuCategories as staticMenuCategories,
} from '@/infrastructure/menu/static-menu-data';

interface MenuContextValue {
  categories: MenuCategory[];
  allItems: MenuItem[];
  getItemById: (id: string) => MenuItem | undefined;
  isLoading: boolean;
  refreshMenu: () => Promise<void>;
}

const MenuContext = createContext<MenuContextValue>({
  categories: staticMenuCategories,
  allItems: staticAllMenuItems,
  getItemById: (id) => staticAllMenuItems.find((item) => item.id === id),
  isLoading: false,
  refreshMenu: async () => {},
});

export function MenuProvider({ children }: { children: ReactNode }) {
  const [categories, setCategories] = useState<MenuCategory[]>(staticMenuCategories);
  const [isLoading, setIsLoading] = useState(true);

  const refreshMenu = useCallback(async () => {
    try {
      const response = await fetch('/api/menu', { cache: 'no-store' });
      if (!response.ok) return;

      const data = (await response.json()) as { categories?: MenuCategory[] };
      if (Array.isArray(data.categories) && data.categories.length > 0) {
        setCategories(data.categories);
      }
    } catch {
      // Keep the last known menu (static seed on first load).
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    void refreshMenu();
  }, [refreshMenu]);

  // Refetch when the tab becomes visible again (e.g. after editing in /admin).
  useEffect(() => {
    const onVisible = () => {
      if (document.visibilityState === 'visible') {
        void refreshMenu();
      }
    };
    const onMenuUpdated = () => {
      void refreshMenu();
    };
    document.addEventListener('visibilitychange', onVisible);
    window.addEventListener('shahi-menu-updated', onMenuUpdated);
    return () => {
      document.removeEventListener('visibilitychange', onVisible);
      window.removeEventListener('shahi-menu-updated', onMenuUpdated);
    };
  }, [refreshMenu]);

  const allItems = useMemo(() => categories.flatMap((category) => category.items), [categories]);

  const getItemById = useCallback(
    (id: string) => allItems.find((item) => item.id === id),
    [allItems],
  );

  const value = useMemo(
    () => ({
      categories,
      allItems,
      getItemById,
      isLoading,
      refreshMenu,
    }),
    [categories, allItems, getItemById, isLoading, refreshMenu],
  );

  return <MenuContext.Provider value={value}>{children}</MenuContext.Provider>;
}

export function useMenu() {
  return useContext(MenuContext);
}