"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
import { Checkbox } from "@/components/ui/checkbox"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Eye, EyeOff, Mail, ArrowLeft, User, Building, Loader2, AlertCircle, CheckCircle, Shield, Check, X } from "lucide-react"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { useToast } from "@/components/ui/toast"
import { DataAPI } from "@/lib/data-api"
import Image from "next/image"
import Link from "next/link"

export default function RegisterPage() {
  const router = useRouter()
  const toast = useToast()
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [userType, setUserType] = useState<"family" | "facility">("family")
  const [isLoading, setIsLoading] = useState(false)
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    email: "",
    password: "",
    confirmPassword: "",
    facilityName: "",
    facilityType: "",
    licenseNumber: "",
    agreeToTerms: false,
    agreeToPrivacy: false,
  })

  const handleInputChange = (field: string, value: string | boolean) => {
    setFormData((prev) => ({ ...prev, [field]: value }))
    
    // Real-time validation for email field
    if (field === 'email' && typeof value === 'string') {
      const emailError = validateEmail(value)
      setErrors((prev) => ({ ...prev, email: emailError }))
    }
    // Real-time validation for password field
    else if (field === 'password' && typeof value === 'string') {
      const passwordErrors = validatePassword(value)
      if (value && passwordErrors.length > 0) {
        setErrors((prev) => ({ ...prev, password: passwordErrors.join(", ") }))
      } else {
        setErrors((prev) => ({ ...prev, password: "" }))
      }
      
      // Also re-validate confirm password if it has a value
      if (formData.confirmPassword) {
        if (formData.confirmPassword !== value) {
          setErrors((prev) => ({ ...prev, confirmPassword: "Passwords do not match" }))
        } else {
          setErrors((prev) => ({ ...prev, confirmPassword: "" }))
        }
      }
    }
    // Real-time validation for confirm password
    else if (field === 'confirmPassword' && typeof value === 'string') {
      if (value && value !== formData.password) {
        setErrors((prev) => ({ ...prev, confirmPassword: "Passwords do not match" }))
      } else {
        setErrors((prev) => ({ ...prev, confirmPassword: "" }))
      }
    }
    else if (errors[field]) {
      // Clear error when user starts typing for other fields
      setErrors((prev) => ({ ...prev, [field]: "" }))
    }
  }

  const validatePassword = (password: string) => {
    const errors = []
    if (password.length < 8) errors.push("At least 8 characters")
    if (!/[A-Z]/.test(password)) errors.push("One uppercase letter")
    if (!/[a-z]/.test(password)) errors.push("One lowercase letter")
    if (!/[0-9]/.test(password)) errors.push("One number")
    if (!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) errors.push("One special character (!@#$%^&* etc.)")
    return errors
  }

  const passwordRequirements = [
    { text: "At least 8 characters", met: formData.password.length >= 8 },
    { text: "One uppercase letter", met: /[A-Z]/.test(formData.password) },
    { text: "One lowercase letter", met: /[a-z]/.test(formData.password) },
    { text: "One number", met: /[0-9]/.test(formData.password) },
    { text: "One special character (!@#$%^&* etc.)", met: /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(formData.password) },
  ]

  const validateEmail = (email: string) => {
    if (!email.trim()) return "Email is required"
    
    // More comprehensive email validation matching backend
    const emailRegex = /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/
    if (!emailRegex.test(email)) {
      // Provide specific error messages for common issues
      if (!email.includes('@')) return "Email must contain @ symbol"
      if (!email.includes('.')) return "Email must contain a domain (e.g., .com, .org)"
      if (email.split('.').pop()?.length === 1) return "Domain extension must be at least 2 characters (e.g., .com, .org)"
      if (email.endsWith('.')) return "Email cannot end with a dot"
      if (email.includes('..')) return "Email cannot contain consecutive dots"
      return "Please enter a valid email address"
    }
    
    return ""
  }

  const validateForm = () => {
    const newErrors: Record<string, string> = {}

    // Common validations
    if (!formData.firstName.trim()) newErrors.firstName = "First name is required"
    if (!formData.lastName.trim()) newErrors.lastName = "Last name is required"
    
    const emailError = validateEmail(formData.email)
    if (emailError) newErrors.email = emailError
    
    // Password validation with strength requirements
    if (!formData.password) {
      newErrors.password = "Password is required"
    } else {
      const passwordErrors = validatePassword(formData.password)
      if (passwordErrors.length > 0) {
        newErrors.password = passwordErrors.join(", ")
      }
    }
    
    if (formData.password !== formData.confirmPassword) newErrors.confirmPassword = "Passwords do not match"
    if (!formData.agreeToTerms) newErrors.agreeToTerms = "You must agree to the Terms of Service"
    if (!formData.agreeToPrivacy) newErrors.agreeToPrivacy = "You must agree to the Privacy Policy"

    // No additional validations for facility owners in step 1

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleRegister = async () => {
    console.log('Registration attempt started')
    console.log('Form data:', { ...formData, password: '[HIDDEN]', confirmPassword: '[HIDDEN]' })
    
    if (!validateForm()) {
      console.log('Form validation failed:', errors)
      toast.error("Please fix the errors below and try again.", {
        title: "Validation Error"
      })
      return
    }

    console.log('Form validation passed, starting registration process')
    setIsLoading(true)

    try {
      if (userType === "facility") {
        // Use new 3-step facility signup flow
        const facilitySignupData = {
          firstName: formData.firstName.trim(),
          lastName: formData.lastName.trim(),
          email: formData.email.trim().toLowerCase(),
          password: formData.password,
          confirmPassword: formData.confirmPassword
        }

        console.log('Calling facility signup API with data:', facilitySignupData)
        const response = await DataAPI.auth.facilitySignup(facilitySignupData)
        console.log('Facility signup API response:', response)

        if (response.success) {
          console.log('Facility signup successful, redirecting to OTP verification')
          toast.success("Please check your email for the verification code to continue.", {
            title: "Registration Started!"
          })

          // Redirect to OTP verification with user data
          const redirectUrl = `/facility/verify-otp?email=${encodeURIComponent(formData.email)}&userId=${response.data?.userId}`
          console.log('Redirecting to:', redirectUrl)
          router.push(redirectUrl)
        } else {
          console.error('Facility signup failed:', response.message)
          throw new Error(response.message || "Registration failed")
        }
      } else {
        // Use new 3-step user signup flow
        const userSignupData = {
          firstName: formData.firstName.trim(),
          lastName: formData.lastName.trim(),
          email: formData.email.trim().toLowerCase(),
          password: formData.password,
          confirmPassword: formData.confirmPassword
        }

        console.log('Calling user signup API with data:', userSignupData)
        const response = await DataAPI.auth.userSignup(userSignupData)
        console.log('User signup API response:', response)

        if (response.success) {
          console.log('User signup successful, redirecting to OTP verification')
          toast.success("Please check your email for the verification code to continue.", {
            title: "Registration Started!"
          })

          // Redirect to OTP verification with user data
          const redirectUrl = `/user/verify-otp?email=${encodeURIComponent(formData.email)}&userId=${response.data?.userId}`
          console.log('Redirecting to:', redirectUrl)
          router.push(redirectUrl)
        } else {
          console.error('User signup failed:', response.message)
          throw new Error(response.message || "Registration failed")
        }
      }
    } catch (error: any) {
      console.error("Registration error:", error)
      toast.error(error.message || "An error occurred during registration. Please try again.", {
        title: "Registration Failed"
      })
    } finally {
      setIsLoading(false)
    }
  }


  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50">
      {/* Header */}
      <header className="border-b border-slate-200 bg-white/80 backdrop-blur-sm">
        <div className="container mx-auto px-6 py-6"> 
          <div className="flex items-center justify-between">
            <Link href="/" className="flex items-center space-x-4 group">
              <ArrowLeft className="h-5 w-5 text-slate-400 group-hover:text-slate-600 transition-colors" />
              <Image
                src="/images/geezer-guide-logo.png"
                alt="Geezer Guide"
                width={220}
                height={110}
                className="h-14 w-auto drop-shadow-sm"
              />
            </Link>
            <Link href="/login">
              <Button variant="outline" className="font-body bg-transparent text-base px-6 py-2 border-slate-300 hover:bg-slate-50">
                Sign In
              </Button>
            </Link>
          </div>
        </div>
      </header>

      <div className="container mx-auto px-6 py-16">
        <div className="max-w-2xl mx-auto">
          <div className="text-center mb-12">
            <div className="inline-flex items-center justify-center w-16 h-16 bg-blue-100 rounded-full mb-6">
              <svg className="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
              </svg>
            </div>
            <h1 className="font-heading text-4xl md:text-5xl text-slate-800 mb-4 font-bold">Create Your Account</h1>
            <p className="font-body text-lg text-slate-600 leading-relaxed max-w-lg mx-auto">
              Save favorites, write reviews, and get personalized recommendations
            </p>
            <p className="font-body text-base text-slate-500 mt-2">We never sell your data. Your privacy is protected.</p>
          </div>

          <Card className="shadow-2xl border-0 bg-white/90 backdrop-blur-sm">
            <CardHeader className="pb-8 pt-10">
              <CardTitle className="font-heading text-3xl md:text-4xl text-center text-slate-800 mb-2">Get Started</CardTitle>
              <p className="text-center text-slate-500 text-sm">Choose your account type and create your profile</p>
            </CardHeader>
            <CardContent className="space-y-8 px-10 pb-10">
              {/* User Type Selection */}
              <Tabs value={userType} onValueChange={(value) => setUserType(value as "family" | "facility")}>
                <TabsList className="grid w-full grid-cols-2 font-body h-16 text-xl bg-slate-100 rounded-xl">
                  <TabsTrigger value="family" className="flex items-center gap-3 rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-sm">
                    <User className="h-5 w-5" />
                    Family
                  </TabsTrigger>
                  <TabsTrigger value="facility" className="flex items-center gap-3 rounded-lg data-[state=active]:bg-white data-[state=active]:shadow-sm">
                    <Building className="h-5 w-5" />
                    Facility Owner
                  </TabsTrigger>
                </TabsList>

                <TabsContent value="family" className="space-y-8 mt-8">
                  <div className="text-center mb-6">
                    <p className="font-body text-lg text-slate-600">
                      For families searching for senior care facilities
                    </p>
                  </div>

                  {/* Family Registration Form */}
                  <div className="grid grid-cols-2 gap-6">
                    <div className="space-y-3">
                      <Label htmlFor="firstName" className="font-body text-base font-medium text-slate-700">
                        First Name
                      </Label>
                      <Input
                        id="firstName"
                        placeholder="John"
                        value={formData.firstName}
                        onChange={(e) => handleInputChange("firstName", e.target.value)}
                        className={`font-body h-14 text-base border-slate-200 focus:border-green-500 focus:ring-green-500/20 rounded-xl bg-slate-50 focus:bg-white transition-all duration-200 ${errors.firstName ? 'border-red-300 focus:border-red-500' : ''}`}
                      />
                      {errors.firstName && (
                        <p className="text-sm text-red-600 flex items-center gap-2">
                          <AlertCircle className="h-4 w-4" />
                          {errors.firstName}
                        </p>
                      )}
                    </div>
                    <div className="space-y-3">
                      <Label htmlFor="lastName" className="font-body text-base font-medium text-slate-700">
                        Last Name
                      </Label>
                      <Input
                        id="lastName"
                        placeholder="Doe"
                        value={formData.lastName}
                        onChange={(e) => handleInputChange("lastName", e.target.value)}
                        className={`font-body h-14 text-base border-slate-200 focus:border-green-500 focus:ring-green-500/20 rounded-xl bg-slate-50 focus:bg-white transition-all duration-200 ${errors.lastName ? 'border-red-300 focus:border-red-500' : ''}`}
                      />
                      {errors.lastName && (
                        <p className="text-sm text-red-600 flex items-center gap-2">
                          <AlertCircle className="h-4 w-4" />
                          {errors.lastName}
                        </p>
                      )}
                    </div>
                  </div>

                  <div className="space-y-3">
                    <Label htmlFor="email" className="font-body text-base font-medium text-slate-700">
                      Email Address
                    </Label>
                    <div className="relative group">
                      <Mail className="absolute left-4 top-1/2 transform -translate-y-1/2 h-5 w-5 text-slate-400 group-focus-within:text-green-500 transition-colors" />
                      <Input
                        id="email"
                        type="email"
                        placeholder="john@example.com"
                        value={formData.email}
                        onChange={(e) => handleInputChange("email", e.target.value)}
                        className={`pl-12 pr-4 font-body h-14 text-base border-slate-200 focus:border-blue-500 focus:ring-blue-500/20 rounded-xl bg-slate-50 focus:bg-white transition-all duration-200 ${
                          errors.email ? 'border-red-300 focus:border-red-500' : 
                          formData.email && !errors.email ? 'border-blue-300' : ''
                        }`}
                        autoComplete="email"
                        spellCheck="false"
                      />
                    </div>
                    {errors.email ? (
                      <p className="text-sm text-red-600 flex items-center gap-2">
                        <AlertCircle className="h-4 w-4" />
                        {errors.email}
                      </p>
                    ) : formData.email && !errors.email ? (
                      <p className="text-sm text-blue-600 flex items-center gap-2">
                        <CheckCircle className="h-4 w-4" />
                        Valid email address
                      </p>
                    ) : null}
                    <p className="text-sm text-slate-500">We'll send account alerts to this email.</p>
                  </div>

                </TabsContent>

                <TabsContent value="facility" className="space-y-8 mt-8">
                  <div className="text-center mb-6">
                    <p className="font-body text-lg text-slate-600">For facility owners and social workers</p>
                    <div className="bg-blue-50 p-6 rounded-xl mt-6 border border-blue-100">
                      <p className="text-sm text-blue-800 leading-relaxed">
                        <strong>3-Step Process:</strong> First, we'll create your account and verify your email. Then you'll complete your facility profile.
                      </p>
                    </div>
                  </div>

                  {/* Simplified Facility Registration Form - Step 1 */}
                  <div className="space-y-6">
                    <div className="grid grid-cols-2 gap-6">
                      <div className="space-y-3">
                        <Label htmlFor="firstName" className="font-body text-base font-medium text-slate-700">
                          First Name
                        </Label>
                        <Input
                          id="firstName"
                          placeholder="John"
                          value={formData.firstName}
                          onChange={(e) => handleInputChange("firstName", e.target.value)}
                          className={`font-body h-14 text-base border-slate-200 focus:border-blue-500 focus:ring-blue-500/20 rounded-xl bg-slate-50 focus:bg-white transition-all duration-200 ${errors.firstName ? 'border-red-300 focus:border-red-500' : ''}`}
                        />
                        {errors.firstName && (
                          <p className="text-sm text-red-600 flex items-center gap-2">
                            <AlertCircle className="h-4 w-4" />
                            {errors.firstName}
                          </p>
                        )}
                      </div>
                      <div className="space-y-3">
                        <Label htmlFor="lastName" className="font-body text-base font-medium text-slate-700">
                          Last Name
                        </Label>
                        <Input
                          id="lastName"
                          placeholder="Doe"
                          value={formData.lastName}
                          onChange={(e) => handleInputChange("lastName", e.target.value)}
                          className={`font-body h-14 text-base border-slate-200 focus:border-blue-500 focus:ring-blue-500/20 rounded-xl bg-slate-50 focus:bg-white transition-all duration-200 ${errors.lastName ? 'border-red-300 focus:border-red-500' : ''}`}
                        />
                        {errors.lastName && (
                          <p className="text-sm text-red-600 flex items-center gap-2">
                            <AlertCircle className="h-4 w-4" />
                            {errors.lastName}
                          </p>
                        )}
                      </div>
                    </div>

                    <div className="space-y-3">
                      <Label htmlFor="email" className="font-body text-base font-medium text-slate-700">
                        Email Address
                      </Label>
                      <div className="relative group">
                        <Mail className="absolute left-4 top-1/2 transform -translate-y-1/2 h-5 w-5 text-slate-400 group-focus-within:text-blue-500 transition-colors" />
                        <Input
                          id="email"
                          type="email"
                          placeholder="john@facility.com"
                          value={formData.email}
                          onChange={(e) => handleInputChange("email", e.target.value)}
                          className={`pl-12 pr-4 font-body h-14 text-base border-slate-200 focus:border-blue-500 focus:ring-blue-500/20 rounded-xl bg-slate-50 focus:bg-white transition-all duration-200 ${
                            errors.email ? 'border-red-300 focus:border-red-500' : 
                            formData.email && !errors.email ? 'border-blue-300' : ''
                          }`}
                          autoComplete="email"
                          spellCheck="false"
                        />
                      </div>
                      {errors.email ? (
                        <p className="text-sm text-red-600 flex items-center gap-2">
                          <AlertCircle className="h-4 w-4" />
                          {errors.email}
                        </p>
                      ) : formData.email && !errors.email ? (
                        <p className="text-sm text-blue-600 flex items-center gap-2">
                          <CheckCircle className="h-4 w-4" />
                          Valid email address
                        </p>
                      ) : null}
                      <p className="text-sm text-slate-500">We'll send a verification code to this email.</p>
                    </div>
                  </div>
                </TabsContent>
              </Tabs>

              {/* Password Fields */}
              <div className="space-y-6">
                <div className="space-y-3">
                  <Label htmlFor="password" className="font-body text-base font-medium text-slate-700">
                    Password <span className="text-red-500">*</span>
                  </Label>
                  <div className="relative group">
                    <Input
                      id="password"
                      type={showPassword ? "text" : "password"}
                      placeholder="Create a strong password"
                      value={formData.password}
                      onChange={(e) => handleInputChange("password", e.target.value)}
                      className={`pr-12 pl-4 font-body h-14 text-base border-slate-200 focus:border-blue-500 focus:ring-blue-500/20 rounded-xl bg-slate-50 focus:bg-white transition-all duration-200 ${
                        errors.password ? 'border-red-300 focus:border-red-500' : 
                        formData.password && !errors.password && passwordRequirements.every(req => req.met) ? 'border-green-500' : ''
                      }`}
                      autoComplete="new-password"
                      spellCheck="false"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-4 top-1/2 transform -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors"
                      tabIndex={-1}
                    >
                      {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                    </button>
                  </div>
                  {errors.password && (
                    <p className="text-sm text-red-600 flex items-center gap-2">
                      <AlertCircle className="h-4 w-4" />
                      {errors.password}
                    </p>
                  )}
                  {!errors.password && formData.password && passwordRequirements.every(req => req.met) && (
                    <p className="text-sm text-green-600 flex items-center gap-2">
                      <CheckCircle className="h-4 w-4" />
                      Strong password! All requirements met.
                    </p>
                  )}
                  
                  {/* Password Requirements */}
                  {formData.password && (
                    <div className={`rounded-xl p-6 border-2 transition-all ${
                      passwordRequirements.every(req => req.met) 
                        ? 'bg-green-50 border-green-200' 
                        : 'bg-slate-50 border-slate-200'
                    }`}>
                      <p className="text-sm font-medium text-slate-700 font-body flex items-center gap-2 mb-4">
                        <Shield className={`w-4 h-4 ${passwordRequirements.every(req => req.met) ? 'text-green-600' : 'text-slate-600'}`} />
                        Password Requirements
                      </p>
                      <div className="space-y-2">
                        {passwordRequirements.map((req, index) => (
                          <div key={index} className="flex items-center gap-3 text-sm font-body">
                            {req.met ? (
                              <Check className="w-4 h-4 text-green-600 flex-shrink-0" />
                            ) : (
                              <X className="w-4 h-4 text-slate-400 flex-shrink-0" />
                            )}
                            <span className={req.met ? "text-green-700 font-medium" : "text-slate-600"}>
                              {req.text}
                            </span>
                          </div>
                        ))}
                      </div>
                      {!passwordRequirements.every(req => req.met) && (
                        <p className="text-xs text-slate-500 mt-3 pt-3 border-t border-slate-200">
                          💡 Tip: Use a mix of letters, numbers, and symbols like !@#$%^&* for a strong password
                        </p>
                      )}
                    </div>
                  )}
                </div>

                <div className="space-y-3">
                  <Label htmlFor="confirmPassword" className="font-body text-base font-medium text-slate-700">
                    Confirm Password <span className="text-red-500">*</span>
                  </Label>
                  <div className="relative group">
                    <Input
                      id="confirmPassword"
                      type={showConfirmPassword ? "text" : "password"}
                      placeholder="Confirm your password"
                      value={formData.confirmPassword}
                      onChange={(e) => handleInputChange("confirmPassword", e.target.value)}
                      className={`pr-12 pl-4 font-body h-14 text-base border-slate-200 focus:border-blue-500 focus:ring-blue-500/20 rounded-xl bg-slate-50 focus:bg-white transition-all duration-200 ${
                        errors.confirmPassword ? 'border-red-300 focus:border-red-500' : 
                        formData.confirmPassword && formData.confirmPassword === formData.password ? 'border-green-500' : ''
                      }`}
                      autoComplete="new-password"
                      spellCheck="false"
                    />
                    <button
                      type="button"
                      onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                      className="absolute right-4 top-1/2 transform -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors"
                      tabIndex={-1}
                    >
                      {showConfirmPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                    </button>
                  </div>
                  {errors.confirmPassword && (
                    <p className="text-sm text-red-600 flex items-center gap-2">
                      <AlertCircle className="h-4 w-4" />
                      {errors.confirmPassword}
                    </p>
                  )}
                  {!errors.confirmPassword && formData.confirmPassword && formData.confirmPassword === formData.password && (
                    <p className="text-sm text-green-600 flex items-center gap-2">
                      <CheckCircle className="h-4 w-4" />
                      Passwords match!
                    </p>
                  )}
                </div>
              </div>

              {/* Terms and Privacy */}
              <div className="space-y-4">
                <div className="flex items-start space-x-3">
                  <Checkbox
                    id="terms"
                    checked={formData.agreeToTerms}
                    onCheckedChange={(checked) => handleInputChange("agreeToTerms", checked as boolean)}
                    className={`mt-1 border-slate-300 data-[state=checked]:bg-blue-600 data-[state=checked]:border-blue-600 ${errors.agreeToTerms ? 'border-red-300' : ''}`}
                  />
                  <Label htmlFor="terms" className="font-body text-base leading-relaxed text-slate-600">
                    I agree to the{" "}
                    <Link href="/terms" className="text-blue-600 hover:text-blue-700 hover:underline font-medium">
                      Terms of Service
                    </Link>
                  </Label>
                </div>
                {errors.agreeToTerms && (
                  <p className="text-sm text-red-600 flex items-center gap-2 ml-8">
                    <AlertCircle className="h-4 w-4" />
                    {errors.agreeToTerms}
                  </p>
                )}

                <div className="flex items-start space-x-3">
                  <Checkbox
                    id="privacy"
                    checked={formData.agreeToPrivacy}
                    onCheckedChange={(checked) => handleInputChange("agreeToPrivacy", checked as boolean)}
                    className={`mt-1 border-slate-300 data-[state=checked]:bg-blue-600 data-[state=checked]:border-blue-600 ${errors.agreeToPrivacy ? 'border-red-300' : ''}`}
                  />
                  <Label htmlFor="privacy" className="font-body text-base leading-relaxed text-slate-600">
                    I agree to the{" "}
                    <Link href="/privacy" className="text-blue-600 hover:text-blue-700 hover:underline font-medium">
                      Privacy Policy
                    </Link>{" "}
                    and understand that my data will never be sold
                  </Label>
                </div>
                {errors.agreeToPrivacy && (
                  <p className="text-sm text-red-600 flex items-center gap-2 ml-8">
                    <AlertCircle className="h-4 w-4" />
                    {errors.agreeToPrivacy}
                  </p>
                )}
              </div>

              <Button
                onClick={handleRegister}
                disabled={isLoading || !formData.agreeToTerms || !formData.agreeToPrivacy || !!errors.email}
                className="w-full h-16 text-xl bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 font-body font-semibold rounded-xl shadow-lg hover:shadow-xl transition-all duration-200 border-0 disabled:opacity-50"
              >
                {isLoading ? (
                  <>
                    <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                    {userType === "facility" ? "Submitting..." : "Creating Account..."}
                  </>
                ) : (
                  userType === "facility" ? "Submit for Approval" : "Create Account"
                )}
              </Button>

              {userType === "facility" && (
                <div className="bg-amber-50 p-6 rounded-xl border border-amber-200">
                  <p className="font-body text-sm text-amber-800 leading-relaxed">
                    <strong>Note:</strong> Facility accounts require admin approval. You'll receive an email once your
                    account is verified and activated.
                  </p>
                </div>
              )}

              <Separator className="my-8" />

              <div className="text-center">
                <p className="font-body text-lg text-slate-600 leading-relaxed">
                  Already have an account?{" "}
                  <Link href="/login" className="text-blue-600 hover:text-blue-700 hover:underline font-semibold">
                    Sign in here
                  </Link>
                </p>
              </div>
            </CardContent>
          </Card>

          <div className="text-center mt-10">
            <div className="inline-flex items-center space-x-2 text-slate-500 text-sm">
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <span>Need help? Email us at{" "}
                <a href="mailto:info@geezerguide.com" className="text-blue-600 hover:text-blue-700 hover:underline font-medium">
                  info@geezerguide.com
                </a>
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}