import React, { useEffect, useState } from 'react';
import { useFonts } from 'expo-font';
import { enableScreens } from 'react-native-screens';
import * as SplashScreen from 'expo-splash-screen';
import { Platform } from 'react-native';
import * as Notifications from 'expo-notifications';

import { createStackNavigator, TransitionPresets } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createDrawerNavigator } from '@react-navigation/drawer';

import WelcomeScreen from './src/screens/WelcomeScreen';
import LoginScreen from './src/screens/LoginScreen';
import ResetPasswordScreen from './src/screens/ResetPasswordScreen';
import ResetPasswordDeepScreen from './src/screens/ResetPasswordDeepScreen';
import JoinUsScreen from './src/screens/RegisterScreen/JoinUs';
import EditAccount from './src/screens/RegisterScreen/EditAccount';

import MapScreen from './src/screens/InAppScreens/MapScreen';
import TravelsScreen from './src/screens/InAppScreens/TravelsScreen';
import ProfileScreen from './src/screens/InAppScreens/ProfileScreen';
import TravellersScreen from './src/screens/InAppScreens/TravellersScreen';

import { EditPersonalInfo } from './src/screens/InAppScreens/ProfileScreen/Profile/edit-personal-info';
import Settings from './src/screens/InAppScreens/ProfileScreen/Settings/';

import MasterRankingScreen from './src/screens/InAppScreens/TravellersScreen/MasterRankingScreen';
import LPIRanking from './src/screens/InAppScreens/TravellersScreen/LPIRankingScreen';
import InMemoriamScreen from './src/screens/InAppScreens/TravellersScreen/InMemoriamScreen';
import InHistoryScreen from './src/screens/InAppScreens/TravellersScreen/InHistoryScreen';
import UNMastersScreen from './src/screens/InAppScreens/TravellersScreen/UNMasters';
import StatisticsScreen from './src/screens/InAppScreens/TravellersScreen/StatisticsScreen';
import StatisticsListScreen from './src/screens/InAppScreens/TravellersScreen/StatisticsListScreen';
import TriumphsScreen from 'src/screens/InAppScreens/TravellersScreen/TriumphsScreen';
import SeriesRankingScreen from 'src/screens/InAppScreens/TravellersScreen/SeriesRankingScreen';
import SeriesRankingListScreen from 'src/screens/InAppScreens/TravellersScreen/SeriesRankingListScreen';
import UsersMapScreen from 'src/screens/InAppScreens/ProfileScreen/UsersMap';

import SeriesScreen from 'src/screens/InAppScreens/TravelsScreen/Series';
import { SeriesItemScreen } from 'src/screens/InAppScreens/TravelsScreen/SeriesItemScreen';
import EarthScreen from 'src/screens/InAppScreens/TravelsScreen/EarthScreen';
import PhotosScreen from 'src/screens/InAppScreens/TravelsScreen/PhotosScreen';
import MorePhotosScreen from 'src/screens/InAppScreens/TravelsScreen/MorePhotosScreen';
import AddPhotoScreen from 'src/screens/InAppScreens/TravelsScreen/AddPhotoScreen';
import TripsScreen from 'src/screens/InAppScreens/TravelsScreen/TripsScreen';
import AddNewTripScreen from 'src/screens/InAppScreens/TravelsScreen/AddNewTripScreen';
import AddRegionsScreen from 'src/screens/InAppScreens/TravelsScreen/AddRegionsScreen';
import CountriesScreen from 'src/screens/InAppScreens/TravelsScreen/CountriesScreen';
import RegionsScreen from 'src/screens/InAppScreens/TravelsScreen/RegionsScreen';
import DareScreen from 'src/screens/InAppScreens/TravelsScreen/DareScreen';
import FixersScreen from 'src/screens/InAppScreens/TravelsScreen/FixersScreen';
import AddNewFixerScreen from 'src/screens/InAppScreens/TravelsScreen/AddNewFixerScreen';
import FixersCommentsScreen from 'src/screens/InAppScreens/TravelsScreen/FixersCommentsScreen';

