import { create } from "zustand";
import type { MenuItem } from "@/types";

interface MenuState {
  topMenus: { OBJID: string; MENU_NAME_KOR: string }[];
  sideMenus: MenuItem[];
  activeTopMenu: string;
  activeSubMenu: string;
  isCollapsed: boolean;
  /** 모바일에서 사이드바 오버레이로 펼침 여부 */
  mobileOpen: boolean;
  /** 관리자 모드 / 사용자 모드 — 사이드바에 보일 메뉴 그룹 결정 */
  viewMode: "user" | "admin";
  setTopMenus: (menus: { OBJID: string; MENU_NAME_KOR: string }[]) => void;
  setSideMenus: (menus: MenuItem[]) => void;
  setActiveTopMenu: (id: string) => void;
  setActiveSubMenu: (id: string) => void;
  toggleCollapsed: () => void;
  setMobileOpen: (v: boolean) => void;
  setViewMode: (v: "user" | "admin") => void;
  fetchTopMenus: () => Promise<void>;
  fetchSideMenus: (menuObjId: string) => Promise<void>;
}

export const useMenuStore = create<MenuState>((set) => ({
  topMenus: [],
  sideMenus: [],
  activeTopMenu: "",
  activeSubMenu: "",
  isCollapsed: false,
  mobileOpen: false,
  viewMode: "user",

  setTopMenus: (topMenus) => set({ topMenus }),
  setSideMenus: (sideMenus) => set({ sideMenus }),
  setActiveTopMenu: (activeTopMenu) => set({ activeTopMenu }),
  setActiveSubMenu: (activeSubMenu) => set({ activeSubMenu }),
  toggleCollapsed: () => set((s) => ({ isCollapsed: !s.isCollapsed })),
  setMobileOpen: (v) => set({ mobileOpen: v }),
  setViewMode: (v) => set({ viewMode: v }),

  fetchTopMenus: async () => {
    const res = await fetch("/api/menu/top");
    if (res.ok) {
      const data = await res.json();
      set({ topMenus: data.menus || [] });
    }
  },

  fetchSideMenus: async (menuObjId: string) => {
    const res = await fetch("/api/menu", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ MENUOBJID: menuObjId }),
    });
    if (res.ok) {
      const data = await res.json();
      const items = (data.RESULT || []) as MenuItem[];

      // 트리 구조 빌드 (menu.jsp add_menu 로직 대응)
      const parents = items.filter((i) => i.level === "1" || Number(i.level) < 2);
      const children = items.filter((i) => i.level !== "1" && Number(i.level) >= 2);

      const tree = parents.map((p) => {
        const kids = children.filter((c) => c.parentObjId === p.objid);
        // 동일 메뉴명 중복 제거 (SEQ 순서 유지, 첫 번째만 유지)
        const seen = new Set<string>();
        const uniqueKids = kids.filter((c) => {
          if (seen.has(c.menuNameKor)) return false;
          seen.add(c.menuNameKor);
          return true;
        });
        return { ...p, children: uniqueKids };
      });

      set({ sideMenus: tree, activeTopMenu: menuObjId });
    }
  },
}));
