// import React, {
//   useEffect,
//   useState,
//   useCallback,
//   useRef,
//   useMemo,
// } from "react";
// import {
//   SafeAreaView,
//   View,
//   BackHandler,
//   Text,
//   StyleSheet,
//   Image,
//   Modal,
//   FlatList,
//   ScrollView,
//   TouchableWithoutFeedback,
// } from "react-native";
// import { useFocusEffect, useIsFocused } from "@react-navigation/native";
// import { commonStyles } from "../../../styles/commonStyle";
// import { TodayOfferContainer } from "../../../components/homeScreen/todaysOffer";
// import { TopCategory } from "../../../components/homeScreen/topCategory";
// import { HomeSlider } from "../../../components/homeScreen/slider";
// import { HeaderContainer } from "../../../components/homeScreen/headerContainer";
// import styles from "./styles";
// import { useValues } from "@src/utils/context/index";
// import { Button, LowBalance } from "@src/commonComponent";
// import { external } from "../../../styles/externalStyle";
// import {
//   appColors,
//   appFonts,
//   fontSizes,
//   windowHeight,
//   windowWidth,
// } from "@src/themes";
// import { useDispatch, useSelector } from "react-redux";
// import {
//   vehicleData,
//   vehicleTypeDataGet,
// } from "../../../api/store/actions/vehicleTypeAction";
// import { useAppNavigation } from "@src/utils/navigation";
// import { Recentbooking } from "@src/screens/recentBooking";
// import {
//   allRides,
//   notificationDataGet,
//   paymentsData,
//   serviceDataGet,
//   taxidosettingDataGet,
//   userSaveLocation,
//   walletData,
// } from "@src/api/store/actions";
// import { HomeLoader } from "../HomeLoader";
// import useSmartLocation from "@src/components/helper/locationHelper";
// import BottomSheet, {
//   BottomSheetBackdrop,
//   BottomSheetFlatList,
//   BottomSheetScrollView,
//   BottomSheetView,
// } from "@gorhom/bottom-sheet";
// import { getValue } from "@src/utils/localstorage";
// import { userZone } from "@src/api/store/actions";
// import Images from "@src/utils/images";
// import AsyncStorage from "@react-native-async-storage/async-storage";
// import { WebView } from "react-native-webview";
// import { AppDispatch } from "@src/api/store";

// export function HomeScreen() {
//   const dispatch = useDispatch<AppDispatch>();
//   const {
//     textColorStyle,
//     viewRTLStyle,
//     isDark,
//     bgFullStyle,
//     setIsRTL,
//     isRTL,
//     Google_Map_Key,
//   } = useValues();
//   const isFocused = useIsFocused();
//   const { translateData, taxidoSettingData } = useSelector(
//     (state: any) => state.setting
//   );
//   const { reset } = useAppNavigation();
//   const { self } = useSelector((state: any) => state.account);
//   const { homeScreenDataPrimary, loading } = useSelector(
//     (state: any) => state.home
//   );
//   const { currentLatitude: latitude, currentLongitude: longitude } =
//     useSmartLocation();

//   const [displayLatitude, setDisplayLatitude] = useState<number | null>(null);
//   const [displayLongitude, setDisplayLongitude] = useState<number | null>(null);
//   const [lowBalance, setLowBalance] = useState<boolean>(false)

//   const exitBottomSheetRef = useRef<BottomSheet>(null);
//   const homeBottomSheetRef = useRef<BottomSheet>(null);

//   const exitSnapPoints = useMemo(() => ["1%", "22%"], []);
//   const homeSnapPoints = useMemo(() => ["35%", "85%"], []);

//   const [serviceAvilable, setServiceAvailable] = useState<null | boolean>(null);
//   const [loaderService, setLoaderService] = useState(false);
//   const [sheetIndex, setSheetIndex] = useState(0);

//   const mapType = taxidoSettingData?.cabbooking_values?.location?.map_provider;

//   useEffect(() => {
//     const fetchSelectedLocation = async () => {
//       const selectedLat = await getValue("user_latitude_Selected");
//       const selectedLng = await getValue("user_longitude_Selected");

