"use client";

import React, { useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { getAdminSession, AdminUser } from "@/lib/admin-auth";

export default function AdminAuthGuard({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();
  const [session, setSession] = useState<AdminUser | null>(null);
  const [isChecking, setIsChecking] = useState(true);

  useEffect(() => {
    // Skip auth guard for login page itself
    if (pathname === "/admin/login") {
      setIsChecking(false);
      return;
    }

    const currentSession = getAdminSession();
    if (!currentSession) {
      const callback = encodeURIComponent(pathname);
      router.replace(`/admin/login?callbackUrl=${callback}`);
    } else {
      setSession(currentSession);
      setIsChecking(false);
    }
  }, [pathname, router]);

  // Don't protect non-admin pages if wrapper is applied globally
  if (pathname === "/admin/login") {
    return <>{children}</>;
  }

  if (isChecking) {
    return (
      <div className="min-h-screen bg-[#09090b] text-[#fafafa] flex flex-col items-center justify-center p-6 antialiased selection:bg-[#D4AF37]/30 selection:text-[#D4AF37]">
        <div className="flex flex-col items-center space-y-4">
          <div className="relative w-14 h-14 flex items-center justify-center">
            <div className="absolute inset-0 rounded-2xl bg-gradient-to-tr from-[#D4AF37] to-[#F59E0B] opacity-20 blur-md animate-pulse" />
            <div className="w-12 h-12 rounded-xl bg-[#121215] border border-[#D4AF37]/40 flex items-center justify-center shadow-xl">
              <span className="font-extrabold text-[#D4AF37] text-xl">M</span>
            </div>
          </div>
          <div className="flex items-center gap-2 text-xs font-semibold text-zinc-400">
            <div className="w-2 h-2 rounded-full bg-[#D4AF37] animate-ping" />
            Yönetici Oturumu Doğrulanıyor...
          </div>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}