import { API, NAVIGATION_PAGES } from './src/types';
import { storage, StoreType } from './src/storage';
import { openDatabases } from './src/db';

import TabBarButton from './src/components/TabBarButton';
import { ParamListBase, RouteProp, useIsFocused } from '@react-navigation/native';
import setupDatabaseAndSync, { initializeDatabase, invalidateMapCache } from 'src/database';
import { MenuDrawer } from 'src/components';
import { API_URL, APP_VERSION } from 'src/constants';
import {
  InfoScreen,
  PlanInfoScreen,
  JoinInfoScreen,
  DiscoverInfoScreen,
  FirstStepsInfoScreen,
  CountriesInfoScreen,
  RegionsInfoScreen,
  EarthInfoScreen,
  DareInfoScreen,
  TripsInfoScreen,
  FixersInfoScreen
} from 'src/screens/InfoScreens';
import RegionViewScreen from 'src/screens/InAppScreens/MapScreen/RegionViewScreen';
import UsersListScreen from 'src/screens/InAppScreens/MapScreen/UsersListScreen';
import SuggestSeriesScreen from 'src/screens/InAppScreens/TravelsScreen/SuggestSeriesScreen';
import MyFriendsScreen from 'src/screens/InAppScreens/ProfileScreen/MyFriendsScreen';
import CountryViewScreen from 'src/screens/InAppScreens/MapScreen/CountryViewScreen';
import { userApi } from '@api/user';
import axios from 'axios';
import PreviewScreen from 'src/screens/InAppScreens/ProfileScreen/ShareScreen';
import { PushNotificationProvider } from 'src/contexts/PushNotificationContext';
import NotificationsScreen from 'src/screens/NotificationsScreen';
import NotificationsListScreen from 'src/screens/NotificationsScreen/NotificationsListScreen';
import FriendsNotificationsScreen from 'src/screens/NotificationsScreen/FriendsNotificactionsScreen';
import MessagesNotificationsScreen from 'src/screens/NotificationsScreen/MessagesNotificationsScreen';
import SystemNotificationsScreen from 'src/screens/NotificationsScreen/SystemNotificationsScreen';
import MessagesScreen from 'src/screens/InAppScreens/MessagesScreen';
import ChatScreen from 'src/screens/InAppScreens/MessagesScreen/ChatScreen';
import { Splash } from 'src/components/SplashSpinner';
import { useMessagesStore } from 'src/stores/unreadMessagesStore';
import LocationSharingScreen from 'src/screens/LocationSharingScreen';
import { useFriendsNotificationsStore } from 'src/stores/friendsNotificationsStore';
import EventsScreen from 'src/screens/InAppScreens/TravelsScreen/EventsScreen';
import { NavigationProvider } from 'src/contexts/NavigationContext';
import FullMapScreen from 'src/screens/InAppScreens/MessagesScreen/FullMapScreen';
import EventScreen from 'src/screens/InAppScreens/TravelsScreen/EventScreen';
import GroupChatScreen from 'src/screens/InAppScreens/MessagesScreen/GroupChatScreen';
import GroupSettingScreen from 'src/screens/InAppScreens/MessagesScreen/GroupSettingsScreen';
import CreateEventScreen from 'src/screens/InAppScreens/TravelsScreen/CreateEvent';
import MembersListScreen from 'src/screens/InAppScreens/MessagesScreen/MembersListScreen';
import AllEventPhotosScreen from 'src/screens/InAppScreens/TravelsScreen/AllEventPhotosScreen';
import ParticipantsListScreen from 'src/screens/InAppScreens/TravelsScreen/ParticipantsListScreen';
import OfflineMapsScreen from 'src/screens/OfflineMapsScreen';
import EventsNotificationsScreen from 'src/screens/NotificationsScreen/EventsNotificationsScreen';
import SelectOwnMapScreen from 'src/screens/OfflineMapsScreen/SelectOwnMapScreen';
import { SelectRegionScreen } from 'src/screens/OfflineMapsScreen/SelectRegionsScreen';
import EditCountryDataScreen from 'src/screens/InAppScreens/TravelsScreen/EditCountryDataScreen';
import CreateSharedTripScreen from 'src/screens/InAppScreens/TravelsScreen/CreateSharedTrip';
import EditNmDataScreen from 'src/screens/InAppScreens/TravelsScreen/EditNmDataScreen';
import { testConnectionSpeed } from 'src/database/speedService';
import Trips2025Screen from 'src/screens/InAppScreens/TravelsScreen/Trips2025Screen';
import AddNewTrip2025Screen from 'src/screens/InAppScreens/TravelsScreen/AddNewTrip2025Screen';
import AddRegionsNewScreen from 'src/screens/InAppScreens/TravelsScreen/AddRegionsNewScreen';
import RegionsVisitedScreen from 'src/screens/InAppScreens/TravelsScreen/RegionsVisitedScreen';
import { clearLocalDatabaseOnLogout } from 'src/watermelondb/features/chat/data/chat.repo';
import { stopAutoSyncListener } from 'src/watermelondb/features/chat/networkSync';
import DataReportScreen from 'src/screens/DataReportScreen';

