'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import LoginForm from './components/LoginForm'
import PageLayout from '../components/PageLayout'
import useAuthStore from '../store/authStore'
import GlobalAnimatedBackground from '../background/GlobalAnimatedBackground'

export default function LoginPage() {
  const [showBackground, setShowBackground] = useState(false)
  const router = useRouter()
  const user = useAuthStore(state => state.user)
  
  // Check if user is already logged in
  useEffect(() => {
    if (user) {
      router.push('/dashboard')
    }
  }, [user, router])
  
  // Responsive background detection
  useEffect(() => {
    const handleResize = () => setShowBackground(window.innerWidth >= 768)
    handleResize() // Initial check
    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [])
  
  // Don't render if user is already logged in
  if (user) {
    return (
      <PageLayout>
        <div className="min-h-screen flex items-center justify-center">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#8D6B1D] mx-auto mb-4"></div>
            <p className="text-[#4A4A4A]">You are already logged in. Redirecting...</p>
          </div>
        </div>
      </PageLayout>
    )
  }

  return (
    <PageLayout showFooter={false}>
      <div className="relative w-full flex flex-col min-h-screen">
        {/* Animated background for desktop */}
        {showBackground && (
          <div className="absolute inset-0 z-0">
            <GlobalAnimatedBackground />
          </div>
        )}
        
        <div className="relative z-10 flex-1 flex items-center justify-center py-12 px-4">
          <div className="w-full">
            <LoginForm />
          </div>
        </div>
        
        {/* Footer for mobile */}
        <div className="relative z-10 md:hidden">
          <div className="text-center py-4 text-sm text-[#4A4A4A]">
            © 2024 Profit Planet. Alle Rechte vorbehalten.
          </div>
        </div>
      </div>
    </PageLayout>
  )
}