import { useEffect, useState } from 'react'
import { useVaults } from '@/hooks/useVault'
import { VaultPage } from '@/pages/VaultPage'
import { EntriesPage } from '@/pages/EntriesPage'
import { AuditPage } from '@/pages/AuditPage'
import { useVaultContext } from '@/context/VaultProvider'

/**
 * VaultApp — the complete self-contained vault UI.
 * Now uses real URL-based navigation for better UX and breadcrumb support.
 */
export function VaultApp({ path: externalPath }: { path?: string } = {}) {
  const { basePath } = useVaultContext()
  const [path, setPath] = useState(externalPath || window.location.pathname)

  // Sync with external path prop if provided (e.g. from host router)
  useEffect(() => {
    if (externalPath) setPath(externalPath)
  }, [externalPath])

  // Sync state with browser navigation
  useEffect(() => {
    const handlePopState = () => setPath(window.location.pathname)
    window.addEventListener('popstate', handlePopState)
    return () => window.removeEventListener('popstate', handlePopState)
  }, [])

  const navigate = (to: string) => {
    // Ensure 'to' starts with a slash
    const target = to.startsWith('/') ? to : `/${to}`
    // Only prepend basePath if the target doesn't already start with it
    const newPath = target.startsWith(basePath) ? target : `${basePath}${target}`
    
    window.history.pushState({}, '', newPath)
    setPath(newPath)
  }

  const { data: vaults = [] } = useVaults()

  // Parse current route relative to basePath
  const relativePath = path.startsWith(basePath) 
    ? path.slice(basePath.length).replace(/\/$/, '') || '/'
    : '/'

  // Route: /vault (Root)
  if (relativePath === '/' || relativePath === '') {
    return (
      <VaultPage
        onNavigate={(to, vaultId) => {
          if (to === 'audit') navigate('/audit')
          else if (vaultId) navigate(`/${vaultId}`)
        }}
      />
    )
  }

  // Route: /audit
  if (relativePath === '/audit') {
    return (
      <AuditPage />
    )
  }

  // Route: /vault/:vaultId
  const vaultMatch = relativePath.match(/^\/([^/]+)$/)
  if (vaultMatch) {
    const [, vaultId] = vaultMatch
    const vault = vaults.find(v => v.id === vaultId)
    return (
      <EntriesPage
        vaultId={vaultId}
        isOwner={!!vault?.is_owner}
        onNavigate={(to) => {
          if (to === 'vaults') navigate('/')
        }}
      />
    )
  }

  // Fallback to root
  return <VaultPage onNavigate={(_to, vaultId) => navigate(`/${vaultId}`)} />
}