enableScreens();


SplashScreen.preventAutoHideAsync();

const ScreenStack = createStackNavigator();
const BottomTab = createBottomTabNavigator();
const MapDrawer = createDrawerNavigator();

function UnmountOnBlur({ children }: { children: React.ReactNode }) {
  const isFocused = useIsFocused();
  if (!isFocused) return null;
  return <>{children}</>;
}

const Route = () => {
  const [token, setToken] = useState<string | null>(
    storage.get('token', StoreType.STRING) as string
  );

  const [fontsLoaded] = useFonts({
    'redhat-900': require('./assets/fonts/RedHatDisplay-Black-900.ttf'),
    'redhat-700': require('./assets/fonts/RedHatDisplay-Bold-700.ttf'),
    'redhat-600': require('./assets/fonts/RedHatDisplay-SemiBold-600.ttf'),
    'montserrat-700': require('./assets/fonts/Montserrat-Bold.ttf'),
    'montserrat-600': require('./assets/fonts/Montserrat-SemiBold.ttf'),
    'montserrat-400': require('./assets/fonts/Montserrat-Regular.ttf')
  });
  const [dbLoaded, setDbLoaded] = useState(false);
  const uid = storage.get('uid', StoreType.STRING);
  const updateNotificationStatus = useFriendsNotificationsStore(
    (state) => state.updateNotificationStatus
  );
  const updateUnreadMessagesCount = useMessagesStore((state) => state.updateUnreadMessagesCount);

  const checkNmToken = async () => {
    if (token && uid) {
      try {
        const response = await axios.postForm(
          API_URL + '/' + API.CHECK_TOKEN,
          {
            token,
            user_id: +uid
          },
          {
            headers: {
              Platform: Platform.OS,
              'App-Version': APP_VERSION
            }
          }
        );

        if (response.data.result !== 'OK') {
          handleLogout();
        }
      } catch (error) {
        console.error('Error checking token:', error);
      }
    }
  };

  const handleLogout = async () => {
    setToken(null);
    stopAutoSyncListener();
    await clearLocalDatabaseOnLogout();
    storage.remove('token');
    storage.remove('uid');
    storage.remove('currentUserData');
    storage.remove('showNomads');
    storage.remove('filterSettings');
    storage.remove('visitedRegions');
    storage.remove('visitedCountries');
    storage.remove('visitedDares');
    storage.remove('visitedSeries');

    updateNotificationStatus();
    updateUnreadMessagesCount();
  };

  const fetchAndSaveUserInfo = async () => {
    if (uid && token) {
      const profileData = await userApi.getProfileInfoData(token, +uid);
      const userInfo = {
        avatar: profileData?.data?.data?.user_data.avatar ?? '',
        first_name: profileData?.data?.data?.user_data.first_name,
        last_name: profileData?.data?.data?.user_data.last_name,
        homebase_flag: profileData?.data?.data?.user_data.flag1
      };
      storage.set('currentUserData', JSON.stringify(userInfo));
    }
  };

  useEffect(() => {
    const prepareApp = async () => {
      await checkNmToken();
      await openDatabases();
      setDbLoaded(true);
      await invalidateMapCache();
      updateNotificationStatus();
      updateUnreadMessagesCount();
      if (uid && token) {
        try {
          const speed = await testConnectionSpeed();
          if (
            (speed?.downloadSpeed && speed.downloadSpeed < 0.2) ||
            (speed?.ping && speed.ping > 1500)
          ) {
            console.warn('Internet too slow for sync');
            return;
          }
        } catch {}
        await initializeDatabase(token);
      }
    };

    prepareApp();
  }, []);

  useEffect(() => {
    const hideSplashScreen = async () => {
      if (fontsLoaded) {
        await SplashScreen.hideAsync();
        await setupDatabaseAndSync();
        await fetchAndSaveUserInfo();
      }
    };

    hideSplashScreen();
  }, [fontsLoaded]);

  const checkTokenAndUpdate = async () => {
    const storedToken = storage.get('deviceToken', StoreType.STRING);
    const { status } = await Notifications.getPermissionsAsync();
    if (status !== 'granted') {
      return;
    }
    const currentToken = await Notifications.getDevicePushTokenAsync();

    if (storedToken && currentToken?.data !== storedToken) {
      storage.set('deviceToken', currentToken.data);
    }
  };

  if (!fontsLoaded || !dbLoaded) {
    return <Splash />;
  }

  const screenOptions = ({
    route,
    navigation
  }: {
    route: RouteProp<ParamListBase, string>;
    navigation: any;
  }) => ({
    headerShown: false,
    tabBarButton: (props: any) => (
      <TabBarButton {...props} label={route.name} navigation={navigation} />
    ),
    tabBarStyle: {
      ...Platform.select({
        android: {
          // height: 58
        }
      })
    },
    cardStyle: { backgroundColor: 'white' },
    unmountOnBlur: true,
    popToTopOnBlur: true,
    gestureEnabled: Platform.OS === 'ios' ? true : false,
    lazy: false
  });

  const regionViewScreenOptions = {
    ...screenOptions,
    ...(Platform.OS === 'ios' ? TransitionPresets.ModalSlideFromBottomIOS : {}),
    contentStyle: {
      flex: 1
    }
  };

  const BottomTabNavigator = () => (
    <BottomTab.Navigator screenOptions={screenOptions}>
      <BottomTab.Screen
        name={NAVIGATION_PAGES.IN_APP_MAP_TAB}
        layout={({ children }) => <UnmountOnBlur>{children}</UnmountOnBlur>}
      >
        {() => (
          <ScreenStack.Navigator screenOptions={screenOptions}>
            <ScreenStack.Screen name={NAVIGATION_PAGES.MAP_TAB} component={MapScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW}
              component={ProfileScreen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.USERS_MAP} component={UsersMapScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.REGION_PREVIEW}
              component={RegionViewScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.USERS_LIST}
              component={UsersListScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.FRIENDS_LIST}
              component={UsersListScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.COUNTRY_PREVIEW}
              component={CountryViewScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.ADD_PHOTO} component={AddPhotoScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.PROFILE_TAB} component={ProfileScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.EDIT_PERSONAL_INFO}
              component={EditPersonalInfo}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.SETTINGS} component={Settings} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.MY_FRIENDS} component={MyFriendsScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.SHARE_PROFILE} component={PreviewScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.EDIT_COUNTRY_DATA}
              component={EditCountryDataScreen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.EDIT_NM_DATA} component={EditNmDataScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.TRIPS_2025} component={Trips2025Screen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.ADD_TRIP_2025}
              component={AddNewTrip2025Screen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.ADD_REGIONS_NEW}
              component={AddRegionsNewScreen}
            />
          </ScreenStack.Navigator>
        )}
      </BottomTab.Screen>
      <BottomTab.Screen
        name={NAVIGATION_PAGES.IN_APP_TRAVELS_TAB}
        layout={({ children }) => <UnmountOnBlur>{children}</UnmountOnBlur>}
      >
        {() => (
          <ScreenStack.Navigator screenOptions={screenOptions}>
            <ScreenStack.Screen name={NAVIGATION_PAGES.TRAVELS_TAB} component={TravelsScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.SERIES} component={SeriesScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.SERIES_ITEM} component={SeriesItemScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.EARTH} component={EarthScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.PHOTOS} component={PhotosScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.MORE_PHOTOS} component={MorePhotosScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.ADD_PHOTO} component={AddPhotoScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.TRIPS} component={TripsScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.ADD_TRIP} component={AddNewTripScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.ADD_REGIONS} component={AddRegionsScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.REGIONS_VISITED}
              component={RegionsVisitedScreen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.COUNTRIES} component={CountriesScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.REGIONS} component={RegionsScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.DARE} component={DareScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.FIXERS} component={FixersScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.ADD_FIXER} component={AddNewFixerScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.EDIT_COUNTRY_DATA}
              component={EditCountryDataScreen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.EDIT_NM_DATA} component={EditNmDataScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.FIXERS_COMMENTS}
              component={FixersCommentsScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.REGION_PREVIEW}
              component={RegionViewScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.USERS_LIST}
              component={UsersListScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW}
              component={ProfileScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.EDIT_PERSONAL_INFO}
              component={EditPersonalInfo}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.USERS_MAP} component={UsersMapScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.SUGGEST_SERIES}
              component={SuggestSeriesScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.FRIENDS_LIST}
              component={UsersListScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.COUNTRY_PREVIEW}
              component={CountryViewScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.TRIPS_2025} component={Trips2025Screen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.ADD_TRIP_2025}
              component={AddNewTrip2025Screen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.ADD_REGIONS_NEW}
              component={AddRegionsNewScreen}
            />
          </ScreenStack.Navigator>
        )}
      </BottomTab.Screen>
      <BottomTab.Screen
        name={NAVIGATION_PAGES.IN_APP_TRAVELLERS_TAB}
        layout={({ children }) => <UnmountOnBlur>{children}</UnmountOnBlur>}
      >
        {() => (
          <ScreenStack.Navigator screenOptions={screenOptions}>
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.TRAVELLERS_TAB}
              component={TravellersScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.MASTER_RANKING}
              component={MasterRankingScreen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.LPI_RANKING} component={LPIRanking} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.IN_MEMORIAM} component={InMemoriamScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.IN_HISTORY} component={InHistoryScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.UN_MASTERS} component={UNMastersScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.STATISTICS} component={StatisticsScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW}
              component={ProfileScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.EDIT_PERSONAL_INFO}
              component={EditPersonalInfo}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.STATISTICS_LIST_DATA}
              component={StatisticsListScreen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.TRIUMPHS} component={TriumphsScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.SERIES_RANKING}
              component={SeriesRankingScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.SERIES_RANKING_LIST}
              component={SeriesRankingListScreen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.USERS_MAP} component={UsersMapScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.FRIENDS_LIST}
              component={UsersListScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.MY_FRIENDS} component={MyFriendsScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.REGION_PREVIEW}
              component={RegionViewScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.USERS_LIST}
              component={UsersListScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.COUNTRY_PREVIEW}
              component={CountryViewScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.ADD_PHOTO} component={AddPhotoScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.EDIT_COUNTRY_DATA}
              component={EditCountryDataScreen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.EDIT_NM_DATA} component={EditNmDataScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.TRIPS_2025} component={Trips2025Screen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.ADD_TRIP_2025}
              component={AddNewTrip2025Screen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.ADD_REGIONS_NEW}
              component={AddRegionsNewScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.REGIONS_VISITED}
              component={RegionsVisitedScreen}
            />
          </ScreenStack.Navigator>
        )}
      </BottomTab.Screen>

      <BottomTab.Screen
        name={NAVIGATION_PAGES.IN_APP_TRIPS_TAB}
        layout={({ children }) => <UnmountOnBlur>{children}</UnmountOnBlur>}
      >
        {() => (
          <ScreenStack.Navigator screenOptions={screenOptions}>
            <ScreenStack.Screen name={NAVIGATION_PAGES.TRIPS_2025} component={Trips2025Screen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.ADD_TRIP_2025}
              component={AddNewTrip2025Screen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.ADD_TRIP} component={AddNewTripScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.ADD_REGIONS} component={AddRegionsScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.ADD_REGIONS_NEW}
              component={AddRegionsNewScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.REGIONS_VISITED}
              component={RegionsVisitedScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.EDIT_COUNTRY_DATA}
              component={EditCountryDataScreen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.EDIT_NM_DATA} component={EditNmDataScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.REGION_PREVIEW}
              component={RegionViewScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.USERS_LIST}
              component={UsersListScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW}
              component={ProfileScreen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.USERS_MAP} component={UsersMapScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.ADD_PHOTO} component={AddPhotoScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.COUNTRY_PREVIEW}
              component={CountryViewScreen}
              options={regionViewScreenOptions}
            />
          </ScreenStack.Navigator>
        )}
      </BottomTab.Screen>
      <BottomTab.Screen
        name={NAVIGATION_PAGES.IN_APP_EVENTS_TAB}
        layout={({ children }) => <UnmountOnBlur>{children}</UnmountOnBlur>}
      >
        {() => (
          <ScreenStack.Navigator screenOptions={screenOptions}>
            <ScreenStack.Screen name={NAVIGATION_PAGES.EVENTS} component={EventsScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.EVENT} component={EventScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.PARTICIPANTS_LIST}
              component={ParticipantsListScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.CREATE_EVENT}
              component={CreateEventScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.CREATE_SHARED_TRIP}
              component={CreateSharedTripScreen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.ADD_REGIONS} component={AddRegionsScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.ALL_EVENT_PHOTOS}
              component={AllEventPhotosScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.USERS_LIST}
              component={UsersListScreen}
              options={regionViewScreenOptions}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW}
              component={ProfileScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.EDIT_PERSONAL_INFO}
              component={EditPersonalInfo}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.USERS_MAP} component={UsersMapScreen} />
          </ScreenStack.Navigator>
        )}
      </BottomTab.Screen>
      <BottomTab.Screen
        name={NAVIGATION_PAGES.IN_APP_MESSAGES_TAB}
        layout={({ children }) => <UnmountOnBlur>{children}</UnmountOnBlur>}
      >
        {() => (
          <ScreenStack.Navigator screenOptions={screenOptions}>
            <ScreenStack.Screen name={NAVIGATION_PAGES.CHATS_LIST} component={MessagesScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.CHAT} component={ChatScreen} />
            <ScreenStack.Screen name={NAVIGATION_PAGES.GROUP_CHAT} component={GroupChatScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.GROUP_SETTINGS}
              component={GroupSettingScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.MEMBERS_LIST}
              component={MembersListScreen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.FULL_MAP_VIEW} component={FullMapScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW}
              component={ProfileScreen}
            />
            <ScreenStack.Screen name={NAVIGATION_PAGES.USERS_MAP} component={UsersMapScreen} />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.NOTIFICATIONS}
              component={NotificationsScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.FRIENDS_NOTIFICATIONS}
              component={FriendsNotificationsScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.EVENTS_NOTIFICATIONS}
              component={EventsNotificationsScreen}
            />
          </ScreenStack.Navigator>
        )}
      </BottomTab.Screen>
      <BottomTab.Screen
        name={NAVIGATION_PAGES.MENU_DRAWER}
        layout={({ children }) => <UnmountOnBlur>{children}</UnmountOnBlur>}
      >
        {() => (
          <ScreenStack.Navigator screenOptions={screenOptions}>
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.NOTIFICATIONS}
              component={NotificationsScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.NOTIFICATIONS_LIST}
              component={NotificationsListScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.FRIENDS_NOTIFICATIONS}
              component={FriendsNotificationsScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.MESSAGES_NOTIFICATIONS}
              component={MessagesNotificationsScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.SYSTEM_NOTIFICATIONS}
              component={SystemNotificationsScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.LOCATION_SHARING}
              component={LocationSharingScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.OFFLINE_MAPS}
              component={OfflineMapsScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.EVENTS_NOTIFICATIONS}
              component={EventsNotificationsScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.OFFLINE_SELECT_MAP}
              component={SelectOwnMapScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.OFFLINE_SELECT_REGIONS}
              component={SelectRegionScreen}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.EDIT_PERSONAL_INFO}
              component={EditPersonalInfo}
            />
            <ScreenStack.Screen
              name={NAVIGATION_PAGES.DATA_REPORT}
              component={DataReportScreen}
            />
          </ScreenStack.Navigator>

        )}
      </BottomTab.Screen>
    </BottomTab.Navigator>
  );

  return (
    <PushNotificationProvider>
      <NavigationProvider>
        <ScreenStack.Navigator
          screenOptions={{ headerShown: false, cardStyle: { backgroundColor: 'white' } }}
          initialRouteName={token ? NAVIGATION_PAGES.IN_APP : NAVIGATION_PAGES.WELCOME}
        >
          <ScreenStack.Screen name={NAVIGATION_PAGES.WELCOME} component={WelcomeScreen} />
          <ScreenStack.Screen name={NAVIGATION_PAGES.LOGIN} component={LoginScreen} />
          <ScreenStack.Screen name={NAVIGATION_PAGES.REGISTER} component={JoinUsScreen} />
          <ScreenStack.Screen
            name={NAVIGATION_PAGES.REGISTER_ACCOUNT_DATA}
            component={EditAccount}
          />
          <ScreenStack.Screen
            name={NAVIGATION_PAGES.RESET_PASSWORD}
            component={ResetPasswordScreen}
          />
          <ScreenStack.Screen
            name={NAVIGATION_PAGES.RESET_PASSWORD_DEEP}
            component={ResetPasswordDeepScreen}
          />
          <ScreenStack.Screen name={NAVIGATION_PAGES.INFO} component={InfoScreen} />
          <ScreenStack.Screen name={NAVIGATION_PAGES.JOIN_INFO} component={JoinInfoScreen} />
          <ScreenStack.Screen
            name={NAVIGATION_PAGES.DISCOVER_INFO}
            component={DiscoverInfoScreen}
          />
          <ScreenStack.Screen name={NAVIGATION_PAGES.PLAN_INFO} component={PlanInfoScreen} />
          <ScreenStack.Screen
            name={NAVIGATION_PAGES.FIRST_STEPS_INFO}
            component={FirstStepsInfoScreen}
          />
          <ScreenStack.Screen
            name={NAVIGATION_PAGES.COUNTRIES_INFO}
            component={CountriesInfoScreen}
          />
          <ScreenStack.Screen name={NAVIGATION_PAGES.DARE_INFO} component={DareInfoScreen} />
          <ScreenStack.Screen name={NAVIGATION_PAGES.REGIONS_INFO} component={RegionsInfoScreen} />
          <ScreenStack.Screen name={NAVIGATION_PAGES.TRIPS_INFO} component={TripsInfoScreen} />
          <ScreenStack.Screen name={NAVIGATION_PAGES.FIXERS_INFO} component={FixersInfoScreen} />
          <ScreenStack.Screen name={NAVIGATION_PAGES.EARTH_INFO} component={EarthInfoScreen} />
          <ScreenStack.Screen name={NAVIGATION_PAGES.IN_APP}>
            {() => (
              <MapDrawer.Navigator drawerContent={(props) => <MenuDrawer {...props} />}>
                <MapDrawer.Screen
                  name="DrawerApp"
                  component={BottomTabNavigator}
                  options={{ headerShown: false }}
                />
              </MapDrawer.Navigator>
            )}
          </ScreenStack.Screen>
        </ScreenStack.Navigator>
      </NavigationProvider>
    </PushNotificationProvider>
  );
};

export default Route;
