import LeafletMap from '@/components/map/LeafletMap.tsx';
import MapHeader from '@/components/map/MapHeader.tsx';
import MapSidebar from '@/components/map/MapSidebar.tsx';
import ModuleErrorBoundary from '@/components/ui/ModuleErrorBoundary.tsx';
import { MapProvider, useMapUI } from '@/contexts/MapContexts.tsx';
import { useOrganizations } from '@/hooks/useOrganizations.ts';

const MapView = () => {
  const { organizations, isLoading } = useOrganizations();

  // Show loading state while organizations are loading
  if (isLoading || !organizations) {
    return (
      <div className="h-screen w-screen flex items-center justify-center bg-background">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
          <p className="mt-2 text-sm text-muted-foreground">Loading map...</p>
        </div>
      </div>
    );
  }

  const MapContent = () => {
    const { isSidebarOpen, setIsSidebarOpen } = useMapUI();

    return (
      <>
        <MapHeader />
        <div className="flex-1 flex overflow-hidden">
          {isSidebarOpen && (
            <div
              onClick={() => setIsSidebarOpen(false)}
              className="fixed inset-0 bg-black/50 z-20 md:hidden"
              aria-hidden="true"
            />
          )}
          <MapSidebar />
          <main className="flex-1 relative">
            <ModuleErrorBoundary moduleName="interactive map">
              <LeafletMap />
            </ModuleErrorBoundary>
          </main>
        </div>
      </>
    );
  };

  return (
    <MapProvider organizations={organizations}>
      <div className="h-screen w-screen flex flex-col bg-background">
        <MapContent />
      </div>
    </MapProvider>
  );
};

export default MapView;
