'use client';

import { createContext, useCallback, useContext, useEffect, useState } from 'react';

type PlatformSidebarContextType = {
  isExpanded: boolean;
  isMobileOpen: boolean;
  isHovered: boolean;
  toggleSidebar: () => void;
  toggleMobileSidebar: () => void;
  closeMobileSidebar: () => void;
  setIsHovered: (v: boolean) => void;
};

const PlatformSidebarContext = createContext<PlatformSidebarContextType | undefined>(undefined);

export function PlatformSidebarProvider({ children }: { children: React.ReactNode }) {
  const [isExpanded, setIsExpanded] = useState(true);
  const [isMobileOpen, setIsMobileOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [isHovered, setIsHovered] = useState(false);

  useEffect(() => {
    const handleResize = () => {
      const mobile = window.innerWidth < 1024;
      setIsMobile(mobile);
      if (!mobile) setIsMobileOpen(false);
    };
    handleResize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const toggleSidebar = useCallback(() => setIsExpanded((p) => !p), []);
  const toggleMobileSidebar = useCallback(() => setIsMobileOpen((p) => !p), []);
  const closeMobileSidebar = useCallback(() => setIsMobileOpen(false), []);

  return (
    <PlatformSidebarContext.Provider
      value={{
        isExpanded: isMobile ? false : isExpanded,
        isMobileOpen,
        isHovered,
        toggleSidebar,
        toggleMobileSidebar,
        closeMobileSidebar,
        setIsHovered,
      }}
    >
      {children}
    </PlatformSidebarContext.Provider>
  );
}

export function usePlatformSidebar() {
  const ctx = useContext(PlatformSidebarContext);
  if (!ctx) throw new Error('usePlatformSidebar must be used within PlatformSidebarProvider');
  return ctx;
}
