import { useCallback, useSyncExternalStore } from "react";
import {
  clearTokens,
  getToken,
  isAuthenticated,
  setTokens,
} from "../lib/auth";

/** Simple external store for auth state reactivity */
const authListeners: Set<() => void> = new Set();

function notifyAuthChange() {
  authListeners.forEach((l) => l());
}

function subscribeAuth(listener: () => void) {
  authListeners.add(listener);
  return () => {
    authListeners.delete(listener);
  };
}

/** React hook for authentication state and actions */
export function useAuth() {
  const authenticated = useSyncExternalStore(subscribeAuth, isAuthenticated);
  const token = useSyncExternalStore(subscribeAuth, getToken);

  const login = useCallback(
    (accessToken: string, refreshToken?: string) => {
      setTokens(accessToken, refreshToken);
      notifyAuthChange();
    },
    [],
  );

  const logout = useCallback(() => {
    clearTokens();
    notifyAuthChange();
  }, []);

  return { authenticated, token, login, logout };
}
