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

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

// localStorage key
const SIDEBAR_EXPANDED_KEY = 'sidebarExpanded';

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

  setHydrated: () => {
    // Hydration 完成后，从 localStorage 读取真实的状态
    if (typeof window !== 'undefined') {
      try {
        const saved = localStorage.getItem(SIDEBAR_EXPANDED_KEY);
        if (saved !== null) {
          const parsed = JSON.parse(saved);
          let actualState = false;

          // 从 persist 中间件的格式中提取 state.isSidebarExpanded
          if (typeof parsed === 'object' && parsed !== null && 'state' in parsed) {
            actualState = parsed.state.isSidebarExpanded ?? false;
          }
          // 兼容新格式（直接保存布尔值）
          else if (typeof parsed === 'boolean') {
            actualState = parsed;
          }

          set({ hydrated: true, isSidebarExpanded: actualState });
          return;
        }
      } catch (error) {
        console.error('Failed to load sidebar state from localStorage:', error);
      }
    }

    set({ hydrated: true });
  },

  setSidebarExpanded: (isSidebarExpanded: boolean) => {
    // 更新状态
    set({ isSidebarExpanded });

    // 手动保存到 localStorage
    if (typeof window !== 'undefined') {
      try {
        localStorage.setItem(SIDEBAR_EXPANDED_KEY, JSON.stringify(isSidebarExpanded));
      } catch (error) {
        console.error('Failed to save sidebar state to localStorage:', error);
      }
    }
  },
}));
