import React, { useEffect, useMemo } from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  useNavigate,
  useLocation,
} from "react-router-dom";
import { ApolloProvider } from "@apollo/client";

import Login from "./pages/Customer/Login";
import ResetPassword from "./pages/Customer/ResetPassword";
import Signup from "./pages/Customer/Signup";
import ClientOnBoard from "./pages/Customer/ClientOnBoard";
import ChangePassword from "./pages/Customer/ChangePassword";
import AdminSignup from "./pages/Admin/AdminSignup";
import AdminChangePassword from "./pages/Admin/AdminChangePassword";
import AdminClientOnBoard from "./pages/Admin/AdminClientOnboard";
import AdminResetPassword from "./pages/Admin/AdminResetPassword";
import AdminLogin from "./pages/Admin/AdminLogin";
import AdminMembershipAccount from "./pages/Admin/AdminMembershipAccount";
import AdminDashboard from "./pages/Shared/Dashboard";
import Profile from "./pages/Shared/Profile";
import ChangePasswordonProfile from "./pages/Shared/ChangePasswordonProfile";
import Home from "./pages/Shared/Home";
import Layout from "./components/layout";
import { SidebarProvider } from "./components/sidebarContext";
import { SessionContextProvider, useSession } from "./context/sessioncontext";
import { client } from "./apollo/client";
import Assets from "./pages/Admin/Assets";
import AddAsset from "./pages/Admin/AddAsset";
import AssetView from "./pages/Admin/AssetView";
import CustomerAssets from "./pages/Customer/CustomerAsset";
import CustomerAssetView from "./pages/Customer/CustomerAssetView";
import CustomerProductDetails from "./pages/Customer/CustomerProductDetails";
import MarketsCards from "./pages/Shared/MarketsCards";
import CommoditiesList from "./pages/Shared/CommoditiesList";
import Gold from "./pages/Shared/Gold/Gold";
import Silver from "./pages/Shared/Silver";
import Oil from "./pages/Shared/Oil";
import Copper from "./pages/Shared/Copper";
import IntelliTradeGold from "./pages/Shared/Gold/IntelliTradeGold";
import IntelliTradeGnosisGold from "./pages/Shared/Gold/IntelliTradeGnosisGold";
import AdminEmailVerification from "./pages/Admin/AdminEmailVerification";
import EmailVerification from "./pages/Customer/EmailVerification";
import IntelliTradeOil from "./pages/Shared/IntelliTradeOil";
import IntelliTradeSilver from "./pages/Shared/IntelliTradeSilver";
import OrderBookGold from "./pages/Shared/Gold/OrderBookGold";
import IntelliTradeCopper from "./pages/Shared/IntelliTradeCopper";
import AuthCallback from "./pages/Shared/DiditVerification";
import DiditVerification from "./pages/Shared/DiditVerification";
import VerificationCallback from "./pages/Shared/VerificationCallback";
import KycStatus from "./pages/Shared/KycStatus";
import Arbitrum from "./pages/Shared/Arbitrum";
import AdminUserManagement from "./pages/Admin/AdminUserManagement";
import RGold from "./pages/Shared/Gold/RGold";
import NewIntelliTradeGold from "./pages/Shared/Gold/newIntellitradegold";
import IntelliTradeWTI from "./pages/Shared/IntelliTradewti";
import NewIntelliTradeSilver from "./pages/Shared/NewIntellitradeSilver";
import NewIntelliTradeCopper from "./pages/Shared/NewIntelliTradeCopper";
import IntelliTradeGoldWithoutSLTP from "./pages/Shared/WithoutSLTP/IntelliTradeGoldWithoutSLTP";
import IntelliTradeWTIWithoutSLTP from "./pages/Shared/WithoutSLTP/IntelliTradeWTIWithoutSLTP";
import IntelliTradeSilverWithoutSLTP from "./pages/Shared/WithoutSLTP/IntelliTradeSilverWithoutSLTP";
import IntelliTradeCopperWithoutSLTP from "./pages/Shared/WithoutSLTP/IntelliTradeCopperWithoutSLTP";


