'use client';
// components/AuthGuard.tsx
//
// Client-side route guard — the only auth protection possible under
// `output: "export"` (no middleware.ts / server runtime).
//
// variant="dashboard" → authenticated users only; redirects → /login
// variant="auth"      → unauthenticated users only; redirects → /
//
// Gates on _hydrated to prevent a flash before the cookie is read.

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore, type AuthInfo } from '@/lib/auth/store';

interface AuthGuardProps {
  children: React.ReactNode;
  variant: 'dashboard' | 'auth';
}

function isBlocked(authInfo: AuthInfo): boolean {
  const blocked = authInfo.is_blocked;
  return blocked === true || blocked === 1;
}

function hasActiveSession(authInfo: AuthInfo | null): boolean {
  return !!authInfo?.token && !isBlocked(authInfo);
}

export default function AuthGuard({ children, variant }: Readonly<AuthGuardProps>) {
  const router = useRouter();
  const authInfo = useAuthStore((s) => s.authInfo);
  const hydrated = useAuthStore((s) => s._hydrated);

  const isAuthed = hasActiveSession(authInfo);

  useEffect(() => {
    if (!hydrated) return;
    if (variant === 'dashboard' && !isAuthed) {
      router.replace('/login');
    } else if (variant === 'auth' && isAuthed) {
      router.replace('/');
    }
  }, [hydrated, isAuthed, variant, router]);

  // While the store is rehydrating from the cookie, show a neutral full-screen
  // placeholder so there is no content flash before the redirect fires.
  if (!hydrated) {
    return (
      <div className="min-h-screen bg-[#13151A] flex items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <div className="w-12 h-12 bg-[#FCD704]/20 rounded-2xl flex items-center justify-center">
            <i className="ri-flashlight-fill text-[#FCD704] text-2xl" />
          </div>
          <i className="ri-loader-4-line animate-spin text-[#FCD704] text-2xl" />
        </div>
      </div>
    );
  }

  // After hydration: if we're about to redirect, don't flash the protected
  // content even for one frame.
  if (variant === 'dashboard' && !isAuthed) return null;
  if (variant === 'auth' && isAuthed) return null;

  return <>{children}</>;
}