//       if (selectedLat && selectedLng) {
//         setDisplayLatitude(parseFloat(selectedLat));
//         setDisplayLongitude(parseFloat(selectedLng));
//       } else {
//         setDisplayLatitude(latitude);
//         setDisplayLongitude(longitude);
//       }
//     };
//     fetchSelectedLocation();
//   }, [latitude, longitude, isFocused]);

//   const googleMapHtml = useMemo(() => {
//     if (!displayLatitude || !displayLongitude) return "";

//     const mapStyles = isDark
//       ? [
//         { elementType: "geometry", stylers: [{ color: "#212121" }] },
//         { elementType: "labels.icon", stylers: [{ visibility: "off" }] },
//         { elementType: "labels.text.fill", stylers: [{ color: "#757575" }] },
//         {
//           elementType: "labels.text.stroke",
//           stylers: [{ color: "#212121" }],
//         },
//         {
//           featureType: "administrative",
//           elementType: "geometry",
//           stylers: [{ color: "#757575" }],
//         },
//         {
//           featureType: "poi",
//           elementType: "geometry",
//           stylers: [{ color: "#282828" }],
//         },
//         {
//           featureType: "road",
//           elementType: "geometry",
//           stylers: [{ color: "#383838" }],
//         },
//         {
//           featureType: "water",
//           elementType: "geometry",
//           stylers: [{ color: "#000000" }],
//         },
//       ]
//       : [];

//     return `
//     <!DOCTYPE html>
//     <html>
//       <head>
//         <meta name="viewport" content="initial-scale=1.0, width=device-width" />
//         <style>
//           html, body, #map {
//             height: 100%;
//             width: 100%;
//             margin: 0;
//             padding: 0;
//           }
//         </style>
//         <script src="https://maps.googleapis.com/maps/api/js?key=${Google_Map_Key}"></script>
//         <script>
//           function initMap() {
//             const center = { lat: ${displayLatitude}, lng: ${displayLongitude} };
//             const map = new google.maps.Map(document.getElementById('map'), {
//               center,
//               zoom: 15,
//               disableDefaultUI: true,
//               styles: ${JSON.stringify(mapStyles)}
//             });
//             new google.maps.Marker({
//               position: center,
//               map
//             });
//           }
//           window.onload = initMap;
//         </script>
//       </head>
//       <body>
//         <div id="map"></div>
//       </body>
//     </html>
//     `;
//   }, [displayLatitude, displayLongitude, isDark]);

//   const osmHtml = useMemo(() => {
//     if (!displayLatitude || !displayLongitude) return "";

//     return `
//     <!DOCTYPE html>
//     <html>
//       <head>
//         <meta name="viewport" content="width=device-width, initial-scale=1.0">
//         <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
//         <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
//         <style>
//           html, body, #map {
//             height: 100%;
//             width: 100%;
//             margin: 0;
//             padding: 0;
//           }
//         </style>
//       </head>
//       <body>
//         <div id="map"></div>
//         <script>
//           const map = L.map('map').setView([${displayLatitude}, ${displayLongitude}], 15);
//           L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
//             maxZoom: 19
//           }).addTo(map);
//           L.marker([${displayLatitude}, ${displayLongitude}]).addTo(map);
//         </script>
//       </body>
//     </html>
//     `;
//   }, [displayLatitude, displayLongitude]);

//   useEffect(() => {
//     const loadLanguageFromStorage = async () => {
//       const savedLanguage = await AsyncStorage.getItem("selectedLanguage");
//       if (savedLanguage === "ar") setIsRTL(true);
//       else setIsRTL(false);
//     };
//     loadLanguageFromStorage();
//   }, []);

//   const getVehicleTypes = useCallback(async () => {
//     if (latitude && longitude) {
//       dispatch(
//         vehicleTypeDataGet({
//           locations: [{ lat: latitude, lng: longitude }],
//         })
//       );
//     }
//   }, [dispatch, latitude, longitude]);

//   useEffect(() => {
//     dispatch(taxidosettingDataGet());
//     dispatch(allRides());
//     dispatch(serviceDataGet());
//     dispatch(vehicleData());
//     dispatch(walletData());
//     dispatch(paymentsData());
//     dispatch(notificationDataGet());
//     dispatch(userSaveLocation());
//     getVehicleTypes();
//   }, [dispatch, getVehicleTypes]);

