
import React, { useEffect, useState, useRef, useMemo } from 'react';
import { View, Text, StyleSheet, FlatList, Dimensions, TouchableOpacity, ActivityIndicator, Platform, Animated, Easing, unstable_batchedUpdates, InteractionManager } from 'react-native';
import MapView, { Polyline, Marker, AnimatedRegion } from 'react-native-maps';
import polyline from '@mapbox/polyline';
import Tts from 'react-native-tts';
import { useFocusEffect, useRoute } from '@react-navigation/native';
import Geolocation from 'react-native-geolocation-service';
import Icon from 'react-native-vector-icons/MaterialIcons';
import Container from '../../components/container';
import { Props } from 'react-native-image-zoom-viewer/built/image-viewer.type';
import { BackHandler, Alert } from 'react-native';
import Aviatoricon from '../../assets/image/aviatoricon.svg';
import { OLA_MAP_KEY } from '../../constants/constants';
import { requestLocationPermission } from '../../controller/functions';
import { notify } from '../../components/notify';
const { width, height } = Dimensions.get('window');

const NavigationScreen = (props) => {
  const route = useRoute();
  const { routeData: paramRouteData } = route.params ?? {};
  const [routeData, setRouteData] = useState(() => paramRouteData);
  const data = routeData;

  const mapRef = useRef(null);
  const [routeCoordinates, setRouteCoordinates] = useState([]);
  const [instructions, setInstructions] = useState([]);
  const [isSpeaking, setIsSpeaking] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [currentStepIndex, setCurrentStepIndex] = useState(0);
  const [nextInstruction, setNextInstruction] = useState({ text: '', distance: '', icon: '' });
  const [destinationInfo, setDestinationInfo] = useState({ name: '', distance: '', time: '' });
  const [currentToDestinationCoords, setCurrentToDestinationCoords] = useState([]);
  const [isPanelExpanded, setIsPanelExpanded] = useState(false);
  const [speed, setSpeed] = useState(0);
  const prevPosition = useRef(null);
  const isInitialized = useRef(false);
  const prevRouteDataHash = useRef(null);
  const hasArrived = useRef(false);
  const rotation = useRef(new Animated.Value(0)).current;
  const [isPolylineLoading, setIsPolylineLoading] = useState(false);


  useFocusEffect(
    React.useCallback(() => {
      const backHandler = BackHandler.addEventListener(
        "hardwareBackPress",
        () => {
          props.navigation.goBack();
          return true;
        }
      );
      return () => backHandler.remove();
    }, [])
  );

  const simpleHash = (str) => {
    let hash = 0;
    for (let i = 0; i < (str?.length || 0); i++) {
      const char = str.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash;
    }
    return Math.abs(hash).toString(16);
  };

  const calculateDistance = (point1, point2) => {
    if (!point1?.latitude || !point2?.latitude) return Infinity;
    const R = 6371e3;
    const lat1 = (point1.latitude * Math.PI) / 180;
    const lat2 = (point2.latitude * Math.PI) / 180;
    const deltaLat = ((point2.latitude - point1.latitude) * Math.PI) / 180;
    const deltaLng = ((point2.longitude - point1.longitude) * Math.PI) / 180;
    const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
      Math.cos(lat1) * Math.cos(lat2) * Math.sin(deltaLng / 2) * Math.sin(deltaLng / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return R * c;
  };

  const getManeuverIcon = (maneuver = '') => {
    const m = maneuver.toLowerCase();
    // 🟢 START
    if (m.includes('depart') || m.includes('head')) {
      return 'arrow-upward'; // start / head north
    }
    // 🏁 DESTINATION
    if (m.includes('arrive')) {
      return 'check-circle'; // or 'location-on'
    }
    // 🔄 U-TURN
    if (m.includes('uturn') || m.includes('u-turn')) {
      return 'u-turn-left'; // MaterialIcons
    }
    // ⬅ LEFT
    if (m.includes('left')) {
      return 'arrow-back';
    }
    // ➡ RIGHT
    if (m.includes('right')) {
      return 'arrow-forward';
    }
    // ⬆ STRAIGHT / CONTINUE
    if (m.includes('straight') || m.includes('continue')) {
      return 'arrow-upward';
    }
    // 🛣 MERGE / RAMP
    if (m.includes('merge') || m.includes('ramp')) {
      return 'call_merge';
    }
    // 🔵 ROUNDABOUT
    if (m.includes('roundabout') || m.includes('rotary')) {
      return 'sync'; // best available Material icon
    }
    // DEFAULT
    return 'arrow-forward';
  };

  useEffect(() => {
    const polylineString =
      data?.routes?.[0]?.overview_polyline?.points ||
      data?.routes?.[0]?.overview_polyline;

    if (!polylineString) return;
    let isMounted = true;
    setIsPolylineLoading(true);

    InteractionManager.runAfterInteractions(() => {
      try {
        const decoded = polyline.decode(polylineString).map(([lat, lng]) => ({
          latitude: lat,
          longitude: lng,
        }));
        if (isMounted) {
          setRouteCoordinates(decoded);
          setCurrentToDestinationCoords(decoded);
        }
      } catch (e) {
        console.error('Polyline decode failed', e);
      } finally {
        if (isMounted) setIsPolylineLoading(false);
      }
    });

    return () => {
      isMounted = false;
    };
  }, [data]);

  const calculateBearing = (from, to) => {
    const lat1 = from.latitude * (Math.PI / 180);
    const lon1 = from.longitude * (Math.PI / 180);
    const lat2 = to.latitude * (Math.PI / 180);
    const lon2 = to.longitude * (Math.PI / 180);
    const dLon = lon2 - lon1;
    const y = Math.sin(dLon) * Math.cos(lat2);
    const x =
      Math.cos(lat1) * Math.sin(lat2) -
      Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
    let brng = Math.atan2(y, x) * (180 / Math.PI); // convert to degrees
    brng = (brng + 360) % 360; // normalize to 0-360°
    return brng;
  };


  const stripHtml = (text = '') =>
    text.replace(/<[^>]*>/g, '');

  const updateRouteUI = async (route) => {
    if (!route?.routes?.[0]?.legs?.[0]) return;

    const leg = route.routes[0].legs[0];
    const steps = leg.steps || [];
    setInstructions(steps);
    setCurrentStepIndex(0);

    if (steps.length > 0) {
      setNextInstruction({
        text: steps[0].instructions || 'Follow the route',
        distance: steps[0].readable_distance || '',
        icon: getManeuverIcon(steps[0].maneuver),
      });
    }

    const end = leg.end_location;
    const destinationName = await reverseGeocode(end.lat, end.lng);

    setDestinationInfo({
      name: destinationName || 'Destination',
      distance: leg.readable_distance,
      time: leg.duration
        ? `${Math.round(leg.duration / 60)} mins`
        : 'N/A',
    });
  };


  // init TTS
  useEffect(() => {
    Tts.getInitStatus().then(() => {
      Tts.setDefaultLanguage('en-US');
      Tts.setDefaultRate(0.5);
    });

    return () => Tts.stop();
  }, []);

  // speak on instruction change
  useEffect(() => {
    if (!nextInstruction?.text) return;
    const cleanText = stripHtml(nextInstruction.text);

    Tts.stop();
    Tts.speak(`${cleanText || 'Continue'}. In ${nextInstruction?.distance || '0 m'}.`);
  }, [nextInstruction?.text]);

  useEffect(() => {
    const currentRouteDataHash = simpleHash(JSON.stringify(data));
    let watchId;
    const initialize = async () => {
      try {
        setIsLoading(true);
        console.log('Initializing navigation, timestamp:', Date.now());
        const hasPermission = await requestLocationPermission();
        if (!hasPermission) {
          setError('Location permission denied');
          setIsLoading(false);
          return;
        }

        if (!data?.routes?.[0]?.legs?.[0]) {
          setError('Invalid route data');
          setIsLoading(false);
          return;
        }

        await updateRouteUI(data);

        setIsLoading(false);
        isInitialized.current = true;
        prevRouteDataHash.current = currentRouteDataHash;
      } catch (err) {
        console.error('Initialization error:', err);
        setError('Failed to initialize navigation: ' + err.message);
        setIsLoading(false);
      }
    };

    initialize();

    return () => {
      console.log('Cleaning up initialization useEffect, timestamp:', Date.now());
      if (watchId) Geolocation.clearWatch(watchId);
      isInitialized.current = false;
    };
  }, []);



  const reverseGeocode = async (lat, lng) => {
    try {
      const url = `https://api.olamaps.io/places/v1/reverse-geocode?latlng=${lat},${lng}&language=en&api_key=${OLA_MAP_KEY}`;
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'X-Request-Id': 'my-app-request-123',       // optional, for tracking
          'X-Correlation-Id': 'my-app-correlation-456' // optional
        }
      });

      if (!response.ok) {
        throw new Error(`Reverse geocode failed with status ${response.status}`);
      }
      const data = await response.json();
      return getLastFormattedAddress(data);
    } catch (error) {
      console.error('Error in reverse geocoding:', error);
      return null;
    }
  };

  const getLastFormattedAddress = (apiResponse) => {
    if (
      apiResponse?.status === 'ok' &&
      Array.isArray(apiResponse.results) &&
      apiResponse.results.length > 0
    ) {
      const lastItem = apiResponse.results[apiResponse.results.length - 1];
      return lastItem.formatted_address || '';
    }
    return '';
  };

  const rotateMarker = (bearing) => {
    Animated.timing(rotation, {
      toValue: bearing,
      duration: 300,
      easing: Easing.linear,
      useNativeDriver: false,
    }).start();
  };


  const decodePolyline = (encoded) => {
    if (!encoded) return [];
    return polyline.decode(encoded).map(([lat, lng]) => ({
      latitude: lat,
      longitude: lng,
    }));
  };

  const refetchRouteFromHere = async (userLoc) => {
    try {
      notify("Re-routing…")
      const destinationLat = endLocation.lat;
      const destinationLng = endLocation.lng;
      const url =
        `https://api.olamaps.io/routing/v1/routeOptimizer` +
        `?locations=${userLoc.latitude},${userLoc.longitude}` +
        `|${destinationLat},${destinationLng}` +
        `&mode=driving&api_key=${OLA_MAP_KEY}`;

      const response = await fetch(url, { method: "POST" });

      if (!response.ok) {
        throw new Error("Failed to fetch reroute");
      }

      const newRoute = await response.json();
      // 1️⃣ Decode polyline first
      const encodedPolyline = newRoute?.routes?.[0]?.overview_polyline?.points || newRoute?.routes?.[0]?.overview_polyline;
      const newRouteCoords = decodePolyline(encodedPolyline);
      // 🔁 Swap atomically (NO blank map)
      unstable_batchedUpdates(() => {
        setRouteData(newRoute);
        setRouteCoordinates(newRouteCoords);
        setCurrentToDestinationCoords(newRouteCoords);
        setCurrentStepIndex(0);
        prevPosition.current = null;
      });

      await updateRouteUI(newRoute);

      // 3️⃣ Smooth camera movement (optional)
      mapRef.current?.animateCamera({
        center: userLoc,
        heading: 0,
        pitch: 45,
        zoom: 15,
        duration: 800,
      });

    } catch (err) {
      console.error("❌ Re-route failed:", err.message);
    }
  };

  useEffect(() => {
    let watchId;
    if (isLoading || error || !data?.routes?.[0]?.legs?.[0]?.steps || routeCoordinates.length === 0) {
      return;
    }
    const steps = data.routes[0].legs[0].steps;
    const offRouteCount = { current: 0 };
    const lastRerouteTime = { current: 0 };
    const isRerouting = { current: false };
    watchId = Geolocation.watchPosition(
      position => {
        const { latitude, longitude, speed, heading } = position.coords;
        const userLoc = { latitude, longitude };
        // -----------------------------
        // SPEED (km/h)
        // -----------------------------
        const speedKmh = speed != null && speed >= 0 ? Math.max((speed * 3.6).toFixed(1), 0) : 0;
        setSpeed(speedKmh < 1 ? 0 : speedKmh);
        // -----------------------------
        // BEARING
        // -----------------------------
        const prev = prevPosition.current;
        const brng = prev ? calculateBearing(prev, userLoc) : heading || 0;
        prevPosition.current = userLoc;
        // -----------------------------
        // MOVE USER MARKER
        // -----------------------------
        coordinate.timing({
          latitude,
          longitude,
          duration: 1000,
          useNativeDriver: false,
        }).start();

        rotateMarker(brng);
        // -----------------------------
        // CAMERA (Google-style)
        // -----------------------------
        mapRef.current?.animateCamera({
          center: userLoc,
          heading: brng,
          pitch: 45,
          zoom: 15,
        });

        // -----------------------------
        // SMART OFF-ROUTE CHECK (FIXED)
        // -----------------------------

        let nearestIndex = -1;
        let minDist = Infinity;
        //console.log("routeCoordinates---", routeCoordinates)
        routeCoordinates.forEach((coord, i) => {
          const d = calculateDistance(userLoc, coord);
          if (d < minDist) {
            minDist = d;
            nearestIndex = i;
          }
        });

        const lookAhead = 5;
        const safeIndex = nearestIndex !== -1 ? Math.min(nearestIndex + lookAhead, routeCoordinates.length - 1) : null;
        const nextRoutePoint = safeIndex !== null ? routeCoordinates[safeIndex] : null;
        const routeBearing = nextRoutePoint ? calculateBearing(userLoc, nextRoutePoint) : brng;
        // Proper circular bearing diff
        const headingDiff = Math.abs(((routeBearing - brng + 540) % 360) - 180);
        const offRoute = nearestIndex === -1 || minDist > 40 || headingDiff > 35;
        const now = Date.now();
        console.log("routeCoordinates---", offRoute, offRouteCount.current)
        if (offRoute) {
          offRouteCount.current += 1;
          if (offRouteCount.current >= 3 && now - lastRerouteTime.current > 8000 && !isRerouting.current) {
            console.log("🔁 Re-routing (Google-style)");
            isRerouting.current = true;
            lastRerouteTime.current = now;
            offRouteCount.current = 0;
            refetchRouteFromHere(userLoc);
            setTimeout(() => {
              isRerouting.current = false;
            }, 4000);
            return;
          }
        } else {
          offRouteCount.current = 0;
        }

        // -----------------------------
        // STEP NAVIGATION
        // -----------------------------
        let newStepIndex = currentStepIndex;
        let shouldSpeak = false;
        let instructionText = '';
        let nextInstructionData = {};
        if (currentStepIndex < steps.length) {
          const step = steps[currentStepIndex];
          const distanceToEnd = calculateDistance(userLoc, step.end_location || endLocation);
          if (distanceToEnd < 50) {
            newStepIndex++;
            if (newStepIndex < steps.length) {
              const nextStep = steps[newStepIndex];
              const dist = calculateDistance(userLoc, nextStep.start_location || endLocation);
              const distStr = dist > 1000 ? (dist / 1000).toFixed(1) + ' km' : Math.round(dist) + ' m';
              instructionText = `In ${distStr}, ${nextStep.instructions}.`;
              shouldSpeak = true;
              nextInstructionData = {
                text: nextStep.instructions,
                distance: distStr,
                icon: getManeuverIcon(nextStep.maneuver),
              };
            } else {
              instructionText = "You have arrived at your destination.";
              shouldSpeak = true;
            }
          } else {
            nextInstructionData = {
              text: step.instructions,
              distance: step.readable_distance,
              duration: step.readable_duration,
              icon: getManeuverIcon(step.maneuver),
            };
          }
        }

        // -----------------------------
        // UPDATE ROUTE PROGRESS
        // -----------------------------
        if (nearestIndex !== -1) {
          setCurrentToDestinationCoords(
            routeCoordinates.slice(nearestIndex)
          );
        }

        if (newStepIndex !== currentStepIndex) {
          setCurrentStepIndex(newStepIndex);
        }

        setNextInstruction(nextInstructionData);
      },
      err => {
        console.error("Location error:", err);
        setError("Location tracking failed");
        setIsLoading(false);
      },
      {
        enableHighAccuracy: false,
        distanceFilter: 3,
        interval: 1000,
        fastestInterval: 800,
        showLocationDialog: true,
        forceRequestLocation: true,
      }
    );

    return () => {
      if (watchId) Geolocation.clearWatch(watchId);
    };
  }, [
    isLoading,
    error,
    data,
    currentStepIndex,
    routeCoordinates,
    isSpeaking,
  ]);

  const startLocation = data?.routes?.[0]?.legs?.[0]?.start_location || { lat: 28.527537, lng: 77.275524 };
  const endLocation = data?.routes?.[0]?.legs?.[0]?.end_location || { lat: 28.562196, lng: 77.445004 };
  const coordinate = useRef(
    new AnimatedRegion({
      latitude: startLocation?.lat,
      longitude: startLocation?.lng,
      latitudeDelta: 0,
      longitudeDelta: 0,
    })
  ).current;

  const initialRegion = useMemo(() => {
    const latDelta = Math.abs(endLocation.lat - startLocation.lat) * 1.5 || 0.02;
    const lngDelta = Math.abs(endLocation.lng - startLocation.lng) * 1.5 || 0.02;
    return {
      latitude: (startLocation.lat + endLocation.lat) / 2,
      longitude: (startLocation.lng + endLocation.lng) / 2,
      latitudeDelta: latDelta,
      longitudeDelta: lngDelta,
    };
  }, [startLocation, endLocation]);


  // Function to center map on user's current location with error handling
  const centerMapOnUser = (flag) => {
    console.log('Attempting to center map on user location');

    Geolocation.getCurrentPosition(
      position => {
        const { latitude, longitude } = position.coords;
        const newLoc = { latitude, longitude };
        // Calculate bearing ONLY for marker
        const brng = prevPosition.current
          ? calculateBearing(prevPosition.current, newLoc)
          : position.coords.heading || 0;

        prevPosition.current = newLoc;

        // ✅ MOVE AVIATOR
        coordinate.timing({
          latitude,
          longitude,
          duration: 1000,
          useNativeDriver: false,
        }).start();

        // ✅ ROTATE ONLY AVIATOR
        let values = flag ? 16 : 15
        mapRef.current?.animateCamera({
          center: { latitude, longitude },
          heading: 0,
          pitch: 0,
          zoom: values,
        });

        console.log('Centered map bottom → top (north-up)');
      },
      err => {
        console.error('Error getting current location:', err);
        Alert.alert('Location Error', 'Unable to fetch your location.');
      },
      {
        enableHighAccuracy: true,
        timeout: 15000,
        maximumAge: 10000,
      }
    );
  };

  const renderInstruction = ({ item, index }) => (
    <View style={[styles.instructionItem, index === currentStepIndex && styles.activeInstruction]}>
      <Text style={styles.instructionText}>
        {item.instructions || 'No instruction'} ({item.readable_distance || 'N/A'})
      </Text>

      {/* <TouchableOpacity
        style={[styles.speakButton, isSpeaking && styles.speakButtonDisabled]}
        onPress={() => speakInstruction(item.instructions, item.readable_distance)}
        disabled={isSpeaking}
      >
        <Text style={styles.speakButtonText}>{isSpeaking ? 'Speaking...' : 'Speak'}</Text>
      </TouchableOpacity> */}
    </View>
  );

  if (isLoading && isPolylineLoading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#007AFF" />
        <Text style={styles.loadingText}>Loading navigation...</Text>
      </View>
    );
  }

  if (error) {
    return (
      <View style={styles.errorContainer}>
        <Text style={styles.errorText}>{error}</Text>
        <TouchableOpacity style={styles.retryButton} onPress={() => {
          setError(null);
          setIsLoading(true);
          isInitialized.current = false;
          hasArrived.current = false;
        }}>
          <Text style={styles.retryButtonText}>Retry</Text>
        </TouchableOpacity>
      </View>
    );
  }
  const nextInstructionHeight = 80;
  const myLocationButtonTop = Platform.OS === 'ios' ? nextInstructionHeight + 10 : nextInstructionHeight + 40;


  return (
    <>
      <Container {...Props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
        <View style={styles.container}>
          <View style={[styles.nextInstructionContainer, { marginTop: 30 }]}>
            <Icon name={nextInstruction.icon} size={32} color="#007AFF" style={styles.maneuverIcon} />
            <View style={styles.nextInstructionTextContainer}>
              <Text style={styles.nextInstructionText}>{nextInstruction.text || 'Follow the route'}</Text>
              <Text style={styles.nextInstructionDistance}>{nextInstruction.distance || ''}</Text>
              <Text style={styles.destinationInfoText}>
                Destination: {destinationInfo.name}
                {'\n'}
                Duration: {destinationInfo.distance} • {destinationInfo.time}
              </Text>
            </View>
          </View>
          <MapView
            ref={mapRef}
            style={styles.map}
            showsUserLocation={false}
            initialRegion={initialRegion}
            rotateEnabled={false} // allows map to rotate with heading
            followsUserLocation={false}
            showsMyLocationButton={false}
            zoomControlEnabled={false}
            toolbarEnabled={false}
            showsTraffic={true}
            showsCompass={false}   // ⛔ avoid conflict
            loadingEnabled={true}
            pitchEnabled={false}

          >

            <Marker.Animated
              coordinate={coordinate}
              anchor={{ x: 0.5, y: 0.5 }}
              rotation={rotation.__getValue()}
              tracksViewChanges={false}
              flat={true}
            >
              <Aviatoricon width={80} height={80} />
            </Marker.Animated>


            <Marker
              coordinate={{ latitude: startLocation.lat, longitude: startLocation.lng }}
              tracksViewChanges={false}
              title="Start"

            >
              <View style={{ alignItems: "center" }}>
                <View
                  style={{
                    width: 10,
                    height: 10,
                    borderRadius: 6,
                    backgroundColor: "white",
                    marginTop: 3,
                    borderWidth: 1,
                    borderColor: "red", // ✅ adds border for visibility
                  }}
                />
              </View>

            </Marker>
            <Marker
              coordinate={{ latitude: endLocation.lat, longitude: endLocation.lng }}
              tracksViewChanges={false}
              title="Destination"
              anchor={{ x: 0.5, y: 0.5 }}
            >

              <View style={{
                backgroundColor: "#1f7dbc",
                borderRadius: 25,
                padding: 6,
                borderWidth: 2,
                borderColor: "#fff",
              }}>
                <Icon name="store" size={28} color="#fff" />
              </View>
            </Marker>
            {routeCoordinates.length > 0 && (
              <Polyline
                coordinates={routeCoordinates}
                strokeColor="rgba(31, 125, 188, 0.3)"
                strokeWidth={10}
              />
            )}
            {currentToDestinationCoords.length > 0 && (
              <Polyline
                coordinates={currentToDestinationCoords}
                strokeColor="#1f7dbc"
                strokeWidth={10}
              />
            )}
          </MapView>

          <TouchableOpacity
            style={[styles.myLocationButton, { top: myLocationButtonTop }]}
            onPress={centerMapOnUser}
          >
            <Icon name="my-location" size={24} color="#FF0000" ></Icon>
          </TouchableOpacity>

          {/* Zoom Controls */}
          <View style={styles.zoomControls}>
            <TouchableOpacity
              style={styles.zoomButton}
              onPress={() => {
                centerMapOnUser(true)
              }}
            >
              <Text style={styles.zoomText}>＋</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={styles.zoomButton}
              onPress={() => {
                mapRef.current.animateToRegion({
                  ...initialRegion,
                  latitudeDelta: initialRegion.latitudeDelta * 2,
                  longitudeDelta: initialRegion.longitudeDelta * 2,
                });
              }}
            >
              <Text style={styles.zoomText}>－</Text>
            </TouchableOpacity>
          </View>

          <View style={[styles.bottomPanel, isPanelExpanded ? styles.expandedPanel : styles.collapsedPanel]}>
            <View style={styles.panelHandle} onTouchEnd={() => setIsPanelExpanded(!isPanelExpanded)}>
              <View style={styles.handleLine} />
            </View>
            <FlatList
              data={instructions}
              renderItem={renderInstruction}
              keyExtractor={(item, index) => index.toString()}
              contentContainerStyle={styles.instructionsList}
              ListEmptyComponent={<Text style={styles.emptyText}>No instructions available</Text>}
              initialScrollIndex={currentStepIndex}
              getItemLayout={(data, index) => ({ length: 50, offset: 50 * index, index })}
              scrollEnabled={isPanelExpanded}
            />
          </View>

          {/* Speed Display */}
          <View style={styles.speedBox}>
            <Text style={styles.speedText}>
              {speed === 0 ? "0 km/h" : `${speed} km/h`}
            </Text>
          </View>

        </View>
      </Container>
    </>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#fff' },
  nextInstructionContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(255, 255, 255, 0.5)', // semi-transparent white
    padding: 12,
    borderBottomWidth: 0, // optional: remove bottom border
    elevation: 6,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 4,
    zIndex: 10,
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
  },

  maneuverIcon: { marginRight: 12 },
  nextInstructionTextContainer: { flex: 1 },
  nextInstructionText: { fontSize: 18, fontWeight: '600', color: '#333' },
  nextInstructionDistance: { fontSize: 14, color: '#007AFF' },
  destinationInfoText: { fontSize: 14, color: 'black', marginTop: 4 },
  map: { width, height: '100%' },
  bottomPanel: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    backgroundColor: '#fff',
    borderTopLeftRadius: 16,
    borderTopRightRadius: 16,
    elevation: 6,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: -2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  collapsedPanel: { height: 60 },
  expandedPanel: { height: height * 0.4 },
  panelHandle: { alignItems: 'center', paddingVertical: 8 },
  handleLine: { width: 40, height: 4, backgroundColor: '#ccc', borderRadius: 2 },
  instructionsList: { paddingBottom: 16 },
  instructionItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 12,
    backgroundColor: '#fff',
  },
  activeInstruction: {
    backgroundColor: '#e6f0ff',
    borderLeftWidth: 4,
    borderLeftColor: '#007AFF',
  },
  instructionText: { fontSize: 16, color: '#333', flex: 1, marginRight: 12 },
  speakButton: {
    backgroundColor: '#007AFF',
    paddingVertical: 6,
    paddingHorizontal: 12,
    borderRadius: 8,
  },
  speakButtonDisabled: { backgroundColor: '#aaa' },
  speakButtonText: { color: '#fff', fontSize: 12, fontWeight: '600' },
  instructionMarker: {
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    padding: 6,
    borderRadius: 6,
    borderWidth: 1,
    borderColor: '#fff',
  },
  instructionMarkerText: {
    fontSize: 14,
    color: '#fff',
    textAlign: 'center',
    fontWeight: '500',
  },
  loadingContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff' },
  loadingText: { marginTop: 12, fontSize: 16, color: '#333' },
  errorContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff', padding: 20 },
  errorText: { fontSize: 18, color: '#FF3B30', textAlign: 'center', marginBottom: 20 },
  retryButton: { backgroundColor: '#007AFF', paddingVertical: 12, paddingHorizontal: 24, borderRadius: 8 },
  retryButtonText: { color: '#fff', fontSize: 16, fontWeight: '600' },
  emptyText: { fontSize: 16, color: '#666', textAlign: 'center', marginTop: 20 },
  zoomControls: {
    position: 'absolute',
    right: 20,
    bottom: 80, // 👈 margin from bottom
    flexDirection: 'column',
  },
  zoomButton: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
    marginVertical: 5,
    elevation: 4, // Android shadow
    shadowColor: '#000',
    shadowOpacity: 0.2,
    shadowRadius: 3,
    shadowOffset: { width: 0, height: 2 }, // iOS shadow
  },
  zoomText: {
    fontSize: 20,
    fontWeight: 'bold',
    color: "black"
  },
  myLocationButton: {
    position: 'absolute',
    right: 20,
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 10,
    elevation: 4,
    marginLeft: 10,
    marginTop: 10,
    shadowColor: '#000',
    shadowOpacity: 0.2,
    shadowRadius: 3,
    shadowOffset: { width: 0, height: 2 },
    zIndex: 20, // Increased zIndex to ensure visibility
  }, speedBox: {
    position: "absolute",
    bottom: 80,
    left: 20,
    backgroundColor: "rgba(0,0,0,0.7)",
    padding: 10,
    borderRadius: 8,
  },
  speedText: {
    color: "#fff",
    fontSize: 20,
    fontWeight: "bold",
  },

});

export default NavigationScreen;
