import { Outlet, Navigate } from "react-router-dom"
import { Spinner } from "@heroui/react"
import { useAuth } from "../contexts/AuthContext"
import BrandLogo from "../components/BrandLogo"
import { useBranding } from "../contexts/BrandingContext"

export default function AuthLayout() {
  const { user, isLoading } = useAuth()
  const { auth_background_type, auth_background_url } = useBranding()

  if (isLoading) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-white">
        <Spinner size="lg" />
      </div>
    )
  }

  if (user) {
    return <Navigate to="/dashboard" replace />
  }

  return (
    <div className="relative flex min-h-screen overflow-hidden">
      {/* 视频背景 */}
      {auth_background_type === "video" ? <video
        autoPlay
        loop
        muted
        playsInline
        className="pointer-events-none absolute inset-0 h-full w-full object-cover"
        style={{ zIndex: 0 }}
      >
        <source src={auth_background_url} />
      </video> : <img src={auth_background_url} className="pointer-events-none absolute inset-0 h-full w-full object-cover" />}
      {/* Soft overlay */}
      <div className="absolute inset-0 bg-gradient-to-r from-white/80 via-white/50 to-transparent" />

      {/* Left: brand area */}
      <div className="relative z-10 hidden lg:flex flex-1 flex-col justify-center items-start px-16">
        <div className="flex items-center gap-5">
          <BrandLogo className="h-32 object-contain shrink-0" />
          <h2 className="text-4xl font-bold text-gray-800 leading-tight">
            简洁高效地<br />管理您的云服务
          </h2>
        </div>
        <p className="mt-4 text-gray-500 max-w-md leading-relaxed">
          一站式 IDC 财务管理平台，轻松管理服务器、域名、SSL 证书等产品，享受流畅的购买与续费体验。
        </p>
      </div>

      {/* Right: form area */}
      <div className="relative z-10 flex w-full lg:w-[700px] shrink-0 items-center justify-center p-6">
        <div className="w-full max-w-sm">
          <Outlet />
        </div>
      </div>
    </div>
  )
}
