import { create } from "zustand";

import type { TileProvider } from "@/hooks/use-leaflet-heatmap";
import type { Point } from "@/types/api";

type Nullable<T> = T | null;

interface AppState {
  userLocation: Nullable<Point>;
  locationError: Nullable<string>;
  isRequestingLocation: boolean;
  // UI state
  isSidebarOpen: boolean;
  isHeaderCollapsed: boolean;
  isMobileHeaderOpen: boolean;
  tileProvider: TileProvider;
  setUserLocation: (location: Nullable<Point>) => void;
  setLocationError: (error: Nullable<string>) => void;
  setIsRequestingLocation: (isRequesting: boolean) => void;
  setIsSidebarOpen: (open: boolean) => void;
  setIsHeaderCollapsed: (collapsed: boolean) => void;
  setIsMobileHeaderOpen: (open: boolean) => void;
  setTileProvider: (provider: TileProvider) => void;
}

export const useAppStore = create<AppState>(set => ({
  userLocation: null,
  locationError: null,
  isRequestingLocation: false,
  isSidebarOpen: typeof window !== "undefined" ? window.innerWidth >= 1024 : false,
  isHeaderCollapsed: typeof window !== "undefined" ? window.innerWidth < 768 : false,
  isMobileHeaderOpen: false,
  tileProvider: "openstreetmap",
  setUserLocation: userLocation => set({ userLocation }),
  setLocationError: locationError => set({ locationError }),
  setIsRequestingLocation: isRequestingLocation => set({ isRequestingLocation }),
  setIsSidebarOpen: isSidebarOpen => set({ isSidebarOpen }),
  setIsHeaderCollapsed: isHeaderCollapsed => set({ isHeaderCollapsed }),
  setIsMobileHeaderOpen: isMobileHeaderOpen => set({ isMobileHeaderOpen }),
  setTileProvider: tileProvider => set({ tileProvider }),
}));
