"use client";
import { useState, useEffect, useCallback } from "react";
import { useUserWithMetaSettings } from "./useUserSettings";
function useSidebarState() {
  const { data: userData, updateEntity, isLoading } = useUserWithMetaSettings();
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [isInitialized, setIsInitialized] = useState(false);
  useEffect(() => {
    var _a;
    if (((_a = userData == null ? void 0 : userData.meta) == null ? void 0 : _a.uiPreferences) && !isInitialized) {
      const uiPrefs = userData.meta.uiPreferences;
      const savedState = uiPrefs.sidebarCollapsed;
      if (typeof savedState === "boolean") {
        setIsCollapsed(savedState);
      }
      setIsInitialized(true);
    }
  }, [userData, isInitialized]);
  const updateSidebarState = useCallback(async (newState) => {
    try {
      setIsCollapsed(newState);
      await updateEntity({
        meta: {
          uiPreferences: {
            sidebarCollapsed: newState
          }
        }
      });
    } catch (error) {
      console.error("Error updating sidebar state:", error);
      setIsCollapsed(!newState);
    }
  }, [updateEntity]);
  const toggleSidebar = useCallback(() => {
    updateSidebarState(!isCollapsed);
  }, [isCollapsed, updateSidebarState]);
  return {
    isCollapsed,
    toggleSidebar,
    setIsCollapsed: updateSidebarState,
    isLoading: isLoading || !isInitialized
  };
}
export {
  useSidebarState
};
