"use client";

import { createContext, useContext, useState, useCallback, useMemo } from "react";

interface SidebarContextValue {
  collapsed: boolean;
  mobileOpen: boolean;
  collapse: () => void;       // force-collapse (desktop icon-only)
  expand: () => void;         // force-expand (desktop full)
  toggle: () => void;         // header ☰ button behaviour
  closeMobile: () => void;
  openMobile: () => void;
}

const SidebarContext = createContext<SidebarContextValue | null>(null);

export function SidebarProvider({ children }: { children: React.ReactNode }) {
  const [collapsed, setCollapsed] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);

  const collapse = useCallback(() => setCollapsed(true), []);
  const expand = useCallback(() => setCollapsed(false), []);

  const toggle = useCallback(() => {
    if (typeof window !== "undefined" && window.innerWidth >= 768) {
      setCollapsed((p) => !p);
    } else {
      setMobileOpen((p) => !p);
    }
  }, []);

  const closeMobile = useCallback(() => setMobileOpen(false), []);
  const openMobile = useCallback(() => setMobileOpen(true), []);

  const value = useMemo(
    () => ({ collapsed, mobileOpen, collapse, expand, toggle, closeMobile, openMobile }),
    [collapsed, mobileOpen, collapse, expand, toggle, closeMobile, openMobile],
  );

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

export function useSidebar(): SidebarContextValue {
  const ctx = useContext(SidebarContext);
  if (!ctx) throw new Error("useSidebar must be used inside SidebarProvider");
  return ctx;
}
