import { useState, useEffect, useCallback } from 'react';

async function verifyAuthFromStorage() {
  const token = localStorage.getItem('auth_token');

  const headers = {
    'Content-Type': 'application/json',
  };

  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  try {
    const response = await fetch('/api/auth/verify', { headers });
    if (response.ok) {
      return await response.json();
    }

    if (token) {
      localStorage.removeItem('auth_token');
    }
    return null;
  } catch (error) {
    console.error('Auth check failed:', error);
    return null;
  }
}

export function useAuth() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;

    void (async () => {
      const verifiedUser = await verifyAuthFromStorage();
      if (!active) return;
      setUser(verifiedUser);
      setLoading(false);
    })();

    return () => {
      active = false;
    };
  }, []);

  const refreshAuth = useCallback(async () => {
    const verifiedUser = await verifyAuthFromStorage();
    setUser(verifiedUser);
    setLoading(false);
  }, []);

  const logout = () => {
    localStorage.removeItem('auth_token');
    setUser(null);
  };

  return {
    user,
    loading,
    logout,
    refreshAuth,
  };
}
