import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
import { login as apiLogin, logout as apiLogout, getToken, onAuthCleared } from "./api";

interface AuthState {
  ready: boolean; // finished the initial token load
  signedIn: boolean;
  signIn: (pin: string) => Promise<void>;
  signOut: () => Promise<void>;
}

const Ctx = createContext<AuthState | null>(null);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [ready, setReady] = useState(false);
  const [signedIn, setSignedIn] = useState(false);

  useEffect(() => {
    getToken().then((t) => {
      setSignedIn(!!t);
      setReady(true);
    });
    // Keep state in sync when the token is cleared elsewhere (401 handling).
    onAuthCleared(() => setSignedIn(false));
    return () => onAuthCleared(null);
  }, []);

  const signIn = async (pin: string) => {
    await apiLogin(pin);
    setSignedIn(true);
  };
  const signOut = async () => {
    await apiLogout();
    setSignedIn(false);
  };

  return <Ctx.Provider value={{ ready, signedIn, signIn, signOut }}>{children}</Ctx.Provider>;
}

export function useAuth(): AuthState {
  const c = useContext(Ctx);
  if (!c) throw new Error("useAuth must be used within AuthProvider");
  return c;
}
