import React, { createContext, useContext, useState, useEffect } from 'react';
import { TEXT } from '../const';

interface SidebarContextType {
  isOpen: boolean;
  toggleSidebar: () => void;
}

const SidebarContext = createContext<SidebarContextType | undefined>(undefined);

export const SidebarProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [isOpen, setIsOpen] = useState(() => {
    return localStorage.getItem('sidebarIsOpen') === 'true' || false;
  });

  useEffect(() => {
    localStorage.setItem('sidebarIsOpen', isOpen.toString());
  }, [isOpen]);

  const toggleSidebar = () => {
    setIsOpen((prev) => !prev);
  };

  return (
    <SidebarContext.Provider value={{ isOpen, toggleSidebar }}>
      {children}
    </SidebarContext.Provider>
  );
};

export const useSidebar = () => {
  const context = useContext(SidebarContext);
  if (context === undefined) {
    throw new Error("TEXT.SIDEBAR_ERR");
  }
  return context;
};