import React, { useEffect, useMemo, useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Activity, 
  Building2, 
  ShieldCheck, 
  Truck, 
  User, 
  ChevronRight, 
  Zap, 
  Route, 
  Plus,
  MoreVertical,
  CheckCircle2,
  XCircle,
  Phone,
  Mail,
  Calendar,
  ClipboardList,
  Package,
  History,
  Link2,
  BarChart3,
  Users,
  Eye,
  EyeOff,
  Lock,
  HardDrive,
  AlertTriangle,
  FileText,
  Fuel,
  Gauge,
  Thermometer,
  Wind,
  Download,
  CreditCard,
  LayoutGrid,
  Search,
  Bell,
  Settings,
  MapPin,
  Map,
  Clock,
  Navigation,
  Fingerprint,
  Briefcase,
  Award,
  Stethoscope,
  Globe,
  Hash,
  Edit2,
  Loader2
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { Card, StatCard } from '../components/Common';
import { authApi } from '../api/auth';
import { fleetApi } from '../api/fleet';
import './FleetDispatch.css';

type FleetModule = 
  | 'DASHBOARD'
  | 'OWNERS'
  | 'STATIONS'
  | 'VEHICLES'
  | 'STAFF'
  | 'SCHEDULING'
  | 'ATTENDANCE'
  | 'INVENTORY'
  | 'TRIPS'
  | 'TELEMATICS'
  | 'REFERRALS'
  | 'REPORTS';

// Mock data and sub-components removed to reduce clutter and resolve unused warnings.
// Use live backend data via authApi.getUsers() filter roles.includes('FLEET_OPERATOR').

type VehicleType = 'ALS' | 'BLS' | 'TRANSFER' | 'MORTUARY' | 'AIR' | 'NEO' | 'SUPPORT';

type FleetVehicle = {
  id: string;
  number: string;
  chassis: string;
  engine: string;
  brand: string;
  model: string;
  make: string;
  year: number;
  type: VehicleType;
  capacity: number;
  ownership: 'SELF' | 'HOSPITAL' | 'LEASED';
  station: string;
  status: 'IDLE' | 'EN_ROUTE' | 'AT_SCENE' | 'TRANSPORTING' | 'AT_HOSPITAL' | 'BREAKDOWN' | 'OFF_DUTY';
  // Telemetry
  lat: number;
  lng: number;
  fuel: number;
  speed: number;
  temp: number;
  odometer: number;
  lastService: string;
  nextService: string;
  // Documents
  rcExpiry: string;
  fcExpiry: string;
  permitExpiry: string;
  insuranceExpiry: string;
  pucExpiry: string;
};

// --- MOCK DATA ---
const MOCK_VEHICLES: FleetVehicle[] = [
  {
    id: 'V001', number: 'TN-01-AM-1024', chassis: 'CH-882910293', engine: 'EN-99102',
    brand: 'Force', model: 'Traveller', make: '2023', year: 2023, type: 'ALS', capacity: 1,
    ownership: 'SELF', station: 'Central Dispatch', status: 'EN_ROUTE',
    lat: 13.0827, lng: 80.2707, fuel: 82, speed: 45, temp: 88, odometer: 12450,
    lastService: '2024-03-01', nextService: '2024-06-01',
    rcExpiry: '2033-05-12', fcExpiry: '2025-05-12', permitExpiry: '2025-05-12', insuranceExpiry: '2025-05-12', pucExpiry: '2024-09-12'
  },
  {
    id: 'V002', number: 'TN-05-AM-5521', chassis: 'CH-771029384', engine: 'EN-88491',
    brand: 'Tata', model: 'Winger', make: '2022', year: 2022, type: 'BLS', capacity: 2,
    ownership: 'HOSPITAL', station: 'Adyar Station', status: 'IDLE',
    lat: 13.0067, lng: 80.2575, fuel: 65, speed: 0, temp: 75, odometer: 45000,
    lastService: '2024-02-15', nextService: '2024-05-15',
    rcExpiry: '2032-02-15', fcExpiry: '2025-02-15', permitExpiry: '2025-02-15', insuranceExpiry: '2025-02-15', pucExpiry: '2024-08-15'
  },
  {
    id: 'V003', number: 'TN-07-AM-1122', chassis: 'CH-661029384', engine: 'EN-55491',
    brand: 'Mahindra', model: 'Supro', make: '2024', year: 2024, type: 'TRANSFER', capacity: 1,
    ownership: 'LEASED', station: 'OMR Hub', status: 'TRANSPORTING',
    lat: 12.9667, lng: 80.2475, fuel: 45, speed: 52, temp: 92, odometer: 8200,
    lastService: '2024-03-10', nextService: '2024-06-10',
    rcExpiry: '2034-03-10', fcExpiry: '2026-03-10', permitExpiry: '2026-03-10', insuranceExpiry: '2026-03-10', pucExpiry: '2024-09-10'
  },
  {
    id: 'V004', number: 'TN-09-AM-9988', chassis: 'CH-441029384', engine: 'EN-33491',
    brand: 'Tata', model: 'Winger', make: '2021', year: 2021, type: 'AIR', capacity: 1,
    ownership: 'SELF', station: 'Airport Station', status: 'AT_SCENE',
    lat: 12.9941, lng: 80.1709, fuel: 78, speed: 0, temp: 82, odometer: 68000,
    lastService: '2024-01-20', nextService: '2024-04-20',
    rcExpiry: '2031-01-20', fcExpiry: '2025-01-20', permitExpiry: '2025-01-20', insuranceExpiry: '2025-01-20', pucExpiry: '2024-07-20'
  },
  {
    id: 'V005', number: 'TN-02-AM-4422', chassis: 'CH-221029384', engine: 'EN-11491',
    brand: 'Force', model: 'Citiline', make: '2023', year: 2023, type: 'NEO', capacity: 1,
    ownership: 'SELF', station: 'Egmore Station', status: 'AT_HOSPITAL',
    lat: 13.0782, lng: 80.2604, fuel: 92, speed: 5, temp: 85, odometer: 15400,
    lastService: '2024-03-22', nextService: '2024-06-22',
    rcExpiry: '2033-03-22', fcExpiry: '2025-03-22', permitExpiry: '2025-03-22', insuranceExpiry: '2025-03-22', pucExpiry: '2024-09-22'
  },
  {
    id: 'V006', number: 'TN-10-AM-7733', chassis: 'CH-111029384', engine: 'EN-00491',
    brand: 'Force', model: 'Traveller', make: '2020', year: 2020, type: 'MORTUARY', capacity: 1,
    ownership: 'SELF', station: 'Royapettah Hub', status: 'OFF_DUTY',
    lat: 13.0513, lng: 80.2588, fuel: 30, speed: 0, temp: 70, odometer: 112000,
    lastService: '2024-01-05', nextService: '2024-04-05',
    rcExpiry: '2030-01-05', fcExpiry: '2025-01-05', permitExpiry: '2025-01-05', insuranceExpiry: '2025-01-05', pucExpiry: '2024-07-05'
  }
];

// --- LEAFLET MAP COMPONENT (REUSED & REFINED) ---
const LiveLeafletMap: React.FC<{ vehicles: FleetVehicle[], selectedId: string | null }> = ({ vehicles, selectedId }) => {
  const [isMapReady, setIsMapReady] = useState(false);
  const mapRef = useRef<any>(null);
  const markersRef = useRef<{ [key: string]: any }>({});
  const [L, setL] = useState<any>(null);
  const [mapType, setMapType] = useState<'light' | 'satellite'>('light');
  const tileLayerRef = useRef<any>(null);

  useEffect(() => {
    if (typeof window === 'undefined') return;
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
    document.head.appendChild(link);

    const script = document.createElement('script');
    script.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
    script.async = true;
    script.onload = () => {
      const leaflet = (window as any).L;
      if (leaflet) {
        setL(leaflet);
        if (!mapRef.current) {
          const m = leaflet.map('leaflet-map-container', {
            zoomControl: false,
            attributionControl: false
          }).setView([13.0827, 80.2707], 11);
          
          mapRef.current = m;
          m.whenReady(() => setIsMapReady(true));
        }
      }
    };
    document.head.appendChild(script);

    return () => {
      if (mapRef.current) {
        try { mapRef.current.remove(); } catch (e) {}
        mapRef.current = null;
      }
    };
  }, []);

  useEffect(() => {
    if (!L || !mapRef.current || !isMapReady) return;
    
    if (tileLayerRef.current) {
      tileLayerRef.current.remove();
    }

    const url = mapType === 'satellite' 
      ? 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
      : 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png';
    
    tileLayerRef.current = L.tileLayer(url, {
      maxZoom: mapType === 'satellite' ? 19 : 20,
      attribution: mapType === 'satellite' ? 'Tiles &copy; Esri' : ''
    }).addTo(mapRef.current);
  }, [L, isMapReady, mapType]);

  useEffect(() => {
    if (!L || !mapRef.current || !isMapReady) return;
    const map = mapRef.current;
    
    vehicles.forEach(v => {
      const colorMap: any = {
        IDLE: '#94A3B8',
        EN_ROUTE: '#3B82F6',
        AT_SCENE: '#FFB800',
        TRANSPORTING: '#FF3B3B',
        AT_HOSPITAL: '#A855F7',
        BREAKDOWN: '#1A1A1A',
        OFF_DUTY: '#FFFFFF'
      };
      const color = colorMap[v.status] || '#3B82F6';

      if (!markersRef.current[v.id]) {
        const icon = L.divIcon({
          className: 'custom-vehicle-icon',
          html: `<div style="background-color: ${color}; width: 20px; height: 20px; border-radius: 50% 50% 50% 0; transform: rotate(-45deg); display: flex; align-items: center; justify-content: center; box-shadow: 0 0 15px ${color}, inset 0 0 4px #fff; border: 2px solid #fff;">
                  <div style="width: 6px; height: 6px; background: #fff; border-radius: 50%; transform: rotate(45deg);"></div>
                </div>`,
          iconSize: [20, 20],
          iconAnchor: [10, 20]
        });
        const marker = L.marker([v.lat, v.lng], { icon }).addTo(map);
        
        // Detailed Popup
        marker.bindPopup(`
          <div style="padding: 12px; min-width: 180px; font-family: 'Inter', sans-serif;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 8px;">
              <span style="font-weight: 800; color: var(--text-primary); font-size: 0.9rem;">${v.number}</span>
              <span style="font-size: 0.65rem; background: ${color}33; color: ${color}; border: 1px solid ${color}; padding: 2px 6px; border-radius: 4px; font-weight: 900;">${v.status}</span>
            </div>
            <div style="font-size: 0.75rem; color: var(--text-secondary); margin-bottom: 12px;">${v.brand} ${v.model} • ${v.type}</div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; background: rgba(0,0,0,0.03); padding: 8px; border-radius: 6px;">
              <div>
                <div style="font-size: 0.6rem; color: #64748B; text-transform: uppercase;">Speed</div>
                <div style="font-weight: 700; color: #3B82F6;">${v.speed} km/h</div>
              </div>
              <div>
                <div style="font-size: 0.6rem; color: #64748B; text-transform: uppercase;">Fuel</div>
                <div style="font-weight: 700; color: #3B82F6;">${v.fuel}%</div>
              </div>
            </div>
          </div>
        `, {
          className: 'glass-popup',
          closeButton: false
        });

        // Hover Tooltip
        marker.bindTooltip(v.number, {
          permanent: false,
          direction: 'top',
          offset: [0, -20],
          className: 'v-tooltip'
        });

        markersRef.current[v.id] = marker;
      } else {
        markersRef.current[v.id].setLatLng([v.lat, v.lng]);
        // Update popup speed/data if it's open (simplified here)
      }
    });

    if (selectedId && markersRef.current[selectedId]) {
      const v = vehicles.find(veh => veh.id === selectedId);
      if (v) map.flyTo([v.lat, v.lng], 14, { duration: 1.5 });
    }
  }, [vehicles, selectedId, L, isMapReady]);

  return (
    <div id="leaflet-map-container" className="glass" style={{ height: '500px', borderRadius: '16px', overflow: 'hidden', position: 'relative', border: '1px solid var(--card-border)' }}>
       {!L && <div className="flex-center" style={{ height: '100%', color: 'var(--text-secondary)' }}>INITIALIZING GLOBAL TRACKING...</div>}
       
       <div style={{ position: 'absolute', top: '16px', right: '16px', zIndex: 1000 }}>
         <div className="pill-toggle">
            <button className={mapType === 'light' ? 'active' : ''} onClick={() => setMapType('light')}>Light</button>
            <button className={mapType === 'satellite' ? 'active' : ''} onClick={() => setMapType('satellite')}>Satellite</button>
         </div>
       </div>

       <div style={{ position: 'absolute', bottom: '16px', right: '16px', zIndex: 1000, background: 'rgba(255,255,255,0.8)', backdropFilter: 'blur(8px)', padding: '8px 12px', borderRadius: '8px', border: '1px solid var(--card-border)', fontSize: '0.7rem', color: 'var(--text-primary)' }}>
          LIVE TELEMETRY ACTIVE
       </div>
    </div>
  );
};

// --- LOCATION PICKER MAP (FOR ONBOARDING) ---
const LocationPickerMap: React.FC<{ 
  lat: number; 
  lng: number; 
  onLocationSelect: (lat: number, lng: number) => void 
}> = ({ lat, lng, onLocationSelect }) => {
  const [isMapReady, setIsMapReady] = useState(false);
  const mapRef = useRef<any>(null);
  const markerRef = useRef<any>(null);
  const [L, setL] = useState<any>(null);
  const [mapType, setMapType] = useState<'light' | 'satellite'>('satellite');
  const tileLayerRef = useRef<any>(null);
  
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<any[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [address, setAddress] = useState<string | null>(null);
  const [isLocating, setIsLocating] = useState(false);
  const [ripples, setRipples] = useState<{ id: number, x: number, y: number }[]>([]);

  // Reverse Geocoding
  useEffect(() => {
    const fetchAddress = async () => {
      if (lat && lng) {
        try {
          const res = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&zoom=18&addressdetails=1`);
          const data = await res.json();
          setAddress(data.display_name);
        } catch (e) {
          console.error("Geocoding error", e);
        }
      }
    };
    const timer = setTimeout(fetchAddress, 500);
    return () => clearTimeout(timer);
  }, [lat, lng]);

  useEffect(() => {
    if (typeof window === 'undefined') return;
    
    // Ensure Leaflet is loaded
    const leaflet = (window as any).L;
    if (leaflet) {
      setL(leaflet);
      if (!mapRef.current) {
        const m = leaflet.map('location-picker-map', {
          zoomControl: false,
          attributionControl: false
        }).setView([lat || 13.0827, lng || 80.2707], 13);
        
        mapRef.current = m;
        m.whenReady(() => setIsMapReady(true));

        m.on('click', (e: any) => {
          onLocationSelect(e.latlng.lat, e.latlng.lng);
          // Add ripple effect
          const ripple = { id: Date.now(), x: e.containerPoint.x, y: e.containerPoint.y };
          setRipples(prev => [...prev, ripple]);
          setTimeout(() => setRipples(prev => prev.filter(r => r.id !== ripple.id)), 600);
        });
      }
    }
  }, []);

  useEffect(() => {
    if (!L || !mapRef.current || !isMapReady) return;
    
    if (tileLayerRef.current) {
      tileLayerRef.current.remove();
    }

    const url = mapType === 'satellite' 
      ? 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
      : 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png';
    
    tileLayerRef.current = L.tileLayer(url, {
      maxZoom: mapType === 'satellite' ? 19 : 20,
      attribution: mapType === 'satellite' ? 'Tiles &copy; Esri' : ''
    }).addTo(mapRef.current);
  }, [L, isMapReady, mapType]);

  useEffect(() => {
    if (!L || !mapRef.current || !isMapReady) return;
    const map = mapRef.current;

    if (markerRef.current) {
      markerRef.current.setLatLng([lat, lng]);
    } else {
      const icon = L.divIcon({
        className: 'custom-picker-icon',
        html: `<div style="background-color: var(--accent-cyan); width: 24px; height: 24px; border-radius: 50% 50% 50% 0; transform: rotate(-45deg); display: flex; align-items: center; justify-content: center; box-shadow: 0 0 20px var(--accent-cyan); border: 2px solid #fff;">
                <div style="width: 8px; height: 8px; background: #fff; border-radius: 50%; transform: rotate(45deg);"></div>
              </div>`,
        iconSize: [24, 24],
        iconAnchor: [12, 24]
      });
      const marker = L.marker([lat, lng], { 
        icon,
        draggable: true
      }).addTo(map);
      
      marker.on('dragend', (e: any) => {
        const newPos = e.target.getLatLng();
        onLocationSelect(newPos.lat, newPos.lng);
      });
      
      markerRef.current = marker;
    }
  }, [lat, lng, L, isMapReady]);

  const handleSearch = async (query: string) => {
    setSearchQuery(query);
    if (query.length < 3) {
      setSearchResults([]);
      return;
    }

    setIsSearching(true);
    try {
      const res = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}&limit=5`);
      const data = await res.json();
      setSearchResults(data);
    } catch (e) {
      console.error("Search error", e);
    } finally {
      setIsSearching(false);
    }
  };

  const selectSearchResult = (result: any) => {
    const nLat = parseFloat(result.lat);
    const nLng = parseFloat(result.lon);
    onLocationSelect(nLat, nLng);
    if (mapRef.current) {
      mapRef.current.flyTo([nLat, nLng], 16);
    }
    setSearchResults([]);
    setSearchQuery('');
  };

  const handleGetCurrentLocation = () => {
    if (!navigator.geolocation) {
      alert('Geolocation is not supported by your browser');
      return;
    }

    setIsLocating(true);
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude, accuracy } = position.coords;
        console.log(`GPS Lock: ${latitude}, ${longitude} (Accuracy: ${accuracy}m)`);
        
        onLocationSelect(latitude, longitude);
        if (mapRef.current) {
          mapRef.current.flyTo([latitude, longitude], 18); // Zoom in closer for GPS
        }
        setIsLocating(false);
        
        if (accuracy > 100) {
          console.log('GPS Warning', 'Location accuracy is low. Please manually adjust the pin.', 'info');
        }
      },
      (error) => {
        console.error('Error getting location:', error);
        let msg = 'Unable to retrieve your location.';
        if (error.code === 1) msg = 'Location permission denied.';
        else if (error.code === 3) msg = 'Location request timed out.';
        
        console.log('GPS Error', msg, 'error');
        setIsLocating(false);
      },
      { 
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 0 
      }
    );
  };

  return (
    <div style={{ position: 'relative', marginTop: '16px' }}>
      <div id="location-picker-map" className="glass" style={{ height: '400px', borderRadius: '16px', overflow: 'hidden', border: '1px solid var(--card-border)' }} />
      
      {/* Top Controls Row */}
      <div className="picker-top-row">
        <div className="picker-search-bar">
          {isSearching ? <Loader2 size={16} className="spin-slow" color="var(--accent-cyan)" /> : <Search size={16} color="var(--accent-cyan)" />}
          <input 
            type="text" 
            placeholder="Search location..." 
            value={searchQuery}
            onChange={(e) => handleSearch(e.target.value)}
          />
          <AnimatePresence>
            {searchResults.length > 0 && (
              <motion.div 
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="search-results-dropdown glass"
              >
                {searchResults.map((r, i) => (
                  <div key={i} className="search-result-item" onClick={() => selectSearchResult(r)}>
                    <div className="place-name">{r.display_name.split(',')[0]}</div>
                    <div className="place-address">{r.display_name.split(',').slice(1, 3).join(',')}</div>
                  </div>
                ))}
              </motion.div>
            )}
          </AnimatePresence>
        </div>

        <div className="pill-toggle map-theme-toggle">
          <button type="button" className={mapType === 'light' ? 'active' : ''} onClick={() => setMapType('light')}>Light</button>
          <button type="button" className={mapType === 'satellite' ? 'active' : ''} onClick={() => setMapType('satellite')}>Sat</button>
        </div>
      </div>

      {/* Address Overlay */}
      <AnimatePresence>
        {address && (
          <motion.div 
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            className="picker-address-overlay"
          >
            <MapPin size={16} color="var(--accent-cyan)" style={{ marginTop: '2px' }} />
            <div>{address}</div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Coordinate Badge */}
      <div className="picker-coord-badge">
        <div className="label">GPS COORDINATES</div>
        <div className="value">{lat.toFixed(6)}, {lng.toFixed(6)}</div>
      </div>

      {/* Ripple Effects */}
      {ripples.map(r => (
        <div key={r.id} className="click-ripple" style={{ left: r.x - 20, top: r.y - 20 }} />
      ))}
      
      <button
        type="button"
        onClick={handleGetCurrentLocation}
        disabled={isLocating}
        style={{
          position: 'absolute',
          bottom: '12px',
          right: '12px',
          zIndex: 1000,
          background: 'var(--accent-cyan)',
          border: 'none',
          borderRadius: '10px',
          padding: '10px 14px',
          color: '#fff',
          fontWeight: 800,
          fontSize: '0.75rem',
          display: 'flex',
          alignItems: 'center',
          gap: '8px',
          cursor: isLocating ? 'wait' : 'pointer',
          boxShadow: '0 8px 20px rgba(59, 130, 246, 0.3)',
          transition: 'all 0.3s ease'
        }}
        className="hover-glow"
      >
        <Navigation size={14} className={isLocating ? 'spin-slow' : ''} />
        {isLocating ? 'LOCATING...' : 'MY GPS'}
      </button>

      <div style={{ 
        position: 'absolute', 
        bottom: '75px', 
        left: '50%', 
        transform: 'translateX(-50%)', 
        zIndex: 1000, 
        background: 'rgba(255, 255, 255, 0.8)', 
        padding: '6px 14px', 
        borderRadius: '50px', 
        fontSize: '0.65rem', 
        color: 'var(--accent-cyan)', 
        fontWeight: 800, 
        border: '1px solid rgba(59, 130, 246, 0.3)', 
        backdropFilter: 'blur(8px)', 
        pointerEvents: 'none',
        letterSpacing: '0.05em',
        boxShadow: '0 4px 15px rgba(0,0,0,0.1)'
      }}>
        TAP MAP OR DRAG PIN TO ADJUST
      </div>
    </div>
  );
};

// --- SUB-COMPONENTS ---

const ModuleTab: React.FC<{ active: boolean; icon: any; label: string; onClick: () => void }> = ({ active, icon: Icon, label, onClick }) => (
  <button 
    onClick={onClick}
    className={`sub-nav-item ${active ? 'active' : ''}`}
    style={{
      padding: '12px 16px',
      display: 'flex',
      alignItems: 'center',
      gap: '10px',
      background: active ? 'rgba(59, 130, 246, 0.05)' : 'transparent',
      border: 'none',
      borderLeft: `3px solid ${active ? 'var(--accent-cyan)' : 'transparent'}`,
      color: active ? 'var(--accent-cyan)' : 'var(--text-secondary)',
      cursor: 'pointer',
      fontSize: '0.85rem',
      fontWeight: 600,
      width: '100%',
      textAlign: 'left',
      transition: 'all 0.2s',
      borderRadius: '0 8px 8px 0'
    }}
  >
    <Icon size={18} />
    {label}
  </button>
);


const InventoryManagement: React.FC<{ data: any[]; loading: boolean }> = ({ data, loading }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
    <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <h3 className="section-title"><Package size={24} /> Inventory & Medical Logistics</h3>
      <div style={{ display: 'flex', gap: '12px' }}>
        <button className="btn-secondary"><HardDrive size={18} /> MASTER CATALOG</button>
        <button className="btn-primary"><Plus size={18} /> NEW PROCUREMENT</button>
      </div>
    </header>

    <div className="inventory-grid">
       <Card title="Global Stock Master">
          {loading ? (
             <div style={{ textAlign: 'center', padding: '40px' }}>
                <Activity className="spin-slow" color="var(--accent-cyan)" />
                <div style={{ marginTop: '12px', color: 'var(--text-secondary)' }}>SYNCING STOCK CATALOG...</div>
             </div>
          ) : (
            <div className="table-container" style={{ maxHeight: '400px', overflowY: 'auto' }}>
               <table>
                  <thead>
                     <tr>
                        <th>Item Name</th>
                        <th>Category</th>
                        <th>UOM</th>
                        <th>Min Stock</th>
                        <th>Status</th>
                     </tr>
                  </thead>
                  <tbody>
                     {data.length === 0 ? (
                        <tr><td colSpan={5} style={{ textAlign: 'center', color: 'var(--text-secondary)' }}>No items in master catalog.</td></tr>
                     ) : (
                        data.map(item => (
                           <tr key={item.id}>
                              <td><div style={{ fontWeight: 700 }}>{item.name}</div><div style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>{item.sku || 'SKU-000'}</div></td>
                              <td><span className="badge">{item.category}</span></td>
                              <td>{item.unit_of_measure}</td>
                              <td className="mono">{item.min_stock_level}</td>
                              <td><span className="badge" style={{ background: 'rgba(59, 130, 246, 0.05)', color: 'var(--accent-cyan)' }}>ACTIVE</span></td>
                           </tr>
                        ))
                     )}
                  </tbody>
               </table>
            </div>
          )}
       </Card>

       <Card title="Global Stock Alerts">
          <div className="alert-list">
             <div className="alert-item warning">
                <AlertTriangle size={16} />
                <div className="alert-content">
                   <div className="alert-title">Adrenaline 1mg - Low Stock</div>
                   <div className="alert-desc">Only 42 units remaining across 12 stations. Reorder point: 100.</div>
                </div>
                <button className="btn-action">ORDER</button>
             </div>
             <div className="alert-item danger">
                <XCircle size={16} />
                <div className="alert-content">
                   <div className="alert-title">Oxygen Cylinders - Expiry Alert</div>
                   <div className="alert-desc">14 cylinders (Batch B-22) in TN-01-AM-1024 expire in 3 days.</div>
                </div>
                <button className="btn-action">REPLACE</button>
             </div>
          </div>
       </Card>
    </div>
  </div>
);

const CrewScheduling: React.FC<{ onAddRoster: () => void }> = ({ onAddRoster }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
    <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <h3 className="section-title"><Calendar size={24} /> Crew Scheduling & Rosters</h3>
      <div style={{ display: 'flex', gap: '12px' }}>
         <div className="view-selector">
            <button className="active">DAILY</button>
            <button>WEEKLY</button>
         </div>
         <button className="btn-primary" onClick={onAddRoster}><Plus size={18} /> NEW ROSTER</button>
      </div>
    </header>

    <Card>
       <div className="scheduler">
          <div className="scheduler-header">
             <div className="col-staff">CREW UNIT</div>
             <div className="col-time">08:00</div>
             <div className="col-time">12:00</div>
             <div className="col-time">16:00</div>
             <div className="col-time">20:00</div>
             <div className="col-time">00:00</div>
          </div>
          <div className="scheduler-body">
             {[1,2,3,4,5].map(i => (
               <div key={i} className="scheduler-row">
                  <div className="unit-cell">
                     <div className="unit-name">Alpha-{i}</div>
                     <div className="unit-crew">Dinesh / Bala</div>
                  </div>
                  <div className="shift-line shift-morning" style={{ left: '150px', width: '250px' }}>
                     <div className="shift-label">ON DUTY - TN-01-AM...</div>
                  </div>
               </div>
             ))}
          </div>
       </div>
    </Card>
  </div>
);

const OrganisationStationMgmt: React.FC<{ 
  onAddStation: () => void; 
  organisationId?: string;
  organisationName?: string;
  onViewVehicles?: (stationId: string) => void;
  onViewStaff?: (stationId: string) => void;
  onViewManifest?: (station: any) => void;
}> = ({ onAddStation, organisationId, organisationName, onViewVehicles, onViewStaff, onViewManifest }) => {
  const [stations, setStations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchStations = async () => {
      try {
        const token = localStorage.getItem('teleems_token') || '';
        if (!token) return;
        const response = await fleetApi.getStations(token, organisationId);
        // Handle nested response structure { data: { data: [...] } } or flat array
        let stationArr = response.data?.data || (Array.isArray(response.data) ? response.data : []);
        if (Array.isArray(stationArr)) {
          // Strict frontend filtering to ensure only respective owner stations are shown
          if (organisationId) {
            stationArr = stationArr.filter((s: any) => s.organisationId === organisationId);
          }
          setStations(stationArr);
        }
      } catch (error) {
        console.error('Failed to fetch stations:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchStations();
  }, [organisationId]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
      <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h3 className="section-title"><Building2 size={24} /> Organisation & Stations</h3>
        <button className="btn-primary" onClick={onAddStation}><Plus size={18} /> NEW STATION</button>
      </header>

      <div className="org-profile glass">
        <div className="org-cover" />
        <div className="org-header">
          <div className="org-logo">{organisationName?.[0] || 'L'}</div>
          <div className="org-meta">
            <h2>{organisationName || 'Lifeline Aggregator Services'}</h2>
            <div className="org-badges">
              <span className="badge">HQ: Chennai, TN</span>
              <span className="badge">EST: 2018</span>
            </div>
          </div>
        </div>
      </div>

      <div className="stations-grid">
        {loading ? (
          <div style={{ gridColumn: '1 / -1', textAlign: 'center', padding: '40px' }}>
            <Activity className="spin-slow" size={32} color="var(--accent-cyan)" />
            <p style={{ marginTop: '12px', color: 'var(--text-secondary)' }}>Loading stations...</p>
          </div>
        ) : stations.length === 0 ? (
          <div style={{ gridColumn: '1 / -1', textAlign: 'center', padding: '60px', background: 'rgba(0,0,0,0.1)', borderRadius: '16px', border: '1px dashed rgba(255,255,255,0.1)' }}>
            <Building2 size={48} color="rgba(255,255,255,0.1)" />
            <p style={{ marginTop: '16px', color: 'var(--text-secondary)' }}>No stations registered for this organisation.</p>
            <button className="btn-ghost" onClick={onAddStation} style={{ marginTop: '12px' }}>Add Your First Station</button>
          </div>
        ) : (
          stations.map((s: any) => (
            <Card key={s.id} title={s.name} subtitle={s.address}>
              <div className="station-stat">
                <div className="stat">
                  <MapPin size={14} color="var(--accent-cyan)" />
                  <span style={{ fontSize: '0.8rem' }}>{s.gps_lat}, {s.gps_lon}</span>
                </div>
                <div className="stat">
                  <Phone size={14} color="var(--accent-cyan)" />
                  <span>{s.phone}</span>
                </div>
                <div className="stat">
                  <Users size={14} color="var(--accent-cyan)" />
                  <span>{s.staff_count || 0} Staff Units</span>
                </div>
              </div>
              <div className="station-incharge">
                <User size={14} />
                <span>In-charge: {s.incharge_name || 'Not Assigned'}</span>
              </div>
              <div className="station-actions">
                <button className="btn-ghost-sm" style={{ flex: 1 }} onClick={() => onViewVehicles?.(s.id)}>VEHICLES</button>
                <button className="btn-ghost-sm" style={{ flex: 1 }} onClick={() => onViewStaff?.(s.id)}>STAFF</button>
                <button className="btn-primary-sm" onClick={() => onViewManifest?.(s)}>MANIFEST</button>
              </div>
            </Card>
          ))
        )}
      </div>
    </div>
  );
};

const TripManagement = () => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
    <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <h3 className="section-title"><Route size={24} /> Trip Execution & History</h3>
      <div className="filter-group">
         <div className="search-box glass" style={{ width: '250px' }}>
            <Search size={16} />
            <input type="text" placeholder="Search trips..." />
         </div>
      </div>
    </header>

    <div className="stats-bar">
       <Card title="Total Trips" value="1,420" icon={History} color="var(--accent-cyan)" />
       <Card title="Active" value="12" icon={Activity} color="var(--accent-green)" />
       <Card title="Completed" value="1,380" icon={CheckCircle2} color="var(--accent-cyan)" />
       <Card title="Cancelled" value="28" icon={XCircle} color="var(--alert-red)" />
       <Card title="Avg Dist" value="8.4 km" icon={Map} color="var(--text-secondary)" />
       <Card title="Avg Time" value="22 min" icon={Clock} color="var(--accent-cyan)" />
    </div>

    <Card>
       <div className="table-container">
          <table>
             <thead>
                <tr>
                   <th>Trip ID</th>
                   <th>Patient / Vitals</th>
                   <th>Vehicle & Crew</th>
                   <th>Timeline</th>
                   <th>Status</th>
                   <th style={{ textAlign: 'right' }}>ePCR</th>
                </tr>
             </thead>
             <tbody>
                {[1,2,3,4,5].map(i => (
                  <tr key={i}>
                     <td>
                        <div className="mono" style={{ fontWeight: 800, color: 'var(--accent-cyan)' }}>#TRP-4420{i}</div>
                        <div style={{ fontSize: '0.65rem', color: 'var(--text-secondary)' }}>INC-9921-X</div>
                     </td>
                     <td>
                        <div style={{ fontWeight: 700 }}>Mrs. Selvi (45F)</div>
                        <div style={{ display: 'flex', gap: '8px', marginTop: '4px' }}>
                           <span className="tag tag-ALS" style={{ fontSize: '0.6rem' }}>Critical</span>
                           <span style={{ fontSize: '0.7rem', color: 'var(--accent-green)' }}>BP: 120/80</span>
                        </div>
                     </td>
                     <td>
                        <div style={{ fontWeight: 600 }}>TN-01-AM-1024</div>
                        <div style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Pilot: Dinesh | EMT: Bala</div>
                     </td>
                     <td>
                        <div style={{ fontSize: '0.8rem' }}>14:20 - 15:05</div>
                        <div style={{ fontSize: '0.65rem', color: 'var(--text-secondary)' }}>45 mins duration</div>
                     </td>
                     <td>
                        <div className="status-indicator">
                           <div className="status-pulse" style={{ background: 'var(--accent-green)' }} />
                           <span style={{ fontSize: '0.75rem', fontWeight: 700 }}>COMPLETED</span>
                        </div>
                     </td>
                     <td style={{ textAlign: 'right' }}>
                        <button className="btn-ghost-sm"><FileText size={14} /> VIEW</button>
                     </td>
                  </tr>
                ))}
             </tbody>
          </table>
       </div>
    </Card>
  </div>
);

const GPSTelematics: React.FC<{ vehicles: FleetVehicle[] }> = ({ vehicles }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
    <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <h3 className="section-title"><Zap size={24} /> Advanced Telematics (Letstrack)</h3>
      <button className="btn-secondary"><HardDrive size={18} /> EXPORT TELEMETRY</button>
    </header>

    <div style={{ display: 'grid', gridTemplateColumns: '1fr 350px', gap: '24px' }}>
       <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
          <LiveLeafletMap vehicles={vehicles} selectedId="V001" />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '16px' }}>
             <Card>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                   <Fuel size={20} color="var(--accent-cyan)" />
                   <div>
                      <div className="mono" style={{ fontSize: '1.2rem', fontWeight: 800 }}>68.4 L</div>
                      <div style={{ fontSize: '0.6rem', color: 'var(--text-secondary)' }}>AVG CONSUMPTION</div>
                   </div>
                </div>
             </Card>
             <Card>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                   <Gauge size={20} color="var(--accent-cyan)" />
                   <div>
                      <div className="mono" style={{ fontSize: '1.2rem', fontWeight: 800 }}>12m 4s</div>
                      <div style={{ fontSize: '0.6rem', color: 'var(--text-secondary)' }}>AVG IDLE TIME</div>
                   </div>
                </div>
             </Card>
             <Card>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                   <Thermometer size={20} color="var(--alert-red)" />
                   <div>
                      <div className="mono" style={{ fontSize: '1.2rem', fontWeight: 800 }}>88° C</div>
                      <div style={{ fontSize: '0.6rem', color: 'var(--text-secondary)' }}>COOLANT TEMP</div>
                   </div>
                </div>
             </Card>
             <Card>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                   <Wind size={20} color="var(--accent-green)" />
                   <div>
                      <div className="mono" style={{ fontSize: '1.2rem', fontWeight: 800 }}>Active</div>
                      <div style={{ fontSize: '0.6rem', color: 'var(--text-secondary)' }}>A/C USAGE TRACKER</div>
                   </div>
                </div>
             </Card>
          </div>
       </div>

       <Card title="Security & Alerts">
          <div className="alert-list">
             <div className="alert-item warning">
                <Gauge size={18} />
                <div className="alert-content">
                   <div className="alert-title">Over-speed Detected</div>
                   <div className="alert-desc">V-102: 95km/h in 60km/h zone.</div>
                   <div className="time">5m ago • OMR Road</div>
                </div>
             </div>
             <div className="alert-item danger">
                <MapPin size={18} />
                <div className="alert-content">
                   <div className="alert-title">Geo-fence Breach</div>
                   <div className="alert-desc">V-088 exited "Central Zone".</div>
                   <div className="time">12m ago • Port Area</div>
                </div>
             </div>
             <div style={{ marginTop: '20px', borderTop: '1px solid var(--card-border)', paddingTop: '20px' }}>
                <h4 style={{ fontSize: '0.75rem', marginBottom: '12px' }}>ANTI-THEFT CONTROL</h4>
                <button className="btn-primary" style={{ width: '100%', background: 'var(--alert-red)', color: '#fff' }}>
                   REMOTE ENGINE CUT
                </button>
             </div>
          </div>
       </Card>
    </div>
  </div>
);

const ReferralNetwork = () => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
    <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <h3 className="section-title"><Link2 size={24} /> Referral Network Setup</h3>
      <button className="btn-primary"><Plus size={18} /> ADD PARTNER</button>
    </header>

    <div className="stations-grid">
       {[
         { name: 'Apollo Main Hospital', type: 'Tertiary Care', contact: 'Dr. Srinivas', phone: '+91 99000 11223' },
         { name: 'SRM Medical College', type: 'Teaching Hospital', contact: 'Mr. Adesh', phone: '+91 99000 44556' },
         { name: 'City Mortuary East', type: 'Mortuary', contact: 'In-charge', phone: '+91 99000 77889' }
       ].map((p, i) => (
         <Card key={i} title={p.name} subtitle={p.type}>
            <div className="stat" style={{ marginTop: '16px' }}>
               <User size={14} color="var(--accent-cyan)" />
               <span>Coord: {p.contact}</span>
            </div>
            <div className="stat" style={{ marginTop: '8px' }}>
               <Phone size={14} color="var(--accent-cyan)" />
               <span>{p.phone}</span>
            </div>
            <div style={{ marginTop: '20px', display: 'flex', gap: '8px' }}>
               <button className="btn-ghost-sm" style={{ flex: 1 }}>PROTOCOLS</button>
               <button className="btn-ghost-sm" style={{ flex: 1 }}>HISTORY</button>
            </div>
         </Card>
       ))}
    </div>
  </div>
);

