'use client';
import { create } from 'zustand';

const responsiveConfig = {
  xs: 375,
  sm: 768,
  md: 1024,
  lg: 1280,
  xl: 1440,
};

type ResponsiveResponse =
  | (Record<keyof typeof responsiveConfig, boolean> & { isMobile: boolean; isPC: boolean })
  | null;

type LayoutStore = {
  isSidebarExpanded: boolean;
  setSidebarExpanded: (isSidebarExpanded: boolean) => void;
  hydrated: boolean;
  setHydrated: () => void;
  response: ResponsiveResponse;
  initResponse: () => void;
};

// localStorage key
const SIDEBAR_EXPANDED_KEY = 'sidebarExpanded';

export const useLayoutStore = create<LayoutStore>((set, get) => ({
  // 默认值在服务器端和客户端都是 false，确保 Hydration 一致
  isSidebarExpanded: false,
  hydrated: false,
  response: null,

  initResponse: () => {
    const onResize = () => {
      const newResponse = Object.fromEntries(
        Object.entries(responsiveConfig).map(([key, value]) => {
          if (window.innerWidth > value) {
            return [key, true];
          }
          return [key, false];
        })
      ) as Record<keyof typeof responsiveConfig, boolean>;
      set({
        response: { ...newResponse, isMobile: !newResponse.sm, isPC: newResponse.sm },
      });
    };
    window.addEventListener('resize', onResize);
    onResize();
  },

  setSidebarExpanded: (isSidebarExpanded: boolean) => {
    set({ isSidebarExpanded });
    localStorage.setItem(SIDEBAR_EXPANDED_KEY, JSON.stringify(isSidebarExpanded));
  },

  setHydrated: () => {
    const { initResponse, setSidebarExpanded } = get();
    const saved = localStorage.getItem(SIDEBAR_EXPANDED_KEY);
    initResponse();
    setSidebarExpanded(JSON.parse(saved || 'false'));
    set({ hydrated: true });
  },
}));