//   useEffect(() => {
//     const getAddress = async () => {
//       let lat = await getValue("user_latitude_Selected");
//       let lng = await getValue("user_longitude_Selected");

//       let finalLat = lat ? parseFloat(lat) : latitude;
//       let finalLng = lng ? parseFloat(lng) : longitude;

//       if (!finalLat || !finalLng) return;

//       setLoaderService(true);
//       dispatch(
//         userZone({ lat: finalLat.toString(), lng: finalLng.toString() })
//       ).then((res: any) => {
//         setServiceAvailable(!!res?.payload?.id);
//         setLoaderService(false);
//       });
//     };
//     getAddress();
//   }, [latitude, longitude, isFocused]);

//   useEffect(() => {
//     const backAction = () => {
//       exitBottomSheetRef.current?.expand();
//       return true;
//     };
//     if (isFocused) {
//       const backHandler = BackHandler.addEventListener(
//         "hardwareBackPress",
//         backAction
//       );
//       return () => backHandler.remove();
//     }
//   }, [isFocused]);

//   const exitAndRestart = useCallback(() => {
//     exitBottomSheetRef.current?.close();
//     setTimeout(() => {
//       BackHandler.exitApp();
//       reset({ index: 0, routes: [{ name: "Splash" }] });
//     }, 500);
//   }, [reset]);

//   const renderBackdrop = useCallback(
//     (props: any) => (
//       <BottomSheetBackdrop
//         {...props}
//         appearsOnIndex={0}
//         disappearsOnIndex={-1}
//         pressBehavior="close"
//       />
//     ),
//     []
//   );
//   const { walletTypedata }: any = useSelector((state: any) => state.wallet);

//   const isDataEmpty =
//     !homeScreenDataPrimary || Object.keys(homeScreenDataPrimary).length === 0;


//   useFocusEffect(
//     useCallback(() => {
//       if (walletTypedata?.balance < 0) {
//         setLowBalance(true);
//       } else {
//         setLowBalance(false);
//       }
//     }, [walletTypedata?.balance])
//   );
//   const renderItem = useCallback(({ item }) => {
//     return (
//       <View style={styles.card}>
//         <Text>Item {item.id}</Text>
//       </View>
//     )
//   }, [])

//   const horizontalData = Array.from({ length: 10 }).map((_, i) => ({
//     id: i.toString(),
//   }))

//   return (
//     <View
//       style={[
//         commonStyles.flexContainer,
//         {
//           backgroundColor: isDark ? appColors.solidBorder : appColors.lightGray,
//         },
//       ]}
//     >

//       <Modal
//         visible={lowBalance}
//         transparent
//         animationType="fade"
//       >
//         <LowBalance setLowBalance={setLowBalance} />
//       </Modal>

//       <SafeAreaView
//         style={[
//           styles.container,
//           {
//             backgroundColor: isDark
//               ? appColors.primaryText
//               : appColors.whiteColor,
//           },
//         ]}
//       >
//         <HeaderContainer />
//       </SafeAreaView>

//       {displayLatitude && displayLongitude ? (
//         <WebView
//           originWhitelist={["*"]}
//           source={{
//             html: mapType === "osm" ? osmHtml : googleMapHtml,
//           }}
//           style={{ flex: 1 }}
//           javaScriptEnabled
//           domStorageEnabled
//         />
//       ) : (
//         <View style={{ flex: 1 }} />
//       )}

//       <BottomSheet
//         ref={homeBottomSheetRef}
//         index={0}
//         snapPoints={homeSnapPoints}
//         onChange={setSheetIndex}
//         enableContentPanningGesture={false}
//         handleIndicatorStyle={{
//           backgroundColor: appColors.primary,
//           width: windowWidth(55),
//           height: windowHeight(4.8),
//         }}
//         backgroundStyle={{
//           backgroundColor: isDark
//             ? appColors.primaryText
//             : appColors.whiteColor,
//         }}
//       >
//         {loading || isDataEmpty ? (
//           <HomeLoader />
//         ) : (
//           <BottomSheetScrollView
//             showsVerticalScrollIndicator={false}
//             contentContainerStyle={styles.content}
//           >
//             <TouchableWithoutFeedback>
//               {loaderService || serviceAvilable === null ? (
//                 <HomeLoader />
//               ) : serviceAvilable ? (
//                 <>
//                   {homeScreenDataPrimary?.service_categories?.length > 0 && (
//                     <TopCategory
//                       categoryData={homeScreenDataPrimary.service_categories}
//                       sheetIndex={sheetIndex}
//                       home
//                     />
//                   )}

