"use client"

import { useState, useEffect, useRef } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Header } from "@/components/ui/header"
import { Footer } from "@/components/ui/footer"
import { AnimatedCard } from "@/components/ui/animated-card"
import { AnimatedButton } from "@/components/ui/animated-button"
import { AnimatedInput } from "@/components/ui/animated-input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Search, Star, MapPin, ThumbsUp, Award, TrendingUp, Users, MessageSquare, Loader2 } from "lucide-react"
import Link from "next/link"
import { motion, useInView } from "framer-motion"
import { DataAPI } from "@/lib/data-api"
import { useToast } from "@/components/ui/toast"

interface CareTypeBreakdown {
  name: string
  reviewCount: number
  facilityCount: number
}

interface ReviewInsights {
  averageRating: number
  totalReviews: number
  verifiedFamilies: number
  recommendRate: number
  topCareType: string
  careTypeBreakdown: CareTypeBreakdown[]
}

interface Review {
  id: string
  rating: number
  comment?: string
  relationship?: string
  verified: boolean
  helpful: number
  unhelpful: number
  createdAt: string
  user?: {
    firstName: string
    lastName: string
    profilePicture?: string
  }
  facility?: {
    name: string
    location?: {
      city: string
      state: string
    }
    careTypes?: string[]
  }
}

interface Pagination {
  page: number
  limit: number
  total: number
  pages: number
  hasNext: boolean
  hasPrev: boolean
}

