'use client';
import { createContext, useContext, useReducer } from 'react';
import type { Dispatch, FunctionComponent, PropsWithChildren } from 'react';
import { authReducer } from './authReducer';
import { INITIAL_AUTH_STATE } from './types';
import type { AuthAction, AuthState } from './types';

export type AuthContextValue = [AuthState, Dispatch<AuthAction>];

const AuthContext = createContext<AuthContextValue>([INITIAL_AUTH_STATE, () => null]);

interface AuthProviderProps extends PropsWithChildren {
  // Auth state resolved on the server from the request's access-token cookie.
  // Seeding the reducer with it means the first client render already reflects
  // the real session — no logged-out flash, no post-mount cookie read.
  initialState?: AuthState;
}

export const AuthProvider: FunctionComponent<AuthProviderProps> = ({ initialState, children }) => {
  const value = useReducer(authReducer, initialState ?? INITIAL_AUTH_STATE);
  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

export const useAuth = (): AuthContextValue => useContext(AuthContext);
