/**
 * Private Gallery Auth Context Provider
 *
 * Provides authentication state and methods to all private gallery components
 */

import { createContext, useContext, ReactNode, useEffect } from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { usePrivateGalleryAuth, UsePrivateGalleryAuthResult } from '../../hooks/usePrivateGalleryAuth'

const PrivateGalleryContext = createContext<UsePrivateGalleryAuthResult | null>(null)

export function PrivateGalleryProvider({ children }: { children: ReactNode }) {
  const auth = usePrivateGalleryAuth()

  // Listen for keyboard shortcut to access private gallery
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Ctrl+Shift+P or Cmd+Shift+P
      if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'P') {
        e.preventDefault()
        window.location.href = '/private-gallery'
      }
    }

    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [])

  return (
    <PrivateGalleryContext.Provider value={auth}>
      {children}
    </PrivateGalleryContext.Provider>
  )
}

export function usePrivateGalleryContext(): UsePrivateGalleryAuthResult {
  const context = useContext(PrivateGalleryContext)
  if (!context) {
    throw new Error('usePrivateGalleryContext must be used within a PrivateGalleryProvider')
  }
  return context
}

/**
 * Wrapper component that requires private gallery to be unlocked.
 * Use this to wrap Gallery and Config pages.
 */
export function RequirePrivateGalleryAuth({ children }: { children: ReactNode }) {
  const { isLoading, isUnlocked } = usePrivateGalleryContext()
  const location = useLocation()

  // Show loading spinner while checking auth
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-background">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    )
  }

  // Redirect to unlock page if not authenticated
  if (!isUnlocked) {
    return <Navigate to="/private-gallery/unlock" state={{ from: location }} replace />
  }

  return <>{children}</>
}

export default PrivateGalleryProvider
