"use client";

import { type ReactNode, useEffect, useState } from "react";

import { useRouter } from "next/navigation";

import { useAuthStore } from "@/stores/auth-store";

// ─── Spinner ─────────────────────────────────────────────────────────────────

function LoadingSpinner() {
  return (
    <div className="flex min-h-screen items-center justify-center">
      <div className="size-6 animate-spin rounded-full border-2 border-teal-600 border-t-transparent" />
    </div>
  );
}

// ─── User Auth Guard ──────────────────────────────────────────────────────────

export function UserAuthGuard({ children }: Readonly<{ children: ReactNode }>) {
  const router = useRouter();
  const { isAuthenticated, isAdmin, loadFromStorage } = useAuthStore();
  const [ready, setReady] = useState(false);

  useEffect(() => {
    loadFromStorage();
    const state = useAuthStore.getState();

    if (!state.isAuthenticated) {
      router.replace("/auth/login");
      return;
    }

    if (state.isAdmin) {
      router.replace("/admin");
      return;
    }

    setReady(true);
  }, [router, loadFromStorage]);

  // Re-evaluate after store updates
  useEffect(() => {
    if (isAuthenticated && !isAdmin) {
      setReady(true);
    }
  }, [isAuthenticated, isAdmin]);

  if (!ready) return <LoadingSpinner />;

  return <>{children}</>;
}

// ─── Admin Auth Guard ─────────────────────────────────────────────────────────

export function AdminAuthGuard({ children }: Readonly<{ children: ReactNode }>) {
  const router = useRouter();
  const { isAuthenticated, isAdmin, loadFromStorage } = useAuthStore();
  const [ready, setReady] = useState(false);

  useEffect(() => {
    loadFromStorage();
    const state = useAuthStore.getState();

    if (!state.isAuthenticated || !state.isAdmin) {
      router.replace("/admin/login");
      return;
    }

    setReady(true);
  }, [router, loadFromStorage]);

  useEffect(() => {
    if (isAuthenticated && isAdmin) {
      setReady(true);
    }
  }, [isAuthenticated, isAdmin]);

  if (!ready) return <LoadingSpinner />;

  return <>{children}</>;
}

// ─── Legacy export (kept for backward compat) ─────────────────────────────────

export { UserAuthGuard as AuthGuard };