//                   {homeScreenDataPrimary?.banners?.length > 0 && (
//                     <HomeSlider bannerData={homeScreenDataPrimary.banners} />
//                   )}

//                   {homeScreenDataPrimary?.recent_rides?.length > 0 && (
//                     <Recentbooking
//                       recentRideData={homeScreenDataPrimary.recent_rides}
//                     />
//                   )}

//                   {homeScreenDataPrimary?.coupons?.length > 0 &&
//                     taxidoSettingData?.cabbooking_values?.activation?.coupon_enable ==
//                     1 && (
//                       <View style={styles.todayOfferContainer}>
//                         <TodayOfferContainer
//                           couponsData={homeScreenDataPrimary.coupons}
//                         />
//                       </View>
//                     )}
//                 </>
//               ) : (
//                 <View
//                   style={{
//                     justifyContent: "center",
//                     alignItems: "center",
//                     minHeight: 300,
//                   }}
//                 >
//                   <Image
//                     source={
//                       isDark
//                         ? Images.noServiceImageDark
//                         : Images.noServiceImage
//                     }
//                     resizeMode="contain"
//                     style={styles.image}
//                   />
//                   <Text
//                     style={[
//                       styles.titles,
//                       {
//                         color: isDark
//                           ? appColors.whiteColor
//                           : appColors.primaryText,
//                       },
//                     ]}
//                   >
//                     {translateData.ServiceUnavailableNo}
//                   </Text>
//                 </View>
//               )}
//             </TouchableWithoutFeedback>
//           </BottomSheetScrollView>
//         )}

//       </BottomSheet>



//       <BottomSheet
//         ref={exitBottomSheetRef}
//         index={-1}
//         snapPoints={exitSnapPoints}
//         enablePanDownToClose
//         backdropComponent={renderBackdrop}
//         handleIndicatorStyle={{
//           backgroundColor: appColors.primary,
//           width: "13%",
//         }}
//         backgroundStyle={{ backgroundColor: bgFullStyle }}
//       >
//         <BottomSheetView
//           style={[
//             bottomSheetStyles.contentContainer,
//             {
//               backgroundColor: isDark
//                 ? appColors.primaryText
//                 : appColors.whiteColor,
//             },
//           ]}
//         >
//           <View style={styles.modelView}>
//             <Text
//               style={[
//                 external.ti_center,
//                 {
//                   color: textColorStyle,
//                   fontFamily: appFonts.medium,
//                   fontSize: fontSizes.FONT22,
//                   paddingVertical: windowHeight(10),
//                 },
//               ]}
//             >
//               {translateData?.exitTitle}
//             </Text>
//           </View>
//           <View
//             style={[
//               external.ai_center,
//               external.js_space,
//               { flexDirection: viewRTLStyle },
//             ]}
//           >
//             <Button
//               width={"47%"}
//               title={translateData.no}
//               onPress={() => exitBottomSheetRef.current?.close()}
//               backgroundColor={
//                 isDark ? appColors.blackColor : appColors.blackColor
//               }
//               textColor={appColors.whiteColor}
//             />
//             <Button
//               width={"47%"}
//               backgroundColor={
//                 isDark ? appColors.whiteColor : appColors.lightGray
//               }
//               title={translateData.yes}
//               textColor={isDark ? appColors.blackColor : appColors.primaryText}
//               onPress={exitAndRestart}
//             />
//           </View>
//         </BottomSheetView>
//       </BottomSheet>
//     </View>
//   );
// }

// const bottomSheetStyles = StyleSheet.create({
//   contentContainer: {
//     flex: 1,
//     paddingHorizontal: windowHeight(15),
//     backgroundColor: appColors.whiteColor,
//   },
// });










