"use client";
import {
  createContext, useContext, useState, useMemo, useCallback, type ReactNode,
} from "react";

interface MarketplaceContextValue {
  searchQuery: string;
  setSearchQuery: (q: string) => void;
  activeCategory: string | null;
  setActiveCategory: (c: string | null) => void;
  sidebarOpen: boolean;
  toggleSidebar: () => void;
  closeSidebar: () => void;
  mode: "buyer" | "seller";
  setMode: (m: "buyer" | "seller") => void;
  mobileSidebarOpen: boolean;
  openMobileSidebar: () => void;
  closeMobileSidebar: () => void;
}

const MarketplaceContext = createContext<MarketplaceContextValue | null>(null);

export function MarketplaceProvider({ children }: { children: ReactNode }) {
  const [searchQuery, setSearchQuery] = useState("");
  const [activeCategory, setActiveCategory] = useState<string | null>(null);
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
  const [mode, setMode] = useState<"buyer" | "seller">("buyer");

  const toggleSidebar = useCallback(() => setSidebarOpen((v) => !v), []);
  const closeSidebar = useCallback(() => setSidebarOpen(false), []);
  const openMobileSidebar = useCallback(() => setMobileSidebarOpen(true), []);
  const closeMobileSidebar = useCallback(() => setMobileSidebarOpen(false), []);

  const value = useMemo(
    () => ({
      searchQuery, setSearchQuery,
      activeCategory, setActiveCategory,
      sidebarOpen, toggleSidebar, closeSidebar,
      mode, setMode,
      mobileSidebarOpen, openMobileSidebar, closeMobileSidebar,
    }),
    [searchQuery, activeCategory, sidebarOpen, toggleSidebar, closeSidebar, mode, mobileSidebarOpen, openMobileSidebar, closeMobileSidebar]
  );

  return <MarketplaceContext.Provider value={value}>{children}</MarketplaceContext.Provider>;
}

export function useMarketplaceContext() {
  const ctx = useContext(MarketplaceContext);
  if (!ctx) throw new Error("useMarketplaceContext must be used inside MarketplaceProvider");
  return ctx;
}
