"use client";

import { create } from "zustand";
import { devtools, persist } from "zustand/middleware";
import { getUserMenus } from "@/services/menuService";
import type { UserMenuResponse } from "@/types/menu";

interface MenuStore {
  menus: UserMenuResponse[];
  flatMenus: UserMenuResponse[];
  loading: boolean;
  error: string | null;
  collapsed: boolean;
  openKeys: string[];
  fetchMenus: () => Promise<void>;
  setCollapsed: (collapsed: boolean) => void;
  setOpenKeys: (keys: string[]) => void;
}

export const flattenMenus = (menus: UserMenuResponse[]): UserMenuResponse[] =>
  menus.flatMap((item) => [item, ...(item.children ? flattenMenus(item.children) : [])]);

export const getFirstLeafMenu = (menu: UserMenuResponse | null): UserMenuResponse | null => {
  if (!menu) return null;
  if (!menu.children || menu.children.length === 0) return menu;
  return getFirstLeafMenu(menu.children[0]);
};

export const useMenuStore = create<MenuStore>()(
  devtools(
    persist(
      (set) => ({
        menus: [],
        flatMenus: [],
        loading: false,
        error: null,
        collapsed: false,
        openKeys: [],
        fetchMenus: async () => {
          set({ loading: true, error: null });
          try {
            const menus = await getUserMenus();
            set({ menus, flatMenus: flattenMenus(menus), loading: false });
          } catch (error) {
            set({ loading: false, error: error instanceof Error ? error.message : "加载菜单失败" });
          }
        },
        setCollapsed: (collapsed) => set({ collapsed }),
        setOpenKeys: (openKeys) => set({ openKeys })
      }),
      {
        name: "menu-storage",
        partialize: (state) => ({ collapsed: state.collapsed, openKeys: state.openKeys })
      }
    )
  )
);