import React, {
  useEffect,
  useState,
  useCallback,
  useRef,
  useMemo,
} from "react";
import {
  SafeAreaView,
  View,
  BackHandler,
  Text,
  StyleSheet,
  Image,
  Modal,
} from "react-native";
import { useFocusEffect, useIsFocused } from "@react-navigation/native";
import { commonStyles } from "../../../styles/commonStyle";
import { TodayOfferContainer } from "../../../components/homeScreen/todaysOffer";
import { TopCategory } from "../../../components/homeScreen/topCategory";
import { HomeSlider } from "../../../components/homeScreen/slider";
import { HeaderContainer } from "../../../components/homeScreen/headerContainer";
import styles from "./styles";
import { useValues } from "@src/utils/context/index";
import { Button, LowBalance } from "@src/commonComponent";
import { external } from "../../../styles/externalStyle";
import {
  appColors,
  appFonts,
  fontSizes,
  windowHeight,
  windowWidth,
} from "@src/themes";
import { useDispatch, useSelector } from "react-redux";
import {
  vehicleData,
  vehicleTypeDataGet,
} from "../../../api/store/actions/vehicleTypeAction";
import { useAppNavigation } from "@src/utils/navigation";
import { Recentbooking } from "@src/screens/recentBooking";
import {
  allRides,
  notificationDataGet,
  paymentsData,
  serviceDataGet,
  taxidosettingDataGet,
  userSaveLocation,
  walletData,
} from "@src/api/store/actions";
import { HomeLoader } from "../HomeLoader";
import useSmartLocation from "@src/components/helper/locationHelper";
import BottomSheet, {
  BottomSheetBackdrop,
  BottomSheetFlatList,
  BottomSheetScrollView,
  BottomSheetView,
} from "@gorhom/bottom-sheet";
import { getValue } from "@src/utils/localstorage";
import { userZone } from "@src/api/store/actions";
import Images from "@src/utils/images";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { WebView } from "react-native-webview";
import { AppDispatch } from "@src/api/store";
import { BottomTitle } from "@src/components";
import useStoredLocation from "@src/components/helper/useStoredLocation";

