// AppRoutes.jsx
import React, { useEffect, useState } from 'react';
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import ProtectedRoutes from './ProtectedRoutes';
import { isMobile, isIOS } from "react-device-detect";
import { routesConfig } from './routesConfig';
import { checkSession } from "./features/signInPage/signInPage.js";
import { clearSession, getSession } from "./Services/others.js";
import devtools from 'devtools-detect';
import useVisitLogger from "./useVisitLogger.jsx";

import { useSearchParams } from "react-router-dom";

const subDirectory = import.meta.env.ENV_MAIN_BASE_URL
const AppRoutes = () => {
  const [searchParams] = useSearchParams();
  useVisitLogger()
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [devToolsOpen, setDevToolsOpen] = useState(false);

  useEffect(() => {
    console.log("search raw:", window.location.search);
    console.log("queryParams size:", [...searchParams.entries()].length);
    console.log("queryParams entries:", [...searchParams.entries()]);
    console.log("token:", searchParams.get("token"));
    console.log("id:", searchParams.get("id"));
  }, [searchParams]);
  useEffect(() => {
    const handlePopState = (e) => {
      // Skip session clearing for PostEditorPage
      if (window.location.pathname.includes('PostEditorPage')) {
        return;
      }
      const SessionId = getSession('SessionId');
      if (!SessionId) {
        clearSession();
        window.location.replace(`${subDirectory}`);
      }
      else {
        window.history.go(1);
      }
    };

    window.addEventListener('popstate', handlePopState);
    return () => {
      window.removeEventListener('popstate', handlePopState);
    };
  }, []);
  useEffect(() => {

    const hasAuthorizedSession = new URLSearchParams(window.location.search).has('SD');
    console.log("hasAuthorizedSession", hasAuthorizedSession)

    if (!hasAuthorizedSession) {
      sessionCheckFun();
    } else {
      const url = new URL(window.location);
      url.search = '';
      window.history.replaceState({}, document.title, url.toString());
    }
  }, [navigate]);
  // 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')
    if (UserId && SessionId && sessionStorage.getItem("auth")) {
      const res = await dispatch(checkSession({ UserId, SessionId })).unwrap();
      if (res?.data?.statusCode === 1) {
        if (res?.data?.response === 'False') {
          clearSession();
          window.location.replace(`${subDirectory}`);

        }
      }
    }
  }
  return (
    <ProtectedRoutes routesConfig={routesConfig} />
  );
};

export default AppRoutes;
