"use client";

import { useEffect, useState } from "react";
import { useRouter, usePathname } from "next/navigation";
import Cookies from "js-cookie";
import { ComponentType } from "react";

const withAuth = <P extends object>(WrappedComponent: ComponentType<P>) => {
  return function AuthWrapper(props: P) {
    const router = useRouter();
    const pathname = usePathname();
    const [isAllowed, setIsAllowed] = useState(false);
    const [checked, setChecked] = useState(false);

    useEffect(() => {
      const checkAuth = async () => {
        try {
          // First check for client-side token (legacy support)
          const clientToken = Cookies.get("token");
          
          if (clientToken) {
            // Client-side token exists, allow access
            setIsAllowed(true);
            setChecked(true);
            return;
          }

          // If no client-side token, check server-side HTTP-only cookie
          const response = await fetch('/api/auth/check', {
            method: 'GET',
            credentials: 'include',
          });

          const data = await response.json();

          if (!data.authenticated) {
            // redirect with current path
            router.push(`/auth/login?redirect=${encodeURIComponent(pathname)}`);
          } else {
            setIsAllowed(true);
          }
        } catch (error) {
          console.error('Auth check failed:', error);
          router.push(`/auth/login?redirect=${encodeURIComponent(pathname)}`);
        } finally {
          setChecked(true);
        }
      };

      checkAuth();
    }, [pathname, router]);

    if (!checked) {
      return <div className="text-center text-gray-500">Checking authentication...</div>;
    }

    return isAllowed ? <WrappedComponent {...props} /> : null;
  };
};

export default withAuth;