export default function ReviewsPage() {
  const toast = useToast()
  const heroRef = useRef(null)
  const searchRef = useRef(null)
  const reviewsRef = useRef(null)

  const heroInView = useInView(heroRef, { once: true, margin: "-100px" })
  const searchInView = useInView(searchRef, { once: true, margin: "-100px" })
  const reviewsInView = useInView(reviewsRef, { once: true, margin: "-100px" })

  // State
  const [insights, setInsights] = useState<ReviewInsights | null>(null)
  const [reviews, setReviews] = useState<Review[]>([])
  const [pagination, setPagination] = useState<Pagination | null>(null)
  const [loading, setLoading] = useState(true)
  const [loadingMore, setLoadingMore] = useState(false)
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [filters, setFilters] = useState({
    search: '',
    rating: 'all',
    careType: 'all',
    page: 1,
    limit: 2  // Changed to 2 for testing
  })

  // Check authentication status on mount
  useEffect(() => {
    setIsAuthenticated(DataAPI.isAuthenticated())
  }, [])

  // Fetch insights on mount
  useEffect(() => {
    fetchInsights()
  }, [])

  // Fetch reviews on initial load only
  useEffect(() => {
    fetchReviews()
  }, []) // Empty dependency array - only runs once on mount

  const fetchInsights = async () => {
    try {
      const response = await DataAPI.reviews.getInsights()
      if (response.success && response.data) {
        setInsights(response.data)
      }
    } catch (error) {
      console.error('Failed to fetch insights:', error)
    }
  }

  const fetchReviews = async (isLoadingMore = false) => {
    try {
      if (isLoadingMore) {
        setLoadingMore(true)
      } else {
        setLoading(true)
      }

      const response = await DataAPI.reviews.getAll(filters)

      if (response.success && response.data) {
        const data = response.data
        if (isLoadingMore) {
          // Append new reviews to existing ones
          setReviews(prev => [...prev, ...data.reviews])
        } else {
          // Replace reviews (for new search/filter)
          setReviews(data.reviews)
        }
        // Fix: pagination is inside data, not at top level
        setPagination(data.pagination || null)

        // Debug logging
        console.log('[Reviews Page] Loaded reviews:', data.reviews.length)
        console.log('[Reviews Page] Pagination:', data.pagination)
        console.log('[Reviews Page] Has Next:', data.pagination?.hasNext)
        console.log('[Reviews Page] Total Reviews:', data.pagination?.total)
      }
    } catch (error) {
      console.error('Failed to fetch reviews:', error)
      toast.error('Failed to load reviews. Please try again.')
    } finally {
      setLoading(false)
      setLoadingMore(false)
    }
  }

  const handleSearch = (value: string) => {
    // Just update state, don't fetch yet
    setFilters(prev => ({ ...prev, search: value, page: 1 }))
  }

  const handleFilterChange = (key: string, value: string) => {
    // Just update state, don't fetch yet
    setFilters(prev => ({ ...prev, [key]: value, page: 1 }))
  }

  const handleApplyFilters = () => {
    // This is called when user clicks "Filter Reviews" button
    // Reset to page 1 when applying filters
    setFilters(prev => ({ ...prev, page: 1 }))
    fetchReviews(false) // false = not loading more, replace existing reviews
  }

  const handleLoadMore = async () => {
    if (pagination && pagination.hasNext && !loadingMore) {
      // Update page number first
      const nextPage = filters.page + 1
      setFilters(prev => ({ ...prev, page: nextPage }))

      // Fetch next page with updated filters
      setLoadingMore(true)
      try {
        const response = await DataAPI.reviews.getAll({
          ...filters,
          page: nextPage
        })

        if (response.success && response.data) {
          const data = response.data
          // Append new reviews to existing ones
          setReviews(prev => [...prev, ...data.reviews])
          // Fix: pagination is inside data, not at top level
          setPagination(data.pagination || null)
        }
      } catch (error) {
        console.error('Failed to load more reviews:', error)
        toast.error('Failed to load more reviews. Please try again.')
      } finally {
        setLoadingMore(false)
      }
    }
  }

  const handleHelpful = async (reviewId: string) => {
    // Check if user is authenticated before attempting to vote
    const isAuth = DataAPI.isAuthenticated()

    if (!isAuth) {
      toast.error('Please log in to vote on reviews.', {
        title: 'Login Required'
      })
      return
    }

    try {
      const response = await DataAPI.reviews.markHelpful(reviewId)
      if (response.success) {
        // Update the review in state
        setReviews(prev => prev.map(review =>
          review.id === reviewId
            ? { ...review, helpful: response.data?.helpful || review.helpful }
            : review
        ))
        toast.success('Thank you for your feedback!')
      }
    } catch (error: any) {
      console.error('Failed to vote:', error)
      if (error.message?.includes('authentication') || error.message?.includes('401')) {
        toast.error('Your session has expired. Please log in again.')
      } else {
        toast.error('Failed to record your vote. Please try again.')
      }
    }
  }

  const formatRelationship = (relationship?: string) => {
    if (!relationship) return null
    return relationship.charAt(0).toUpperCase() + relationship.slice(1)
  }

  const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    const now = new Date()
    const diffTime = Math.abs(now.getTime() - date.getTime())
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

    if (diffDays < 30) {
      return `${diffDays} day${diffDays !== 1 ? 's' : ''} ago`
    } else if (diffDays < 365) {
      const months = Math.floor(diffDays / 30)
      return `${months} month${months !== 1 ? 's' : ''} ago`
    } else {
      const years = Math.floor(diffDays / 365)
      return `${years} year${years !== 1 ? 's' : ''} ago`
    }
  }

  const getInitials = (firstName?: string, lastName?: string) => {
    return `${firstName?.charAt(0) || ''}${lastName?.charAt(0) || ''}`.toUpperCase() || 'U'
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50/30 relative">
      {/* Background Patterns */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute top-0 right-0 w-96 h-96 bg-gradient-to-br from-blue-100/20 to-indigo-100/20 rounded-full blur-3xl"></div>
        <div className="absolute bottom-0 left-0 w-96 h-96 bg-gradient-to-br from-purple-100/20 to-blue-100/20 rounded-full blur-3xl"></div>
      </div>

      <Header />

      {/* Hero Section */}
      <motion.section
        ref={heroRef}
        className="py-20 px-4 relative overflow-hidden"
        style={{
          background: "linear-gradient(135deg, rgba(63, 92, 234, 0.05) 0%, rgba(91, 115, 240, 0.08) 25%, rgba(255, 255, 255, 0.95) 50%, rgba(147, 197, 253, 0.06) 75%, rgba(99, 102, 241, 0.04) 100%)"
        }}
      >
        {/* Enhanced Background Animation */}
        <div className="absolute inset-0">
          <div className="absolute -top-32 -right-32 w-80 h-80 bg-gradient-to-br from-blue-200/25 to-indigo-200/25 rounded-full blur-3xl"></div>
          <div className="absolute -bottom-32 -left-32 w-80 h-80 bg-gradient-to-br from-indigo-200/25 to-purple-200/25 rounded-full blur-3xl"></div>

          {/* Animated floating elements */}
          {[...Array(10)].map((_, i) => (
            <motion.div
              key={i}
              className="absolute"
              style={{
                left: `${10 + i * 10}%`,
                top: `${15 + (i % 4) * 20}%`,
              }}
              animate={{
                y: [-15, 25, -15],
                opacity: [0.3, 0.8, 0.3],
                scale: [1, 1.2, 1],
                rotate: [0, 180, 360],
              }}
              transition={{
                duration: 8 + i * 1.2,
                repeat: Infinity,
                ease: "easeInOut",
                delay: i * 0.3,
              }}
            >
              <div className={`w-12 h-12 rounded-full blur-sm ${i % 5 === 0 ? 'bg-gradient-to-br from-blue-300/40 to-indigo-300/40' :
                i % 5 === 1 ? 'bg-gradient-to-br from-indigo-300/40 to-purple-300/40' :
                  i % 5 === 2 ? 'bg-gradient-to-br from-purple-300/40 to-blue-300/40' :
                    i % 5 === 3 ? 'bg-gradient-to-br from-cyan-300/40 to-blue-300/40' :
                      'bg-gradient-to-br from-blue-300/40 to-cyan-300/40'
                }`}></div>
            </motion.div>
          ))}

          <div className="absolute top-1/3 left-1/5 w-28 h-28 border border-blue-200/40 rounded-full transform rotate-12"></div>
          <div className="absolute bottom-1/4 right-1/4 w-20 h-20 border border-indigo-200/40 rounded-lg transform -rotate-12"></div>
        </div>

        <div className="container mx-auto max-w-6xl relative z-10">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
            <motion.div
              className="text-center lg:text-left"
              initial={{ opacity: 0, x: -50 }}
              animate={heroInView ? { opacity: 1, x: 0 } : { opacity: 0, x: -50 }}
              transition={{ duration: 0.8, delay: 0.2 }}
            >
              <motion.h1
                className="font-primary text-4xl md:text-5xl lg:text-6xl font-bold mb-8 bg-gradient-to-r from-gray-900 via-gray-800 to-[#3F5CEA] bg-clip-text text-transparent"
                initial={{ opacity: 0, y: 30 }}
                animate={heroInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 30 }}
                transition={{ duration: 0.8, delay: 0.4 }}
              >
                Family Reviews & Experiences
              </motion.h1>

              <motion.p
                className="text-xl md:text-2xl lg:text-2xl text-gray-700 mb-10 leading-relaxed font-medium"
                initial={{ opacity: 0, y: 30 }}
                animate={heroInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 30 }}
                transition={{ duration: 0.8, delay: 0.6 }}
              >
                Read <span className="text-[#3F5CEA] font-bold">authentic reviews</span> from real families who have experience with senior care facilities. Make informed decisions based on honest feedback.
              </motion.p>

              <motion.div
                className="flex flex-col sm:flex-row gap-4 justify-center lg:justify-start"
                initial={{ opacity: 0, y: 30 }}
                animate={heroInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 30 }}
                transition={{ duration: 0.8, delay: 0.8 }}
              >
                <Link href="/register">
                  <AnimatedButton className="bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] hover:from-[#09183D] hover:to-[#3F5CEA] text-white text-lg px-8 py-4 shadow-lg hover:shadow-xl">
                    Write a Review
                  </AnimatedButton>
                </Link>
                <AnimatedButton
                  variant="outline"
                  className="border-[#3F5CEA] text-[#3F5CEA] hover:bg-[#3F5CEA] hover:text-white text-lg px-8 py-4"
                  onClick={() => {
                    document.getElementById('reviews-section')?.scrollIntoView({ behavior: 'smooth' })
                  }}
                >
                  Browse Reviews
                </AnimatedButton>
              </motion.div>
            </motion.div>

            <motion.div
              initial={{ opacity: 0, x: 50 }}
              animate={heroInView ? { opacity: 1, x: 0 } : { opacity: 0, x: 50 }}
              transition={{ duration: 0.8, delay: 0.4 }}
              className="relative"
            >
              <div className="relative">
                {/* Review insights card */}
                <div className="bg-white/80 backdrop-blur-sm rounded-3xl shadow-2xl p-8 border border-white/50">
                  <div className="absolute -inset-1 bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] rounded-3xl opacity-10"></div>
                  <div className="relative">
                    <div className="text-center mb-6">
                      <h3 className="font-primary text-3xl font-black text-gray-900 mb-3 care-sub-heading">Review Insights</h3>
                      <p className="text-lg text-gray-700 font-medium">What families are saying</p>
                    </div>

                    {insights ? (
                      <>
                        <div className="grid grid-cols-2 gap-4">
                          <div className="text-center">
                            <div className="bg-gradient-to-br from-blue-50 to-indigo-50 p-4 rounded-2xl mb-3">
                              <Award className="h-8 w-8 text-[#3F5CEA] mx-auto" />
                            </div>
                            <h4 className="font-bold text-lg text-gray-900 mb-1">{insights.averageRating}/5</h4>
                            <p className="text-base text-gray-700">Average Rating</p>
                          </div>

                          <div className="text-center">
                            <div className="bg-gradient-to-br from-indigo-50 to-purple-50 p-4 rounded-2xl mb-3">
                              <MessageSquare className="h-8 w-8 text-[#5B73F0] mx-auto" />
                            </div>
                            <h4 className="font-bold text-lg text-gray-900 mb-1">{insights.totalReviews.toLocaleString()}</h4>
                            <p className="text-base text-gray-700">Total Reviews</p>
                          </div>

                          <div className="text-center">
                            <div className="bg-gradient-to-br from-purple-50 to-blue-50 p-4 rounded-2xl mb-3">
                              <Users className="h-8 w-8 text-indigo-600 mx-auto" />
                            </div>
                            <h4 className="font-bold text-lg text-gray-900 mb-1">{insights.verifiedFamilies}+</h4>
                            <p className="text-base text-gray-700">Verified Families</p>
                          </div>

                          <div className="text-center">
                            <div className="bg-gradient-to-br from-green-50 to-emerald-50 p-4 rounded-2xl mb-3">
                              <TrendingUp className="h-8 w-8 text-green-500 mx-auto" />
                            </div>
                            <h4 className="font-bold text-lg text-gray-900 mb-1">{insights.recommendRate}%</h4>
                            <p className="text-base text-gray-700">Recommend Rate</p>
                          </div>
                        </div>


                        <div className="mt-6 pt-6 border-t border-gray-200/50">
                          <div className="text-center">
                            <div className="flex items-center justify-center gap-1 mb-3">
                              {[...Array(5)].map((_, i) => (
                                <Star key={i} className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                              ))}
                            </div>
                            {insights.totalReviews > 0 ? (
                              <p className="text-sm text-gray-600">
                                Most reviewed: <span className="font-semibold text-gray-900">{insights.topCareType}</span>
                              </p>
                            ) : (
                              <p className="text-sm text-gray-600">
                                Most common: <span className="font-semibold text-gray-900">{insights.topCareType}</span>
                              </p>
                            )}

                            {/* Care Type Breakdown */}
                            {insights.careTypeBreakdown && insights.careTypeBreakdown.length > 0 && (
                              <div className="mt-4 space-y-2">
                                <p className="text-xs text-gray-500 font-medium mb-2">Care Type Statistics:</p>
                                <div className="grid grid-cols-1 gap-2 max-h-32 overflow-y-auto">
                                  {insights.careTypeBreakdown.map((careType, index) => (
                                    <div
                                      key={index}
                                      className="flex items-center justify-between text-xs bg-white/50 px-3 py-2 rounded-lg"
                                    >
                                      <span className="font-medium text-gray-700">{careType.name}</span>
                                      <span className="text-gray-600">
                                        {insights.totalReviews > 0
                                          ? `${careType.reviewCount} reviews`
                                          : `${careType.facilityCount} facilities`}
                                      </span>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            )}
                          </div>
                        </div>
                      </>
                    ) : (
                      <div className="flex justify-center py-8">
                        <Loader2 className="h-8 w-8 animate-spin text-[#3F5CEA]" />
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </motion.div>
          </div>
        </div>
      </motion.section>

      {/* Search & Filter Section */}
      <motion.section
        ref={searchRef}
        className="py-12 px-4 bg-white/60 backdrop-blur-sm border-y border-white/50"
      >
        <div className="container mx-auto max-w-6xl">
          <motion.div
            className="bg-white rounded-2xl shadow-xl border border-slate-200/50 p-6"
            initial={{ opacity: 0, y: 30 }}
            animate={searchInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 30 }}
            transition={{ duration: 0.8, delay: 0.2 }}
          >
            <div className="flex flex-col lg:flex-row gap-4 items-center">
              <div className="flex-1 w-full">
                <div className="relative">
                  <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 h-5 w-5 text-slate-400" />
                  <AnimatedInput
                    placeholder="Search reviews by facility name or location..."
                    value={filters.search}
                    onChange={(e) => handleSearch(e.target.value)}
                    className="pl-12 pr-4 py-4 text-lg border-0 focus-visible:ring-2 focus-visible:ring-[#3F5CEA]/20 bg-slate-50 rounded-xl font-medium placeholder:text-slate-400"
                  />
                </div>
              </div>

              <div className="flex flex-col sm:flex-row gap-3 w-full lg:w-auto">
                <Select value={filters.rating} onValueChange={(value) => handleFilterChange('rating', value)}>
                  <SelectTrigger className="w-full sm:w-40 bg-slate-50 border-0 rounded-xl">
                    <SelectValue placeholder="Rating" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Ratings</SelectItem>
                    <SelectItem value="5">5 Stars</SelectItem>
                    <SelectItem value="4">4+ Stars</SelectItem>
                    <SelectItem value="3">3+ Stars</SelectItem>
                  </SelectContent>
                </Select>

                <Select value={filters.careType} onValueChange={(value) => handleFilterChange('careType', value)}>
                  <SelectTrigger className="w-full sm:w-40 bg-slate-50 border-0 rounded-xl">
                    <SelectValue placeholder="Care Type" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Types</SelectItem>
                    <SelectItem value="independent">Independent Living</SelectItem>
                    <SelectItem value="assisted">Assisted Living</SelectItem>
                    <SelectItem value="memory">Memory Care</SelectItem>
                    <SelectItem value="skilled">Skilled Nursing</SelectItem>
                  </SelectContent>
                </Select>

                <AnimatedButton
                  className="bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] hover:from-[#09183D] hover:to-[#3F5CEA] text-white px-6 py-3 rounded-xl shadow-lg hover:shadow-xl"
                  onClick={handleApplyFilters}
                  disabled={loading}
                >
                  {loading ? <Loader2 className="h-5 w-5 animate-spin" /> : 'Filter Reviews'}
                </AnimatedButton>
              </div>
            </div>
          </motion.div>
        </div>
      </motion.section>

      {/* Reviews List */}
      <motion.section
        ref={reviewsRef}
        id="reviews-section"
        className="py-20 px-4 relative"
      >
        <div className="container mx-auto max-w-5xl">
          <motion.div
            className="text-center mb-12"
            initial={{ opacity: 0, y: 30 }}
            animate={reviewsInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 30 }}
            transition={{ duration: 0.8 }}
          >
            <h2 className="font-primary text-4xl md:text-5xl lg:text-6xl font-black bg-gradient-to-r from-gray-900 to-[#3F5CEA] bg-clip-text text-transparent mb-6">
              What Families Are Saying
            </h2>
            <p className="text-xl md:text-2xl text-gray-700 max-w-3xl mx-auto leading-relaxed font-medium">
              Real experiences from families who have chosen senior care facilities for their loved ones
            </p>
          </motion.div>

          {loading ? (
            <div className="flex justify-center py-20">
              <Loader2 className="h-12 w-12 animate-spin text-[#3F5CEA]" />
            </div>
          ) : reviews.length === 0 ? (
            <div className="text-center py-20">
              <MessageSquare className="h-16 w-16 text-gray-300 mx-auto mb-4" />
              <h3 className="text-2xl font-bold text-gray-900 mb-2">No Reviews Found</h3>
              <p className="text-gray-600 mb-6">Try adjusting your filters or search terms</p>
              <AnimatedButton
                onClick={() => setFilters({ search: '', rating: 'all', careType: 'all', page: 1, limit: 10 })}
                variant="outline"
                className="border-[#3F5CEA] text-[#3F5CEA] hover:bg-[#3F5CEA] hover:text-white"
              >
                Clear Filters
              </AnimatedButton>
            </div>
          ) : (
            <div className="space-y-8">
              {reviews.map((review, index) => (
                <motion.div
                  key={review.id}
                  initial={{ opacity: 0, y: 40 }}
                  animate={reviewsInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 40 }}
                  transition={{ duration: 0.6, delay: 0.1 * index }}
                >
                  <AnimatedCard className="bg-gradient-to-br from-white to-blue-50/30 border-0 shadow-lg hover:shadow-xl transition-all duration-300">
                    <CardContent className="p-10">
                      <div className="flex items-start justify-between mb-8">
                        <div>
                          <h3 className="font-primary text-3xl md:text-4xl lg:text-5xl font-black text-gray-900 mb-4">
                            {review.facility?.name || 'Senior Living Facility'}
                          </h3>
                          {review.facility?.location && (
                            <p className="text-lg text-gray-700 flex items-center gap-2 font-medium">
                              <MapPin className="h-5 w-5" />
                              {review.facility.location.city}, {review.facility.location.state}
                            </p>
                          )}
                        </div>
                        {review.verified && (
                          <Badge className="bg-gradient-to-r from-green-100 to-emerald-100 text-green-700 border-0 px-3 py-1 font-semibold">
                            ✓ Verified Review
                          </Badge>
                        )}
                      </div>

                      <div className="flex items-center gap-3 mb-6">
                        <div className="flex items-center bg-yellow-50 px-3 py-1 rounded-full">
                          {[...Array(5)].map((_, i) => (
                            <Star
                              key={i}
                              className={`h-4 w-4 ${i < review.rating ? 'fill-yellow-400 text-yellow-400' : 'text-gray-300'}`}
                            />
                          ))}
                        </div>
                        <span className="text-sm text-gray-600 font-medium">
                          {review.rating}.0 • {formatDate(review.createdAt)}
                        </span>
                      </div>

                      {review.comment && (
                        <div className="bg-white/80 rounded-xl p-8 mb-8 border border-blue-100/50">
                          <p className="text-gray-700 leading-relaxed text-xl">
                            "{review.comment}"
                          </p>
                        </div>
                      )}

                      <div className="flex items-center justify-between pt-4 border-t border-blue-100/50">
                        <div className="flex items-center gap-4">
                          <div className="flex items-center gap-2">
                            <div className="w-8 h-8 bg-gradient-to-br from-[#3F5CEA] to-[#5B73F0] rounded-full flex items-center justify-center text-white font-bold text-sm">
                              {getInitials(review.user?.firstName, review.user?.lastName)}
                            </div>
                            <span className="text-gray-700 font-medium">
                              {review.user?.firstName} {review.user?.lastName?.charAt(0)}.
                              {review.relationship && ` • ${formatRelationship(review.relationship)}`}
                            </span>
                          </div>
                          {review.facility?.careTypes && review.facility.careTypes[0] && (
                            <Badge variant="outline" className="border-blue-200 text-blue-700 bg-blue-50">
                              {review.facility.careTypes[0].split('_').map((w: string) =>
                                w.charAt(0).toUpperCase() + w.slice(1)
                              ).join(' ')}
                            </Badge>
                          )}
                        </div>
                        <AnimatedButton
                          variant="ghost"
                          size="sm"
                          className={`text-gray-600 hover:text-[#3F5CEA] hover:bg-blue-50 ${!isAuthenticated ? 'opacity-70' : ''}`}
                          onClick={() => handleHelpful(review.id)}
                          title={!isAuthenticated ? 'Log in to vote on reviews' : 'Mark this review as helpful'}
                        >
                          <ThumbsUp className="h-4 w-4 mr-2" />
                          Helpful ({review.helpful})
                          {!isAuthenticated && (
                            <span className="ml-1 text-xs text-gray-400">(Login)</span>
                          )}
                        </AnimatedButton>
                      </div>
                    </CardContent>
                  </AnimatedCard>
                </motion.div>
              ))}
            </div>
          )}

          {/* Load More / Pagination */}
          {pagination && pagination.hasNext && !loading && (
            <motion.div
              className="text-center mt-12"
              initial={{ opacity: 0, y: 20 }}
              animate={reviewsInView ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
              transition={{ duration: 0.8, delay: 0.8 }}
            >
              <AnimatedButton
                variant="outline"
                className="border-[#3F5CEA] text-[#3F5CEA] hover:bg-[#3F5CEA] hover:text-white bg-white px-8 py-3 shadow-lg hover:shadow-xl"
                onClick={handleLoadMore}
                disabled={loadingMore}
              >
                {loadingMore ? (
                  <>
                    <Loader2 className="h-5 w-5 animate-spin mr-2" />
                    Loading...
                  </>
                ) : (
                  `Load More Reviews (${pagination.total - (pagination.page * pagination.limit)} remaining)`
                )}
              </AnimatedButton>
            </motion.div>
          )}
        </div>
      </motion.section>

      {/* CTA Section */}
      <section className="py-20 px-4 bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] relative overflow-hidden">
        {/* Background decoration */}
        <div className="absolute inset-0">
          {[...Array(6)].map((_, i) => (
            <motion.div
              key={i}
              className="absolute w-32 h-32 bg-white/10 rounded-full blur-xl"
              style={{
                left: `${20 + i * 15}%`,
                top: `${25 + (i % 2) * 50}%`,
              }}
              animate={{
                scale: [1, 1.2, 1],
                opacity: [0.3, 0.6, 0.3],
              }}
              transition={{
                duration: 4 + i,
                repeat: Infinity,
                ease: "easeInOut",
                delay: i * 0.5,
              }}
            />
          ))}
        </div>

        <div className="container mx-auto text-center max-w-4xl relative z-10">
          <motion.h2
            className="font-primary text-4xl md:text-5xl lg:text-6xl font-black text-white mb-8"
            initial={{ opacity: 0, y: 30 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8 }}
          >
            Share Your Experience
          </motion.h2>
          <motion.p
            className="text-xl md:text-2xl text-white/90 mb-10 leading-relaxed max-w-3xl mx-auto"
            initial={{ opacity: 0, y: 30 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8, delay: 0.2 }}
          >
            Help other families by sharing your experience with a senior care facility. Your honest review can make a
            difference in someone's journey to finding the right care.
          </motion.p>
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8, delay: 0.4 }}
          >
            <Link href="/register">
              <AnimatedButton
                size="lg"
                className="bg-white text-[#3F5CEA] hover:bg-gray-100 px-10 py-4 shadow-lg hover:shadow-xl font-semibold text-xl"
              >
                Write a Review
              </AnimatedButton>
            </Link>
          </motion.div>
        </div>
      </section>

      <Footer />
    </div>
  )
}
