"use client";
import { createContext, useReducer, useEffect, useState } from "react";

export * from "./useMainLayout";

const MainLayoutContext = createContext<{
  isSidebarExpanded: boolean;
  dispatch: (action: { type: "updateState", payload: Partial<typeof initialState> }) => void;
}>({
  isSidebarExpanded: false,
  dispatch: () => {},
});

const initialState = {
  isSidebarExpanded: false,
};

const reducer = (state: typeof initialState, action: { type: "updateState", payload: Partial<typeof initialState> }) => {
  switch (action.type) {
    case "updateState":
      return {
        ...state,
        ...action.payload,
      };
  }
  return state;
}

export const MainLayoutProvider = ({ children }: { children: React.ReactNode }) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  const [isHydrated, setIsHydrated] = useState(false);

  // 客户端 hydration 后从 localStorage 恢复状态
  useEffect(() => {
    setIsHydrated(true);
    const saved = localStorage.getItem('sidebarExpanded');
    if (saved !== null) {
      dispatch({
        type: "updateState",
        payload: {
          isSidebarExpanded: JSON.parse(saved)
        }
      });
    }
  }, []);

  // 当状态改变时保存到 localStorage
  useEffect(() => {
    if (isHydrated) {
      localStorage.setItem('sidebarExpanded', JSON.stringify(state.isSidebarExpanded));
    }
  }, [state.isSidebarExpanded, isHydrated]);

  return (
    <MainLayoutContext.Provider value={{ isSidebarExpanded: state.isSidebarExpanded, dispatch }}>
      {children}
    </MainLayoutContext.Provider>
  );
}
 
export default MainLayoutContext;