/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import { useState, useEffect, useMemo, useRef } from 'react';
import { Property, Booking, UserAccount, Mechanic, RepairBooking, EmergencySubscription } from './types';
import { INITIAL_PROPERTIES, INITIAL_MECHANICS } from './data';
import MapContainer from './components/MapContainer';
import PropertyCard from './components/PropertyCard';
import BookingForm from './components/BookingForm';

// Upgraded custom modular components
import AuthScreens from './components/AuthScreens';
import OwnerDashboard from './components/OwnerDashboard';
import AdminDashboard from './components/AdminDashboard';
import PaymentModal from './components/PaymentModal';
import MyBookingsPage from './components/MyBookingsPage';
import ProfilePage from './components/ProfilePage';
import OffersSlider from './components/OffersSlider';
import HelpPage from './components/HelpPage';
import RepairPage from './components/RepairPage';
import VoiceAssistant from './components/VoiceAssistant';

import { 
  Search, 
  Sparkles, 
  SlidersHorizontal, 
  RotateCcw, 
  HelpCircle, 
  LifeBuoy,
  X, 
  Ticket, 
  CheckCircle, 
  Trash2, 
  MapPin, 
  TrendingUp, 
  Filter,
  CheckCircle2,
  Calendar,
  Clock,
  Car,
  AlertTriangle,
  Map,
  List,
  IndianRupee,
  Activity,
  LogOut,
  User,
  ShieldAlert,
  QrCode,
  Copy,
  Check,
  Bell,
  Wrench,
  ShieldCheck,
  ChevronRight,
  Timer,
  ArrowRight
} from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';

