import { useEffect, lazy, Suspense, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { App as CapacitorApp } from '@capacitor/app';
import { Routes, Route } from 'react-router-dom';
import { useSelector } from 'react-redux';
import ProtectedRoutes from './ProtectedRoutes';
import SelfBooking from './Pages/SelfBooking/SelfBooking.jsx';
import { isMobile, isIOS } from 'react-device-detect';
import { routesConfig } from './routesConfig';
import { GlobalItemCard } from './Features/BookingScreen/BookingData/BookingData.js';
import { clearSession, getSession, sessionStore } from './Services/Others.js';

const KisokSelBooking = lazy(
  () => import('./Pages/SelfBooking/KisokSelBooking')
);
const IndividualBooking = lazy(
  () => import('./Pages/SelfBooking/IndividualBooking')
);

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';
import useSubscriptionManager from './useSubscriptionManager.js';
import useSessionManager from './useSessionManager.js';
import ExtendSubscriptionModal from './Pages/ExtentedModal/ExtendSubscriptionModal.jsx';
import devtools from 'devtools-detect';
import { useDevToolsDetection } from './utils/useDevToolsDetection.js';
import { Capacitor } from '@capacitor/core';

// const isCapacitor = () => !!window.Capacitor?.isNativePlatform?.();
const isCapacitor = () => Capacitor.isNativePlatform();
// ✅ Define your home/exit pages here
const HOME_PAGES = [
  '/app-page/home', // android minimize
  '/apps/retail/app-page/home',
  '/', // android minimize
];

const LOGIN_PAGES = ['signin', 'login', 'auth'];

const AppRoutes = () => {
  const ItemCard = useSelector(GlobalItemCard);
  const { sessionData, logout } = useSessionManager(ItemCard);
  const {
    remainingDays,
    handleCancel,
    freeExtend,
    extendModel,
    handlePay,
    setExtendModel,
  } = useSubscriptionManager(sessionData, logout);
  const location = useLocation();
  const navigate = useNavigate();
  const [devToolsOpen, setDevToolsOpen] = useState(false);
  // ✅ Flag to prevent stack push when back button navigates
  const isBackNav = useRef(false);
  console.log(isCapacitor(), 'Is Capacitor');
  // ✅ Build navigation stack
  useEffect(() => {
    // Skip pushing to stack when back button caused this navigation
    if (isBackNav.current) {
      isBackNav.current = false;
      return;
    }

    try {
      const path = location.pathname + (location.search || '');

      // Don't track login pages
      if (LOGIN_PAGES.some((p) => path.includes(p))) return;

      const raw = getSession('navStack');
      console.log('🎯 Current path:', path);
      let stack = raw ? JSON.parse(raw) : [];

      if (stack.length === 0 || stack[stack.length - 1] !== path) {
        stack.push(path);
        if (stack.length > 50) stack = stack.slice(-50);
        sessionStore('navStack', JSON.stringify(stack));
        console.log('📍 Stack:', stack);
      }
    } catch (e) { }
  }, [location.pathname, location.search]);

  // ✅ Web — block browser back button
  useEffect(() => {
    if (isCapacitor()) return; // Android handled separately

    const handlePopState = () => {
      const currentPath = location.pathname;

      const SessionId = getSession('SessionId');
      console.log('SessionId:', SessionId, 'CurrentPath:', currentPath)
      // 🟢 If session exists → allow navigation
      if (SessionId) {
        console.log('Browser back allowed');
        return;
      }

      // 🔴 Only redirect if user is on protected page
      if (!LOGIN_PAGES.some((p) => currentPath.includes(p))) {
        console.log('Session missing → redirecting login');
        clearSession();
        window.location.replace(`${commonSubDir}`);
      }
    };

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

    return () => window.removeEventListener('popstate', handlePopState);
  }, [location.pathname]);

  // ✅ Android — Capacitor back button
 useEffect(() => {
  if (!isCapacitor()) return;

  const handler = async () => {
    try {
      const currentPath = window.location.pathname + window.location.search; // Bug 2 fix

      const raw = getSession('navStack');
      let stack = raw ? JSON.parse(raw) : [];

      while (stack.length && stack[stack.length - 1] === currentPath) {
        stack.pop();
      }

      if (stack.length > 0) {
        const previous = stack[stack.length - 1];
        sessionStore('navStack', JSON.stringify(stack));
        isBackNav.current = true;  // Bug 3 fix — BEFORE navigate
        navigate(previous);
        return;
      }

      if (HOME_PAGES?.some((p) => currentPath?.includes(p))) {
        await CapacitorApp.minimizeApp();
        return;
      }

      if (LOGIN_PAGES?.some((p) => currentPath?.includes(p))) {
        await CapacitorApp.minimizeApp();
        return;
      }

      const home = '/app-page/home';
      isBackNav.current = true;  // Bug 3 fix here too
      sessionStore('navStack', JSON.stringify([home]));
      navigate(home);
    } catch (e) {
      console.error('Back handler error:', e);
      await CapacitorApp.minimizeApp();
    }
  };

  const listenerPromise = CapacitorApp.addListener('backButton', handler); // Bug 1 fix
  return () => {
    listenerPromise.then(({ remove }) => remove());
  };
}, [navigate,location.pathname, location.search]);
  // 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 isBlocked = useDevToolsDetection(() => {
  //   // optional: log, notify, etc.
  //   console.warn('DevTools detected');
  // });

  // if (isBlocked) {
  //   return (
  //     <div style={{
  //       display: 'flex',
  //       justifyContent: 'center',
  //       alignItems: 'center',
  //       height: '100vh',
  //       flexDirection: 'column',
  //       gap: '1rem'
  //     }}>
  //       <h1 style={{ color: 'red' }}>
  //         DevTools detected. Please close it to continue.
  //       </h1>
  //     </div>
  //   );
  // }
  if (extendModel) {
    return (
      <ExtendSubscriptionModal
        onClose={handleCancel}
        onPayNow={handlePay}
        onContinueWithCredits={freeExtend}
        setExtendModel={setExtendModel}
      />
    );
  }
  return (
    <Suspense fallback={null}>
      <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>
    </Suspense>
  );
};

export default AppRoutes;
