// AppRoutes.jsx
import React, { useEffect, useState, useRef, } from 'react';
import { Routes, Route } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import ProtectedRoutes from './ProtectedRoutes';
import SelfBooking  from './Pages/SelfBooking/SelfBooking.jsx'
import { isMobile, isIOS } from "react-device-detect";
// const { routesConfig }=lazy(()=>import('./routesConfig'));
import { routesConfig } from './routesConfig';
import {
  ChangeAppExpDateData,
  changeHeightforExpDate,
  getAppSubscriptionDate,
  GlobalItemCard,
} from './Features/BookingScreen/BookingData/BookingData.js';
import {
  checkSession,
  GenerateLogout,
} from './Features/BrachLogin/BranchLogin.js';
import {
  clearSession,
  getSession,
  TokendecryptedValuesFun,
} from './Services/Others.js';
import devtools from 'devtools-detect';
import KisokSelBooking from './Pages/SelfBooking/KisokSelBooking.jsx';
import IndividualBooking from './Pages/SelfBooking/IndividualBooking.jsx';
const commonSubDir = import.meta.env.ENV_COMMON_BASE_URL;
const subDirectory = import.meta.env.ENV_BASE_URL;
import "../ownLib/my-ui-lib.css"
import CustomerMenuPage from './Pages/Reports/MenuQRCode/CustomerMenuPage.jsx';
import WeightScaleApp from './Pages/BookingScreen/WeightscaleApp.jsx';
const AppRoutes = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const ItemCard = useSelector(GlobalItemCard);
  const [remainingDays, setRemainingDays] = useState(null);
  const prevRemainingDays = useRef(null);
  const [sessionData, setSessionData] = useState(null);
  const [devToolsOpen, setDevToolsOpen] = useState(false);
  useEffect(() => {
    const handlePopState = (e) => {
      const SessionId = getSession('SessionId');
      if (!SessionId) {
        alert(
          'Session invalid and Unauthorized action detected. Redirecting to login...'
        );
        clearSession();
        window.location.replace(`${commonSubDir}`);
      } else {
        window.history.go(1);
      }
    };

    // Add event listener on mount
    window.addEventListener('popstate', handlePopState);

    // Clean up the event listener on unmount
    return () => {
      window.removeEventListener('popstate', handlePopState);
    };
  }, []);

   //cmd it start
      // useEffect(() => {
      //   sessionCheckFun()
      // }, [navigate, ItemCard]);

    //cmd it End


  useEffect(() => {
    const loadSessionData = () => {
      const CompId = getSession('CompId');
      const AppId = getSession('AppId');
      const BranchId = getSession('BranchId');
      const UserType = getSession('UserType');
      console.log('loadSessionData:', CompId, AppId, BranchId, UserType);

      if (CompId && AppId && BranchId) {
        setSessionData({ CompId, AppId, BranchId, UserType });
        return true; // Indicate that session data is available
      }
      return false; // Indicate that session data is not yet available
    };

    if (!loadSessionData()) {
      const interval = setInterval(() => {
        if (loadSessionData()) {
          clearInterval(interval); // Stop checking once data is available
        }
      }, 1000);

      return () => clearInterval(interval); // Cleanup interval on unmount
    }
  }, []);

  useEffect(() => {
    const fetchExpDate = async () => {
      if (!sessionData) {
        console.log('Session data not available, skipping API call...');
        return;
      }

      try {
        const { CompId, AppId, BranchId, UserType } = sessionData;
        const data = { CompId, BranchId, AppId };

        let res = await dispatch(getAppSubscriptionDate(data)).unwrap();

        if (res?.data?.statusCode === 1 && res?.data?.data?.length > 0) {
          const expData = res?.data?.data?.[0];

          if (prevRemainingDays.current !== expData.RemainingDays) {
            prevRemainingDays.current = expData.RemainingDays;
            setRemainingDays(expData.RemainingDays);
            dispatch(ChangeAppExpDateData(expData));
            dispatch(changeHeightforExpDate(expData.RemainingDays));

            if (
              expData.RemainingDays < 1 &&
              expData.RemainingHours < 1 &&
              expData.RemainingMinutes < 1 &&
              expData.RemainingSeconds < 1
            ) {
              if (
                UserType !== 'Super Admin' ||
                UserType !== 'Super Admin User'
              ) {
                console.log('Subscription expired, logging out...');
                alert(
                  'Subscription expired, logging out. Redirecting to login...'
                );
                Logout();
              }
            }
          }
        } else {
          console.log('No subscription data found, logging out...');
          alert(
            'No subscription data found, logging out. Redirecting to login...'
          );
          Logout();
        }
      } catch (error) {
        console.error('Error fetching subscription data:', error);
      }
    };

    if (remainingDays === null) {
      fetchExpDate();
    }

    const interval = setInterval(fetchExpDate, 60 * 60 * 1000);

    return () => clearInterval(interval);
  }, [sessionData, remainingDays]);

  const Logout = async () => {
    const UserId = getSession('UserId');
    const status = 'N';
    try {
      const res = await dispatch(GenerateLogout({ UserId, status })).unwrap();
      if (res?.data?.statusCode === 1) {
        sessionStorage.clear();
        window.location.replace(`${commonSubDir}`);
      }
    } catch (error) {
      console.error('Logout failed:', error);
    }
  };
    // mohan
    // useEffect(() => {
    //    if (isMobile || isIOS) {
    //       console.log("📱 Mobile/iOS device → skipping DevTools detection");
    //       return;
    //     }
    //     const checkDevTools = setInterval(() => {
    //       if (devtools.isOpen && !devToolsOpen) {
    //         setDevToolsOpen(true);
    //         document.body.innerHTML =
    //           "<h1 style='color: red; text-align: center;'>Close Inspect to continue using the application.</h1>";
    //       }
    //       else if (!devtools.isOpen && devToolsOpen) {
    //         setDevToolsOpen(false);
  
    //         setTimeout(() => {
    //           window.location.reload();
    //         }, 100);
  
    //         clearInterval(checkDevTools);
    //       }
  
    //       if (!devtools.isOpen) {
    //         let before = performance.now();
  
    //         let after = performance.now();
  
    //         let executionDelay = after - before;
  
    //         if (executionDelay > 100) {
    //           setDevToolsOpen(true);
    //           document.body.innerHTML =
    //             "<h1 style='color: red; text-align: center;'>Close Inspect to continue using the application.</h1>";
    //         } else {
    //           setDevToolsOpen(false);
    //         }
    //       }
    //     }, 1000);
  
    //     return () => clearInterval(checkDevTools);
    //   }, [devToolsOpen]);
      
    const sessionCheckFun = async () => {
      const UserId = getSession('UserId');
      const sessionId = getSession('SessionId');
      const IsLogout = getSession('Mode');
      let encryptedLoginType = TokendecryptedValuesFun(
        sessionStorage.getItem('LoginType')
      );
      if (encryptedLoginType != 'Kiosk') {
        const res = await dispatch(checkSession({ UserId, sessionId })).unwrap();
        if (res?.data?.statusCode === 1) {
          if (res?.data?.response === 'False') {
            if (IsLogout !== 'Logout') {
              alert('Session invalid. Redirecting to login...');
            }
            clearSession();
            window.location.replace(commonSubDir);
          }
        }
      }
    };
 
  return (
   <Routes>
      <Route
        path={`${subDirectory}selfBooking/:SelfBookingId`}
        element={<SelfBooking />}
      />
       <Route
        path={`${subDirectory}MenuQRCode`}
        element={<CustomerMenuPage />}
      />
        <Route
        path={`${subDirectory}weightscaleapp`}
        element={<WeightScaleApp />}
      />
      <Route path={`${subDirectory}kioskSelfBooking`} element={<KisokSelBooking />} />

      <Route
        path= {`${subDirectory}kiosk-individual-self-booking`}
        element={<IndividualBooking />}
      />
      <Route
        path="/*"
        element={<ProtectedRoutes routesConfig={routesConfig} />}
      />
    </Routes>

  );
};

export default AppRoutes;