export default function App() {
  // --- Auth State ---
  const [currentUser, setCurrentUser] = useState<UserAccount | null>(() => {
    const saved = localStorage.getItem('ev_parking_current_user');
    return saved ? JSON.parse(saved) : null;
  });

  // State to hold the booking we want to view QR code for:
  const [activeQrBooking, setActiveQrBooking] = useState<Booking | null>(null);

  // --- Properties Database state ---
  const [properties, setProperties] = useState<Property[]>(INITIAL_PROPERTIES);

  // --- Global bookings list ---
  const [bookings, setBookings] = useState<Booking[]>([]);

  // --- Registered user profiles database state (for admin audit) ---
  const [allUsers, setAllUsers] = useState<UserAccount[]>([]);

  // Map & interaction states
  const [selectedPropertyId, setSelectedPropertyId] = useState<string | null>(null);
  const [propertyToBook, setPropertyToBook] = useState<Property | null>(null);
  
  // Pending payment holding parameters
  const [pendingPaymentBooking, setPendingPaymentBooking] = useState<{
    property: Property;
    bookingData: {
      userName: string;
      userEmail: string;
      vehicleNumber: string;
      vehicleType: 'Car' | 'Two-Wheeler';
      bookingDate: string;
      timeSlot: string;
      totalHours: number;
      totalFare: number;
    }
  } | null>(null);

  // Filter States (Drivers App only)
  const [searchQuery, setSearchQuery] = useState('');
  const [typeFilter, setTypeFilter] = useState<'all' | 'charging' | 'parking' | 'both' | 'favorites'>('all');
  const [maxPrice, setMaxPrice] = useState<number>(100);
  const [onlyAvailable, setOnlyAvailable] = useState(false);
  const [showFiltersMobile, setShowFiltersMobile] = useState(false);

  // Favorites state
  const [favorites, setFavorites] = useState<string[]>(() => {
    const saved = localStorage.getItem('ev_parking_favorites');
    return saved ? JSON.parse(saved) : [];
  });

  // Tab State for Mobile responsive view ('list' vs 'map')
  const [mobileView, setMobileView] = useState<'list' | 'map'>('list');

  // Driver high-level active view ('explore' finder vs 'bookings' page)
  const [driverPage, setDriverPage] = useState<'explore' | 'bookings' | 'profile' | 'help' | 'repair'>('explore');

  // Repairing states
  const [mechanics, setMechanics] = useState<Mechanic[]>(INITIAL_MECHANICS);

  const [repairBookings, setRepairBookings] = useState<RepairBooking[]>([]);

  const [emergencySubscriptions, setEmergencySubscriptions] = useState<EmergencySubscription[]>([]);

  // Success Notification
  const [successBooking, setSuccessBooking] = useState<Booking | null>(null);

  // --- Dynamic Base Database Synchronizer (Firestore Loader) ---
  const loadDatabaseData = async () => {
    try {
      const propsRes = await fetch('/api/properties');
      if (propsRes.ok) {
        const propsData = await propsRes.json();
        if (Array.isArray(propsData) && propsData.length > 0) {
          setProperties(propsData);
        }
      }

      const bookingsRes = await fetch('/api/bookings');
      if (bookingsRes.ok) {
        const bookingsData = await bookingsRes.json();
        if (Array.isArray(bookingsData)) {
          setBookings(bookingsData);
        }
      }

      const mechsRes = await fetch('/api/mechanics');
      if (mechsRes.ok) {
        const mechsData = await mechsRes.json();
        if (Array.isArray(mechsData) && mechsData.length > 0) {
          setMechanics(mechsData);
        }
      }

      const repairsRes = await fetch('/api/repairs');
      if (repairsRes.ok) {
        const repairsData = await repairsRes.json();
        if (Array.isArray(repairsData)) {
          setRepairBookings(repairsData);
        }
      }

      const subsRes = await fetch('/api/emergency-subscriptions');
      if (subsRes.ok) {
        const subsData = await subsRes.json();
        if (Array.isArray(subsData)) {
          setEmergencySubscriptions(subsData);
        }
      }

      const usersRes = await fetch('/api/users');
      if (usersRes.ok) {
        const usersData = await usersRes.json();
        if (Array.isArray(usersData)) {
          setAllUsers(usersData);
        }
      }
    } catch (err) {
      console.warn("Firestore collection fetching deferred or had exceptions:", err);
    }
  };

  useEffect(() => {
    loadDatabaseData();
  }, [currentUser]);

  // Check on startup for successful email verification from real Gmail link click
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const verified = params.get('verified');
    const email = params.get('email');
    if (verified === 'true' && email) {
      fetch(`/api/auth/get-user?email=${encodeURIComponent(email)}`)
        .then(res => res.json())
        .then(data => {
          if (data.success && data.user) {
            setCurrentUser(data.user);
            localStorage.setItem('ev_parking_current_user', JSON.stringify(data.user));
            // Remove parameters from address bar for clean UX
            window.history.replaceState({}, document.title, window.location.pathname);
          }
        })
        .catch(err => {
          console.error("Failed to auto-sign in verified user:", err);
        });
    }
  }, []);

  // --- Classic Fallback Syncs ---
  useEffect(() => {
    localStorage.setItem('ev_parking_favorites', JSON.stringify(favorites));
  }, [favorites]);

  useEffect(() => {
    if (currentUser) {
      localStorage.setItem('ev_parking_current_user', JSON.stringify(currentUser));
    } else {
      localStorage.removeItem('ev_parking_current_user');
    }
  }, [currentUser]);

  const handleToggleFavorite = (propertyId: string) => {
    setFavorites(prev => {
      if (prev.includes(propertyId)) {
        return prev.filter(id => id !== propertyId);
      } else {
        return [...prev, propertyId];
      }
    });
  };

  // --- Booking Alerts & Custom Toast States ---
  interface CustomToast {
    id: string;
    propertyId: string;
    propertyName: string;
    message: string;
    timestamp: number;
  }

  const [alerts, setAlerts] = useState<string[]>(() => {
    const saved = localStorage.getItem('ev_parking_slot_alerts');
    return saved ? JSON.parse(saved) : [];
  });

  const [toasts, setToasts] = useState<CustomToast[]>([]);

  useEffect(() => {
    localStorage.setItem('ev_parking_slot_alerts', JSON.stringify(alerts));
  }, [alerts]);

  const handleToggleAlert = (propertyId: string) => {
    setAlerts(prev => {
      const updated = prev.includes(propertyId)
        ? prev.filter(id => id !== propertyId)
        : [...prev, propertyId];
      return updated;
    });
  };

  // Toast adder helper
  const addToastNotification = (propertyId: string, propertyName: string, message: string) => {
    const newToast: CustomToast = {
      id: Math.random().toString(36).substring(2, 9),
      propertyId,
      propertyName,
      message,
      timestamp: Date.now()
    };
    setToasts(prev => [...prev, newToast]);

    // Keep active for 10 seconds unless manually closed
    setTimeout(() => {
      setToasts(prev => prev.filter(t => t.id !== newToast.id));
    }, 10000);
  };

  // Keep a ref of previous properties state to capture slot increases
  const previousPropertiesRef = useRef<Property[]>([]);

  useEffect(() => {
    const oldProps = previousPropertiesRef.current;
    if (oldProps && oldProps.length > 0) {
      properties.forEach(current => {
        const matchingOld = oldProps.find(p => p.id === current.id);
        if (matchingOld) {
          // If available slots increased
          if (current.availableSlots > matchingOld.availableSlots) {
            // Check if user is listening to alerts on this station
            if (alerts.includes(current.id)) {
              addToastNotification(
                current.id,
                current.title,
                `🎉 Slot Opened: A smart spot became available at "${current.title}"! Hurry up to reserved your spot.`
              );
            }
          }
        }
      });
    }
    previousPropertiesRef.current = properties;
  }, [properties, alerts]);

  // --- Geolocation & Distance Proximity States ---
  const [userLocation, setUserLocation] = useState<{ lat: number; lng: number } | null>(null);
  const [proximityRadius, setProximityRadius] = useState<number | null>(null);
  const [locationStatus, setLocationStatus] = useState<'idle' | 'loading' | 'success' | 'outside' | 'error'>('idle');
  const [nearPropertyTitle, setNearPropertyTitle] = useState<string | null>(null);

  // Haversine distance calculator
  const getDistanceInKm = (lat1: number, lon1: number, lat2: number, lon2: number) => {
    const R = 6371; // Earth radius in Km
    const dLat = (lat2 - lat1) * Math.PI / 180;
    const dLon = (lon2 - lon1) * Math.PI / 180;
    const a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
      Math.sin(dLon / 2) * Math.sin(dLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return R * c;
  };

  const simulateNearby = (property: Property) => {
    // Navigate user near the property area in Bihar
    const simLat = property.location.lat + 0.012;
    const simLng = property.location.lng - 0.008;
    setUserLocation({ lat: simLat, lng: simLng });
    setProximityRadius(15);
    setLocationStatus('outside');
  };

  const handleShowNearby = (property: Property) => {
    setLocationStatus('loading');
    setNearPropertyTitle(property.title);

    if (!navigator.geolocation) {
      simulateNearby(property);
      return;
    }

    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords;
        const distToBihar = getDistanceInKm(latitude, longitude, 24.9540, 84.0142);

        // If user is more than 120km away from Bihar (e.g. testing from US/Europe/Singapore),
        // we simulate their position near this property so that they actually see results!
        if (distToBihar > 120) {
          const simLat = property.location.lat + 0.015;
          const simLng = property.location.lng - 0.010;
          setUserLocation({ lat: simLat, lng: simLng });
          setProximityRadius(15); // 15 km limit
          setLocationStatus('outside');
        } else {
          setUserLocation({ lat: latitude, lng: longitude });
          setProximityRadius(15); // 15 km limit
          setLocationStatus('success');
        }
      },
      (error) => {
        console.warn("Geolocation fetching error - engaging smart simulated proximity:", error);
        simulateNearby(property);
      },
      { enableHighAccuracy: true, timeout: 6000 }
    );
  };

  const clearProximityFilter = () => {
    setUserLocation(null);
    setProximityRadius(null);
    setLocationStatus('idle');
    setNearPropertyTitle(null);
  };

  // --- Filtering Logic for Driver View ---
  // Note: Customers should ONLY view properties where option isApproved is TRUE!
  const filteredProperties = useMemo(() => {
    return properties.filter(prop => {
      // 1. Validation Approval Check (Strict security constraint!)
      if (!prop.isApproved) return false;

      // 2. Search Query
      const query = searchQuery.toLowerCase().trim();
      const matchSearch = query === '' || 
        prop.title.toLowerCase().includes(query) || 
        prop.location.address.toLowerCase().includes(query) ||
        prop.location.city.toLowerCase().includes(query);

      // 3. Type Filter / Favorites Filter
      let matchType = false;
      if (typeFilter === 'favorites') {
        matchType = favorites.includes(prop.id);
      } else {
        matchType = typeFilter === 'all' || 
          (typeFilter === 'charging' && (prop.type === 'charging' || prop.type === 'both')) ||
          (typeFilter === 'parking' && (prop.type === 'parking' || prop.type === 'both')) ||
          (typeFilter === 'both' && prop.type === 'both');
      }

      // 4. Price Filter
      const matchPrice = prop.fare <= maxPrice;

      // 5. Proximity Geolocation Filter
      let matchProximity = true;
      if (userLocation && proximityRadius) {
        const dist = getDistanceInKm(userLocation.lat, userLocation.lng, prop.location.lat, prop.location.lng);
        matchProximity = dist <= proximityRadius;
      }

      // 6. Availability Filter
      const matchAvailability = !onlyAvailable || prop.availableSlots > 0;

      return matchSearch && matchType && matchPrice && matchProximity && matchAvailability;
    });
  }, [properties, searchQuery, typeFilter, maxPrice, onlyAvailable, favorites, userLocation, proximityRadius]);

  // --- Total statistics ---
  const stats = useMemo(() => {
    const approvedList = properties.filter(p => p.isApproved);
    const totalChargingPorts = approvedList.reduce((acc, p) => p.type !== 'parking' ? acc + p.totalSlots : acc, 0);
    const totalParkingPlaces = approvedList.reduce((acc, p) => p.type !== 'charging' ? acc + p.totalSlots : acc, 0);
    const totalBookings = currentUser 
      ? bookings.filter(b => b.userEmail === currentUser.email && b.status !== 'Cancelled').length 
      : bookings.filter(b => b.status !== 'Cancelled').length;
    const activeAvailable = approvedList.reduce((acc, p) => acc + p.availableSlots, 0);
    return {
      chargingCount: totalChargingPorts,
      parkingCount: totalParkingPlaces,
      bookingsCount: totalBookings,
      availableCount: activeAvailable
    };
  }, [properties, bookings, currentUser]);

  // --- Core Handlers ---
  const handleSelectProperty = (id: string | null) => {
    setSelectedPropertyId(id);
    if (id && window.innerWidth < 1024) {
      setMobileView('map');
    }
  };

  const handleBookNowClick = (property: Property) => {
    setPropertyToBook(property);
  };

  // Intermediate state router: routes booking parameters onto checkout payment screen first!
  const handleRouteToPaymentGateway = (bookingData: Omit<Booking, 'id' | 'propertyId' | 'propertyTitle' | 'propertyType' | 'createdAt' | 'paymentStatus' | 'status' | 'paymentMethod'>) => {
    if (!propertyToBook) return;

    setPendingPaymentBooking({
      property: propertyToBook,
      bookingData: {
        ...bookingData,
        totalFare: bookingData.totalFare // Keep accurate rate
      }
    });

    // Close booking parameters form
    setPropertyToBook(null);
  };

  // Finalizes real slot values after secure payment callback resolves successfully
  const handleCompleteTransactionByGateway = (paymentMethod: 'PhonePe' | 'Card' | 'COD', paymentStatus: 'Paid' | 'Pending') => {
    if (!pendingPaymentBooking) return;

    const { property: targetProp, bookingData } = pendingPaymentBooking;
    const randomBookingID = 'CP-' + Math.floor(100000 + Math.random() * 900000).toString();

    const finalizedBooking: Booking = {
      ...bookingData,
      id: randomBookingID,
      propertyId: targetProp.id,
      propertyTitle: targetProp.title,
      propertyType: targetProp.type,
      paymentMethod,
      paymentStatus,
      status: 'Confirmed',
      createdAt: new Date().toISOString()
    };

    // Decrement slots on the target property
    setProperties(prevProps => {
      return prevProps.map(p => {
        if (p.id === targetProp.id && p.availableSlots > 0) {
          const updatedP = { ...p, availableSlots: p.availableSlots - 1 };
          fetch('/api/properties', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(updatedP)
          }).catch(console.error);
          return updatedP;
        }
        return p;
      });
    });

    // Write persistent booking details
    setBookings(prevBookings => [finalizedBooking, ...prevBookings]);
    fetch('/api/bookings', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(finalizedBooking)
    }).catch(console.error);

    setPendingPaymentBooking(null);
    setSuccessBooking(finalizedBooking);

    // Auto clear victory layout banners
    setTimeout(() => {
      setSuccessBooking(null);
    }, 9000);
  };

  const handleCancelBooking = (booking: Booking) => {
    if (!confirm(`Are you sure you want to cancel booking ${booking.id}?\nYour refund of ₹${booking.totalFare} will be credited to your respective method shortly.`)) {
      return;
    }

    // Restore free slots back
    setProperties(prevProps => {
      return prevProps.map(p => {
        if (p.id === booking.propertyId) {
          const updatedP = { ...p, availableSlots: Math.min(p.totalSlots, p.availableSlots + 1) };
          fetch('/api/properties', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(updatedP)
          }).catch(console.error);
          return updatedP;
        }
        return p;
      });
    });

    // Cancel state changes instead of deleting
    const cancelledBooking: Booking = { ...booking, status: 'Cancelled' };
    setBookings(prevBookings => prevBookings.map(b => b.id === booking.id ? cancelledBooking : b));
    fetch('/api/bookings', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(cancelledBooking)
    }).catch(console.error);
    
    if (successBooking?.id === booking.id) {
      setSuccessBooking(null);
    }
  };

  const handleUpdateProfile = (updatedUser: UserAccount) => {
    setCurrentUser(updatedUser);
    fetch('/api/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updatedUser)
    }).catch(console.error);
    setAllUsers(prevUsers => {
      const updatedList = prevUsers.map(u => u.id === updatedUser.id ? updatedUser : u);
      return updatedList;
    });
  };

  const handleSubmitReview = (propertyId: string, bookingId: string, rating: number, comment: string) => {
    if (!currentUser) return;
    
    const newReview = {
      id: 'rev-' + Math.floor(100000 + Math.random()*900000).toString(),
      bookingId,
      propertyId,
      userEmail: currentUser.email,
      userName: currentUser.name,
      rating,
      comment,
      createdAt: new Date().toISOString()
    };

    setProperties(prevProps => {
      const updated = prevProps.map(p => {
        if (p.id === propertyId) {
          const currentReviews = p.reviews || [];
          if (currentReviews.some(r => r.bookingId === bookingId)) return p;
          
          const newReviewsList = [...currentReviews, newReview];
          const sum = newReviewsList.reduce((acc, r) => acc + r.rating, 0);
          const newAvgRating = parseFloat((sum / newReviewsList.length).toFixed(1));
          
          const updatedP = {
            ...p,
            rating: newAvgRating,
            reviews: newReviewsList
          };

          fetch('/api/properties', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(updatedP)
          }).catch(console.error);

          return updatedP;
        }
        return p;
      });
      return updated;
    });
  };

  // --- Admin/Owner Operations ---
  const handleAddProperty = (newProp: Property) => {
    setProperties(prev => [newProp, ...prev]);
    fetch('/api/properties', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(newProp)
    }).catch(console.error);
  };

  const handleUpdateProperty = (updated: Property) => {
    setProperties(prev => prev.map(p => p.id === updated.id ? updated : p));
    fetch('/api/properties', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updated)
    }).catch(console.error);
  };

  const handleDeleteProperty = (id: string) => {
    setProperties(prev => prev.filter(p => p.id !== id));
    fetch(`/api/properties/${id}`, {
      method: 'DELETE'
    }).catch(console.error);
  };

  const handleApprovePropertyToggle = (id: string, approve: boolean) => {
    setProperties(prev => prev.map(p => {
      if (p.id === id) {
        const nextP = { ...p, isApproved: approve };
        fetch('/api/properties', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(nextP)
        }).catch(console.error);
        return nextP;
      }
      return p;
    }));
  };

  const handleApproveMechanicToggle = (id: string, approve: boolean) => {
    setMechanics(prev => prev.map(m => {
      if (m.id === id) {
        const nextM = { ...m, isApproved: approve };
        fetch('/api/mechanics', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(nextM)
        }).catch(console.error);
        return nextM;
      }
      return m;
    }));
  };

  const handleDeleteMechanic = (id: string) => {
    setMechanics(prev => prev.filter(m => m.id !== id));
    fetch(`/api/mechanics/${id}`, {
      method: 'DELETE'
    }).catch(console.error);
  };

  const handleAddMechanic = (mech: Mechanic) => {
    setMechanics(prev => [...prev, mech]);
    fetch('/api/mechanics', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(mech)
    }).catch(console.error);
  };

  const handleUpdateBooking = (updated: Booking) => {
    // Check if transitioning to Completed status to assign user rewards
    const oldBooking = bookings.find(b => b.id === updated.id);
    const becameCompleted = updated.status === 'Completed' && oldBooking?.status !== 'Completed';

    setBookings(prev => prev.map(b => b.id === updated.id ? updated : b));
    fetch('/api/bookings', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updated)
    }).catch(console.error);

    if (becameCompleted) {
      setAllUsers(prevUsers => {
        const nextUsers = prevUsers.map(u => {
          if (u.email.toLowerCase() === updated.userEmail.toLowerCase()) {
            const currentBal = u.walletBalance ?? 250;
            const currentCheckins = u.completedCheckins ?? 0;
            const updatedU = {
              ...u,
              walletBalance: currentBal + 100, // Reward ₹100 money in wallet
              nextDiscountPercent: 5, // Reward 5% off on next booking coupon
              completedCheckins: currentCheckins + 1
            };
            fetch('/api/users', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(updatedU)
            }).catch(console.error);
            
            // If current logged-in driver completed this checkin, also update currentUser state instantly!
            if (currentUser && currentUser.email.toLowerCase() === updated.userEmail.toLowerCase()) {
              setCurrentUser(updatedU);
            }

            return updatedU;
          }
          return u;
        });
        
        return nextUsers;
      });
    }
  };

  const handleLogout = () => {
    setCurrentUser(null);
    setPropertyToBook(null);
    setPendingPaymentBooking(null);
  };

  const resetFilters = () => {
    setSearchQuery('');
    setTypeFilter('all');
    setMaxPrice(100);
    setOnlyAvailable(false);
  };

  // ================= RENDER LOGICAL GATEWAYS =================
  
  // 1. Unauthenticated Visitor Flow: Redirect to credentials registry screen
  if (!currentUser) {
    return (
      <AuthScreens 
        onAuthSuccess={(user) => {
          setCurrentUser(user);
          loadDatabaseData();
        }} 
      />
    );
  }

  // 2. Real Authorized Property Owner Portal View
  if (currentUser.role === 'owner') {
    return (
      <OwnerDashboard
        currentOwner={currentUser}
        properties={properties}
        bookings={bookings}
        onAddProperty={handleAddProperty}
        onUpdateProperty={handleUpdateProperty}
        onDeleteProperty={handleDeleteProperty}
        onUpdateBooking={handleUpdateBooking}
        onLogout={handleLogout}
      />
    );
  }

  // 3. Real Master system Administrator Dashboard View
  if (currentUser.role === 'admin') {
    return (
      <AdminDashboard
        currentAdmin={currentUser}
        properties={properties}
        bookings={bookings}
        users={allUsers}
        mechanics={mechanics}
        onApproveProperty={handleApprovePropertyToggle}
        onDeleteProperty={handleDeleteProperty}
        onUpdateProperty={handleUpdateProperty}
        onApproveMechanic={handleApproveMechanicToggle}
        onDeleteMechanic={handleDeleteMechanic}
        onAddMechanic={handleAddMechanic}
        onLogout={handleLogout}
      />
    );
  }

  // 4. Default: Customer/Driver GPS Locator Hub Map view
  return (
    <div className="min-h-screen bg-slate-950 flex flex-col font-sans text-slate-100 selection:bg-amber-500 selection:text-slate-950">
      
      {/* ================= DRIVER HEADER BRAND BAR ================= */}
      <header className="sticky top-0 z-30 bg-slate-900 border-b border-slate-850 select-none">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
          
          {/* Logo & Caption */}
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-slate-950 rounded-xl border border-amber-500/40 overflow-hidden flex items-center justify-center shadow-lg shadow-amber-500/5">
              <img 
                src="/src/assets/images/charge_buddy_logo_1782140417233.jpg" 
                alt="Charge Buddy Logo" 
                className="w-full h-full object-cover scale-110"
                referrerPolicy="no-referrer"
              />
            </div>
            <div>
              <h1 className="font-extrabold text-base tracking-tight text-white flex items-center gap-1.5">
                ChargeBuddy <span className="text-[10px] bg-emerald-500 text-slate-950 font-extrabold px-1.5 py-0.5 rounded-md leading-none">India</span>
              </h1>
              <p className="text-[10px] text-slate-400 font-medium font-bold">EV Reservoirs & Smart Parking Spots</p>
            </div>
          </div>

          {/* User profile controls and Logout Switch */}
          <div className="flex items-center gap-4 text-xs">
            
            {/* User credentials identifier */}
            <div className="hidden sm:flex items-center gap-2 bg-slate-950 px-3 py-1.5 rounded-xl border border-slate-800">
              <User className="w-3.5 h-3.5 text-amber-500" />
              <div className="text-left leading-none">
                <span className="text-slate-200 font-extrabold block">{currentUser.name}</span>
                <span className="text-[9px] text-slate-500 font-mono font-bold italic">Client Driver</span>
              </div>
            </div>

            <button
              onClick={handleLogout}
              className="p-2 bg-slate-800 hover:bg-rose-950 hover:text-rose-455 text-slate-300 rounded-xl transition-all border border-slate-700/60"
              title="Logout Profile"
            >
              <LogOut className="w-4 h-4" />
            </button>
          </div>

        </div>
      </header>

      {/* ================= MAIN CONTAINER BODY ================= */}
      <main className="flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col gap-6">

        {/* ================= HERO STATS & WELCOME BANNER ================= */}
        <div className="bg-slate-900 rounded-2xl p-5 md:p-6 shadow-sm border border-slate-800 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
          <div>
            <h2 className="font-extrabold text-xl md:text-2xl text-white tracking-tight flex items-center gap-2">
              Locate & Reserve Smart Parking Plugs <Sparkles className="w-5 h-5 text-amber-500 fill-amber-500" />
            </h2>
            <p className="text-slate-400 text-xs md:text-sm mt-1 max-w-2xl font-bold">
              Compare rates in Rupees, inspect real-time charging plug parameters, and avoid waiting. Select your spot, specify arrival hours, and complete secure payment directly from PhonePe or on Arrival.
            </p>
          </div>
          
          {/* Quick Metrics Cards */}
          <div className="flex gap-3 w-full md:w-auto shrink-0 select-none">
            <div className="flex-1 bg-slate-950/80 border border-slate-850 rounded-xl p-3 text-center min-w-[90px]">
              <span className="block text-xs font-bold text-slate-500 uppercase tracking-widest leading-none">Live Hubs</span>
              <span className="text-xl font-extrabold text-slate-100 font-mono mt-1 block">{filteredProperties.length}</span>
            </div>
            <div className="flex-1 bg-slate-950/80 border border-slate-850 rounded-xl p-3 text-center min-w-[90px]">
              <span className="block text-xs font-bold text-slate-500 uppercase tracking-widest leading-none">Free Slots</span>
              <span className="text-xl font-extrabold text-emerald-400 font-mono mt-1 block">{stats.availableCount}</span>
            </div>
            <div className="flex-1 bg-slate-950/80 border border-slate-850 rounded-xl p-3 text-center min-w-[90px]">
              <span className="block text-xs font-bold text-slate-500 uppercase tracking-widest leading-none">My Permits</span>
              <span className="text-xl font-extrabold text-amber-500 font-mono mt-1 block">{stats.bookingsCount}</span>
            </div>
          </div>
        </div>

        {/* ================= SUCCESS ACTION BANNER ================= */}
        {successBooking && (
          <motion.div 
            initial={{ opacity: 0, y: -10 }} 
            animate={{ opacity: 1, y: 0 }} 
            exit={{ opacity: 0 }}
            className="bg-emerald-600 text-white rounded-2xl p-5 shadow-lg flex flex-col md:flex-row justify-between items-start md:items-center gap-4 border border-emerald-500 z-20"
          >
            <div className="flex gap-3 items-start">
              <div className="bg-emerald-700/80 p-2 rounded-xl text-white shrink-0">
                <CheckCircle className="w-5 h-5 font-black" />
              </div>
              <div className="space-y-1">
                <h3 className="font-extrabold text-bse tracking-tight flex items-center gap-2">
                  Booking Confirmed! Slot Saved Successfully.
                </h3>
                <p className="text-emerald-100/90 text-xs">
                  A high-tech digital entry pass <strong className="text-white bg-slate-900 px-1.5 py-0.5 rounded font-mono font-bold">{successBooking.id}</strong> is registered under <strong>{successBooking.userName}</strong>. Checkpoint method set to <strong className="text-slate-100 font-mono uppercase bg-emerald-800 px-1 py-0.2 rounded">{successBooking.paymentMethod}</strong>.
                </p>
                <div className="flex gap-4 pt-1 text-[11px] font-semibold text-emerald-100">
                  <span className="flex items-center gap-1"><Calendar className="w-3.5 h-3.5" /> Date: {successBooking.bookingDate}</span>
                  <span className="flex items-center gap-1"><Clock className="w-3.5 h-3.5" /> Clock: {successBooking.timeSlot}</span>
                </div>
              </div>
            </div>
            <div className="flex items-center gap-2 shrink-0 self-end md:self-center">
              <button
                onClick={() => setSuccessBooking(null)}
                className="px-3 py-1.5 rounded-lg bg-emerald-700 hover:bg-emerald-800 text-white text-xs font-bold transition-all flex items-center gap-1"
              >
                Dismiss
              </button>
            </div>
          </motion.div>
        )}

        {/* ================= DRIVER PAGE NAVIGATION TABS ================= */}
        <div className="flex bg-slate-900/60 p-1.5 rounded-2xl border border-slate-800 self-start gap-1 select-none w-full sm:w-auto">
          <button
            onClick={() => setDriverPage('explore')}
            className={`flex-1 sm:flex-initial px-5 py-2.5 rounded-xl text-xs font-extrabold tracking-tight transition-all flex items-center justify-center gap-2
              ${driverPage === 'explore'
                ? 'bg-amber-500 text-slate-950 font-black shadow-md'
                : 'text-slate-400 hover:text-slate-200 hover:bg-slate-850'
              }`}
          >
            <Map className="w-4 h-4" />
            <span>Interactive Finder Map</span>
          </button>
          
          <button
            onClick={() => setDriverPage('bookings')}
            className={`flex-1 sm:flex-initial px-5 py-2.5 rounded-xl text-xs font-extrabold tracking-tight transition-all flex items-center justify-center gap-2 relative
              ${driverPage === 'bookings'
                ? 'bg-amber-500 text-slate-950 font-black shadow-md'
                : 'text-slate-400 hover:text-slate-200 hover:bg-slate-850'
              }`}
          >
            <Ticket className="w-4 h-4" />
            <span>My Bookings & Permits</span>
            {bookings.filter(b => b.userEmail === currentUser.email && b.status === 'Confirmed').length > 0 && (
              <span className="absolute -top-1 -right-1 bg-rose-500 text-white font-extrabold text-[9px] w-4.5 h-4.5 rounded-full flex items-center justify-center border-2 border-slate-950 leading-none">
                {bookings.filter(b => b.userEmail === currentUser.email && b.status === 'Confirmed').length}
              </span>
            )}
          </button>

          <button
            onClick={() => setDriverPage('profile' as any)}
            className={`flex-1 sm:flex-initial px-5 py-2.5 rounded-xl text-xs font-extrabold tracking-tight transition-all flex items-center justify-center gap-2 relative
              ${driverPage === 'profile'
                ? 'bg-amber-500 text-slate-950 font-black shadow-md'
                : 'text-slate-400 hover:text-slate-200 hover:bg-slate-850'
              }`}
          >
            <div className="w-4.5 h-4.5 rounded-md overflow-hidden bg-slate-950 flex items-center justify-center border border-slate-700">
              <img 
                src="/src/assets/images/charge_buddy_logo_1782140417233.jpg" 
                alt="Profile Logo" 
                className="w-full h-full object-cover scale-110"
                referrerPolicy="no-referrer"
              />
            </div>
            <span>Driver Profile & Rewards</span>
            {currentUser?.nextDiscountPercent && currentUser.nextDiscountPercent > 0 ? (
              <span className="absolute -top-1 -right-1 bg-emerald-500 text-slate-950 font-black text-[8px] px-1.5 py-0.5 rounded-md border border-slate-950 leading-none uppercase">
                5% Off
              </span>
            ) : null}
          </button>

          <button
            onClick={() => setDriverPage('repair')}
            className={`flex-1 sm:flex-initial px-5 py-2.5 rounded-xl text-xs font-extrabold tracking-tight transition-all flex items-center justify-center gap-2 relative border border-teal-500/10
              ${driverPage === 'repair'
                ? 'bg-gradient-to-r from-amber-500 to-amber-400 text-slate-950 font-black shadow-md border-transparent'
                : 'text-slate-400 hover:text-slate-200 hover:bg-slate-850'
              }`}
          >
            <Wrench className="w-4 h-4 animate-bounce" />
            <span>24/7 Mechanical Support</span>
            <span className="absolute -top-1.5 -right-1 bg-teal-500 text-slate-950 font-black text-[7px] px-1 rounded border border-slate-950 select-none">
              LIVE
            </span>
          </button>

          <button
            onClick={() => setDriverPage('help')}
            className={`flex-1 sm:flex-initial px-5 py-2.5 rounded-xl text-xs font-extrabold tracking-tight transition-all flex items-center justify-center gap-2 relative
              ${driverPage === 'help'
                ? 'bg-amber-500 text-slate-950 font-black shadow-md'
                : 'text-slate-400 hover:text-slate-200 hover:bg-slate-850'
              }`}
          >
            <LifeBuoy className="w-4 h-4" />
            <span>Help Desk & Support</span>
          </button>
        </div>

        <AnimatePresence mode="wait">
          {driverPage === 'explore' ? (
            <motion.div
              key="explore-module"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.15 }}
              className="flex flex-col gap-6 flex-1"
            >
              {/* ================= MOBILE VIEW TAB CONTROLLER ================= */}
              <div className="lg:hidden flex bg-slate-900 border border-slate-800 p-1.5 rounded-xl">
          <button
            onClick={() => setMobileView('list')}
            className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-xs font-bold transition-all
              ${mobileView === 'list' 
                ? 'bg-amber-500 text-slate-950 shadow-sm' 
                : 'text-slate-400 hover:bg-slate-850'}`}
          >
            <List className="w-4 h-4" />
            <span>Show Grid ({filteredProperties.length})</span>
          </button>
          
          <button
            onClick={() => setMobileView('map')}
            className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-xs font-bold transition-all
              ${mobileView === 'map' 
                ? 'bg-amber-500 text-slate-950 shadow-sm' 
                : 'text-slate-400 hover:bg-slate-850'}`}
          >
            <Map className="w-4 h-4" />
            <span>Interactive Map</span>
          </button>
        </div>

        {/* ================= CAMP AND FLASH OFFER BANNER SLIDESHOW ================= */}
        <OffersSlider onSelectProperty={handleSelectProperty} />

        {/* ================= FULL LAYOUT SPLIT GRID ================= */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-stretch flex-1">
          
          {/* ================= LEFT 5 COLUMNS: FILTERS & CARDS LIST ================= */}
          <div className={`col-span-1 lg:col-span-6 xl:col-span-5 flex flex-col gap-6 ${mobileView === 'list' ? 'block' : 'hidden lg:flex'}`}>
            
            {/* Search and Advanced Filters Panel */}
            <div className="bg-slate-900 rounded-2xl p-5 shadow-sm border border-slate-800 flex flex-col gap-4">
              
              {/* Main Search Input */}
              <div className="relative">
                <Search className="absolute top-3.5 left-3.5 w-4 font-bold h-4 text-slate-500" />
                <input
                  type="text"
                  placeholder="Filtered Bihar locations (e.g. Sasaram, Nokha, Bikramganj, Kaimur)..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-10 pr-20 py-3 bg-slate-950 border border-slate-800 rounded-xl text-xs sm:text-sm font-semibold text-slate-200 outline-none focus:ring-2 focus:ring-amber-500 shadow-sm placeholder-slate-600"
                />
                <VoiceAssistant
                  properties={properties}
                  searchQuery={searchQuery}
                  onSearchChange={setSearchQuery}
                  onTypeFilterChange={setTypeFilter}
                  onSelectProperty={handleSelectProperty}
                  onBookProperty={(property) => setPropertyToBook(property)}
                  setDriverPage={setDriverPage}
                />
                {searchQuery && (
                  <button
                    onClick={() => setSearchQuery('')}
                    className="absolute right-3.5 top-3.5 text-slate-500 hover:text-slate-300"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>

              {/* Filters toggle header line */}
              <div className="flex items-center justify-between border-t border-slate-800 pt-3">
                <button
                  type="button"
                  onClick={() => setShowFiltersMobile(!showFiltersMobile)}
                  className="flex items-center gap-1.5 text-xs font-bold text-slate-300 hover:text-white transition-colors"
                >
                  <SlidersHorizontal className="w-4 h-4 text-amber-500" />
                  <span>Configure Map Filters</span>
                  {showFiltersMobile ? (
                    <span className="text-[10px] bg-slate-950 text-slate-400 rounded px-1.5 py-0.5 border border-slate-850 font-bold">Hide</span>
                  ) : (
                    <span className="text-[10px] bg-amber-955 text-amber-450 rounded px-1.5 py-0.5 border border-amber-900/30 font-bold">Show</span>
                  )}
                </button>

                {(typeFilter !== 'all' || maxPrice !== 100 || onlyAvailable) && (
                  <button
                    onClick={resetFilters}
                    className="flex items-center gap-1 text-[10px] sm:text-xs font-bold text-rose-400 hover:text-rose-300 transition"
                  >
                    <RotateCcw className="w-3.5 h-3.5" />
                    <span>Reset All</span>
                  </button>
                )}
              </div>

              {/* Expanded Filter Panel */}
              <AnimatePresence>
                {(showFiltersMobile || window.innerWidth >= 1024) && (
                  <motion.div
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    exit={{ opacity: 0, height: 0 }}
                    className="space-y-4 pt-1 overflow-hidden"
                  >
                    
                    {/* Category Type Filter */}
                    <div className="space-y-1.5">
                      <label className="block text-[10px] font-bold text-slate-500 uppercase tracking-wider">Spot Category</label>
                      <div className="grid grid-cols-5 gap-1 bg-slate-950 hover:bg-slate-900 border border-slate-850 p-1 rounded-xl select-none">
                        {[
                          { key: 'all', label: 'All' },
                          { key: 'charging', label: 'Charging' },
                           { key: 'parking', label: 'Parking' },
                          { key: 'both', label: 'Combined' },
                          { key: 'favorites', label: 'Saved 💖' }
                        ].map((btn) => (
                          <button
                            key={btn.key}
                            type="button"
                            onClick={() => setTypeFilter(btn.key as any)}
                            className={`py-1.5 text-[9px] sm:text-xs font-bold rounded-lg transition-all
                              ${typeFilter === btn.key 
                                ? 'bg-amber-500 text-slate-950 font-black shadow-md' 
                                : 'text-slate-400 hover:text-slate-200'}`}
                          >
                            {btn.label}
                          </button>
                        ))}
                      </div>
                    </div>

                    {/* Double Columns for price and checkbox */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      
                      {/* Price Fare Limit Slider */}
                      <div className="space-y-1.5">
                        <div className="flex justify-between text-[10px] font-bold text-slate-500 uppercase tracking-wider">
                          <span>Max Price Tag</span>
                          <span className="text-amber-400 font-extrabold normal-case">Under ₹{maxPrice}/Hr</span>
                        </div>
                        <input
                          type="range"
                          min="30"
                          max="100"
                          step="5"
                          value={maxPrice}
                          onChange={(e) => setMaxPrice(parseInt(e.target.value))}
                          className="w-full h-1 bg-slate-800 rounded-lg appearance-none cursor-pointer accent-amber-500 focus:outline-none"
                        />
                        <div className="flex justify-between text-[8px] font-bold text-slate-500 font-mono">
                          <span>₹30/hr</span>
                          <span>₹65/hr</span>
                          <span>₹100/hr</span>
                        </div>
                      </div>

                      {/* Filter Slot checkbox */}
                      <div className="flex items-center h-full select-none">
                        <label className="relative flex items-center gap-2.5 cursor-pointer pt-3 sm:pt-0">
                          <input
                            type="checkbox"
                            checked={onlyAvailable}
                            onChange={(e) => setOnlyAvailable(e.target.checked)}
                            className="w-4 h-4 rounded bg-slate-950 border-slate-800 text-amber-500 focus:ring-amber-500 cursor-pointer"
                          />
                          <span className="text-xs font-bold text-slate-350 block text-left">
                            Show Available Only ({filteredProperties.filter(p => p.availableSlots > 0).length})
                          </span>
                        </label>
                      </div>

                    </div>

                  </motion.div>
                )}
              </AnimatePresence>

                      {/* Properties Listings Title banner */}
            <div className="flex items-center justify-between select-none px-1">
              <div className="flex items-center gap-1.5">
                <Filter className="w-4 h-4 text-amber-500" />
                <h3 className="font-bold text-slate-200 text-sm">
                  Active Verified spots <span className="bg-slate-800 text-slate-205 px-2 py-0.5 rounded-full text-xs font-bold font-mono">{filteredProperties.length}</span> Locations
                </h3>
              </div>
              <p className="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Rohtas & Kaimur Districts (Bihar)</p>
            </div>

            {/* Active Proximity Filter Banner */}
            {userLocation && proximityRadius && (
              <div className="bg-amber-500/10 border border-amber-500/30 rounded-xl p-3 flex items-center justify-between gap-2.5 text-left select-none">
                <div className="flex items-center gap-2">
                  <div className="w-7 h-7 rounded-lg bg-amber-500/20 flex items-center justify-center text-amber-400 shrink-0">
                    <MapPin className="w-4 h-4 text-amber-400 animate-pulse" />
                  </div>
                  <div>
                    <span className="text-[10px] uppercase font-black tracking-wider text-amber-400 font-mono block leading-none">Geolocation Filter Active</span>
                    <span className="text-[11px] text-slate-300 font-bold leading-relaxed block mt-0.5">
                      Showing spots within {proximityRadius} km of <span className="text-white">"{nearPropertyTitle || 'Target Location'}"</span>
                    </span>
                  </div>
                </div>
                <button
                  onClick={clearProximityFilter}
                  className="px-2.5 py-1.5 bg-amber-500 hover:bg-amber-450 text-slate-950 font-extrabold text-[10px] rounded-lg shadow-sm transition shrink-0"
                  title="Clear location filter"
                >
                  Clear filter
                </button>
              </div>
            )}

            {/* Cards Listing column */}
            <div className="space-y-4 max-h-[60vh] lg:max-h-[750px] overflow-y-auto pr-1">
              {filteredProperties.length === 0 ? (
                <div className="bg-slate-900 rounded-2xl p-8 border border-slate-850 text-center space-y-3">
                  <div className="w-12 h-12 bg-slate-955 rounded-2xl flex items-center justify-center text-slate-500 mx-auto border border-slate-800">
                    <AlertTriangle className="w-6 h-6 text-amber-500" />
                  </div>
                  <h4 className="font-bold text-white text-sm">No Live Spots Active</h4>
                  <p className="text-slate-400 text-xs max-w-xs mx-auto text-left leading-relaxed">
                    We could not find any active verified property listings. The App Admin must first verify or approve user/owner listing applications in order for them to display here.
                  </p>
                  <button
                    onClick={resetFilters}
                    className="px-4 py-2 bg-amber-500 rounded-xl hover:bg-amber-400 font-bold text-xs text-slate-950 transition-colors"
                  >
                    Reset Filters
                  </button>
                </div>
              ) : (
                filteredProperties.map(property => (
                  <PropertyCard
                    key={property.id}
                    property={property}
                    isSelected={selectedPropertyId === property.id}
                    onSelect={handleSelectProperty}
                    onBookNow={handleBookNowClick}
                    isFavorite={favorites.includes(property.id)}
                    onToggleFavorite={handleToggleFavorite}
                    isAlertActive={alerts.includes(property.id)}
                    onToggleAlert={handleToggleAlert}
                    onShowNearby={handleShowNearby}
                  />
                ))
              )}
            </div>

            {/* ================= BOOKINGS HISTORY TAB OVERVIEW ================= */}
            <div className="bg-slate-900 rounded-2xl p-5 shadow-sm border border-slate-800 mt-2">
              <div className="flex items-center justify-between select-none pb-3 border-b border-slate-800">
                <div className="flex items-center gap-2">
                  <div className="p-1 px-1.5 bg-slate-950 text-amber-500 rounded-lg border border-slate-850">
                    <Ticket className="w-4.5 h-4.5 text-amber-500" />
                  </div>
                  <div className="text-left">
                    <h3 className="font-bold text-white text-sm">Your Reserved Permits</h3>
                    <p className="text-[10px] text-slate-500 font-bold">Offline synchronized vehicle gates passes ({bookings.filter(b => b.userEmail === currentUser.email).length})</p>
                  </div>
                </div>
                
                {bookings.filter(b => b.userEmail === currentUser.email).length > 0 && (
                  <span className="text-[10px] font-extrabold text-emerald-400 bg-emerald-950/40 border border-emerald-900/30 px-2 py-0.5 rounded-full uppercase tracking-wider font-mono">Verified Active</span>
                )}
              </div>

              {bookings.filter(b => b.userEmail === currentUser.email).length === 0 ? (
                <div className="py-8 text-center text-slate-500 text-xs">
                  <Activity className="w-8 h-8 text-slate-600 mx-auto mb-2" />
                  <p>No active entry permits detected under {currentUser.email}.</p>
                  <p className="text-[10px] text-slate-600 mt-1 font-bold">Select an EV station above and click "Book Now" to test checkout payment simulator.</p>
                </div>
              ) : (
                <div className="space-y-3 mt-4 max-h-72 overflow-y-auto pr-1">
                  {bookings.filter(b => b.userEmail === currentUser.email).map((booking) => (
                    <div 
                      key={booking.id} 
                      className="group border border-slate-800 bg-slate-950/60 p-4 rounded-xl space-y-3 relative hover:bg-slate-950 transition-colors text-left"
                    >
                      <div className="flex justify-between items-start">
                        <div>
                          <div className="inline-flex items-center gap-1.5 bg-slate-900 text-amber-400 font-mono text-[10px] font-bold px-2 py-0.5 rounded-md border border-slate-800">
                            <span>Permit Code: {booking.id}</span>
                          </div>
                          
                          <h4 className="font-extrabold text-white text-xs mt-1.5 truncate max-w-[200px]" title={booking.propertyTitle}>
                            {booking.propertyTitle}
                          </h4>
                          <p className="text-[10px] text-slate-400 font-bold mt-1">Plate: <span className="font-mono font-black text-slate-205">{booking.vehicleNumber}</span></p>
                          <p className="text-[9px] text-emerald-400 font-bold italic mt-0.5">Method: Paid ({booking.paymentMethod})</p>

                          <div className="mt-1.5">
                            {booking.status === 'Completed' ? (
                              <span className="inline-flex items-center gap-0.5 text-[9px] bg-emerald-950 text-emerald-350 border border-emerald-900/40 font-black px-1.5 py-0.5 rounded uppercase tracking-wider font-mono">
                                ✓ Space Arrived
                              </span>
                            ) : (
                              <span className="inline-flex items-center gap-0.5 text-[9px] bg-amber-955 text-amber-450 border border-amber-900/40 font-black px-1.5 py-0.5 rounded uppercase tracking-wider font-mono">
                                • Confirmed Pass
                              </span>
                            )}
                          </div>
                        </div>

                        {/* Cost & Delete Trigger */}
                        <div className="text-right flex flex-col items-end">
                          <span className="text-xs font-black text-white flex items-center justify-end font-mono">
                            <IndianRupee className="w-3 h-3 stroke-[2.5]" />
                            <span>{booking.totalFare}</span>
                          </span>

                          {booking.status !== 'Completed' && (
                            <button
                              type="button"
                              onClick={() => handleCancelBooking(booking)}
                              className="mt-1.5 p-1 text-slate-500 hover:text-rose-400 rounded-md hover:bg-rose-955/40 transition-colors border border-transparent hover:border-rose-900/40"
                              title="Cancel Reservation Slots"
                            >
                              <Trash2 className="w-3.5 h-3.5 shrink-0" />
                            </button>
                          )}
                        </div>
                      </div>

                      {/* Ticket dynamic metadata Grid */}
                      <div className="grid grid-cols-2 gap-2 bg-slate-900 border border-slate-800 p-2 rounded-lg text-[10px] font-bold text-slate-400 font-mono">
                        <div className="flex items-center gap-1">
                          <Calendar className="w-3 h-3 text-slate-500" />
                          <span>{booking.bookingDate}</span>
                        </div>
                        <div className="flex items-center gap-1 text-right justify-end">
                          <Clock className="w-3 h-3 text-slate-500" />
                          <span className="truncate">{booking.timeSlot}</span>
                        </div>
                      </div>

                      {/* Map Focus helper & QR Code visual trigger */}
                      <div className="grid grid-cols-2 gap-1.5 pt-1">
                        <button
                          type="button"
                          onClick={() => handleSelectProperty(booking.propertyId)}
                          className="py-1 text-center text-[10px] bg-slate-900 hover:bg-slate-850 text-slate-350 font-bold rounded-lg transition-colors flex items-center justify-center gap-1 font-mono border border-slate-800"
                        >
                          <MapPin className="w-3 h-3 text-slate-500" />
                          <span>Locate</span>
                        </button>

                        <button
                          type="button"
                          onClick={() => setActiveQrBooking(booking)}
                          className={`py-1 text-center text-[10px] font-black rounded-lg transition-colors flex items-center justify-center gap-1 font-mono cursor-pointer
                            ${booking.status === 'Completed'
                              ? 'bg-emerald-600 hover:bg-emerald-700 text-white'
                              : 'bg-amber-500 hover:bg-amber-400 text-slate-950'
                            }`}
                        >
                          <QrCode className="w-3 h-3" />
                          <span>{booking.status === 'Completed' ? 'Permit' : 'QR Pass'}</span>
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>        </div>

          </div>

          {/* ================= RIGHT 7 COLUMNS: LEAFLET MAP ELEMENT ================= */}
          <div className={`col-span-1 lg:col-span-6 xl:col-span-7 h-[500px] lg:h-auto min-h-[450px] lg:min-h-[750px] sticky top-20 z-10 flex flex-col ${mobileView === 'map' ? 'block' : 'hidden lg:block'}`}>
            <MapContainer
              properties={filteredProperties}
              selectedPropertyId={selectedPropertyId}
              onSelectProperty={handleSelectProperty}
            />
          </div>

        </div>
            </motion.div>
          ) : driverPage === 'bookings' ? (
            <motion.div
              key="bookings-module"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.15 }}
              className="flex-1"
            >
              <MyBookingsPage
                currentUser={currentUser}
                bookings={bookings}
                properties={properties}
                onCancelBooking={handleCancelBooking}
                onViewQrCode={setActiveQrBooking}
                onSubmitReview={handleSubmitReview}
                onSelectProperty={(propertyId) => {
                  setSelectedPropertyId(propertyId);
                  setDriverPage('explore');
                  if (window.innerWidth < 1024) {
                    setMobileView('map');
                  }
                }}
              />
            </motion.div>
          ) : driverPage === 'profile' ? (
            <motion.div
              key="profile-module"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.15 }}
              className="flex-1"
            >
              <ProfilePage
                currentUser={currentUser}
                onUpdateProfile={handleUpdateProfile}
                bookings={bookings}
              />
            </motion.div>
          ) : driverPage === 'repair' ? (
            <motion.div
              key="repair-module"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.15 }}
              className="flex-1"
            >
              <RepairPage
                currentUser={currentUser!}
                mechanics={mechanics}
                repairBookings={repairBookings}
                emergencySubscriptions={emergencySubscriptions}
                userBookings={bookings}
                onBookRepair={(newBook) => setRepairBookings(prev => [newBook, ...prev])}
                onSubscribeEmergency={(newSub) => setEmergencySubscriptions(prev => [newSub, ...prev])}
                onUpdateWallet={(newBal) => {
                  setCurrentUser(prev => prev ? { ...prev, walletBalance: newBal } : null);
                  setAllUsers(prevUsers => prevUsers.map(u => u.email.toLowerCase() === currentUser?.email.toLowerCase() ? { ...u, walletBalance: newBal } : u));
                }}
                onDispatchEmergency={(bookingId) => {
                  setRepairBookings(prev => prev.map(log => log.id === bookingId ? { ...log, status: 'Completed' } : log));
                }}
              />
            </motion.div>
          ) : (
            <motion.div
              key="help-module"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.15 }}
              className="flex-1"
            >
              <HelpPage
                currentUser={currentUser}
                bookings={bookings}
                properties={properties}
              />
            </motion.div>
          )}
        </AnimatePresence>

      </main>

      {/* ================= BOTTOM DESIGN PHILOSOPHY FOOTER ================= */}
      <footer className="bg-slate-900 border-t border-slate-800 py-6 mt-12 select-none shrink-0 text-slate-400">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-sm flex flex-col sm:flex-row items-center justify-between gap-4">
          <div>
            <p className="font-bold text-slate-300">ChargeBuddy Locator — Bihar Region</p>
            <p className="text-xs text-slate-500 mt-1">Smart Reservation Hub powered by React & Leaflet Routing Map.</p>
          </div>
          <div className="flex items-center gap-1.5 text-xs text-slate-400 bg-slate-950 px-3 py-1.5 border border-slate-800 rounded-lg font-mono">
            <span className="w-2.5 h-2.5 bg-emerald-500 border border-emerald-700 rounded-full inline-block animate-pulse"></span>
            <span>Real-time Gate Access Active</span>
          </div>
        </div>
      </footer>

      {/* ================= MODAL WIZARDS ================= */}
      <AnimatePresence>
        
        {/* Step 1: Booking Wizard details form */}
        {propertyToBook && (
          <BookingForm
            property={propertyToBook}
            onClose={() => setPropertyToBook(null)}
            currentUser={currentUser}
            onConfirmBooking={handleRouteToPaymentGateway}
          />
        )}

        {/* Step 2: Pay via PhonePe, online debit card or COD Payment layout */}
        {pendingPaymentBooking && (
          <PaymentModal
            property={pendingPaymentBooking.property}
            bookingData={pendingPaymentBooking.bookingData}
            currentUser={currentUser!}
            onPaymentSuccess={handleCompleteTransactionByGateway}
            onCancel={() => setPendingPaymentBooking(null)}
          />
        )}

        {/* Step 3: Passenger Station Access Boarding Pass with dynamic API QR Code */}
        {activeQrBooking && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 overflow-y-auto bg-slate-950/80 p-4 flex items-center justify-center backdrop-blur-sm"
          >
            <motion.div
              initial={{ scale: 0.95, y: 15 }}
              animate={{ scale: 1, y: 0 }}
              exit={{ scale: 0.95, y: 15 }}
              className="bg-slate-900 border border-slate-800 rounded-3xl max-w-sm w-full overflow-hidden shadow-2xl relative select-none"
            >
              
              {/* Artistic Background Accent */}
              <div className="absolute top-0 inset-x-0 h-40 bg-gradient-to-b from-indigo-600/15 via-transparent to-transparent pointer-events-none"></div>

              {/* Header */}
              <div className="px-6 pt-6 pb-4 border-b border-slate-800/60 flex justify-between items-center relative z-10">
                <div className="flex items-center gap-1.5 text-indigo-400">
                  <QrCode className="w-5 h-5 text-indigo-400" />
                  <span className="text-[10px] font-black uppercase tracking-wider font-mono">Entry Permit Pass</span>
                </div>
                
                <button
                  type="button"
                  onClick={() => setActiveQrBooking(null)}
                  className="p-1 text-slate-400 hover:text-white hover:bg-slate-800 rounded-lg text-xs font-bold font-mono transition-colors"
                >
                  ✕ Close
                </button>
              </div>

              {/* Pass Main Content */}
              <div className="p-6 space-y-6 relative z-10 text-center">
                
                {/* Boarding Pass cutouts visual layout */}
                <div className="space-y-4">
                  <div>
                    <h3 className="text-base font-black text-white tracking-tight">
                      {activeQrBooking.propertyTitle}
                    </h3>
                    <p className="text-[10px] text-slate-400 font-mono mt-0.5">
                      ChargeBuddy verified spot permit • Bihar Region
                    </p>
                  </div>

                  {/* QR Code Container */}
                  <div className="relative bg-white p-4 rounded-2xl max-w-[200px] mx-auto shadow-md border-2 border-slate-800">
                    
                    <img 
                      src={`https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=${encodeURIComponent(activeQrBooking.id)}&color=020617`} 
                      alt="Digitization entry QR code" 
                      className="w-full h-auto"
                      referrerPolicy="no-referrer"
                    />

                    {/* Stamp overlay if checked in */}
                    {activeQrBooking.status === 'Completed' && (
                      <div className="absolute inset-0 bg-emerald-500/95 backdrop-blur-[2px] flex flex-col justify-center items-center text-slate-950 font-black uppercase rounded-2xl rotate-3 scale-102 border-4 border-white animate-fade-in">
                        <CheckCircle2 className="w-10 h-10 text-slate-950 mb-1 stroke-[2.5]" />
                        <span className="text-xs font-black tracking-widest font-mono">Arrival Verified</span>
                        <span className="text-[8px] tracking-wide font-medium mt-1 font-mono">CHECKED IN</span>
                      </div>
                    )}
                  </div>

                  {/* Permit ID display */}
                  <div className="bg-slate-950/85 border border-slate-800 rounded-xl p-2.5 max-w-[240px] mx-auto flex items-center justify-between text-xs font-mono">
                    <span className="text-slate-500 text-[10px]">PASSCODE:</span>
                    <strong className="text-amber-400 tracking-wider font-extrabold">{activeQrBooking.id}</strong>
                  </div>

                </div>

                {/* Technical Segment list line */}
                <div className="border-t border-dashed border-slate-800 my-4 relative">
                  <div className="absolute -left-9 -top-2.5 w-5 h-5 bg-slate-950 border-r border-slate-800 rounded-full"></div>
                  <div className="absolute -right-9 -top-2.5 w-5 h-5 bg-slate-950 border-l border-slate-800 rounded-full"></div>
                </div>

                {/* Specs Data Grid */}
                <div className="grid grid-cols-2 gap-y-4 gap-x-2 text-left text-xs bg-slate-950/40 p-4 border border-slate-800/80 rounded-2xl font-mono">
                  <div>
                    <span className="text-[9px] text-slate-500 block">DRIVER / EMAIL</span>
                    <span className="text-slate-200 font-bold truncate block max-w-[130px] font-sans" title={activeQrBooking.userName}>
                      {activeQrBooking.userName}
                    </span>
                  </div>

                  <div>
                    <span className="text-[9px] text-slate-500 block">VEHICLE PLATE</span>
                    <span className="text-amber-400 font-extrabold block">{activeQrBooking.vehicleNumber}</span>
                  </div>

                  <div className="border-t border-slate-800/60 pt-2 col-span-2"></div>

                  <div>
                    <span className="text-[9px] text-slate-500 block">TIME SLOT</span>
                    <span className="text-slate-200 block truncate max-w-[130px]">{activeQrBooking.timeSlot}</span>
                  </div>

                  <div>
                    <span className="text-[9px] text-slate-500 block">DATE APPROVED</span>
                    <span className="text-slate-200 block">{activeQrBooking.bookingDate}</span>
                  </div>
                </div>

                {/* Access instructions context helper */}
                <div className="p-3 bg-indigo-500/10 border border-indigo-500/20 text-indigo-300 rounded-xl text-[10px] text-left leading-relaxed font-medium">
                  {activeQrBooking.status === 'Completed' ? (
                    <p className="text-center text-emerald-400 font-extrabold uppercase tracking-wide">
                      ⚡ Check-in Cleared. Charging plug & parking spot is unlocked.
                    </p>
                  ) : (
                    <p>
                      💡 <strong>Access Instructions:</strong> Display this QR Code to the facility terminal gate camera or hand it over to the parking guard to confirm placement and check-in.
                    </p>
                  )}
                </div>

              </div>

            </motion.div>
          </motion.div>
        )}

      </AnimatePresence>

      {/* ================= FLOATING NOTIFICATIONS SYSTEM (SLOT ALERTS & CUSTOM TOAST PANEL) ================= */}
      <div className="fixed bottom-5 right-5 z-50 flex flex-col gap-3 min-w-[280px] max-w-[380px] pointer-events-none">
        <AnimatePresence>
          {toasts.map(toast => (
            <motion.div
              key={toast.id}
              initial={{ opacity: 0, y: 30, scale: 0.9 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={{ opacity: 0, scale: 0.85, transition: { duration: 0.15 } }}
              className="pointer-events-auto bg-slate-900/95 border border-amber-500/40 backdrop-blur-md p-4 rounded-2xl shadow-xl space-y-2 text-left relative cursor-pointer hover:border-amber-400 transition-colors select-none"
              onClick={() => {
                // Focus/scroll/highlight the property!
                handleSelectProperty(toast.propertyId);
                // Highlight/Scroll action
                const el = document.getElementById(`property-card-${toast.propertyId}`);
                if (el) {
                  el.scrollIntoView({ behavior: 'smooth' });
                }
                // Dismiss toast
                setToasts(prev => prev.filter(t => t.id !== toast.id));
              }}
            >
              <div className="flex items-start gap-2.5">
                <div className="w-8 h-8 rounded-xl bg-amber-500/10 flex items-center justify-center text-amber-500 border border-amber-500/20 shrink-0">
                  <Bell className="w-4 h-4 text-amber-400 fill-amber-400 animate-bounce" />
                </div>
                <div className="flex-1">
                  <div className="flex justify-between items-start">
                    <span className="text-[10px] font-extrabold text-amber-400 uppercase tracking-widest leading-none font-mono">Slot Available!</span>
                    <button
                      onClick={(e) => {
                        e.stopPropagation(); // Avoid triggering select action
                        setToasts(prev => prev.filter(t => t.id !== toast.id));
                      }}
                      className="text-slate-400 hover:text-white pb-1 pl-1"
                    >
                      <X className="w-3.5 h-3.5" />
                    </button>
                  </div>
                  <h5 className="text-xs font-bold text-white mt-1">{toast.propertyName}</h5>
                  <p className="text-[11px] text-slate-350 leading-relaxed mt-1">
                    {toast.message}
                  </p>
                </div>
              </div>
              <div className="flex items-center justify-end gap-1 text-[9px] font-bold text-amber-400 pt-1">
                <span>View Spot Listing</span>
                <ArrowRight className="w-3 h-3" />
              </div>
            </motion.div>
          ))}
        </AnimatePresence>
      </div>

    </div>
  );
}