export function HomeScreen() {
  const dispatch = useDispatch<AppDispatch>();
  const {
    textColorStyle,
    viewRTLStyle,
    isDark,
    bgFullStyle,
    setIsRTL,
    Google_Map_Key,
  } = useValues();

  const isFocused = useIsFocused();
  const { translateData, taxidoSettingData } = useSelector(
    (state: any) => state.setting
  );
  const { reset } = useAppNavigation();
  const { self } = useSelector((state: any) => state.account);
  const { homeScreenDataPrimary, loading } = useSelector(
    (state: any) => state.home
  );
  // const { currentLatitude: latitude, currentLongitude: longitude } = useSmartLocation();
  const { currentLatitude, currentLongitude, locationStatus } = useSmartLocation();
  const { latitude, longitude } = useStoredLocation();

  // Determine the actual latitude and longitude to use
  const actualLatitude = latitude || currentLatitude;
  const actualLongitude = longitude || currentLongitude;

  console.log('useSmartLocation', currentLatitude, currentLongitude);
  console.log('useStoredLocation', latitude, longitude);
  console.log('actual location', actualLatitude, actualLongitude);



  const [displayLatitude, setDisplayLatitude] = useState<number | null>(null);
  const [displayLongitude, setDisplayLongitude] = useState<number | null>(null);
  const [isLocationLoading, setIsLocationLoading] = useState(true);
  const [lowBalance, setLowBalance] = useState<boolean>(false);
  const [isInitialLoad, setIsInitialLoad] = useState(true);

  const exitBottomSheetRef = useRef<BottomSheet>(null);
  const homeBottomSheetRef = useRef<BottomSheet>(null);
  const hasLoadedData = useRef(false);

  const exitSnapPoints = useMemo(() => ["1%", "22%"], []);
  const homeSnapPoints = useMemo(() => ["37%", "85%"], []);

  const [serviceAvilable, setServiceAvailable] = useState<null | boolean>(null);
  const [loaderService, setLoaderService] = useState(false);
  const [sheetIndex, setSheetIndex] = useState(0);

  const mapType = taxidoSettingData?.cabbooking_values?.location?.map_provider;

  useEffect(() => {
    const fetchSelectedLocation = async () => {
      // Check if there's a previously selected location
      const selectedLat = await getValue("user_latitude_Selected");
      const selectedLng = await getValue("user_longitude_Selected");

      if (selectedLat && selectedLng) {
        // Use the selected location if available
        setDisplayLatitude(parseFloat(selectedLat));
        setDisplayLongitude(parseFloat(selectedLng));
        setIsLocationLoading(false);
      } else if (actualLatitude && actualLongitude) {
        // Use current location if available
        setDisplayLatitude(actualLatitude);
        setDisplayLongitude(actualLongitude);
        setIsLocationLoading(false);
      } else {
        // Still loading, keep showing loader
        setIsLocationLoading(true);
      }
    };

    fetchSelectedLocation();
  }, [actualLatitude, actualLongitude, isFocused, locationStatus]);

  const googleMapHtml = useMemo(() => {
    if (!displayLatitude || !displayLongitude) return "";

    const mapStyles = isDark
      ? [
        { elementType: "geometry", stylers: [{ color: "#212121" }] },
        { elementType: "labels.icon", stylers: [{ visibility: "off" }] },
        { elementType: "labels.text.fill", stylers: [{ color: "#757575" }] },
        {
          elementType: "labels.text.stroke",
          stylers: [{ color: "#212121" }],
        },
        {
          featureType: "administrative",
          elementType: "geometry",
          stylers: [{ color: "#757575" }],
        },
        {
          featureType: "poi",
          elementType: "geometry",
          stylers: [{ color: "#282828" }],
        },
        {
          featureType: "road",
          elementType: "geometry",
          stylers: [{ color: "#383838" }],
        },
        {
          featureType: "water",
          elementType: "geometry",
          stylers: [{ color: "#000000" }],
        },
      ]
      : [];

    return `
    <!DOCTYPE html>
    <html>
      <head>
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <style>
          html, body, #map {
            height: 100%;
            width: 100%;
            margin: 0;
            padding: 0;
          }
        </style>
        <script src="https://maps.googleapis.com/maps/api/js?key=${Google_Map_Key}"></script>
        <script>
          function initMap() {
            const center = { lat: ${displayLatitude}, lng: ${displayLongitude} };
            const map = new google.maps.Map(document.getElementById('map'), {
              center,
              zoom: 15,
              disableDefaultUI: true,
              styles: ${JSON.stringify(mapStyles)}
            });
            new google.maps.Marker({
              position: center,
              map
            });
          }
          window.onload = initMap;
        </script>
      </head>
      <body>
        <div id="map"></div>
      </body>
    </html>
    `;
  }, [displayLatitude, displayLongitude, isDark]);

  const osmHtml = useMemo(() => {
    if (!displayLatitude || !displayLongitude) return "";

    return `
    <!DOCTYPE html>
    <html>
      <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
        <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
        <style>
          html, body, #map {
            height: 100%;
            width: 100%;
            margin: 0;
            padding: 0;
          }
        </style>
      </head>
      <body>
        <div id="map"></div>
        <script>
          const map = L.map('map').setView([${displayLatitude}, ${displayLongitude}], 15);
          L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19
          }).addTo(map);
          L.marker([${displayLatitude}, ${displayLongitude}]).addTo(map);
        </script>
      </body>
    </html>
    `;
  }, [displayLatitude, displayLongitude]);

  useEffect(() => {
    const loadLanguageFromStorage = async () => {
      const savedLanguage = await AsyncStorage.getItem("selectedLanguage");
      if (savedLanguage === "ar") setIsRTL(true);
      else setIsRTL(false);
    };
    loadLanguageFromStorage();
  }, []);


  // Load all required data when the screen is focused
  useFocusEffect(
    useCallback(() => {
      const loadAllData = async () => {
        // Always fetch fresh data on focus for first time or when needed
        if (!hasLoadedData.current || isInitialLoad) {
          await Promise.all([
            dispatch(taxidosettingDataGet()),
            dispatch(allRides()),
            dispatch(serviceDataGet()),
            dispatch(vehicleData()),
            dispatch(walletData()),
            dispatch(paymentsData()),
            dispatch(notificationDataGet()),
            dispatch(userSaveLocation()),
          ]);

          // Fetch vehicle types if location is available
          if (actualLatitude && actualLongitude) {
            await dispatch(
              vehicleTypeDataGet({
                locations: [{ lat: actualLatitude, lng: actualLongitude }],
              })
            );
          }

          hasLoadedData.current = true;
          setIsInitialLoad(false);
        }
      };

      loadAllData();
    }, [dispatch, actualLatitude, actualLongitude, isInitialLoad, locationStatus])
  );

  useEffect(() => {
    const getAddress = async () => {
      let lat = await getValue("user_latitude_Selected");
      let lng = await getValue("user_longitude_Selected");

      // Use stored location first, then fallback to actual location
      let finalLat = lat ? parseFloat(lat) : actualLatitude;
      let finalLng = lng ? parseFloat(lng) : actualLongitude;

      if (!finalLat || !finalLng) {
        // Wait a bit and try again if location is still null
        setTimeout(() => {
          if (!finalLat || !finalLng) {
            getAddress();
          }
        }, 1000);
        return;
      }

      try {
        setLoaderService(true);
        dispatch(
          userZone({ lat: finalLat.toString(), lng: finalLng.toString() }) as any,
        ).then(async (res: any) => {
          if (!res?.payload?.id) {
            setServiceAvailable(false);
            setLoaderService(false);
          } else {
            setServiceAvailable(true);
            setLoaderService(false);
          }
        });
      } catch (error) {
        console.error("Error fetching address:", error);
      }
    };

    if (actualLatitude && actualLongitude) {
      getAddress();
    }
  }, [dispatch, actualLatitude, actualLongitude, taxidoSettingData, locationStatus]);


  useEffect(() => {
    const backAction = () => {
      exitBottomSheetRef.current?.expand();
      return true;
    };
    if (isFocused) {
      const backHandler = BackHandler.addEventListener(
        "hardwareBackPress",
        backAction
      );
      return () => backHandler.remove();
    }
  }, [isFocused]);

  const exitAndRestart = useCallback(() => {
    exitBottomSheetRef.current?.close();
    setTimeout(() => {
      BackHandler.exitApp();
      reset({ index: 0, routes: [{ name: "Splash" }] });
    }, 500);
  }, [reset]);

  const renderBackdrop = useCallback(
    (props: any) => (
      <BottomSheetBackdrop
        {...props}
        appearsOnIndex={0}
        disappearsOnIndex={-1}
        pressBehavior="close"
      />
    ),
    []
  );
  const { walletTypedata }: any = useSelector((state: any) => state.wallet);

  const isDataEmpty =
    !homeScreenDataPrimary || Object.keys(homeScreenDataPrimary).length === 0;


  useFocusEffect(
    useCallback(() => {
      if (walletTypedata?.balance < 0) {
        setLowBalance(true);
      } else {
        setLowBalance(false);
      }
    }, [walletTypedata?.balance])
  );

  return (
    <View
      style={[
        commonStyles.flexContainer,
        {
          backgroundColor: isDark ? appColors.solidBorder : appColors.lightGray,
        },
      ]}
    >
      <Modal
        visible={lowBalance}
        transparent
        animationType="fade"
      >
        <LowBalance setLowBalance={setLowBalance} />
      </Modal>

      <SafeAreaView
        style={[
          styles.container,
          {
            backgroundColor: isDark
              ? appColors.primaryText
              : appColors.whiteColor,
          },
        ]}
      >
        <HeaderContainer />
      </SafeAreaView>

      {(displayLatitude && displayLongitude && !isLocationLoading) ? (
        <WebView
          originWhitelist={["*"]}
          source={{
            html: mapType === "osm" ? osmHtml : googleMapHtml,
          }}
          style={{ flex: 1 }}
          javaScriptEnabled={true}
          domStorageEnabled={true}
          allowFileAccess={false}
          allowUniversalAccessFromFileURLs={false}
          mixedContentMode="compatibility"
          onError={(error) => console.log('WebView error:', error)}
          onHttpError={(error) => console.log('WebView HTTP error:', error)}
        />
      ) : (
        <View style={{ flex: 1, backgroundColor: isDark ? appColors.primaryText : appColors.whiteColor }} />
      )}

      <BottomSheet
        ref={homeBottomSheetRef}
        index={0}
        snapPoints={homeSnapPoints}
        onChange={setSheetIndex}
        enableContentPanningGesture={false}
        handleIndicatorStyle={{
          backgroundColor: appColors.primary,
          width: windowWidth(55),
          height: windowHeight(4.8),
        }}
        backgroundStyle={{
          backgroundColor: isDark
            ? appColors.primaryText
            : appColors.whiteColor,
        }}
      >
        {(loading || isDataEmpty || isLocationLoading) ? (
          <HomeLoader />
        ) : (
          <BottomSheetScrollView
            showsVerticalScrollIndicator={false}
            contentContainerStyle={styles.content}
            scrollEnabled={sheetIndex !== 0}
          >

            {loaderService || serviceAvilable === null ? (
              <HomeLoader />
            ) : serviceAvilable ? (
              <>
                {homeScreenDataPrimary?.service_categories?.length > 0 && (
                  <TopCategory
                    categoryData={homeScreenDataPrimary.service_categories}
                    sheetIndex={sheetIndex}
                    home
                  />
                )}

                {homeScreenDataPrimary?.banners?.length > 0 && (
                  <HomeSlider bannerData={homeScreenDataPrimary.banners} />
                )}
                {homeScreenDataPrimary?.recent_rides?.length > 0 && (
                  <Recentbooking
                    recentRideData={homeScreenDataPrimary.recent_rides}
                  />
                )}

                {homeScreenDataPrimary?.coupons?.length > 0 &&
                  taxidoSettingData?.cabbooking_values?.activation?.coupon_enable ==
                  1 && (
                    <View style={styles.todayOfferContainer}>
                      <TodayOfferContainer
                        couponsData={homeScreenDataPrimary.coupons}
                      />
                    </View>
                  )}

                <BottomTitle />
              </>
            ) : (
              <View
                style={{
                  justifyContent: "center",
                  alignItems: "center",
                  minHeight: 300,
                }}
              >
                <Image
                  source={
                    isDark
                      ? Images.noServiceImageDark
                      : Images.noServiceImage
                  }
                  resizeMode="contain"
                  style={styles.image}
                />
                <Text
                  style={[
                    styles.titles,
                    {
                      color: isDark
                        ? appColors.whiteColor
                        : appColors.primaryText,
                    },
                  ]}
                >
                  {translateData.ServiceUnavailableNo}
                </Text>
              </View>
            )}

          </BottomSheetScrollView>
        )}

      </BottomSheet>



      <BottomSheet
        ref={exitBottomSheetRef}
        index={-1}
        snapPoints={exitSnapPoints}
        enablePanDownToClose
        backdropComponent={renderBackdrop}
        handleIndicatorStyle={{
          backgroundColor: appColors.primary,
          width: "13%",
        }}
        backgroundStyle={{ backgroundColor: bgFullStyle }}
      >
        <BottomSheetView
          style={[
            bottomSheetStyles.contentContainer,
            {
              backgroundColor: isDark
                ? appColors.primaryText
                : appColors.whiteColor,
            },
          ]}
        >
          <View style={styles.modelView}>
            <Text
              style={[
                external.ti_center,
                {
                  color: textColorStyle,
                  fontFamily: appFonts.medium,
                  fontSize: fontSizes.FONT22,
                  paddingVertical: windowHeight(10),
                },
              ]}
            >
              {translateData?.exitTitle}
            </Text>
          </View>
          <View
            style={[
              external.ai_center,
              external.js_space,
              { flexDirection: viewRTLStyle },
            ]}
          >
            <Button
              width={"47%"}
              title={translateData.no}
              onPress={() => exitBottomSheetRef.current?.close()}
              backgroundColor={
                isDark ? appColors.blackColor : appColors.blackColor
              }
              textColor={appColors.whiteColor}
            />
            <Button
              width={"47%"}
              backgroundColor={
                isDark ? appColors.whiteColor : appColors.lightGray
              }
              title={translateData.yes}
              textColor={isDark ? appColors.blackColor : appColors.primaryText}
              onPress={exitAndRestart}
            />
          </View>
        </BottomSheetView>
      </BottomSheet>
    </View>
  );
}

const bottomSheetStyles = StyleSheet.create({
  contentContainer: {
    flex: 1,
    paddingHorizontal: windowHeight(15),
    backgroundColor: appColors.whiteColor,
  },
});
