"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import sqIcon from '../../../public/assets/icon.png'

export default function AuthGuard({
  children,
}: {
  children: React.ReactNode;
}) {
  const router = useRouter();
  const [authorized, setAuthorized] = useState(false);

  useEffect(() => {
    let active = true;

    async function checkAuth() {
      try {
        const apiUrl = process.env.NEXT_PUBLIC_API_URL?.replace(/\/+$/, "");

        if (!apiUrl) {
          throw new Error("Authentication service is not configured.");
        }

        let response = await fetch(`${apiUrl}/api/v1/auth/me`, {
          method: "GET",
          credentials: "include",
          cache: "no-store",
        });

        if (response.status === 401) {
          const refreshResponse = await fetch(
            `${apiUrl}/api/v1/auth/refresh`,
            {
              method: "POST",
              credentials: "include",
              cache: "no-store",
            },
          );

          if (refreshResponse.ok) {
            response = await fetch(`${apiUrl}/api/v1/auth/me`, {
              method: "GET",
              credentials: "include",
              cache: "no-store",
            });
          }
        }

        if (response.status === 401) {
          router.replace("/signin");
          return;
        }

        if (!response.ok) {
          throw new Error(
            `Authentication check failed: ${response.status}`,
          );
        }

        if (active) {
          setAuthorized(true);
        }
      } catch {
        if (active) {
          router.replace("/signin");
        }
      }
    }

    checkAuth();

    return () => {
      active = false;
    };
  }, [router]);

  if (!authorized) {
    return (
      <div className="fixed inset-0 z-50 flex min-h-screen items-center justify-center overflow-hidden bg-slate-50 px-4">
        <div className="pointer-events-none absolute -left-24 -top-24 h-72 w-72 rounded-full bg-green-300/20 blur-3xl" />
        <div className="pointer-events-none absolute -bottom-24 -right-24 h-72 w-72 rounded-full bg-red-300/20 blur-3xl" />

        <div className="relative flex w-full max-w-sm flex-col items-center rounded-2xl border border-slate-200/70 bg-white/90 px-8 py-10 shadow-xl shadow-slate-200/50 backdrop-blur-xl">
          
          <div className="relative mb-8 flex h-28 w-28 items-center justify-center">
        
            <div className="absolute inset-0 animate-[spin_3s_linear_infinite] rounded-full border-[3px] border-transparent border-t-violet-600 border-l-violet-600/30" />
            
            <div className="absolute inset-1.5 animate-[spin_2s_linear_infinite_reverse] rounded-full border-[3px] border-transparent border-b-violet-600 border-r-violet-600/30" />

            <div className="relative z-10 flex h-16 w-16 items-center justify-center overflow-hidden rounded-xl bg-white p-1.5  ring-1 ring-slate-100 animate-pulse">
              <Image
                src={sqIcon.src}
                alt="SQ Logo"
                width={64}
                height={64}
                className="h-full w-full object-contain"
                priority
              />
            </div>

            <span className="absolute right-0 top-0 h-3 w-3 animate-ping rounded-full bg-violet-500" />
          </div>

          <h2 className="text-lg font-semibold tracking-tight text-slate-800">
            Verifying Your Identity
          </h2>

          <p className="mt-2 text-center text-sm leading-6 text-slate-500">
            Please wait while we securely verify your session.
          </p>

          <div className="mt-7 h-1.5 w-full overflow-hidden rounded-full bg-slate-100">
            <div className="h-full w-2/4 animate-[loading_1.5s_ease-in-out_infinite] rounded-full bg-gradient-to-r from-violet-400 via-violet-500 to-violet-700" />
          </div>

        </div>

        <style jsx>{`
          @keyframes loading {
            0% {
              transform: translateX(-110%);
            }
            50% {
              transform: translateX(100%);
            }
            100% {
              transform: translateX(330%);
            }
          }
        `}</style>
      </div>
    );
  }

  return <>{children}</>;
}