const FleetReports = () => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
   <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <h3 className="section-title"><BarChart3 size={24} /> Fleet Intelligence & Reports</h3>
      <div style={{ display: 'flex', gap: '12px' }}>
         <button className="btn-secondary"><Calendar size={18} /> LAST 30 DAYS</button>
         <button className="btn-primary"><Download size={18} /> EXCEL</button>
      </div>
    </header>

    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '24px' }}>
       <Card title="Utilisation Rate">
          <div className="placeholder-viz" style={{ height: '200px' }}>
             <Activity size={48} color="var(--accent-green)" />
             <div style={{ fontSize: '2rem', fontWeight: 900 }}>88.4%</div>
             <div style={{ color: 'var(--text-secondary)' }}>Avg Daily Fleet Usage</div>
          </div>
       </Card>
       <Card title="Response SLA (m)">
          <div className="placeholder-viz" style={{ height: '200px' }}>
             <Clock size={48} color="var(--accent-cyan)" />
             <div style={{ fontSize: '2rem', fontWeight: 900 }}>11.2m</div>
             <div style={{ color: 'var(--text-secondary)' }}>Avg Response Time</div>
          </div>
       </Card>
       <Card title="Revenue / Unit">
          <div className="placeholder-viz" style={{ height: '200px' }}>
             <CreditCard size={48} color="var(--warning-amber)" />
             <div style={{ fontSize: '2rem', fontWeight: 900 }}>₹ 4.2k</div>
             <div style={{ color: 'var(--text-secondary)' }}>Daily Avg per Vehicle</div>
          </div>
       </Card>
    </div>

    <Card title="Response Time Trend">
       <div style={{ height: '250px', background: 'rgba(0,0,0,0.2)', borderRadius: '12px', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-around', padding: '20px' }}>
          {[60, 45, 80, 55, 90, 70, 85, 40, 65, 50, 75, 95].map((h, i) => (
            <div key={i} style={{ width: '20px', height: `${h}%`, background: 'var(--accent-cyan)', opacity: 0.3 + (h/150), borderRadius: '4px 4px 0 0' }} />
          ))}
       </div>
    </Card>
  </div>
);

const AttendanceModule: React.FC<{ onStartShift: () => void }> = ({ onStartShift }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
    <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <h3 className="section-title"><ClipboardList size={24} /> Attendance & Duty Management</h3>
      <div style={{ display: 'flex', gap: '12px' }}>
         <button className="btn-secondary"><CheckCircle2 size={18} /> MARK DAILY ROLL</button>
         <button className="btn-primary" onClick={onStartShift}><Zap size={18} /> START SHIFT</button>
      </div>
    </header>

    <Card>
       <div className="table-container">
          <table>
             <thead>
                <tr>
                   <th>Staff Name</th>
                   <th>Role</th>
                   <th>Shift</th>
                   <th>Status</th>
                   <th>Log-in Time</th>
                   <th>Log-out Time</th>
                </tr>
             </thead>
             <tbody>
                {[1,2,3,4,5].map(i => (
                  <tr key={i}>
                     <td>Arun Kumar {i}</td>
                     <td>Pilot</td>
                     <td>08:00 - 20:00</td>
                     <td><span className="badge" style={{ background: 'var(--accent-green)', color: '#000' }}>PRESENT</span></td>
                     <td className="mono">07:54 AM</td>
                     <td className="mono">--:--</td>
                  </tr>
                ))}
             </tbody>
          </table>
       </div>
    </Card>
  </div>
);

// --- FORMS & MODALS ---

const FormField: React.FC<{ 
  label: string; 
  name?: string;
  value?: string | number;
  onChange?: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => void;
  type?: string; 
  placeholder?: string; 
  fullWidth?: boolean;
  required?: boolean;
  autoComplete?: string;
  icon?: any;
}> = ({ label, name, value, onChange, type = 'text', placeholder, fullWidth, required, autoComplete = 'off', icon: Icon }) => {
  const [showPassword, setShowPassword] = useState(false);
  const isPassword = type === 'password';
  const inputType = isPassword ? (showPassword ? 'text' : 'password') : type;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '6px', flex: fullWidth ? '1 1 100%' : '1 1 200px', position: 'relative' }}>
      <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase', display: 'flex', justifyContent: 'space-between', alignItems: 'center', letterSpacing: '0.05em' }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
          {Icon && <Icon size={12} color="var(--accent-cyan)" />}
          {label}
        </span>
        {value && String(value).length > 0 && <CheckCircle2 size={12} color="var(--accent-green)" />}
      </label>
      <div style={{ position: 'relative' }}>
        <input 
          name={name}
          type={inputType} 
          value={value}
          onChange={onChange}
          required={required}
          placeholder={placeholder} 
          autoComplete={autoComplete}
          className="glass" 
          style={{ 
            padding: Icon ? (isPassword ? '12px 40px 12px 40px' : '12px 14px 12px 40px') : (isPassword ? '12px 40px 12px 14px' : '12px 14px'), 
            background: 'rgba(255,255,255,0.02)', 
            border: '1px solid rgba(255,255,255,0.08)', 
            borderRadius: '10px', 
            color: '#fff',
            outline: 'none',
            fontSize: '0.9rem',
            width: '100%',
            transition: 'all 0.2s',
            boxShadow: 'inset 0 1px 2px rgba(0,0,0,0.2)'
          }} 
        />
        {Icon && (
          <div style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', opacity: 0.5, color: 'var(--accent-cyan)' }}>
            <Icon size={18} />
          </div>
        )}
        {isPassword && (
          <button 
            type="button"
            onClick={() => setShowPassword(!showPassword)}
            style={{ 
              position: 'absolute', 
              right: '12px', 
              top: '50%', 
              transform: 'translateY(-50%)', 
              background: 'none', 
              border: 'none', 
              color: 'var(--accent-cyan)', 
              cursor: 'pointer',
              opacity: 0.7,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              padding: '4px',
              transition: 'opacity 0.2s'
            }}
            onMouseEnter={(e) => e.currentTarget.style.opacity = '1'}
            onMouseLeave={(e) => e.currentTarget.style.opacity = '0.7'}
          >
            {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
          </button>
        )}
      </div>
    </div>
  );
};

