/**
 * usePasskey — React hook wrapping the vanilla passkey helpers.
 *
 * Checks WebAuthn support once on mount, then exposes memoized `register`
 * and `authenticate` callbacks that delegate to the vanilla functions.
 */
import { useState, useEffect, useCallback } from 'react'
import { registerPasskey, authenticateWithPasskey, isWebAuthnSupported } from '../../passkey/index'
import type {
  WebAuthnRegistrationOptions,
  WebAuthnAuthenticationOptions,
  RegistrationCredential,
  AuthenticationCredential,
} from '../../passkey/index'

export type {
  WebAuthnRegistrationOptions,
  WebAuthnAuthenticationOptions,
  RegistrationCredential,
  AuthenticationCredential,
}

export interface UsePasskeyResult {
  /** Whether the current browser supports the WebAuthn/Passkey API. */
  isSupported: boolean
  /**
   * Register a new passkey.  Delegates to `registerPasskey()`.
   * Throws when WebAuthn is unsupported or the credential could not be created.
   */
  register: (options: WebAuthnRegistrationOptions) => Promise<RegistrationCredential>
  /**
   * Authenticate with an existing passkey.  Delegates to `authenticateWithPasskey()`.
   * Throws when WebAuthn is unsupported or the credential could not be retrieved.
   */
  authenticate: (options: WebAuthnAuthenticationOptions) => Promise<AuthenticationCredential>
}

export function usePasskey(): UsePasskeyResult {
  const [isSupported, setIsSupported] = useState<boolean>(false)

  useEffect(() => {
    setIsSupported(isWebAuthnSupported())
  }, [])

  const register = useCallback(
    (options: WebAuthnRegistrationOptions): Promise<RegistrationCredential> =>
      registerPasskey(options),
    []
  )

  const authenticate = useCallback(
    (options: WebAuthnAuthenticationOptions): Promise<AuthenticationCredential> =>
      authenticateWithPasskey(options),
    []
  )

  return { isSupported, register, authenticate }
}
