
"use client";

import * as React from 'react';

// Context for the main sidebar's properties (e.g., icon-only collapsed state)
interface MainSidebarState {
  collapsed: boolean;
  setCollapsed: (collapsed: boolean) => void;
  // Add other states like isOpenSheet/toggleSheet if the main provider will handle mobile sheet behavior
}

const MainSidebarContext = React.createContext<MainSidebarState | undefined>(undefined);

/**
 * Hook to access the main sidebar's state (e.g., collapsed for icon-only mode).
 */
export function useSidebar() {
  const context = React.useContext(MainSidebarContext);
  if (context === undefined) {
    throw new Error('useSidebar must be used within a SidebarProvider (SidebarContext.Provider)');
  }
  return context;
}

// Context for individual collapsible groups within the sidebar
interface SidebarGroupState {
  collapsed: boolean;
  setCollapsed: (collapsed: boolean) => void;
}

const SidebarGroupContext = React.createContext<SidebarGroupState | undefined>(undefined);

/**
 * This is the main exported object that sidebar.tsx imports as `SidebarContext`.
 * It provides the Provider for the main sidebar and a namespaced Group context.
 */
export const SidebarContext = {
  /**
   * Provider for the main sidebar state. Manages the `collapsed` state for icon-only mode.
   * This is typically used as `<SidebarProvider>` in the layout.
   */
  Provider: ({
    children,
    defaultOpen = false, // If true, sidebar is initially expanded (not collapsed to icons).
  }: {
    children: React.ReactNode;
    defaultOpen?: boolean;
  }) => {
    // 'collapsed' means the sidebar is in icon-only mode.
    // If defaultOpen is true, it means the sidebar is NOT collapsed initially.
    const [collapsed, setCollapsed] = React.useState<boolean>(!defaultOpen);

    return (
      <MainSidebarContext.Provider value={{ collapsed, setCollapsed }}>
        {children}
      </MainSidebarContext.Provider>
    );
  },
  /**
   * Hook to access the main sidebar context. Equivalent to `useSidebar`.
   */
  useContext: useSidebar,
  /**
   * Contextual components for managing collapsible groups within the sidebar.
   */
  Group: {
    Provider: ({
      children,
      defaultCollapsed = false, // If true, the group is initially collapsed.
    }: {
      children: React.ReactNode;
      defaultCollapsed?: boolean;
    }) => {
      const [collapsed, setCollapsed] = React.useState<boolean>(defaultCollapsed);
      return (
        <SidebarGroupContext.Provider value={{ collapsed, setCollapsed }}>
          {children}
        </SidebarGroupContext.Provider>
      );
    },
    useContext: () => {
      const context = React.useContext(SidebarGroupContext);
      if (context === undefined) {
        throw new Error(
          'SidebarContext.Group.useContext must be used within a SidebarContext.Group.Provider'
        );
      }
      return context;
    },
  },
};