const VehicleRegistrationForm: React.FC<{ 
  organisationId: string;
  onSubmit: (data: any) => void;
  loading?: boolean;
  initialData?: any;
}> = ({ organisationId, onSubmit, loading, initialData }) => {
  const [stations, setStations] = useState<any[]>([]);
  const [fetchingStations, setFetchingStations] = useState(false);
  const [formData, setFormData] = useState({
    registration_number: initialData?.registration_number || '',
    brand: initialData?.brand || '',
    model: initialData?.model || '',
    make_year: initialData?.make_year || new Date().getFullYear(),
    vehicle_type: initialData?.vehicle_type || 'ALS',
    stretcher_capacity: initialData?.stretcher_capacity || 1,
    ownership_type: initialData?.ownership_type || 'OWNED',
    status: initialData?.status || 'AVAILABLE',
    isActive: initialData?.isActive ?? true,
    gps_lat: initialData?.gps_lat ? parseFloat(initialData.gps_lat) : 13.0827,
    gps_lon: initialData?.gps_lon ? parseFloat(initialData.gps_lon) : 80.2707,
    station_id: initialData?.station_id || '',
    organisationId: organisationId,
    id: initialData?.id || initialData?._id || undefined
  });

  // Sync form data when editing a different vehicle or resetting
  useEffect(() => {
    if (initialData) {
      setFormData({
        registration_number: initialData.registration_number || '',
        brand: initialData.brand || '',
        model: initialData.model || '',
        make_year: initialData.make_year || new Date().getFullYear(),
        vehicle_type: initialData.vehicle_type || 'ALS',
        stretcher_capacity: initialData.stretcher_capacity || 1,
        ownership_type: initialData.ownership_type || 'OWNED',
        status: initialData.status || 'AVAILABLE',
        isActive: initialData.isActive ?? true,
        gps_lat: initialData.gps_lat ? parseFloat(initialData.gps_lat) : 13.0827,
        gps_lon: initialData.gps_lon ? parseFloat(initialData.gps_lon) : 80.2707,
        station_id: initialData.station_id || '',
        organisationId: organisationId,
        id: initialData.id || initialData._id || undefined
      });
    }
  }, [initialData, organisationId]);

  useEffect(() => {
    const fetchStations = async () => {
      if (!organisationId) return;
      setFetchingStations(true);
      try {
        const token = localStorage.getItem('teleems_token') || '';
        const res = await fleetApi.getStations(token, organisationId);
        let stationArr = res.data?.data || (Array.isArray(res.data) ? res.data : []);
        if (Array.isArray(stationArr)) {
          stationArr = stationArr.filter((s: any) => s.organisationId === organisationId);
          setStations(stationArr);
        }
      } catch (err) {
        console.error('Failed to fetch stations for vehicle form:', err);
      } finally {
        setFetchingStations(false);
      }
    };
    fetchStations();
  }, [organisationId]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'number' ? parseFloat(value) : value
    }));
  };

  const handleFormSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit(formData);
  };

  const handleLocationSelect = (lat: number, lng: number) => {
    setFormData(prev => ({
      ...prev,
      gps_lat: parseFloat(lat.toFixed(7)),
      gps_lon: parseFloat(lng.toFixed(7))
    }));
  };

  return (
   <form id="vehicle-reg-form" onSubmit={handleFormSubmit} style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '24px' }}>
      <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
        <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Truck size={20} color="var(--accent-cyan)" />
        </div>
        <div>
          <h4 style={{ margin: 0, color: '#fff', fontSize: '1.1rem', fontWeight: 800 }}>Basic Identity & Specs</h4>
          <p style={{ margin: 0, fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Core registration and mechanical details.</p>
        </div>
      </div>

      <FormField icon={CreditCard} label="Vehicle Number" name="registration_number" value={formData.registration_number} onChange={handleChange} required placeholder="e.g. MH-18-AB-1234" />
      <FormField icon={Package} label="Brand" name="brand" value={formData.brand} onChange={handleChange} required placeholder="e.g. Force Motors" />
      <FormField icon={Activity} label="Model" name="model" value={formData.model} onChange={handleChange} required placeholder="e.g. Traveller" />
      <FormField icon={Calendar} label="Make Year" name="make_year" type="number" value={formData.make_year} onChange={handleChange} required placeholder="2023" />
      
      <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase', display: 'flex', alignItems: 'center', gap: '6px', letterSpacing: '0.05em' }}>
          <Zap size={12} color="var(--accent-cyan)" />
          Vehicle Type
        </label>
        <div style={{ position: 'relative' }}>
          <select 
            name="vehicle_type"
            value={formData.vehicle_type}
            onChange={handleChange}
            className="glass" 
            style={{ padding: '12px 14px 12px 40px', background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '10px', color: '#fff', outline: 'none', fontSize: '0.9rem', width: '100%', cursor: 'pointer', appearance: 'none' }}
          >
            <option value="ALS" style={{ background: '#0F172A' }}>ALS (Advanced Life Support)</option>
            <option value="BLS" style={{ background: '#0F172A' }}>BLS (Basic Life Support)</option>
            <option value="TRANSFER" style={{ background: '#0F172A' }}>TRANSFER (Patient Transport)</option>
            <option value="MORTUARY" style={{ background: '#0F172A' }}>MORTUARY (Hearse)</option>
            <option value="AIR" style={{ background: '#0F172A' }}>AIR AMBULANCE</option>
            <option value="NEO" style={{ background: '#0F172A' }}>NEONATAL (NICU)</option>
            <option value="SUPPORT" style={{ background: '#0F172A' }}>SUPPORT VEHICLE</option>
            <option value="RECON" style={{ background: '#0F172A' }}>QUICK RESPONSE (QRV)</option>
          </select>
          <Zap size={18} style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', opacity: 0.5, color: 'var(--accent-cyan)' }} />
          <ChevronRight size={14} style={{ position: 'absolute', right: '12px', top: '50%', transform: 'translateY(-50%) rotate(90deg)', opacity: 0.5 }} />
        </div>
      </div>

      <FormField icon={Users} label="Stretcher Capacity" name="stretcher_capacity" type="number" value={formData.stretcher_capacity} onChange={handleChange} required placeholder="1" />
      
      <div style={{ gridColumn: '1 / -1', height: '1px', background: 'linear-gradient(90deg, rgba(59, 130, 246, 0.2) 0%, transparent 100%)', margin: '12px 0' }} />

      <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
        <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Settings size={20} color="var(--accent-cyan)" />
        </div>
        <div>
          <h4 style={{ margin: 0, color: '#fff', fontSize: '1.1rem', fontWeight: 800 }}>Operational Config</h4>
          <p style={{ margin: 0, fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Status, ownership and station mapping.</p>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase', display: 'flex', alignItems: 'center', gap: '6px', letterSpacing: '0.05em' }}>
          <ShieldCheck size={12} color="var(--accent-cyan)" />
          Ownership Type
        </label>
        <div style={{ position: 'relative' }}>
          <select 
            name="ownership_type"
            value={formData.ownership_type}
            onChange={handleChange}
            className="glass" 
            style={{ padding: '12px 14px 12px 40px', background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '10px', color: '#fff', outline: 'none', fontSize: '0.9rem', width: '100%', cursor: 'pointer', appearance: 'none' }}
          >
            <option value="OWNED" style={{ background: '#0F172A' }}>OWNED</option>
            <option value="LEASED" style={{ background: '#0F172A' }}>LEASED</option>
            <option value="RENTED" style={{ background: '#0F172A' }}>RENTED</option>
            <option value="THIRD_PARTY" style={{ background: '#0F172A' }}>THIRD PARTY</option>
          </select>
          <ShieldCheck size={18} style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', opacity: 0.5, color: 'var(--accent-cyan)' }} />
          <ChevronRight size={14} style={{ position: 'absolute', right: '12px', top: '50%', transform: 'translateY(-50%) rotate(90deg)', opacity: 0.5 }} />
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase', display: 'flex', alignItems: 'center', gap: '6px', letterSpacing: '0.05em' }}>
          <Building2 size={12} color="var(--accent-cyan)" />
          Assigned Station
        </label>
        <div style={{ position: 'relative' }}>
          <select 
            name="station_id"
            value={formData.station_id}
            onChange={handleChange}
            required
            className="glass" 
            style={{ padding: '12px 14px 12px 40px', background: 'rgba(59, 130, 246, 0.01)', border: '1px solid rgba(59, 130, 246, 0.2)', borderRadius: '10px', color: '#fff', outline: 'none', fontSize: '0.9rem', width: '100%', cursor: fetchingStations ? 'wait' : 'pointer', appearance: 'none' }}
            disabled={fetchingStations}
          >
            <option value="" style={{ background: '#0F172A' }}>{fetchingStations ? 'Fetching...' : 'Select Station'}</option>
            {stations.map(s => (
              <option key={s.id} value={s.id} style={{ background: '#0F172A' }}>{s.name}</option>
            ))}
          </select>
          <Building2 size={18} style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', opacity: 0.5, color: 'var(--accent-cyan)' }} />
          <ChevronRight size={14} style={{ position: 'absolute', right: '12px', top: '50%', transform: 'translateY(-50%) rotate(90deg)', opacity: 0.5 }} />
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase', display: 'flex', alignItems: 'center', gap: '6px', letterSpacing: '0.05em' }}>
          <Activity size={12} color="var(--accent-cyan)" />
          Status
        </label>
        <div style={{ position: 'relative' }}>
          <select 
            name="status"
            value={formData.status}
            onChange={handleChange}
            className="glass" 
            style={{ padding: '12px 14px 12px 40px', background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '10px', color: '#fff', outline: 'none', fontSize: '0.9rem', width: '100%', cursor: 'pointer', appearance: 'none' }}
          >
            <option value="AVAILABLE" style={{ background: '#0F172A' }}>AVAILABLE</option>
            <option value="BUSY" style={{ background: '#0F172A' }}>BUSY / ON TRIP</option>
            <option value="MAINTENANCE" style={{ background: '#0F172A' }}>MAINTENANCE</option>
            <option value="OFF_DUTY" style={{ background: '#0F172A' }}>OFF DUTY</option>
          </select>
          <Activity size={18} style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', opacity: 0.5, color: 'var(--accent-cyan)' }} />
          <ChevronRight size={14} style={{ position: 'absolute', right: '12px', top: '50%', transform: 'translateY(-50%) rotate(90deg)', opacity: 0.5 }} />
        </div>
      </div>

      <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '12px', marginTop: '12px', marginBottom: '8px' }}>
        <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <MapPin size={20} color="var(--accent-cyan)" />
        </div>
        <div>
          <h4 style={{ margin: 0, color: '#fff', fontSize: '1.1rem', fontWeight: 800 }}>GPS Metadata</h4>
          <p style={{ margin: 0, fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Initial tracking coordinates.</p>
        </div>
      </div>

      <div style={{ gridColumn: '1 / -1', display: 'flex', flexWrap: 'wrap', gap: '24px' }}>
        <div style={{ flex: '1 1 250px', display: 'flex', flexDirection: 'column', gap: '16px' }}>
          <FormField icon={MapPin} label="Latitude" name="gps_lat" type="number" value={formData.gps_lat} onChange={handleChange} required placeholder="18.5204" />
          <FormField icon={Navigation} label="Longitude" name="gps_lon" type="number" value={formData.gps_lon} onChange={handleChange} required placeholder="73.8567" />
          <p style={{ fontSize: '0.7rem', color: 'var(--text-secondary)', background: 'rgba(59, 130, 246, 0.05)', padding: '12px', borderRadius: '8px', border: '1px solid rgba(59, 130, 246, 0.1)' }}>
            <strong>TIP:</strong> You can click anywhere on the map to automatically set the vehicle's initial deployment coordinates.
          </p>
        </div>
        <div style={{ flex: '1 1 350px' }}>
          <LocationPickerMap 
            lat={formData.gps_lat} 
            lng={formData.gps_lon} 
            onLocationSelect={handleLocationSelect} 
          />
        </div>
      </div>
   </form>
  );
};

const StaffRegistrationForm: React.FC<{ 
  type: 'DRIVER' | 'EMT' | 'DOCTOR'; 
  onSubmit: (data: any) => void;
  loading?: boolean;
}> = ({ type, onSubmit, loading }) => {
  const getInitialProfessionalDetails = () => {
    if (type === 'DRIVER') {
      return { license_number: '', license_category: '', license_expiry: '' };
    }
    if (type === 'EMT') {
      return { 
        qualification: '', 
        certification_body: '', 
        certificate_number: '', 
        certificate_expiry: '' 
      };
    }
    if (type === 'DOCTOR') {
      return {
        medical_registration_number: '',
        specialization: '',
        qualification: '',
        teleconsult_available: true
      };
    }
    return {};
  };

  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    password: '',
    type: type,
    aadhaar_number: '',
    professional_details: getInitialProfessionalDetails() as any
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value, type: inputType, checked } = e.target as HTMLInputElement;
    
    // Handle nested professional_details
    if (name.startsWith('pd_')) {
      const field = name.replace('pd_', '');
      setFormData(prev => ({
        ...prev,
        professional_details: {
          ...prev.professional_details,
          [field]: inputType === 'checkbox' ? checked : value
        }
      }));
    } else {
      setFormData(prev => ({
        ...prev,
        [name]: value
      }));
    }
  };

  const handleFormSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit(formData);
  };

  return (
   <form id="staff-reg-form" autoComplete="off" onSubmit={handleFormSubmit} style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '24px' }}>
      <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
        <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <User size={20} color="var(--accent-cyan)" />
        </div>
        <div>
          <h4 style={{ margin: 0, color: '#fff', fontSize: '1.1rem', fontWeight: 800 }}>Personal Data</h4>
          <p style={{ margin: 0, fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Identify and contact details for {type}.</p>
        </div>
      </div>

      <FormField icon={User} label="Full Name" name="name" value={formData.name} onChange={handleChange} required placeholder={type === 'DOCTOR' ? 'Dr. Amit Sharma' : (type === 'EMT' ? 'Sarah Williams' : 'Arun Kumar')} autoComplete="off" />
      <FormField icon={Phone} label="Phone Number" name="phone" value={formData.phone} onChange={handleChange} required placeholder="+91-9008500003" autoComplete="tel" />
      <FormField icon={ShieldCheck} label="Password" name="password" type="password" value={formData.password} onChange={handleChange} required placeholder="••••••••" autoComplete="new-password" />
      <FormField icon={Fingerprint} label="Aadhaar Number" name="aadhaar_number" value={formData.aadhaar_number} onChange={handleChange} required placeholder="1234-5678-9003" autoComplete="off" />

      <div style={{ gridColumn: '1 / -1', height: '1px', background: 'linear-gradient(90deg, rgba(59, 130, 246, 0.2) 0%, transparent 100%)', margin: '12px 0' }} />

      <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
        <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Briefcase size={20} color="var(--accent-cyan)" />
        </div>
        <div>
          <h4 style={{ margin: 0, color: '#fff', fontSize: '1.1rem', fontWeight: 800 }}>Professional Credentials</h4>
          <p style={{ margin: 0, fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Licensing and certifications for {type}.</p>
        </div>
      </div>

      {type === 'DRIVER' && (
        <>
          <FormField icon={Award} label="License Number" name="pd_license_number" value={formData.professional_details.license_number} onChange={handleChange} required placeholder="DL-KA-2024-DR1" />
          <FormField icon={Activity} label="License Category" name="pd_license_category" value={formData.professional_details.license_category} onChange={handleChange} required placeholder="MCWG/LMV" />
          <FormField icon={Calendar} label="License Expiry" name="pd_license_expiry" type="date" value={formData.professional_details.license_expiry} onChange={handleChange} required />
        </>
      )}

      {type === 'EMT' && (
        <>
          <FormField icon={Award} label="Qualification" name="pd_qualification" value={formData.professional_details.qualification} onChange={handleChange} required placeholder="B.Sc Paramedicine" />
          <FormField icon={Building2} label="Certification Body" name="pd_certification_body" value={formData.professional_details.certification_body} onChange={handleChange} required placeholder="National Health Academy" />
          <FormField icon={Hash} label="Certificate Number" name="pd_certificate_number" value={formData.professional_details.certificate_number} onChange={handleChange} required placeholder="EMT-CERT-8899" />
          <FormField icon={Calendar} label="Certificate Expiry" name="pd_certificate_expiry" type="date" value={formData.professional_details.certificate_expiry} onChange={handleChange} required />
        </>
      )}

      {type === 'DOCTOR' && (
        <>
          <FormField icon={Award} label="Medical Reg. Number" name="pd_medical_registration_number" value={formData.professional_details.medical_registration_number} onChange={handleChange} required placeholder="MCI/DMC/2024/77" />
          <FormField icon={Stethoscope} label="Specialization" name="pd_specialization" value={formData.professional_details.specialization} onChange={handleChange} required placeholder="Emergency Medicine / Trauma" />
          <FormField icon={Award} label="Qualification" name="pd_qualification" value={formData.professional_details.qualification} onChange={handleChange} required placeholder="MBBS, MD (Emergency)" />
          <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
            <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase', display: 'flex', alignItems: 'center', gap: '6px' }}>
              <Globe size={12} color="var(--accent-cyan)" />
              Teleconsultation
            </label>
            <div className="glass" style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '10px 14px', borderRadius: '10px', background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)' }}>
              <input 
                type="checkbox" 
                name="pd_teleconsult_available" 
                checked={formData.professional_details.teleconsult_available} 
                onChange={handleChange}
                style={{ width: '18px', height: '18px', cursor: 'pointer', accentColor: 'var(--accent-cyan)' }} 
              />
              <span style={{ fontSize: '0.9rem', color: '#fff' }}>Available for Tele-consult</span>
            </div>
          </div>
        </>
      )}
      
      <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase', display: 'flex', alignItems: 'center', gap: '6px', letterSpacing: '0.05em' }}>
          <Zap size={12} color="var(--accent-cyan)" />
          Staff Type
        </label>
        <div style={{ position: 'relative' }}>
          <input 
            className="glass" 
            value={type}
            disabled
            style={{ padding: '12px 14px 12px 40px', background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '10px', color: '#fff', outline: 'none', fontSize: '0.9rem', width: '100%', opacity: 0.6 }}
          />
          <Zap size={18} style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', opacity: 0.5, color: 'var(--accent-cyan)' }} />
        </div>
      </div>
   </form>
  );
};
// --- ROSTER & SHIFT FORMS ---

const RosterForm: React.FC<{ 
  vehicles: any[]; 
  staff: any[]; 
  onSubmit: (data: any) => void;
  loading?: boolean;
}> = ({ vehicles, staff, onSubmit, loading }) => {
  const [formData, setFormData] = useState({
    vehicleId: '',
    driverId: '',
    staffId: '',
    startDate: '',
    endDate: '',
    shiftType: 'DAY',
    notes: ''
  });

  const drivers = staff.filter(s => s.type === 'DRIVER');
  const medicalStaff = staff.filter(s => s.type === 'EMT' || s.type === 'DOCTOR');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    setFormData(prev => ({ ...prev, [e.target.name]: e.target.value }));
  };

  return (
    <form id="roster-form" onSubmit={(e) => { e.preventDefault(); onSubmit(formData); }} style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '24px' }}>
      <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
        <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Calendar size={20} color="var(--accent-cyan)" />
        </div>
        <div>
          <h4 style={{ margin: 0, color: '#fff', fontSize: '1.1rem', fontWeight: 800 }}>Weekly Assignment</h4>
          <p style={{ margin: 0, fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Map crew to vehicles for a specific period.</p>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Vehicle</label>
        <select 
          name="vehicleId" 
          value={formData.vehicleId} 
          onChange={handleChange} 
          required 
          className="glass"
          style={{ padding: '12px', background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '10px', color: '#fff', outline: 'none' }}
        >
          <option value="" style={{ background: '#0F172A' }}>Select Vehicle</option>
          {vehicles.map(v => <option key={v.id} value={v.id} style={{ background: '#0F172A' }}>{v.registration_number} ({v.brand} {v.model})</option>)}
        </select>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Pilot / Driver</label>
        <select 
          name="driverId" 
          value={formData.driverId} 
          onChange={handleChange} 
          required 
          className="glass"
          style={{ padding: '12px', background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '10px', color: '#fff', outline: 'none' }}
        >
          <option value="" style={{ background: '#0F172A' }}>Select Driver</option>
          {drivers.map(d => <option key={d.id} value={d.id} style={{ background: '#0F172A' }}>{d.user?.name || d.name}</option>)}
        </select>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Medical Staff (EMT/Doc)</label>
        <select 
          name="staffId" 
          value={formData.staffId} 
          onChange={handleChange} 
          required 
          className="glass"
          style={{ padding: '12px', background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '10px', color: '#fff', outline: 'none' }}
        >
          <option value="" style={{ background: '#0F172A' }}>Select Staff Member</option>
          {medicalStaff.map(s => <option key={s.id} value={s.id} style={{ background: '#0F172A' }}>{s.user?.name || s.name} - {s.type}</option>)}
        </select>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Shift Type</label>
        <select 
          name="shiftType" 
          value={formData.shiftType} 
          onChange={handleChange} 
          required 
          className="glass"
          style={{ padding: '12px', background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '10px', color: '#fff', outline: 'none' }}
        >
          <option value="DAY" style={{ background: '#0F172A' }}>DAY SHIFT</option>
          <option value="NIGHT" style={{ background: '#0F172A' }}>NIGHT SHIFT</option>
        </select>
      </div>

      <FormField icon={Calendar} label="Start Date" name="startDate" type="date" value={formData.startDate} onChange={handleChange} required />
      <FormField icon={Calendar} label="End Date" name="endDate" type="date" value={formData.endDate} onChange={handleChange} required />

      <div style={{ gridColumn: '1 / -1', display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Assignment Notes</label>
        <textarea 
          name="notes" 
          value={formData.notes} 
          onChange={handleChange} 
          placeholder="e.g. Testing Weekly Assignment"
          className="glass"
          style={{ width: '100%', minHeight: '80px', background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '10px', color: '#fff', padding: '12px', outline: 'none', fontSize: '0.9rem' }}
        />
      </div>
    </form>
  );
};

const ShiftStartForm: React.FC<{ 
  vehicles: any[]; 
  staff: any[]; 
  onSubmit: (data: any) => void;
  loading?: boolean;
}> = ({ vehicles, staff, onSubmit, loading }) => {
  const [formData, setFormData] = useState({
    vehicleId: '',
    driverId: '',
    staffId: '',
    checklist: {
      oxygen: 'FULL',
      fuel: 'FULL',
      stretcher: 'CLEAN',
      monitor: 'OPERATIONAL'
    }
  });

  const drivers = staff.filter(s => s.type === 'DRIVER');
  const medicalStaff = staff.filter(s => s.type === 'EMT' || s.type === 'DOCTOR');

  const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setFormData(prev => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleChecklistChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      checklist: { ...prev.checklist, [field]: value }
    }));
  };

  return (
    <form id="shift-start-form" onSubmit={(e) => { e.preventDefault(); onSubmit(formData); }} style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '24px' }}>
      <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
        <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Zap size={20} color="var(--accent-cyan)" />
        </div>
        <div>
          <h4 style={{ margin: 0, color: '#fff', fontSize: '1.1rem', fontWeight: 800 }}>Start Duty Shift</h4>
          <p style={{ margin: 0, fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Verify readiness and initialize live telemetry.</p>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Vehicle</label>
        <select 
          name="vehicleId" 
          value={formData.vehicleId} 
          onChange={handleChange} 
          required 
          className="glass"
          style={{ padding: '12px', background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '10px', color: '#fff', outline: 'none' }}
        >
          <option value="" style={{ background: '#0F172A' }}>Select Vehicle</option>
          {vehicles.map(v => <option key={v.id} value={v.id} style={{ background: '#0F172A' }}>{v.registration_number}</option>)}
        </select>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Pilot</label>
        <select 
          name="driverId" 
          value={formData.driverId} 
          onChange={handleChange} 
          required 
          className="glass"
          style={{ padding: '12px', background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '10px', color: '#fff', outline: 'none' }}
        >
          <option value="" style={{ background: '#0F172A' }}>Select Pilot</option>
          {drivers.map(d => <option key={d.id} value={d.id} style={{ background: '#0F172A' }}>{d.user?.name || d.name}</option>)}
        </select>
      </div>

      <div style={{ gridColumn: '1 / -1', display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase' }}>Medical Staff On-board</label>
        <select 
          name="staffId" 
          value={formData.staffId} 
          onChange={handleChange} 
          required 
          className="glass"
          style={{ padding: '12px', background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '10px', color: '#fff', outline: 'none' }}
        >
          <option value="" style={{ background: '#0F172A' }}>Select Staff Member</option>
          {medicalStaff.map(s => <option key={s.id} value={s.id} style={{ background: '#0F172A' }}>{s.user?.name || s.name} ({s.type})</option>)}
        </select>
      </div>

      <div style={{ gridColumn: '1 / -1', marginTop: '12px' }}>
        <h5 style={{ fontSize: '0.8rem', color: 'var(--accent-cyan)', marginBottom: '12px', textTransform: 'uppercase', letterSpacing: '0.1em' }}>Safety Checklist</h5>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
          {[
            { label: 'Oxygen Levels', field: 'oxygen', options: ['FULL', 'HALF', 'LOW', 'EMPTY'] },
            { label: 'Fuel Status', field: 'fuel', options: ['FULL', '75%', '50%', '25%'] },
            { label: 'Medical Monitor', field: 'monitor', options: ['OPERATIONAL', 'FAULTY'] },
            { label: 'Stretcher Condition', field: 'stretcher', options: ['CLEAN', 'DIRTY'] }
          ].map(item => (
            <div key={item.field} className="glass" style={{ padding: '12px', borderRadius: '10px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'rgba(255,255,255,0.03)' }}>
              <span style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', fontWeight: 600 }}>{item.label}</span>
              <select 
                value={(formData.checklist as any)[item.field]} 
                onChange={(e) => handleChecklistChange(item.field, e.target.value)} 
                className="glass"
                style={{ padding: '4px 8px', background: 'rgba(59, 130, 246, 0.1)', border: '1px solid var(--accent-cyan)', borderRadius: '6px', color: 'var(--accent-cyan)', fontSize: '0.75rem', fontWeight: 800, outline: 'none', cursor: 'pointer' }}
              >
                {item.options.map(opt => <option key={opt} value={opt} style={{ background: '#0F172A' }}>{opt}</option>)}
              </select>
            </div>
          ))}
        </div>
      </div>
    </form>
  );
};

const StationManifest: React.FC<{ 
  station: any; 
  vehicles: any[]; 
  staff: any[]; 
}> = ({ station, vehicles, staff }) => {
  const stationVehicles = vehicles.filter(v => v.station_id === station.id || v.station_name === station.name);
  
  // For demo/mock purposes, we'll assign some staff to the station
  const stationStaff = staff.slice(0, 3); 

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'rgba(59, 130, 246, 0.05)', padding: '16px', borderRadius: '12px', border: '1px solid rgba(59, 130, 246, 0.2)' }}>
        <div>
          <h4 style={{ margin: 0, fontSize: '1.2rem', color: 'var(--accent-cyan)', fontWeight: 800 }}>{station?.name?.toUpperCase()} MANIFEST</h4>
          <p style={{ margin: 0, fontSize: '0.75rem', color: 'var(--text-secondary)' }}>Daily operational readiness report.</p>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: '0.9rem', color: '#fff', fontWeight: 700 }}>{new Date().toLocaleDateString('en-IN', { weekday: 'long', day: 'numeric', month: 'short' })}</div>
          <div style={{ fontSize: '0.7rem', color: 'var(--accent-green)', textTransform: 'uppercase' }}>System Status: Online</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
        <div className="glass" style={{ padding: '20px', borderRadius: '15px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '16px' }}>
            <Truck size={20} color="var(--accent-cyan)" />
            <h5 style={{ margin: 0, fontSize: '0.9rem', textTransform: 'uppercase', letterSpacing: '0.1em' }}>Deployed Fleet ({stationVehicles.length})</h5>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
            {stationVehicles.length === 0 ? (
              <div style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', fontStyle: 'italic' }}>No vehicles currently docked.</div>
            ) : (
              stationVehicles.map(v => (
                <div key={v.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px', background: 'rgba(255,255,255,0.02)', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.05)' }}>
                  <div>
                    <div style={{ fontSize: '0.85rem', fontWeight: 700 }}>{v.registration_number}</div>
                    <div style={{ fontSize: '0.65rem', color: 'var(--text-secondary)' }}>{v.brand} {v.model}</div>
                  </div>
                  <div className="badge" style={{ fontSize: '0.6rem', background: v.status === 'AVAILABLE' ? 'rgba(0, 226, 114, 0.1)' : 'rgba(59, 130, 246, 0.1)', color: v.status === 'AVAILABLE' ? 'var(--accent-green)' : 'var(--accent-cyan)' }}>
                    {v.status}
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        <div className="glass" style={{ padding: '20px', borderRadius: '15px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '16px' }}>
            <Users size={20} color="var(--accent-cyan)" />
            <h5 style={{ margin: 0, fontSize: '0.9rem', textTransform: 'uppercase', letterSpacing: '0.1em' }}>Active Crew ({stationStaff.length})</h5>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
            {stationStaff.map(s => (
              <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '10px', background: 'rgba(255,255,255,0.02)', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.05)' }}>
                <div style={{ width: '32px', height: '32px', borderRadius: '50%', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <User size={16} color="var(--accent-cyan)" />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: '0.85rem', fontWeight: 700 }}>{s.user?.name || s.name}</div>
                  <div style={{ fontSize: '0.65rem', color: 'var(--text-secondary)' }}>{s.type} • On Call</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="glass" style={{ padding: '16px', borderRadius: '12px', background: 'rgba(255, 171, 0, 0.05)', border: '1px solid rgba(255, 171, 0, 0.2)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: 'var(--accent-amber)', fontSize: '0.8rem', fontWeight: 700, marginBottom: '4px' }}>
          <AlertTriangle size={14} /> STATION ADVISORY
        </div>
        <p style={{ margin: 0, fontSize: '0.75rem', color: 'var(--text-secondary)' }}>
          All units must perform oxygen replenishment before 14:00. Traffic congestion reported on Outer Ring Road.
        </p>
      </div>
    </div>
  );
};

const BrandRegistrationForm: React.FC<{ onSubmit: (data: any) => void; loading?: boolean }> = ({ onSubmit, loading }) => {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    password: '',
    company_name: '',
    gstin: ''
  });
  const [showPassword, setShowPassword] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleFormSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const payload = {
      role: "FLEET_OPERATOR",
      name: formData.name,
      phone: formData.phone,
      email: formData.email,
      password: formData.password,
      metadata: {
        organization: {
          company_name: formData.company_name,
          gstin: formData.gstin
        }
      }
    };
    onSubmit(payload);
  };

  return (
    <form id="brand-reg-form" autoComplete="off" onSubmit={handleFormSubmit} style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '24px' }}>
      <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
        <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <User size={20} color="var(--accent-cyan)" />
        </div>
        <div>
          <h4 style={{ margin: 0, color: '#fff', fontSize: '1.1rem', fontWeight: 800 }}>Administrator Details</h4>
          <p style={{ margin: 0, fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Primary contact and account access.</p>
        </div>
      </div>

      <FormField 
        icon={User}
        label="Full Name" 
        name="name" 
        value={formData.name} 
        onChange={handleChange} 
        required 
        placeholder="e.g. Rajesh Kumar" 
        autoComplete="off"
      />
      <FormField 
        icon={Mail}
        label="Email Address" 
        name="email" 
        type="email" 
        value={formData.email} 
        onChange={handleChange} 
        required 
        placeholder="e.g. ops@lifeline.com" 
        autoComplete="new-email"
      />
      <FormField 
        icon={Phone}
        label="Phone Number" 
        name="phone" 
        value={formData.phone} 
        onChange={handleChange} 
        required 
        placeholder="e.g. 9876543210" 
        autoComplete="off"
      />
      <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
        <label style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase', display: 'flex', justifyContent: 'space-between', letterSpacing: '0.05em' }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
            <Lock size={12} color="var(--accent-cyan)" />
            Access Password
          </span>
          {formData.password && <CheckCircle2 size={12} color="var(--accent-green)" />}
        </label>
        <div style={{ position: 'relative' }}>
          <input 
            name="password" 
            value={formData.password} 
            onChange={handleChange} 
            required 
            type={showPassword ? 'text' : 'password'} 
            placeholder="Enter secure password" 
            autoComplete="new-password"
            className="glass" 
            style={{ padding: '12px 40px 12px 40px', background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '10px', color: '#fff', outline: 'none', fontSize: '0.9rem', width: '100%', transition: 'all 0.2s' }} 
          />
          <Lock size={18} style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', opacity: 0.5, color: 'var(--accent-cyan)' }} />
          <button 
            type="button" 
            onClick={() => setShowPassword(!showPassword)}
            style={{ position: 'absolute', right: '12px', top: '50%', transform: 'translateY(-50%)', background: 'transparent', border: 'none', color: 'var(--text-secondary)', cursor: 'pointer', display: 'flex', alignItems: 'center' }}
          >
            {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
          </button>
        </div>
      </div>

      <div style={{ gridColumn: '1 / -1', height: '1px', background: 'linear-gradient(90deg, rgba(59, 130, 246, 0.2) 0%, transparent 100%)', margin: '12px 0' }} />

      <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
        <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Building2 size={20} color="var(--accent-cyan)" />
        </div>
        <div>
          <h4 style={{ margin: 0, color: '#fff', fontSize: '1.1rem', fontWeight: 800 }}>Organization Profile</h4>
          <p style={{ margin: 0, fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Business and tax identification.</p>
        </div>
      </div>

      <FormField 
        icon={Building2}
        label="Company / Organization Name" 
        name="company_name" 
        value={formData.company_name} 
        onChange={handleChange} 
        required 
        fullWidth 
        placeholder="e.g. Lifeline Ground EMS Services" 
        autoComplete="off"
      />
      <FormField 
        icon={Hash}
        label="GSTIN Number" 
        name="gstin" 
        value={formData.gstin} 
        onChange={handleChange} 
        required 
        placeholder="e.g. 33AABCL1234F1Z1" 
        autoComplete="off"
      />
    </form>
  );
};

const StationRegistrationForm: React.FC<{ 
  onSubmit: (data: any) => void; 
  loading?: boolean;
  organisationId: string;
}> = ({ onSubmit, loading, organisationId }) => {
  const [formData, setFormData] = useState({
    name: '',
    organisationId: organisationId,
    address: '',
    gps_lat: '',
    gps_lon: '',
    incharge_name: '',
    phone: ''
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleFormSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const payload = {
      ...formData,
      gps_lat: parseFloat(formData.gps_lat),
      gps_lon: parseFloat(formData.gps_lon)
    };
    onSubmit(payload);
  };

  const handleLocationSelect = (lat: number, lng: number) => {
    // Keep 7 decimal places for high precision as seen in user example
    setFormData({
      ...formData,
      gps_lat: lat.toFixed(7),
      gps_lon: lng.toFixed(7)
    });
  };

  return (
    <form id="station-reg-form" onSubmit={handleFormSubmit} style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '24px' }}>
      <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
        <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Building2 size={20} color="var(--accent-cyan)" />
        </div>
        <div>
          <h4 style={{ margin: 0, color: '#fff', fontSize: '1.1rem', fontWeight: 800 }}>Station Details</h4>
          <p style={{ margin: 0, fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Physical hub configuration.</p>
        </div>
      </div>

      <FormField 
        icon={Building2}
        label="Station Name" 
        name="name" 
        value={formData.name} 
        onChange={handleChange} 
        required 
        placeholder="e.g. Central Chennai Hub" 
      />
      <FormField 
        icon={Hash}
        label="Organisation ID" 
        name="organisationId" 
        value={formData.organisationId} 
        onChange={handleChange} 
        required 
        placeholder="Organisation ID" 
      />
      <FormField 
        icon={Phone}
        label="Contact Phone" 
        name="phone" 
        value={formData.phone} 
        onChange={handleChange} 
        required 
        placeholder="e.g. +91-9876543210" 
      />
      <FormField 
        icon={User}
        label="In-charge Name" 
        name="incharge_name" 
        value={formData.incharge_name} 
        onChange={handleChange} 
        required 
        placeholder="e.g. Admin Rajiv" 
      />
      <FormField 
        icon={Globe}
        label="Station Address" 
        name="address" 
        value={formData.address} 
        onChange={handleChange} 
        required 
        fullWidth 
        placeholder="Full Physical Address" 
      />
      
      <div style={{ gridColumn: '1 / -1', height: '1px', background: 'linear-gradient(90deg, rgba(59, 130, 246, 0.2) 0%, transparent 100%)', margin: '12px 0' }} />

      <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
        <div style={{ width: '40px', height: '40px', borderRadius: '10px', background: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <MapPin size={20} color="var(--accent-cyan)" />
        </div>
        <div>
          <h4 style={{ margin: 0, color: '#fff', fontSize: '1.1rem', fontWeight: 800 }}>GPS Coordinates</h4>
          <p style={{ margin: 0, fontSize: '0.7rem', color: 'var(--text-secondary)' }}>Precise location mapping.</p>
        </div>
      </div>

      <div style={{ gridColumn: '1 / -1', display: 'flex', flexWrap: 'wrap', gap: '20px' }}>
        <div style={{ flex: '1 1 300px' }}>
          <div style={{ display: 'flex', gap: '16px' }}>
            <FormField 
              icon={MapPin}
              label="Latitude" 
              name="gps_lat" 
              type="number"
              value={formData.gps_lat} 
              onChange={handleChange} 
              required 
              placeholder="e.g. 13.0827" 
            />
            <FormField 
              icon={Navigation}
              label="Longitude" 
              name="gps_lon" 
              type="number"
              value={formData.gps_lon} 
              onChange={handleChange} 
              required 
              placeholder="e.g. 80.2707" 
            />
          </div>
          <p style={{ fontSize: '0.7rem', color: 'var(--text-secondary)', marginTop: '8px' }}>
            Enter coordinates manually or click on the map to set the exact station location.
          </p>
        </div>
        <div style={{ flex: '1 1 300px' }}>
           <LocationPickerMap 
              lat={parseFloat(formData.gps_lat) || 13.0827} 
              lng={parseFloat(formData.gps_lon) || 80.2707} 
              onLocationSelect={handleLocationSelect} 
           />
        </div>
      </div>
    </form>
  );
};


const Modal: React.FC<{ isOpen: boolean; title: string; onClose: () => void; children: React.ReactNode; onSubmit?: () => void; loading?: boolean }> = ({ isOpen, title, onClose, children, onSubmit, loading }) => {
   if (!isOpen) return null;
   return (
      <div className="modal-overlay" style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.8)', backdropFilter: 'blur(8px)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '40px' }}>
         <motion.div initial={{ opacity: 0, scale: 0.9 }} animate={{ opacity: 1, scale: 1 }} className="glass" style={{ width: '100%', maxWidth: '800px', maxHeight: '90vh', overflowY: 'auto', background: 'var(--base-bg)', padding: '32px', borderRadius: '20px', border: '1px solid var(--accent-cyan)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
               <h3 style={{ fontSize: '1.5rem', fontWeight: 800 }}>{title}</h3>
               <button onClick={onClose} className="btn-icon"><XCircle size={24} /></button>
            </div>
            {children}
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '16px', marginTop: '32px' }}>
               <button onClick={onClose} className="btn-secondary" disabled={loading}>CANCEL</button>
               <button 
                onClick={onSubmit} 
                className="btn-primary" 
                disabled={loading}
                style={{ opacity: loading ? 0.7 : 1 }}
               >
                 {loading ? 'PROCESSING...' : 'SUBMIT REGISTRATION'}
               </button>
            </div>
         </motion.div>
      </div>
   );
};

// --- MAIN PAGE COMPONENT ---
export const FleetDispatch: React.FC = () => {
  const [activeModule, setActiveModule] = useState<FleetModule>('OWNERS');
  const [staffSubTab, setStaffSubTab] = useState<'DRIVER' | 'EMT' | 'DOCTOR'>('DRIVER');
  const [selectedVehicleId] = useState<string | null>(null);
  const [selectedOwnerId, setSelectedOwnerId] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalType, setModalType] = useState<'VEHICLE' | 'DRIVER' | 'EMT' | 'DOCTOR' | 'BRAND' | 'STATION' | 'ROSTER' | 'SHIFT' | 'MANIFEST' | null>(null);
  const [selectedStation, setSelectedStation] = useState<any>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [realOwners, setRealOwners] = useState<any[]>([]);
  const [isLoadingOwners, setIsLoadingOwners] = useState(true);
  const [realVehicles, setRealVehicles] = useState<any[]>([]);
  const [isLoadingVehicles, setIsLoadingVehicles] = useState(false);
  const [realStaff, setRealStaff] = useState<any[]>([]);
  const [isLoadingStaff, setIsLoadingStaff] = useState(false);
  const [realInventory, setRealInventory] = useState<any[]>([]);
  const [isLoadingInventory, setIsLoadingInventory] = useState(false);
  const [stationMap, setStationMap] = useState<Record<string, string>>({});
  const [editingVehicle, setEditingVehicle] = useState<any | null>(null);
  const [liveVehicles, setLiveVehicles] = useState<FleetVehicle[]>(MOCK_VEHICLES);
  const [refreshKey, setRefreshKey] = useState(0);
  const [notifications, setNotifications] = useState<any[]>([]);
  const navigate = useNavigate();
  
  const userStr = localStorage.getItem('teleems_user');
  const currentUser = userStr ? JSON.parse(userStr) : null;
  const currentUserRoles = currentUser?.roles?.map((r: any) => String(r).toUpperCase()) || [];

  const notify = (title: string, message: string, type: 'success' | 'error' | 'info' = 'success') => {
    const id = Date.now();
    setNotifications(prev => [...prev, { id, title, message, type }]);
    setTimeout(() => {
      setNotifications(prev => prev.filter(n => n.id !== id));
    }, 5000);
  };

  // --- LIVE MOVEMENT SIMULATION ---
  useEffect(() => {
    const interval = setInterval(() => {
      setLiveVehicles(prev => prev.map(v => {
        if (['EN_ROUTE', 'TRANSPORTING'].includes(v.status)) {
          // Move slightly in a random direction
          return {
            ...v,
            lat: v.lat + (Math.random() - 0.5) * 0.0005,
            lng: v.lng + (Math.random() - 0.5) * 0.0005,
            speed: Math.max(30, Math.min(80, v.speed + (Math.random() - 0.5) * 5)),
            fuel: Math.max(5, v.fuel - 0.01)
          };
        }
        return v;
      }));
    }, 3000);
    return () => clearInterval(interval);
  }, []);

  // --- BRAND SPECIFIC DATA FILTERING ---
  useEffect(() => {
    if (!selectedOwnerId) return;
    // Create a brand-unique version of the mock fleet
    const brandFleet = MOCK_VEHICLES.map(v => ({
      ...v,
      // Distribute them differently on the map based on brand ID to look unique
      lat: v.lat + (parseInt(selectedOwnerId.slice(-1), 16) || 0) * 0.01 - 0.05,
      lng: v.lng + (parseInt(selectedOwnerId.slice(-1), 16) || 0) * 0.01 - 0.05,
      // Randomize initial status slightly per brand
      status: Math.random() > 0.5 ? v.status : (Math.random() > 0.5 ? 'IDLE' : 'EN_ROUTE')
    }));
    setLiveVehicles(brandFleet as any);
  }, [selectedOwnerId]);

  // --- LIVE VEHICLE FETCHING WITH STATION MAPPING ---
  useEffect(() => {
    if (!selectedOwnerId || activeModule !== 'VEHICLES') return;
    
    const fetchData = async () => {
      setIsLoadingVehicles(true);
      try {
        const token = localStorage.getItem('teleems_token') || '';
        if (!token) return;
        
        console.log(`Dispatch: Fetching fleet data for org: ${selectedOwnerId}`);
        
        // 1. Fetch Stations for name mapping
        const stationRes = await fleetApi.getStations(token, selectedOwnerId);
        const sArr = stationRes?.data?.data || (Array.isArray(stationRes?.data) ? stationRes.data : []);
        const mapping = sArr.reduce((acc: any, s: any) => {
          acc[s.id] = s.name;
          return acc;
        }, {});
        setStationMap(mapping);

        // 2. Fetch Vehicles
        const response = await fleetApi.getVehicles(token, selectedOwnerId);
        const vehicleArr = response?.data?.data || (Array.isArray(response?.data) ? response.data : []);
        console.log('Dispatch: Received Vehicles:', vehicleArr.length);
        setRealVehicles(vehicleArr);
      } catch (err) {
        console.error('Failed to fetch fleet data:', err);
      } finally {
        setIsLoadingVehicles(false);
      }
    };
    
    fetchData();
  }, [selectedOwnerId, activeModule, refreshKey]);

  // --- LIVE STAFF FETCHING ---
  useEffect(() => {
    if (!selectedOwnerId || activeModule !== 'STAFF') return;
    
    const fetchStaff = async () => {
      setIsLoadingStaff(true);
      try {
        const token = localStorage.getItem('teleems_token') || '';
        if (!token) return;
        
        console.log(`Dispatch: Fetching staff for org: ${selectedOwnerId}`);
        const response = await fleetApi.getStaff(token, selectedOwnerId);
        
        // Response structure: response.data.data.data
        const staffArr = response?.data?.data?.data || response?.data?.data || (Array.isArray(response?.data) ? response.data : []);
        console.log('Dispatch: Received Staff:', staffArr.length);
        setRealStaff(staffArr);
      } catch (err) {
        console.error('Failed to fetch staff:', err);
      } finally {
        setIsLoadingStaff(false);
      }
    };
    
    fetchStaff();
  }, [selectedOwnerId, activeModule, refreshKey]);

  // --- LIVE INVENTORY FETCHING ---
  useEffect(() => {
    if (activeModule !== 'INVENTORY') return;
    
    const fetchInventory = async () => {
      setIsLoadingInventory(true);
      try {
        const token = localStorage.getItem('teleems_token') || '';
        if (!token) return;
        
        console.log('Dispatch: Fetching master inventory...');
        const response = await fleetApi.getInventoryMaster(token);
        
        const invArr = response?.data?.data || (Array.isArray(response?.data) ? response.data : []);
        console.log('Dispatch: Received Inventory Master:', invArr.length);
        setRealInventory(invArr);
      } catch (err) {
        console.error('Failed to fetch inventory:', err);
      } finally {
        setIsLoadingInventory(false);
      }
    };
    
    fetchInventory();
  }, [activeModule, refreshKey]);

  useEffect(() => {
    const fetchOwners = async () => {
      try {
        const token = localStorage.getItem('teleems_token') || '';
        if (!token) return;
        
        const response = await authApi.getUsers(token);
        
        if (response.status === 401 || response.message?.toLowerCase().includes('expired')) {
          localStorage.removeItem('teleems_auth');
          localStorage.removeItem('teleems_token');
          localStorage.removeItem('teleems_user');
          navigate('/login');
          return;
        }

        // Fetch all stations to calculate real counts per brand
        const stationRes = await fleetApi.getStations(token);
        const allStationsArr = stationRes?.data?.data || (Array.isArray(stationRes?.data) ? stationRes.data : []);
        
        // Group station counts by organisationId
        const stationCountsByOrg = allStationsArr.reduce((acc: any, s: any) => {
          if (s.organisationId) {
            acc[s.organisationId] = (acc[s.organisationId] || 0) + 1;
          }
          return acc;
        }, {});

        if (response.data && Array.isArray(response.data)) {
          const userRoles = currentUser?.roles?.map((r: any) => String(r).toUpperCase()) || [];
          const isSuperAdmin = userRoles.includes('CURESELECT_ADMIN');
          const isStationIncharge = userRoles.includes('STATION_INCHARGE');
          const isFleetOperator = userRoles.includes('FLEET_OPERATOR');

          const operators = response.data
            .filter((u: any) => {
              const roles = u.roles?.map((r: any) => String(r).trim().toUpperCase()) || [];
              const isOp = roles.includes('FLEET_OPERATOR') || 
                           roles.includes('FLEET OPERATOR') ||
                           roles.some((r: string) => r.includes('FLEET') && r.includes('OPERATOR'));
              
              if (!isOp) return false;

              // SuperAdmin sees all fleet operators/brands
              if (isSuperAdmin) return true;

              // Access control for specific users/organisations
              const userOrgId = currentUser?.organisationId;
              const userHospitalId = currentUser?.hospitalId;
              const userId = currentUser?.id;

              return u.id === userId || 
                     (u.organisationId && u.organisationId === userOrgId) ||
                     (u.hospitalId && u.hospitalId === userHospitalId);
            })
            .map((u: any) => {
              const orgId = u.organisationId || u.id;
              const name = u.metadata?.organization?.company_name || u.name || u.username || 'Unnamed Brand';
              const type = u.metadata?.organization?.type || 'Private';
              const city = u.metadata?.organization?.city || 'Chennai';
              
              // Use real station count from aggregation, fallback to metadata if provided, then 0
              // Important: We prioritize real stationCountsByOrg data
              const liveStationCount = stationCountsByOrg[orgId] || 0;
              let stations = liveStationCount || u.metadata?.organization?.stationCount || 0;
              
              // Vehicles and Staff still use metadata or 0 as live API for those is pending
              let vehicles = u.metadata?.organization?.vehicleCount || 0;
              let staff = u.metadata?.organization?.staffCount || 0;

              return {
                id: orgId,
                userId: u.id,
                name,
                type,
                stations,
                vehicles,
                staff,
                status: u.status === 'ACTIVE' ? 'Active' : 'Inactive',
                gstin: u.metadata?.organization?.gstin || 'N/A',
                city,
                rawMetadata: u.metadata
              };
            });

          // De-duplicate brands by ID (either organisationId or userId) to ensure one card per brand
          const uniqueBrands: any[] = [];
          const seenBrandIds = new Set();
          for (const op of operators) {
            if (!seenBrandIds.has(op.id)) {
              seenBrandIds.add(op.id);
              uniqueBrands.push(op);
            }
          }

          setRealOwners(uniqueBrands);
        } else {
          console.warn('FleetDiscovery: No user data array found in response');
        }
      } catch (error) {
        console.error('Failed to fetch owners:', error);
      } finally {
        setIsLoadingOwners(false);
      }
    };

    fetchOwners();
  }, [refreshKey]);

  useEffect(() => {
    const userStr = localStorage.getItem('teleems_user');
    if (!userStr || realOwners.length === 0) return;
    const user = JSON.parse(userStr);
    
    if (user.roles?.includes('FLEET_OPERATOR')) {
      // Find the brand that matches their organisationId or id or name
      const orgName = user.metadata?.organization?.company_name;
      const match = realOwners.find(o => o.id === user.organisationId || o.id === user.id || o.name === orgName);
      if (match) {
        setSelectedOwnerId(match.id);
        setActiveModule('DASHBOARD');
      }
    }
  }, [realOwners]);

  const allOwners = useMemo(() => {
    return realOwners;
  }, [realOwners]);

  const selectedOwner = useMemo(() => allOwners.find(o => o.id === selectedOwnerId), [selectedOwnerId, allOwners]);

  const openRegistration = (type: any) => {
     setEditingVehicle(null);
     setModalType(type);
     setIsModalOpen(true);
  };

  const openEditVehicle = (vehicle: any) => {
    setEditingVehicle(vehicle);
    setModalType('VEHICLE');
    setIsModalOpen(true);
  };

  const handleBrandSubmit = async (data: any) => {
    setIsSubmitting(true);
    try {
      const token = localStorage.getItem('teleems_token') || '';
      if (!token) {
        throw new Error('No authentication token found. Please login again.');
      }
      
      const result = await authApi.registerUser(data, token);
      
      if (result.error || result.status === 401) {
        throw new Error(result.error?.message || result.message || 'Unauthorized');
      }

      console.log('Registration Success:', result);
      console.log('Brand Registered', `Organisation "${data.metadata.organization.company_name}" has been onboarded.`, 'success');
      setRefreshKey(prev => prev + 1);
      setIsModalOpen(false);
    } catch (error: any) {
      console.error('Registration failed:', error);
      const isExpired = error.message.includes('Token has expired');
      console.log('Registration Failed', error.message, 'error');
      
      if (isExpired) {
        localStorage.removeItem('teleems_auth');
        localStorage.removeItem('teleems_token');
        localStorage.removeItem('teleems_user');
        navigate('/login');
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleStationSubmit = async (data: any) => {
    setIsSubmitting(true);
    try {
      const token = localStorage.getItem('teleems_token') || '';
      if (!token) throw new Error('No authentication token found. Please login.');
      
      console.log('Dispatch: Creating Station...', data);
      const result = await fleetApi.createStation(data, token);
      
      // Handle the specific response structure provided by the user
      // response.data.data.id
      const stationId = result.data?.data?.id || result.data?.id;
      
      if (result.error || result.status >= 400 || !stationId) {
        throw new Error(result.message || 'Failed to create station. Verify details and try again.');
      }

      console.log('Dispatch: Station Created Successfully:', stationId);
      console.log('Station Created', `Station "${data.name}" is now active in the system.`, 'success');
      
      setRefreshKey(prev => prev + 1); // Trigger re-fetch of fleet owners/stations
      setIsModalOpen(false);
    } catch (error: any) {
      console.error('Dispatch: Station Creation Failed:', error);
      console.log('Station Error', error.message, 'error');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleVehicleSubmit = async (data: any) => {
    setIsSubmitting(true);
    try {
      const token = localStorage.getItem('teleems_token') || '';
      if (!token) throw new Error('No authentication token found. Please login.');
      
      let result;
      if (data.id) {
        const { id, ...updateData } = data;
        console.log('Dispatch: Updating Vehicle Details...', id, updateData);
        result = await fleetApi.updateVehicleDetails(id, updateData, token);
      } else {
        console.log('Dispatch: Creating Vehicle...', data);
        result = await fleetApi.createVehicle(data, token);
      }
      
      if (result.error || result.status >= 400) {
        throw new Error(result.message || `Failed to ${data.id ? 'update' : 'create'} vehicle.`);
      }

      console.log('Vehicle Updated', `Vehicle "${data.registration_number}" telemetry is now synced.`, 'success');
      setRefreshKey(prev => prev + 1);
      setIsModalOpen(false);
      setEditingVehicle(null);
    } catch (error: any) {
      console.error(`Dispatch: Vehicle ${data.id ? 'Update' : 'Creation'} Failed:`, error);
      console.log('Vehicle Error', error.message, 'error');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleStaffSubmit = async (data: any) => {
    setIsSubmitting(true);
    try {
      const token = localStorage.getItem('teleems_token') || '';
      if (!token) throw new Error('No authentication token found. Please login.');
      
      const payload = {
        ...data,
        organisationId: selectedOwnerId
      };
      console.log('Dispatch: Registering Staff...', payload);
      const result = await fleetApi.createStaff(payload, token);
      
      if (result.error || result.status >= 400) {
        throw new Error(result.message || 'Failed to register staff.');
      }

      console.log('Dispatch: Staff Registered Successfully');
      console.log('Staff Registered', `Personnel file for "${data.name}" has been created.`, 'success');
      setRefreshKey(prev => prev + 1);
      setIsModalOpen(false);
    } catch (error: any) {
      console.error('Dispatch: Staff Registration Failed:', error);
      console.log('Staff Error', error.message, 'error');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleRosterSubmit = async (data: any) => {
    setIsSubmitting(true);
    try {
      const token = localStorage.getItem('teleems_token') || '';
      if (!token) throw new Error('No authentication token found.');
      
      console.log('Dispatch: Creating Roster...', data);
      const result = await fleetApi.createRoster(data, token);
      
      if (result.error || result.status >= 400) {
        throw new Error(result.message || 'Failed to create roster.');
      }

      console.log('Roster Created', 'Crew assignment has been finalized.', 'success');
      setIsModalOpen(false);
    } catch (error: any) {
      console.error('Dispatch: Roster Creation Failed:', error);
      console.log('Roster Error', error.message, 'error');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleShiftStart = async (data: any) => {
    setIsSubmitting(true);
    try {
      const token = localStorage.getItem('teleems_token') || '';
      if (!token) throw new Error('No authentication token found.');
      
      console.log('Dispatch: Starting Shift...', data);
      const result = await fleetApi.startShift(data, token);
      
      if (result.error || result.status >= 400) {
        throw new Error(result.message || 'Failed to start shift.');
      }

      console.log('Shift Started', 'Vehicle is now LIVE and tracking telemetry.', 'success');
      setIsModalOpen(false);
      setRefreshKey(prev => prev + 1);
    } catch (error: any) {
      console.error('Dispatch: Shift Start Failed:', error);
      console.log('Shift Error', error.message, 'error');
    } finally {
      setIsSubmitting(false);
    }
  };

  const triggerSubmit = () => {
    if (modalType === 'BRAND') {
      const form = document.getElementById('brand-reg-form') as HTMLFormElement;
      if (form) form.requestSubmit();
    } else if (modalType === 'STATION') {
      const form = document.getElementById('station-reg-form') as HTMLFormElement;
      if (form) form.requestSubmit();
    } else if (modalType === 'VEHICLE') {
      const form = document.getElementById('vehicle-reg-form') as HTMLFormElement;
      if (form) form.requestSubmit();
    } else if (modalType === 'ROSTER') {
      const form = document.getElementById('roster-form') as HTMLFormElement;
      if (form) form.requestSubmit();
    } else if (modalType === 'SHIFT') {
      const form = document.getElementById('shift-start-form') as HTMLFormElement;
      if (form) form.requestSubmit();
    } else if (['DRIVER', 'EMT', 'DOCTOR'].includes(modalType as string)) {
      const form = document.getElementById('staff-reg-form') as HTMLFormElement;
      if (form) form.requestSubmit();
    } else {
      setIsModalOpen(false);
    }
  };

  const renderModule = () => {
    switch (selectedOwnerId ? activeModule : 'OWNERS') {
      case 'OWNERS': 
        return (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
             <header style={{ display: 'flex', flexWrap: 'wrap', gap: '16px', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                   <h2 style={{ fontSize: '2rem', fontWeight: 900, marginBottom: '8px' }}>Select Fleet Brand</h2>
                   <p style={{ color: 'var(--text-secondary)' }}>Choose an organisation to access its operational command center.</p>
                </div>
                <button className="btn-primary" onClick={() => openRegistration('BRAND')}><Plus size={18} /> REGISTER BRAND</button>
             </header>

             <div className="stats-bar" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
                <StatCard label="Total Brands" value={allOwners.length} icon={ShieldCheck} glowColor="cyan" />
                <StatCard label="Total Fleet" value={allOwners.reduce((acc, o) => acc + (o.vehicles || 0), 0)} icon={Truck} glowColor="green" />
                <StatCard label="Active Duty" value={Math.floor(allOwners.reduce((acc, o) => acc + (o.vehicles || 0), 0) * 0.88)} icon={Activity} glowColor="cyan" />
                <StatCard label="Systems" value="99.9%" icon={Zap} glowColor="cyan" />
             </div>

              {isLoadingOwners && realOwners.length === 0 ? (
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '100px', gap: '20px' }}>
                  <div className="discovery-pulse" />
                  <Activity className="spin-slow" color="var(--text-primary)" size={48} />
                  <p style={{ color: 'var(--text-secondary)', fontWeight: 600 }}>DISCOVERING OPERATIONAL BRANDS...</p>
                </div>
              ) : allOwners.length === 0 ? (
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '100px', gap: '20px', background: 'var(--bg-card)', borderRadius: '24px', border: '1px solid var(--border-color)' }}>
                   <ShieldCheck size={64} color="var(--text-secondary)" />
                   <div style={{ textAlign: 'center' }}>
                      <h3 style={{ fontSize: '1.5rem', marginBottom: '8px' }}>No Fleet Brands Found</h3>
                      <p style={{ color: 'var(--text-secondary)', maxWidth: '400px' }}>Your platform currently has no registered fleet aggregator brands. Register a new brand to begin operational management.</p>
                   </div>
                   <button className="btn-primary" onClick={() => openRegistration('BRAND')} style={{ marginTop: '12px' }}>
                      <Plus size={18} /> REGISTER YOUR FIRST BRAND
                   </button>
                </div>
              ) : (
                <div className="stations-grid">
                  {allOwners.map(owner => (
                     <Card 
                        key={owner.id} 
                        className={`owner-card-item premium ${selectedOwnerId === owner.id ? 'selected' : ''}`} 
                        onClick={() => { setSelectedOwnerId(owner.id); setActiveModule('DASHBOARD'); }}
                     >
                        <div className="card-action-header">
                           <div className="org-logo-square">
                              {owner.name?.[0] || 'B'}
                              <div className="logo-glow" />
                           </div>
                           <div className="status-badge-premium">
                              <span className="pulse-dot" />
                              ACTIVE
                           </div>
                        </div>

                        <div className="brand-ident">
                           <h3 className="brand-name">{owner.name}</h3>
                           <div className="brand-sub">{owner.type} • {owner.city}</div>
                        </div>
                        
                        <div className="brand-stats-row">
                           <div className="stat-unit">
                              <div className="val">{owner.stations}</div>
                              <div className="lab">STATIONS</div>
                           </div>
                           <div className="stat-unit">
                              <div className="val">{owner.vehicles}</div>
                              <div className="lab">FLEET</div>
                           </div>
                           <div className="stat-unit">
                              <div className="val">{owner.staff}</div>
                              <div className="lab">STAFF</div>
                           </div>
                        </div>

                        <div className="card-footer-action">
                           <span>ENTER COMMAND CENTER</span>
                           <ChevronRight size={18} />
                        </div>
                     </Card>
                  ))}
                </div>
              )}
          </div>
        );
      case 'DASHBOARD':
        return (
          <div className="dashboard-view" style={{ display: 'grid', gridTemplateColumns: 'minmax(350px, 400px) 1fr', gap: '24px' }}>
            <div className="dashboard-sidebar">
               <Card title={`${selectedOwner?.name} Overview`}>
                  <div className="quick-kpis">
                     <div className="kpi">
                        <div className="kpi-val">{selectedOwner?.vehicles}</div>
                        <div className="kpi-lab">Active Vehicles</div>
                     </div>
                     <div className="kpi">
                        <div className="kpi-val">12.4m</div>
                        <div className="kpi-lab">Avg Response</div>
                     </div>
                     <div className="kpi">
                        <div className="kpi-val">94%</div>
                        <div className="kpi-lab">SLA Compliance</div>
                     </div>
                  </div>
               </Card>
               <div style={{ marginTop: '24px' }}>
                  <Card title="Live Owner Alerts" className="alert-card">
                     <div className="alert-feed">
                        <div className="feed-item danger">
                           <div className="time">2m ago</div>
                           <div className="msg">SOS: V-102 High Engine Temp</div>
                        </div>
                        <div className="feed-item warning">
                           <div className="time">15m ago</div>
                           <div className="msg">V-098 Exited Service Zone</div>
                        </div>
                     </div>
                  </Card>
               </div>
            </div>
            <div className="dashboard-main">
               <LiveLeafletMap vehicles={liveVehicles} selectedId={selectedVehicleId} />
               <div style={{ marginTop: '24px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px' }}>
                  <Card title="Brand Specific Activity">
                     <div className="trip-list-mini">
                        {[1,2,3].map(i => (
                          <div key={i} className="trip-item">
                             <div className="trip-id">#TRP-882{i}</div>
                             <div className="trip-info">Cardiac • TN-01-AM...</div>
                             <div className="trip-status completed">DONE</div>
                          </div>
                        ))}
                     </div>
                  </Card>
                  <Card title="Resource Heatmap">
                     <div className="placeholder-viz">
                        <BarChart3 size={32} color="var(--accent-cyan)" />
                        <span>Analysis for {selectedOwner?.name}</span>
                     </div>
                  </Card>
               </div>
            </div>
          </div>
        );
      case 'STATIONS': return (
        <OrganisationStationMgmt 
          onAddStation={() => openRegistration('STATION')} 
          organisationId={selectedOwnerId || undefined}
          organisationName={selectedOwner?.name}
          onViewVehicles={(stationId) => {
            // Future: Could set a search filter here
            setActiveModule('VEHICLES');
          }}
          onViewStaff={(stationId) => {
            setActiveModule('STAFF');
          }}
          onViewManifest={(station) => {
            setSelectedStation(station);
            setModalType('MANIFEST');
            setIsModalOpen(true);
          }}
        />
      );
      case 'VEHICLES': 
         return (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
               <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <h3 className="section-title"><Truck size={24} /> {selectedOwner?.name} Fleet</h3>
                  <button className="btn-primary" onClick={() => openRegistration('VEHICLE')}><Plus size={18} /> REGISTER VEHICLE</button>
               </header>
               <div className="stats-bar">
                  <StatCard label="Total Fleet" value={realVehicles.length} icon={Truck} glowColor="cyan" />
                  <StatCard label="Operational" value={realVehicles.filter(v => v.status === 'AVAILABLE' || v.status === 'BUSY' || v.status === 'EN_ROUTE').length} icon={CheckCircle2} glowColor="green" />
                  <StatCard label="Maintenance" value={realVehicles.filter(v => v.status === 'MAINTENANCE').length} icon={Settings} glowColor="amber" />
               </div>
               <Card>
                  <div className="table-header">
                     <div className="search-box glass">
                        <Search size={16} />
                        <input type="text" placeholder="Search by number, model, station..." />
                     </div>
                  </div>
                  <div className="table-container">
                     <table>
                        <thead>
                           <tr>
                              <th>Vehicle Details</th>
                              <th>Type</th>
                              <th>Station</th>
                              <th>Status</th>
                              <th>Odometer</th>
                              <th>Compliance</th>
                              <th style={{ textAlign: 'right' }}>Actions</th>
                           </tr>
                        </thead>
                        <tbody>
                           {isLoadingVehicles ? (
                             <tr>
                               <td colSpan={7} style={{ textAlign: 'center', padding: '40px' }}>
                                 <Activity className="spin-slow" color="var(--accent-cyan)" />
                                 <div style={{ marginTop: '12px', color: 'var(--text-secondary)' }}>DECRYPTING FLEET DATA...</div>
                               </td>
                             </tr>
                           ) : realVehicles.length === 0 ? (
                             <tr>
                               <td colSpan={7} style={{ textAlign: 'center', padding: '40px' }}>
                                 <Truck size={32} color="var(--card-border)" style={{ marginBottom: '12px' }} />
                                 <div style={{ color: 'var(--text-secondary)' }}>No live vehicles found for this brand.</div>
                               </td>
                             </tr>
                           ) : (
                             realVehicles.map(v => (
                                <tr key={v.id || v._id}>
                                   <td>
                                      <div style={{ fontWeight: 700 }}>{v.registration_number || v.number}</div>
                                      <div style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>{v.brand} {v.model} • {v.ownership_type || 'OWNED'}</div>
                                   </td>
                                   <td><span className={`tag tag-${v.vehicle_type || v.type}`}>{v.vehicle_type || v.type}</span></td>
                                   <td>{stationMap[v.station_id] || v.station_name || v.station_id || 'Global Pool'}</td>
                                   <td>
                                      <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                                         <div className="status-pulse" style={{ background: (v.status === 'EN_ROUTE' || v.status === 'BUSY') ? 'var(--accent-cyan)' : 'var(--accent-green)' }} />
                                         <span style={{ fontSize: '0.75rem', fontWeight: 600 }}>{v.status}</span>
                                      </div>
                                   </td>
                                   <td className="mono">{(v.odometer || 0).toLocaleString()} km</td>
                                   <td>
                                      <div style={{ display: 'flex', gap: '4px' }}>
                                         <div title="RC" className="indicator active" />
                                         <div title="FC" className="indicator active" />
                                         <div title="Insurance" className="indicator active" />
                                         <div title="Pollution" className="indicator warning" />
                                      </div>
                                   </td>
                                   <td style={{ textAlign: 'right' }}>
                                      <button className="btn-ghost" title="Edit Vehicle" onClick={() => openEditVehicle(v)}><Edit2 size={18} /></button>
                                      <button className="btn-ghost" title="View Details"><Eye size={18} /></button>
                                      <button className="btn-ghost" title="Operational History"><History size={18} /></button>
                                      <button className="btn-ghost"><MoreVertical size={18} /></button>
                                   </td>
                                </tr>
                             ))
                           )}
                        </tbody>
                     </table>
                  </div>
               </Card>
            </div>
         );
      case 'STAFF': 
         return (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
               <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                     <h3 className="section-title"><Users size={24} /> Staff Management</h3>
                     <div className="pill-toggle">
                        <button className={staffSubTab === 'DRIVER' ? 'active' : ''} onClick={() => setStaffSubTab('DRIVER')}>DRIVERS</button>
                        <button className={staffSubTab === 'EMT' ? 'active' : ''} onClick={() => setStaffSubTab('EMT')}>EMTS</button>
                        <button className={staffSubTab === 'DOCTOR' ? 'active' : ''} onClick={() => setStaffSubTab('DOCTOR')}>DOCTORS</button>
                     </div>
                  </div>
                  <button className="btn-primary" onClick={() => openRegistration(staffSubTab)}><Plus size={18} /> ADD {staffSubTab}</button>
               </header>
               <Card>
                  <div className="staff-grid">
                     {isLoadingStaff ? (
                        <div style={{ gridColumn: '1 / -1', textAlign: 'center', padding: '40px' }}>
                           <Activity className="spin-slow" color="var(--accent-cyan)" />
                           <div style={{ marginTop: '12px', color: 'var(--text-secondary)' }}>RETRIEVING PERSONNEL REGISTRY...</div>
                        </div>
                     ) : realStaff.length === 0 ? (
                        <div style={{ gridColumn: '1 / -1', textAlign: 'center', padding: '40px' }}>
                           <Users size={48} color="var(--card-border)" style={{ marginBottom: '12px' }} />
                           <div style={{ color: 'var(--text-secondary)' }}>No personnel records found for this brand.</div>
                        </div>
                     ) : (
                        realStaff.filter(s => s.type === staffSubTab).length === 0 ? (
                           <div style={{ gridColumn: '1 / -1', textAlign: 'center', padding: '40px' }}>
                              <Users size={32} color="var(--card-border)" style={{ marginBottom: '12px' }} />
                              <div style={{ color: 'var(--text-secondary)' }}>No {staffSubTab.toLowerCase()}s registered yet.</div>
                           </div>
                        ) : (
                          realStaff.filter(s => s.type === staffSubTab).map(s => (
                            <div key={s.id} className="staff-card glass hover-glow">
                               <div className="staff-header">
                                  <div className="avatar">
                                     {s.photo_url ? <img src={s.photo_url} alt={s.user?.name} style={{ width: '100%', height: '100%', borderRadius: '50%', objectFit: 'cover' }} /> : <User size={32} />}
                                  </div>
                                  <div className="staff-info">
                                     <div className="name">{s.user?.name || 'Anonymous'}</div>
                                     <div className="role">
                                        {s.type === 'DRIVER' ? 'Senior Pilot' : (s.type === 'EMT' ? 'Advanced EMT' : 'M.D. Physician')}
                                     </div>
                                  </div>
                                  <div className={`staff-status ${s.status === 'ACTIVE' ? 'online' : 'offline'}`} />
                               </div>
                               <div className="staff-details">
                                  <div className="detail-row"><Phone size={14} /> {s.user?.phone || 'N/A'}</div>
                                  <div className="detail-row"><ShieldCheck size={14} /> {s.aadhaar_number || 'Aadhaar Not Linked'}</div>
                                  <div className="detail-row"><Activity size={14} /> {s.blood_group || 'Blood Group: N/A'}</div>
                               </div>
                               <div className="staff-metrics">
                                  <div className="metric"><div className="val">{s.professional_details?.license_category || 'N/A'}</div><div className="lab">License</div></div>
                                  <div className="metric"><div className="val">4.9</div><div className="lab">Rating</div></div>
                                  <div className="metric"><div className="val">100%</div><div className="lab">SLA</div></div>
                               </div>
                               <div className="staff-footer">
                                  <button className="btn-ghost-sm">VIEW DOSSIER</button>
                                  <button className="btn-ghost-sm">SCHEDULE</button>
                               </div>
                            </div>
                          ))
                        )
                     )}
                  </div>
               </Card>
            </div>
         );
      case 'INVENTORY': return <InventoryManagement data={realInventory} loading={isLoadingInventory} />;
      case 'SCHEDULING': return <CrewScheduling onAddRoster={() => openRegistration('ROSTER')} />;
      case 'TRIPS': return <TripManagement />;
      case 'TELEMATICS': return <GPSTelematics vehicles={liveVehicles} />;
      case 'REFERRALS': return <ReferralNetwork />;
      case 'REPORTS': return <FleetReports />;
      case 'ATTENDANCE': return <AttendanceModule onStartShift={() => openRegistration('SHIFT')} />;
      default: return (
        <div className="flex-center" style={{ height: '400px', flexDirection: 'column', gap: '16px' }}>
          <Settings size={48} className="spin-slow" color="var(--accent-cyan)" />
          <h3 style={{ color: 'var(--text-secondary)' }}>Coming Soon...</h3>
        </div>
      );
    }
  };

  // IF NO OWNER SELECTED, SHOW SELECTION PORTAL
  if (!selectedOwnerId) {
     return (
        <div className="fleet-layout" style={{ background: 'var(--base-bg)' }}>
           <main className="fleet-content" style={{ padding: '60px 10%', overflowY: 'auto' }}>
              <AnimatePresence mode="wait">
                 <motion.div initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.95 }}>
                    {renderModule()}
                 </motion.div>
              </AnimatePresence>
              <Modal 
                isOpen={isModalOpen} 
                title={
                  modalType === 'BRAND' ? 'REGISTER NEW BRAND' : 
                  modalType === 'STATION' ? 'ADD NEW STATION' : 
                  modalType === 'VEHICLE' ? (editingVehicle ? 'EDIT VEHICLE TELEMETRY' : 'REGISTER NEW VEHICLE') :
                  modalType === 'ROSTER' ? 'SCHEDULE NEW ROSTER' :
                  modalType === 'SHIFT' ? 'START OPERATIONAL SHIFT' :
                  `REGISTER NEW ${modalType}`
                } 
                onClose={() => setIsModalOpen(false)}
                onSubmit={triggerSubmit}
                loading={isSubmitting}
              >
                {modalType === 'BRAND' && <BrandRegistrationForm onSubmit={handleBrandSubmit} loading={isSubmitting} />}
                {modalType === 'STATION' && <StationRegistrationForm organisationId={selectedOwnerId || ''} onSubmit={handleStationSubmit} loading={isSubmitting} />}
                {modalType === 'VEHICLE' && <VehicleRegistrationForm organisationId={selectedOwnerId || ''} onSubmit={handleVehicleSubmit} loading={isSubmitting} initialData={editingVehicle} />}
                {modalType === 'ROSTER' && <RosterForm vehicles={realVehicles} staff={realStaff} onSubmit={handleRosterSubmit} loading={isSubmitting} />}
                {modalType === 'SHIFT' && <ShiftStartForm vehicles={realVehicles} staff={realStaff} onSubmit={handleShiftStart} loading={isSubmitting} />}
                {['DRIVER', 'EMT', 'DOCTOR'].includes(modalType as string) && (
                  <StaffRegistrationForm 
                    type={modalType as any} 
                    onSubmit={handleStaffSubmit} 
                    loading={isSubmitting} 
                  />
                )}
              </Modal>
           </main>
        </div>
     );
  }

  return (
    <motion.div className="page-container" initial={{ opacity: 0 }} animate={{ opacity: 1 }} style={{ padding: 0 }}>
      <div className="fleet-layout">
        <aside className="fleet-sub-nav glass">
          <div className="sub-nav-header" style={{ cursor: 'pointer', padding: '16px' }} onClick={() => { setSelectedOwnerId(null); setActiveModule('OWNERS'); }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
               <div className="org-logo" style={{ width: '40px', height: '40px', fontSize: '1.2rem', background: 'rgba(59, 130, 246, 0.1)', border: '1px solid var(--accent-cyan)' }}>{selectedOwner?.name?.[0] || 'B'}</div>
               <div>
                  <div style={{ fontWeight: 800, fontSize: '1rem', letterSpacing: '-0.02em', color: 'var(--accent-cyan)' }}>{selectedOwner?.name || 'Unknown Brand'}</div>
                  <div style={{ fontSize: '0.6rem', color: 'var(--accent-green)', textTransform: 'uppercase', display: 'flex', alignItems: 'center', gap: '4px' }}>
                     <ShieldCheck size={10} /> Active Partner
                  </div>
               </div>
            </div>
          </div>
          
          <div className="sub-nav-groups no-scrollbar">
             {!JSON.parse(localStorage.getItem('teleems_user') || '{}').roles?.includes('FLEET_OPERATOR') && (
               <div style={{ padding: '0 16px 16px' }}>
                  <button className="btn-ghost-sm" style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px', padding: '8px', border: '1px solid rgba(255,255,255,0.1)' }} onClick={() => { setSelectedOwnerId(null); setActiveModule('OWNERS'); }}>
                     <ChevronRight size={14} style={{ transform: 'rotate(180deg)' }} /> SWITCH BRAND
                  </button>
               </div>
             )}

             <div className="nav-group">
                <div className="group-label">OPERATIONS</div>
                <ModuleTab active={activeModule === 'DASHBOARD'} icon={LayoutGrid} label="Dashboard" onClick={() => setActiveModule('DASHBOARD')} />
                <ModuleTab active={activeModule === 'STATIONS'} icon={Building2} label="Dispatch Stations" onClick={() => setActiveModule('STATIONS')} />
                <ModuleTab active={activeModule === 'TRIPS'} icon={Route} label="Trip History" onClick={() => setActiveModule('TRIPS')} />
             </div>

             {/* Management and Resources restricted to non-pilot/emt roles */}
             {!currentUserRoles.includes('PILOT') && !currentUserRoles.includes('EMT') && (
               <>
                 <div className="nav-group" style={{ marginTop: '20px' }}>
                    <div className="group-label">RESOURCES</div>
                    <ModuleTab active={activeModule === 'VEHICLES'} icon={Truck} label="Fleet Vehicles" onClick={() => setActiveModule('VEHICLES')} />
                    <ModuleTab active={activeModule === 'STAFF'} icon={Users} label="Personnel" onClick={() => setActiveModule('STAFF')} />
                    <ModuleTab active={activeModule === 'INVENTORY'} icon={Package} label="Inventory" onClick={() => setActiveModule('INVENTORY')} />
                 </div>

                 <div className="nav-group" style={{ marginTop: '20px' }}>
                    <div className="group-label">LOGISTICS</div>
                    <ModuleTab active={activeModule === 'SCHEDULING'} icon={Calendar} label="Scheduling" onClick={() => setActiveModule('SCHEDULING')} />
                    <ModuleTab active={activeModule === 'ATTENDANCE'} icon={ClipboardList} label="Attendance" onClick={() => setActiveModule('ATTENDANCE')} />
                    <ModuleTab active={activeModule === 'TELEMATICS'} icon={Zap} label="Telematics" onClick={() => setActiveModule('TELEMATICS')} />
                 </div>

                 <div className="nav-group" style={{ marginTop: '20px' }}>
                    <div className="group-label">NETWORK</div>
                    <ModuleTab active={activeModule === 'REFERRALS'} icon={Link2} label="Referral Network" onClick={() => setActiveModule('REFERRALS')} />
                    <ModuleTab active={activeModule === 'REPORTS'} icon={BarChart3} label="Analytics" onClick={() => setActiveModule('REPORTS')} />
                 </div>
               </>
             )}

             {(currentUserRoles.includes('PILOT') || currentUserRoles.includes('EMT')) && (
                <div className="nav-group" style={{ marginTop: '20px' }}>
                   <div className="group-label">LOGISTICS</div>
                   <ModuleTab active={activeModule === 'TELEMATICS'} icon={Zap} label="Telematics" onClick={() => setActiveModule('TELEMATICS')} />
                </div>
             )}
          </div>

          <div className="sub-nav-footer glass">
             <div className="user-mini">
                <div className="user-avatar">AD</div>
                <div className="user-details">
                   <div className="user-name">Admin Dispatch</div>
                   <div className="user-role">{selectedOwner?.city} Station</div>
                </div>
             </div>
          </div>
        </aside>

        <main className="fleet-content">
          <header className="fleet-top-bar">
            <div className="breadcrumb">
               <span style={{ color: 'var(--text-secondary)' }}>{selectedOwner?.name}</span>
               <ChevronRight size={14} color="var(--text-secondary)" />
               <span style={{ fontWeight: 700, color: 'var(--accent-cyan)' }}>{activeModule}</span>
            </div>
            <div className="top-actions">
               <div className="status-indicator">
                  <div className="status-pulse" style={{ background: 'var(--accent-green)' }} />
                  <span>{selectedOwner?.status}</span>
               </div>
               <button className="btn-icon"><Bell size={20} /></button>
               <button className="btn-icon"><Settings size={20} /></button>
            </div>
          </header>
          
          <div className="module-container">
            <AnimatePresence mode="wait">
              <motion.div 
                key={activeModule}
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                transition={{ duration: 0.2 }}
                style={{ height: '100%' }}
              >
                {renderModule()}
              </motion.div>
            </AnimatePresence>
          </div>
        </main>
      </div>

      <Modal 
        isOpen={isModalOpen} 
        title={
          modalType === 'BRAND' ? 'REGISTER NEW BRAND' : 
          modalType === 'STATION' ? 'ADD NEW STATION' : 
          modalType === 'VEHICLE' ? (editingVehicle ? 'EDIT VEHICLE TELEMETRY' : 'REGISTER NEW VEHICLE') :
          modalType === 'ROSTER' ? 'SCHEDULE NEW ROSTER' :
          modalType === 'SHIFT' ? 'START OPERATIONAL SHIFT' :
          `REGISTER NEW ${modalType}`
        } 
        onClose={() => setIsModalOpen(false)}
        onSubmit={triggerSubmit}
        loading={isSubmitting}
      >
        {modalType === 'BRAND' && <BrandRegistrationForm onSubmit={handleBrandSubmit} loading={isSubmitting} />}
        {modalType === 'STATION' && <StationRegistrationForm organisationId={selectedOwnerId || ''} onSubmit={handleStationSubmit} loading={isSubmitting} />}
        {modalType === 'VEHICLE' && <VehicleRegistrationForm organisationId={selectedOwnerId || ''} onSubmit={handleVehicleSubmit} loading={isSubmitting} initialData={editingVehicle} />}
        {modalType === 'ROSTER' && <RosterForm vehicles={realVehicles} staff={realStaff} onSubmit={handleRosterSubmit} loading={isSubmitting} />}
        {modalType === 'SHIFT' && <ShiftStartForm vehicles={realVehicles} staff={realStaff} onSubmit={handleShiftStart} loading={isSubmitting} />}
        {modalType === 'MANIFEST' && <StationManifest station={selectedStation} vehicles={realVehicles} staff={realStaff} />}
        {['DRIVER', 'EMT', 'DOCTOR'].includes(modalType as string) && (
          <StaffRegistrationForm 
            type={modalType as any} 
            onSubmit={handleStaffSubmit} 
            loading={isSubmitting} 
          />
        )}
      </Modal>

      {/* --- PREMIUM NOTIFICATIONS --- */}
      <div className="toast-container">
        <AnimatePresence>
          {notifications.map(n => (
            <motion.div 
              key={n.id}
              initial={{ opacity: 0, x: 50, scale: 0.9 }}
              animate={{ opacity: 1, x: 0, scale: 1 }}
              exit={{ opacity: 0, x: 20, scale: 0.9 }}
              className="toast-notification"
              style={{ borderColor: n.type === 'error' ? 'var(--alert-red)' : (n.type === 'info' ? 'var(--accent-cyan)' : 'var(--accent-green)') }}
            >
              <div className="toast-icon" style={{ 
                color: n.type === 'error' ? 'var(--alert-red)' : (n.type === 'info' ? 'var(--accent-cyan)' : 'var(--accent-green)'),
                background: n.type === 'error' ? 'rgba(255, 59, 59, 0.1)' : (n.type === 'info' ? 'rgba(59, 130, 246, 0.1)' : 'rgba(0, 226, 114, 0.1)')
              }}>
                {n.type === 'success' ? <CheckCircle2 size={24} /> : (n.type === 'error' ? <XCircle size={24} /> : <AlertTriangle size={24} />)}
              </div>
              <div className="toast-content">
                <div className="toast-title" style={{ color: n.type === 'error' ? 'var(--alert-red)' : '#fff' }}>{n.title}</div>
                <div className="toast-message">{n.message}</div>
              </div>
              <div className="toast-close" onClick={() => setNotifications(prev => prev.filter(notif => notif.id !== n.id))}>
                <XCircle size={18} />
              </div>
            </motion.div>
          ))}
        </AnimatePresence>
      </div>
    </motion.div>
  );
};