const allowedPathsWhenLoggedOut = new Set([
  "/reset-password",
  "/signup",
  "/clientonboard",
  "/",
  "/change-password",
  "/admin/signup",
  "/admin/changepassword",
  "/admin/profile",
  "/admin/login",
  "/admin/resetpassword",
  "/admin/emailverification",
  "/emailverification",
  "/auth-callback",
  "/verification-callback",
  "/kyc",
  "/didit-verification",
]);

const NavigateToLogin = () => {
  const { isLoggedIn } = useSession();
  const navigate = useNavigate();
  const location = useLocation();
  const memoizedIsLoggedIn = useMemo(() => isLoggedIn, [isLoggedIn]);

  useEffect(() => {
    const loggedIn = sessionStorage.getItem("isLoggedIn") === "true";
    const normalizePath = (p: string) => {
      const trimmed = p.replace(/\/+$/, "");
      return trimmed === "" ? "/" : trimmed;
    };
    const currentPathname = normalizePath(location.pathname).toLowerCase();
    const currentSearch = location.search;

    if (
      (currentPathname === "/change-password" &&
        currentSearch.includes("token")) ||
      (currentPathname === "/admin/emailverification" &&
        currentSearch.includes("token")) ||
      (currentPathname === "/emailverification" &&
        currentSearch.includes("token"))
    ) {
      console.info(
        "NavigateToLogin: Token present, staying on",
        currentPathname
      );
      return;
    }

    if (!loggedIn && !allowedPathsWhenLoggedOut.has(currentPathname)) {
      console.log("NavigateToLogin: Not logged in, redirecting to /");
      navigate("/", { replace: true });
    }
  }, [memoizedIsLoggedIn, location.pathname, location.search, navigate]);

  return null;
};

