"use client";
import { useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import axios from "axios";

const installSteps = [
  "/snapta-install-1",
  "/snapta-install-2",
  "/snapta-install-3",
  "/snapta-install-4",
  "/snapta-install-5",
];

export default function RouteGuard({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const [loading, setLoading] = useState(true);
  const [isVerified, setIsVerified] = useState<boolean | null>(null);

  // 1. Verify user token status
  useEffect(() => {
    const verify = async () => {
      try {
        const res = await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/verified-token`);
        setIsVerified(res?.data.success);
      } catch (err) {
        console.error("❌ verify error", err);
        setIsVerified(false);
      } finally {
        setLoading(false);
      }
    };
    if (pathname) verify();
  }, [pathname]);

  // 2. Route protection logic
  useEffect(() => {
    if (loading || isVerified === null) return;

    const isInstallRoute = installSteps.includes(pathname);
    const verificationValue = localStorage.getItem("verification_value");
    const stepNumber = Number(pathname?.split("-")?.[2] || 0);

    if (isVerified) {
      // ✅ Verified, but allow install routes IF setup is still ongoing
      if (isInstallRoute && verificationValue) {
        return; // allow step 3–5 to complete
      }

      // ✅ Verified & setup done → block install pages
      if (isInstallRoute || pathname === "/") {
        router.replace("/SignIn");
      }

    } else {
      // ❌ Not verified
      if (!isInstallRoute) {
        router.replace("/snapta-install-1");
        return;
      }

      // Block beyond step 2 without verification_value
      if (stepNumber > 2 && !verificationValue) {
        router.replace("/snapta-install-1");
      }
    }
  }, [loading, isVerified, pathname, router]);

  if (loading || isVerified === null) {
    return <div className="text-center p-8">Checking access...</div>;
  }

  return <>{children}</>;
}
