'use client'

import { useEffect, useState } from 'react'
import { useRouter, usePathname } from 'next/navigation'
import { useStore } from '@/lib/store'
import { AnalyzePanelProvider } from '@/components/analyze/AnalyzePanelProvider'
import { BetaBanner } from '@/components/BetaBanner'
import { Loader2 } from 'lucide-react'

export default function TerminalLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const router = useRouter()
  const pathname = usePathname()
  const { isAuthenticated, isLoading, checkAuth } = useStore()
  const [isChecking, setIsChecking] = useState(true)

  useEffect(() => {
    const verify = async () => {
      await checkAuth()
      setIsChecking(false)
    }
    verify()
  }, [checkAuth])

  useEffect(() => {
    // Once auth check is complete, redirect if not authenticated
    if (!isChecking && !isLoading && !isAuthenticated) {
      // Store the intended destination for after login
      if (typeof window !== 'undefined') {
        sessionStorage.setItem('redirectAfterLogin', pathname)
      }
      router.replace('/login')
    }
  }, [isChecking, isLoading, isAuthenticated, router, pathname])

  // Show loading state while checking auth
  if (isChecking || isLoading) {
    return (
      <div className="min-h-screen bg-[#020202] flex items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="w-8 h-8 text-accent animate-spin" />
          <p className="text-white/40 text-sm font-mono">Loading...</p>
        </div>
      </div>
    )
  }

  // Don't render children if not authenticated (will redirect)
  if (!isAuthenticated) {
    return (
      <div className="min-h-screen bg-[#020202] flex items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="w-8 h-8 text-accent animate-spin" />
          <p className="text-white/40 text-sm font-mono">Redirecting to login...</p>
        </div>
      </div>
    )
  }

  return (
    <AnalyzePanelProvider>
      <BetaBanner />
      {children}
    </AnalyzePanelProvider>
  )
}