const App = () => {
  return (
    <Router>
      <SessionContextProvider>
        <NavigateToLogin />
        <SidebarProvider>
          <ApolloProvider client={client}>
            <Routes>
              <Route
                path="/"
                element={
                  <Layout title="Login">
                    <Login />
                  </Layout>
                }
              />
              <Route
                path="/reset-password"
                element={
                  <Layout title="Reset Password">
                    <ResetPassword />
                  </Layout>
                }
              />
              <Route
                path="/signup"
                element={
                  <Layout title="Sign Up">
                    <Signup />
                  </Layout>
                }
              />
              <Route
                path="/clientonboard"
                element={
                  <Layout title="Client Onboarding">
                    <ClientOnBoard />
                  </Layout>
                }
              />
              <Route
                path="/dashboard"
                element={
                  <Layout title="Dashboard">
                    <AdminDashboard />
                  </Layout>
                }
              />
               <Route
                path="/users"
                element={
                  <Layout title="Client Onboarding">
                    <AdminUserManagement />
                  </Layout>
                }
              />
             <Route
 path="/didit-verification"
   element={
    <Layout title="KYC Verification">
       <DiditVerification />
      </Layout>
   }
  />
   <Route
     path="/auth-callback"
     element={
       <Layout title="KYC Callback">
         <AuthCallback />
       </Layout>
     }
   />
  <Route
    path="/verification-callback"
    element={
      <Layout title="KYC Done">
        <VerificationCallback />
     </Layout>
    }
  />
  <Route
    path="/KYC"
    element={
      <Layout title="KYC Status">
        <KycStatus />
     </Layout>
    }
  />
  <Route
    path="/kyc"
    element={
      <Layout title="KYC Status">
        <KycStatus />
     </Layout>
    }
  />
              <Route
                path="/change-password"
                element={
                  <Layout title="Change Password">
                    <ChangePassword />
                  </Layout>
                }
              />
              <Route
                path="/membership-account"
                element={
                  <Layout title="Membership Account">
                    <AdminMembershipAccount />
                  </Layout>
                }
              />
              <Route
                path="/intellihub"
                element={
                  <Layout title="IntelliHub">
                    <Home />
                  </Layout>
                }
              />
              <Route
                path="/admin/assets"
                element={
                  <Layout title="Assets">
                    <Assets />
                  </Layout>
                }
              />
              <Route
                path="/admin/addasset"
                element={
                  <Layout title="Assets On Board">
                    <AddAsset />
                  </Layout>
                }
              />
              <Route
                path="/admin/assetview/:id"
                element={
                  <Layout title="Asset View">
                    <AssetView />
                  </Layout>
                }
              />
              <Route
                path="/assetsview/:id"
                element={
                  <Layout title="Asset View">
                    <CustomerAssetView />
                  </Layout>
                }
              />
              <Route
                path="/customer/assets"
                element={
                  <Layout title="Assets">
                    <CustomerAssets />
                  </Layout>
                }
              />
              <Route
                path="/markets"
                element={
                  <Layout title="Markets">
                    <MarketsCards />
                  </Layout>
                }
              />
              <Route
                path="/markets/iusdstablecoin"
                element={
                  <Layout title="Markets">
                    <Arbitrum />
                  </Layout>
                }
              />
              <Route
                path="/markets/commodities"
                element={
                  <Layout title="Markets">
                    <CommoditiesList />
                  </Layout>
                }
              />
              <Route
                path="/markets/commodities/gold"
                element={
                  <Layout title="Markets">
                    <Gold />
                  </Layout>
                }
              />
              {/* <Route
                path="/markets/commodities/gold/newintellitradegold"
                element={
                  <Layout title="Markets">
                    <NewIntelliTradeGold />
                  </Layout>
                }
              /> */}
                            <Route
                path="/markets/commodities/gold/intellitradegold"
                element={
                  <Layout title="Markets">
                    <NewIntelliTradeGold />
                  </Layout>
                }
              />
              <Route
                path="/markets/commodities/gold/intellitradegold-gnosis"
                element={
                  <Layout title="Markets">
                    <IntelliTradeGnosisGold />
                  </Layout>
                }
              />
                            <Route
                path="/markets/commodities/gold/iusdacquire"
                element={
                  <Layout title="Markets">
                    <RGold />
                  </Layout>
                }
              />
              <Route
                path="/markets/commodities/gold/orderbookgold"
                element={
                  <Layout title="Markets">
                    <OrderBookGold />
                  </Layout>
                }
              />
              {/* <Route
                path="/markets/commodities/oil/intellitradeoil"
                element={
                  <Layout title="Markets">
                    <IntelliTradeOil />
                  </Layout>
                }
              /> */}
              <Route
                path="/markets/commodities/oil/intellitradeoil"
                element={
                  <Layout title="Markets">
                    <IntelliTradeWTI />
                  </Layout>
                }
              />
              {/* <Route
                path="/markets/commodities/silver/intellitradesilver"
                element={
                  <Layout title="Markets">
                    <IntelliTradeSilver />
                  </Layout>
                }
              /> */}
               <Route
                path="/markets/commodities/silver/intellitradesilver"
                element={
                  <Layout title="Markets">
                    <NewIntelliTradeSilver />
                  </Layout>
                }
              />
              <Route
                path="/markets/commodities/copper/intellitradecopper"
                element={
                  <Layout title="Markets">
                    <NewIntelliTradeCopper />
                  </Layout>
                }
              />
              <Route
                path="/markets/commodities/oil/new/intellitradeoil"
                element={
                  <Layout title="Markets">
                    <IntelliTradeWTIWithoutSLTP />
                  </Layout>
                }
              />
              <Route
                path="/markets/commodities/gold/new/intellitradegold"
                element={
                  <Layout title="Markets">
                    <IntelliTradeGoldWithoutSLTP />
                  </Layout>
                }
              />
               <Route
                path="/markets/commodities/silver/new/intellitradesilver"
                element={
                  <Layout title="Markets">
                    <IntelliTradeSilverWithoutSLTP />
                  </Layout>
                }
              />
              <Route
                path="/markets/commodities/copper/new/intellitradecopper"
                element={
                  <Layout title="Markets">
                    <IntelliTradeCopperWithoutSLTP />
                  </Layout>
                }
              />
              <Route
                path="/markets/commodities/silver"
                element={
                  <Layout title="Markets">
                    <Silver />
                  </Layout>
                }
              />
              <Route
                path="/markets/commodities/oil"
                element={
                  <Layout title="Markets">
                    <Oil />
                  </Layout>
                }
              />
              <Route
                path="/markets/commodities/copper"
                element={
                  <Layout title="Markets">
                    <Copper />
                  </Layout>
                }
              />
               <Route
                path="/markets/commodities/oil/iusdacquire"
                element={
                  <Layout title="Markets">
                    <Arbitrum />
                  </Layout>
                }
              />
              <Route
                path="/markets/commodities/silver/iusdacquire"
                element={
                  <Layout title="Markets">
                    <Arbitrum />
                  </Layout>
                }
              />
              <Route
                path="/markets/commodities/copper/iusdacquire"
                element={
                  <Layout title="Markets">
                    <Arbitrum />
                  </Layout>
                }
              />

              <Route
                path="/assetsview/product/:id"
                element={
                  <Layout title="Assets">
                    <CustomerProductDetails />
                  </Layout>
                }
              />
              <Route
                path="/intellixchange"
                element={
                  <Layout title="IntelliXchange">
                    <Home />
                  </Layout>
                }
              />
              <Route
                path="/intelliswap"
                element={
                  <Layout title="IntelliSwap">
                    <Home />
                  </Layout>
                }
              />
              <Route
                path="/manage-listings"
                element={
                  <Layout title="Manage Listings">
                    <Home />
                  </Layout>
                }
              />
              <Route
                path="/liquidity-pools"
                element={
                  <Layout title="Liquidity Pools">
                    <Home />
                  </Layout>
                }
              />
              <Route
                path="/membership-billing"
                element={
                  <Layout title="Membership Billing">
                    <Home />
                  </Layout>
                }
              />
              <Route
                path="/membership-canceling"
                element={
                  <Layout title="Cancel Membership">
                    <Home />
                  </Layout>
                }
              />
              <Route
                path="/admin/signup"
                element={
                  <Layout title="Admin Sign Up">
                    <AdminSignup />
                  </Layout>
                }
              />
              <Route
                path="/admin/changepassword"
                element={
                  <Layout title="Admin Change Password">
                    <AdminChangePassword />
                  </Layout>
                }
              />
              <Route
                path="/admin/profile"
                element={
                  <Layout title="Admin Profile">
                    <AdminClientOnBoard />
                  </Layout>
                }
              />
              <Route
                path="/admin/login"
                element={
                  <Layout title="Admin Login">
                    <AdminLogin />
                  </Layout>
                }
              />
              <Route
                path="/admin/emailverification"
                element={
                  <Layout title="Email Verification">
                    <AdminEmailVerification />
                  </Layout>
                }
              />
              <Route
                path="/emailverification"
                element={
                  <Layout title="Email Verification">
                    <EmailVerification />
                  </Layout>
                }
              />
              <Route
                path="/admin/resetpassword"
                element={
                  <Layout title="Admin Reset Password">
                    <AdminResetPassword />
                  </Layout>
                }
              />
              <Route
                path="/profile"
                element={
                  <Layout title="User Profile">
                    <Profile />
                  </Layout>
                }
              />
              <Route
                path="/profile/change-password"
                element={
                  <Layout title="Change Password">
                    <ChangePasswordonProfile />
                  </Layout>
                }
              />
            </Routes>
          </ApolloProvider>
        </SidebarProvider>
      </SessionContextProvider>
    </Router>
  );
};

export default App;
