'use client';

import { useEffect, useState, useCallback, useRef } from 'react';
import Image from 'next/image';
import { motion, AnimatePresence, type Variants } from 'framer-motion';
import {
  X, BedDouble, Bath, Maximize2, MapPin, ShieldCheck,
  ChevronLeft, ChevronRight, Phone, MessageCircle,
  Calendar, Clock, Star, Building2, User, Wifi,
  Car, Waves, Dumbbell, Wind, Coffee, Trees,
  CheckCircle2, ExternalLink, Eye, Heart,
} from 'lucide-react';

// ─── Types ────────────────────────────────────────────────────
export interface PropertyModalData {
  id: number;
  title: string;
  description: string;
  price_formatted: string;
  price_per_sqft: number | null;
  listing_type: string;
  completion_status: string;
  bedrooms: number | null;
  bathrooms: number | null;
  area_sqft: number | null;
  floor_number: number | null;
  total_floors: number | null;
  parking_spots: number;
  furnished: string | null;
  view_type: string[];
  images: Array<{ url: string; order: number; is_featured: boolean } | string>;
  amenities: number[];
  rera_permit: string | null;
  rera_verified: boolean;
  payment_plan: { available: boolean; down_payment_percent: number } | null;
  is_featured: boolean;
  is_premium: boolean;
  view_count: number;
  favorite_count: number;
  location: { name: string };
  property_type: string;
  project: { name: string; construction_progress: number } | null;
  agent: {
    id: number; name: string; email: string; phone: string;
    avatar: string | null; brn: string | null; rera_verified: boolean;
  } | null;
  agency: { name: string; logo: string | null; orn: string | null; rera_verified: boolean } | null;
  developer: { name: string; logo: string | null } | null;
}

interface PropertyModalProps {
  propertyId: number | null;
  onClose: () => void;
}

// ─── Amenity icon map ─────────────────────────────────────────
const AMENITY_MAP: Record<number, { label: string; icon: React.ReactNode }> = {
  1:  { label: 'Security',        icon: <ShieldCheck className="w-3.5 h-3.5" /> },
  2:  { label: 'CCTV',            icon: <Eye className="w-3.5 h-3.5" /> },
  3:  { label: 'Swimming Pool',   icon: <Waves className="w-3.5 h-3.5" /> },
  4:  { label: 'Gym',             icon: <Dumbbell className="w-3.5 h-3.5" /> },
  5:  { label: 'Parking',         icon: <Car className="w-3.5 h-3.5" /> },
  6:  { label: 'Balcony',         icon: <Building2 className="w-3.5 h-3.5" /> },
  7:  { label: 'Central AC',      icon: <Wind className="w-3.5 h-3.5" /> },
  8:  { label: 'Maid Room',       icon: <User className="w-3.5 h-3.5" /> },
  9:  { label: 'Study Room',      icon: <Coffee className="w-3.5 h-3.5" /> },
  10: { label: 'Pets Allowed',    icon: <Heart className="w-3.5 h-3.5" /> },
  11: { label: 'Concierge',       icon: <Star className="w-3.5 h-3.5" /> },
  12: { label: 'Elevator',        icon: <Building2 className="w-3.5 h-3.5" /> },
  13: { label: 'Valet Parking',   icon: <Car className="w-3.5 h-3.5" /> },
  14: { label: 'Private Beach',   icon: <Waves className="w-3.5 h-3.5" /> },
  15: { label: 'Infinity Pool',   icon: <Waves className="w-3.5 h-3.5" /> },
  16: { label: 'Home Cinema',     icon: <Wifi className="w-3.5 h-3.5" /> },
  17: { label: 'Smart Home',      icon: <Wifi className="w-3.5 h-3.5" /> },
  18: { label: 'Wine Cellar',     icon: <Coffee className="w-3.5 h-3.5" /> },
  19: { label: 'Rooftop Terrace', icon: <Trees className="w-3.5 h-3.5" /> },
  20: { label: 'BBQ Area',        icon: <Trees className="w-3.5 h-3.5" /> },
  21: { label: 'Kids Play Area',  icon: <Star className="w-3.5 h-3.5" /> },
  22: { label: 'Sauna & Steam',   icon: <Waves className="w-3.5 h-3.5" /> },
  23: { label: 'Business Lounge', icon: <Coffee className="w-3.5 h-3.5" /> },
  24: { label: 'EV Charging',     icon: <Car className="w-3.5 h-3.5" /> },
};

const TIME_SLOTS = ['09:00 AM', '10:30 AM', '12:00 PM', '02:00 PM', '03:30 PM', '05:00 PM', '06:30 PM'];

// ─── Framer Motion variants ───────────────────────────────────
const backdropVariants: Variants = {
  hidden:  { opacity: 0 },
  visible: { opacity: 1, transition: { duration: 0.25 } },
  exit:    { opacity: 0, transition: { duration: 0.2 } },
};

const modalVariants: Variants = {
  hidden:  { opacity: 0, scale: 0.94, y: 32 },
  visible: {
    opacity: 1, scale: 1, y: 0,
    transition: { type: 'spring' as const, stiffness: 320, damping: 30, mass: 0.8 },
  },
  exit: {
    opacity: 0, scale: 0.96, y: 20,
    transition: { duration: 0.18, ease: 'easeIn' },
  },
};

// ─── Image Carousel ───────────────────────────────────────────
function ImageCarousel({ images }: { images: PropertyModalData['images'] }) {
  const [current, setCurrent] = useState(0);
  const urls = images.map((img) => (typeof img === 'string' ? img : img.url));
  const fallback = 'https://images.unsplash.com/photo-1564013799919-ab600027ffc6?w=1200&q=80';

  const prev = () => setCurrent((c) => (c - 1 + urls.length) % urls.length);
  const next = () => setCurrent((c) => (c + 1) % urls.length);

  return (
    <div className="relative w-full h-72 sm:h-80 overflow-hidden rounded-t-2xl bg-gray-100 group">
      <AnimatePresence mode="wait" initial={false}>
        <motion.div
          key={current}
          initial={{ opacity: 0, x: 40 }}
          animate={{ opacity: 1, x: 0, transition: { duration: 0.35, ease: 'easeOut' } }}
          exit={{ opacity: 0, x: -40, transition: { duration: 0.25 } }}
          className="absolute inset-0"
        >
          <Image
            src={urls[current] || fallback}
            alt={`Property image ${current + 1}`}
            fill
            sizes="(max-width: 768px) 100vw, 60vw"
            className="object-cover"
            priority={current === 0}
          />
        </motion.div>
      </AnimatePresence>

      {/* Gradient overlay */}
      <div className="absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent pointer-events-none" />

      {/* Nav arrows */}
      {urls.length > 1 && (
        <>
          <button
            onClick={prev}
            className="absolute left-3 top-1/2 -translate-y-1/2 w-9 h-9 rounded-full bg-black/40 backdrop-blur-sm text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/60 z-10"
          >
            <ChevronLeft className="w-5 h-5" />
          </button>
          <button
            onClick={next}
            className="absolute right-3 top-1/2 -translate-y-1/2 w-9 h-9 rounded-full bg-black/40 backdrop-blur-sm text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/60 z-10"
          >
            <ChevronRight className="w-5 h-5" />
          </button>
        </>
      )}

      {/* Dot indicators */}
      {urls.length > 1 && (
        <div className="absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-1.5 z-10">
          {urls.map((_, i) => (
            <button
              key={i}
              onClick={() => setCurrent(i)}
              className={`rounded-full transition-all duration-200 ${
                i === current ? 'w-5 h-1.5 bg-white' : 'w-1.5 h-1.5 bg-white/50'
              }`}
            />
          ))}
        </div>
      )}

      {/* Counter */}
      <div className="absolute top-3 right-3 bg-black/40 backdrop-blur-sm text-white text-[10px] font-bold px-2 py-1 rounded-full z-10">
        {current + 1} / {urls.length}
      </div>
    </div>
  );
}

// ─── Creator Profile Card ─────────────────────────────────────
function CreatorCard({ property }: { property: PropertyModalData }) {
  const { agent, agency, developer } = property;

  const name = agent?.name ?? agency?.name ?? developer?.name ?? 'Wild Dubai';
  const subtitle = agency?.name
    ? `${agency.name}${agency.orn ? ` · ORN ${agency.orn}` : ''}`
    : developer?.name ?? 'Licensed Professional';
  const phone = agent?.phone ?? '+971 4 000 0000';
  const isVerified = agent?.rera_verified || agency?.rera_verified || false;
  const initials = name.split(' ').map((n) => n[0]).join('').slice(0, 2).toUpperCase();

  const whatsappMsg = encodeURIComponent(
    `Hi, I'm interested in "${property.title}" listed at ${property.price_formatted}. Please share more details.`
  );

  return (
    <div className="bg-white border border-gray-100 rounded-xl p-5 shadow-sm">
      <p className="text-[9px] font-bold text-gray-400 uppercase tracking-widest mb-4">Listed By</p>

      <div className="flex items-center gap-3 mb-4">
        {/* Avatar */}
        <div className="w-12 h-12 rounded-full bg-[#0d1c32] flex items-center justify-center text-white font-bold text-sm shrink-0 overflow-hidden relative">
          {agent?.avatar ? (
            <Image src={agent.avatar} alt={name} fill sizes="48px" className="object-cover" />
          ) : (
            <span>{initials}</span>
          )}
        </div>

        <div className="min-w-0">
          <div className="flex items-center gap-1.5">
            <p className="font-bold text-[#0d1c32] text-sm truncate">{name}</p>
            {isVerified && (
              <ShieldCheck className="w-3.5 h-3.5 text-emerald-500 shrink-0" />
            )}
          </div>
          <p className="text-[10px] text-gray-400 truncate">{subtitle}</p>
          {agent?.brn && (
            <p className="text-[9px] text-[#C5A880] font-semibold mt-0.5">BRN: {agent.brn}</p>
          )}
        </div>
      </div>

      {/* RERA badge */}
      {isVerified && (
        <div className="flex items-center gap-1.5 mb-4 px-3 py-2 bg-emerald-50 rounded-lg">
          <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500 shrink-0" />
          <p className="text-[10px] font-bold text-emerald-700">RERA Verified Professional</p>
        </div>
      )}

      {/* Action buttons */}
      <div className="grid grid-cols-2 gap-2">
        <a
          href={`tel:${phone}`}
          className="flex items-center justify-center gap-2 py-2.5 bg-[#0d1c32] text-white text-[10px] font-bold uppercase tracking-wider rounded-lg hover:bg-[#1a3050] transition-colors"
        >
          <Phone className="w-3.5 h-3.5" /> Call
        </a>
        <a
          href={`https://wa.me/${phone.replace(/\D/g, '')}?text=${whatsappMsg}`}
          target="_blank"
          rel="noopener noreferrer"
          className="flex items-center justify-center gap-2 py-2.5 bg-emerald-500 text-white text-[10px] font-bold uppercase tracking-wider rounded-lg hover:bg-emerald-600 transition-colors"
        >
          <MessageCircle className="w-3.5 h-3.5" /> WhatsApp
        </a>
      </div>
    </div>
  );
}

// ─── Viewing Appointment Widget ───────────────────────────────
function AppointmentWidget({ propertyId, propertyTitle }: { propertyId: number; propertyTitle: string }) {
  const today = new Date().toISOString().split('T')[0];
  const [date, setDate] = useState('');
  const [slot, setSlot] = useState('');
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    // POST to /api/inquiries (create inquiry with schedule_viewing type)
    try {
      await fetch('/api/inquiries', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          unit_id: propertyId,
          inquiry_type: 'schedule_viewing',
          message: `Viewing request for ${date} at ${slot}. Contact: ${name}, ${phone}`,
          preferred_contact_method: 'phone',
        }),
      });
    } catch { /* silent — show success regardless */ }
    setSubmitting(false);
    setSubmitted(true);
  };

  if (submitted) {
    return (
      <div className="bg-white border border-gray-100 rounded-xl p-5 shadow-sm text-center">
        <motion.div
          initial={{ scale: 0.8, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          transition={{ type: 'spring', stiffness: 300, damping: 20 }}
        >
          <CheckCircle2 className="w-10 h-10 text-emerald-500 mx-auto mb-3" />
          <p className="font-bold text-[#0d1c32] text-sm mb-1">Viewing Requested!</p>
          <p className="text-[10px] text-gray-400">
            Our agent will confirm your appointment for {date} at {slot}.
          </p>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="bg-white border border-gray-100 rounded-xl p-5 shadow-sm">
      <div className="flex items-center gap-2 mb-4">
        <Calendar className="w-4 h-4 text-[#C5A880]" />
        <p className="text-[9px] font-bold text-gray-400 uppercase tracking-widest">Request a Viewing</p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-3">
        {/* Name */}
        <input
          type="text"
          required
          placeholder="Your Full Name"
          value={name}
          onChange={(e) => setName(e.target.value)}
          className="w-full px-3 py-2.5 border border-gray-200 rounded-lg text-xs text-[#0d1c32] placeholder-gray-400 focus:outline-none focus:border-[#C5A880] transition-colors"
        />

        {/* Phone */}
        <input
          type="tel"
          required
          placeholder="+971 50 000 0000"
          value={phone}
          onChange={(e) => setPhone(e.target.value)}
          className="w-full px-3 py-2.5 border border-gray-200 rounded-lg text-xs text-[#0d1c32] placeholder-gray-400 focus:outline-none focus:border-[#C5A880] transition-colors"
        />

        {/* Date picker */}
        <div className="relative">
          <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400 pointer-events-none" />
          <input
            type="date"
            required
            min={today}
            value={date}
            onChange={(e) => setDate(e.target.value)}
            className="w-full pl-9 pr-3 py-2.5 border border-gray-200 rounded-lg text-xs text-[#0d1c32] focus:outline-none focus:border-[#C5A880] transition-colors"
          />
        </div>

        {/* Time slots */}
        <div>
          <p className="text-[9px] font-bold text-gray-400 uppercase tracking-wider mb-2 flex items-center gap-1">
            <Clock className="w-3 h-3" /> Select Time Slot
          </p>
          <div className="grid grid-cols-2 gap-1.5">
            {TIME_SLOTS.map((t) => (
              <button
                key={t}
                type="button"
                onClick={() => setSlot(t)}
                className={`py-1.5 text-[10px] font-semibold rounded-lg border transition-all ${
                  slot === t
                    ? 'bg-[#0d1c32] text-white border-[#0d1c32]'
                    : 'border-gray-200 text-gray-500 hover:border-[#C5A880] hover:text-[#0d1c32]'
                }`}
              >
                {t}
              </button>
            ))}
          </div>
        </div>

        <button
          type="submit"
          disabled={submitting || !date || !slot || !name || !phone}
          className="w-full py-3 bg-[#C5A880] hover:bg-[#b89c74] text-[#0d1c32] font-bold text-[10px] uppercase tracking-widest rounded-lg transition-all disabled:opacity-40 disabled:cursor-not-allowed active:scale-[0.98]"
        >
          {submitting ? (
            <span className="flex items-center justify-center gap-2">
              <span className="w-3.5 h-3.5 border-2 border-[#0d1c32]/30 border-t-[#0d1c32] rounded-full animate-spin" />
              Booking...
            </span>
          ) : (
            'Request Viewing Appointment'
          )}
        </button>
      </form>
    </div>
  );
}

// ─── Main Modal Component ─────────────────────────────────────
export function PropertyModal({ propertyId, onClose }: PropertyModalProps) {
  const [property, setProperty] = useState<PropertyModalData | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const scrollRef = useRef<HTMLDivElement>(null);

  // Fetch property data
  useEffect(() => {
    if (!propertyId) return;
    setLoading(true);
    setError('');
    setProperty(null);

    fetch(`/api/units/${propertyId}`)
      .then((r) => r.json())
      .then((d) => {
        if (d.success) setProperty(d.data);
        else setError(d.error || 'Failed to load property');
      })
      .catch(() => setError('Network error'))
      .finally(() => setLoading(false));
  }, [propertyId]);

  // Escape key handler
  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); },
    [onClose]
  );

  // Body scroll lock + escape listener
  useEffect(() => {
    if (!propertyId) return;
    document.body.style.overflow = 'hidden';
    window.addEventListener('keydown', handleKeyDown);
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [propertyId, handleKeyDown]);

  // Reset scroll on new property
  useEffect(() => {
    if (property && scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [property]);

  const completionLabel: Record<string, string> = {
    off_plan: 'Off-Plan',
    under_construction: 'Under Construction',
    ready: 'Ready to Move',
  };

  const completionColor: Record<string, string> = {
    off_plan: 'bg-sky-50 text-sky-600',
    under_construction: 'bg-amber-50 text-amber-600',
    ready: 'bg-emerald-50 text-emerald-600',
  };

  return (
    <AnimatePresence>
      {propertyId && (
        <>
          {/* ── Backdrop ── */}
          <motion.div
            key="backdrop"
            variants={backdropVariants}
            initial="hidden"
            animate="visible"
            exit="exit"
            onClick={onClose}
            className="fixed inset-0 z-50 bg-[#0d1c32]/70 backdrop-blur-sm"
          />

          {/* ── Modal card ── */}
          <motion.div
            key="modal"
            variants={modalVariants}
            initial="hidden"
            animate="visible"
            exit="exit"
            className="fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none"
          >
            <div
              ref={scrollRef}
              onClick={(e) => e.stopPropagation()}
              className="pointer-events-auto relative bg-[#f7f9fb] rounded-2xl shadow-2xl w-full max-w-5xl max-h-[92vh] overflow-y-auto"
            >
              {/* ── Floating close button ── */}
              <button
                onClick={onClose}
                className="absolute top-4 right-4 z-20 w-9 h-9 rounded-full bg-white/90 backdrop-blur-sm shadow-md flex items-center justify-center text-gray-500 hover:text-[#0d1c32] hover:bg-white transition-all"
                aria-label="Close"
              >
                <X className="w-4 h-4" />
              </button>

              {/* ── Loading state ── */}
              {loading && (
                <div className="flex flex-col items-center justify-center py-32 gap-4">
                  <div className="w-10 h-10 border-2 border-[#C5A880] border-t-transparent rounded-full animate-spin" />
                  <p className="text-xs text-gray-400 font-bold uppercase tracking-widest">Loading property...</p>
                </div>
              )}

              {/* ── Error state ── */}
              {error && !loading && (
                <div className="flex flex-col items-center justify-center py-32 gap-3">
                  <p className="text-sm font-bold text-red-500">{error}</p>
                  <button onClick={onClose} className="text-xs text-gray-400 underline">Close</button>
                </div>
              )}

              {/* ── Property content ── */}
              {property && !loading && (
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-0">

                  {/* ── LEFT: Main content ── */}
                  <div className="lg:col-span-2">
                    {/* Image carousel */}
                    <ImageCarousel images={property.images} />

                    <div className="p-6 space-y-6">
                      {/* Badges row */}
                      <div className="flex flex-wrap items-center gap-2">
                        <span className={`text-[9px] font-bold px-2.5 py-1 rounded-full uppercase tracking-wider ${
                          completionColor[property.completion_status] ?? 'bg-gray-100 text-gray-500'
                        }`}>
                          {completionLabel[property.completion_status] ?? property.completion_status}
                        </span>
                        {property.rera_verified && (
                          <span className="flex items-center gap-1 text-[9px] font-bold px-2.5 py-1 rounded-full bg-emerald-50 text-emerald-600 uppercase tracking-wider">
                            <ShieldCheck className="w-3 h-3" /> RERA Verified
                          </span>
                        )}
                        {property.is_premium && (
                          <span className="flex items-center gap-1 text-[9px] font-bold px-2.5 py-1 rounded-full bg-[#C5A880]/15 text-[#725b38] uppercase tracking-wider">
                            <Star className="w-3 h-3" /> Premium
                          </span>
                        )}
                        {property.payment_plan?.available && (
                          <span className="text-[9px] font-bold px-2.5 py-1 rounded-full bg-sky-50 text-sky-600 uppercase tracking-wider">
                            {property.payment_plan.down_payment_percent}% Down Payment
                          </span>
                        )}
                      </div>

                      {/* Title & price */}
                      <div>
                        <p className="text-[10px] font-bold text-[#C5A880] uppercase tracking-widest mb-1 flex items-center gap-1">
                          <MapPin className="w-3 h-3" /> {property.location.name}
                        </p>
                        <h2 className="font-serif text-2xl font-bold text-[#0d1c32] leading-tight mb-2">
                          {property.title}
                        </h2>
                        <div className="flex items-baseline gap-3">
                          <span className="font-serif text-3xl font-bold text-[#0d1c32]">
                            {property.price_formatted}
                          </span>
                          {property.price_per_sqft && (
                            <span className="text-xs text-gray-400 font-medium">
                              AED {property.price_per_sqft.toLocaleString('en-AE')} / sqft
                            </span>
                          )}
                        </div>
                      </div>

                      {/* Core specs grid */}
                      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                        {[
                          { icon: <BedDouble className="w-4 h-4" />, label: 'Bedrooms', value: property.bedrooms ?? 'Studio' },
                          { icon: <Bath className="w-4 h-4" />, label: 'Bathrooms', value: property.bathrooms ?? '—' },
                          { icon: <Maximize2 className="w-4 h-4" />, label: 'Area', value: property.area_sqft ? `${property.area_sqft.toLocaleString()} sqft` : '—' },
                          { icon: <Car className="w-4 h-4" />, label: 'Parking', value: property.parking_spots ?? 0 },
                        ].map((spec) => (
                          <div key={spec.label} className="bg-white border border-gray-100 rounded-xl p-3 text-center shadow-sm">
                            <div className="flex justify-center text-[#C5A880] mb-1.5">{spec.icon}</div>
                            <p className="font-bold text-[#0d1c32] text-sm">{spec.value}</p>
                            <p className="text-[9px] text-gray-400 uppercase tracking-wider mt-0.5">{spec.label}</p>
                          </div>
                        ))}
                      </div>

                      {/* Additional details */}
                      <div className="grid grid-cols-2 gap-2 text-xs">
                        {property.property_type && (
                          <div className="flex justify-between py-2 border-b border-gray-100">
                            <span className="text-gray-400">Type</span>
                            <span className="font-semibold text-[#0d1c32]">{property.property_type}</span>
                          </div>
                        )}
                        {property.floor_number && (
                          <div className="flex justify-between py-2 border-b border-gray-100">
                            <span className="text-gray-400">Floor</span>
                            <span className="font-semibold text-[#0d1c32]">{property.floor_number} / {property.total_floors}</span>
                          </div>
                        )}
                        {property.furnished && (
                          <div className="flex justify-between py-2 border-b border-gray-100">
                            <span className="text-gray-400">Furnished</span>
                            <span className="font-semibold text-[#0d1c32] capitalize">{property.furnished.replace('_', ' ')}</span>
                          </div>
                        )}
                        {property.listing_type && (
                          <div className="flex justify-between py-2 border-b border-gray-100">
                            <span className="text-gray-400">Listing</span>
                            <span className="font-semibold text-[#0d1c32] capitalize">{property.listing_type}</span>
                          </div>
                        )}
                      </div>

                      {/* Description */}
                      {property.description && (
                        <div>
                          <h3 className="text-xs font-bold text-gray-400 uppercase tracking-widest mb-3">About This Property</h3>
                          <p className="text-sm text-gray-600 leading-relaxed">{property.description}</p>
                        </div>
                      )}

                      {/* Amenities */}
                      {property.amenities.length > 0 && (
                        <div>
                          <h3 className="text-xs font-bold text-gray-400 uppercase tracking-widest mb-3">Amenities & Features</h3>
                          <div className="flex flex-wrap gap-2">
                            {property.amenities.map((id) => {
                              const a = AMENITY_MAP[Number(id)];
                              if (!a) return null;
                              return (
                                <span
                                  key={id}
                                  className="flex items-center gap-1.5 px-3 py-1.5 bg-white border border-gray-100 rounded-full text-[10px] font-semibold text-[#0d1c32] shadow-sm"
                                >
                                  <span className="text-[#C5A880]">{a.icon}</span>
                                  {a.label}
                                </span>
                              );
                            })}
                          </div>
                        </div>
                      )}

                      {/* Project info */}
                      {property.project && (
                        <div className="bg-[#0d1c32] rounded-xl p-4 text-white">
                          <p className="text-[9px] font-bold text-[#C5A880] uppercase tracking-widest mb-2">Part of Project</p>
                          <p className="font-serif font-bold text-lg mb-2">{property.project.name}</p>
                          {property.project.construction_progress > 0 && (
                            <div>
                              <div className="flex justify-between text-[10px] text-white/60 mb-1">
                                <span>Construction Progress</span>
                                <span className="font-bold text-white">{property.project.construction_progress}%</span>
                              </div>
                              <div className="h-1.5 bg-white/10 rounded-full overflow-hidden">
                                <motion.div
                                  initial={{ width: 0 }}
                                  animate={{ width: `${property.project.construction_progress}%` }}
                                  transition={{ duration: 1, delay: 0.3, ease: 'easeOut' }}
                                  className="h-full bg-[#C5A880] rounded-full"
                                />
                              </div>
                            </div>
                          )}
                        </div>
                      )}

                      {/* RERA permit */}
                      {property.rera_permit && (
                        <div className="flex items-center gap-2 text-[10px] text-gray-400">
                          <ShieldCheck className="w-3.5 h-3.5 text-emerald-500" />
                          RERA Permit: <span className="font-mono font-semibold text-[#0d1c32]">{property.rera_permit}</span>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* ── RIGHT: Sticky sidebar ── */}
                  <div className="lg:col-span-1 bg-[#f7f9fb] border-t lg:border-t-0 lg:border-l border-gray-100">
                    <div className="p-5 space-y-4 lg:sticky lg:top-0">
                      {/* Stats strip */}
                      <div className="flex items-center gap-4 text-[10px] text-gray-400 pb-4 border-b border-gray-100">
                        <span className="flex items-center gap-1"><Eye className="w-3 h-3" />{property.view_count} views</span>
                        <span className="flex items-center gap-1"><Heart className="w-3 h-3" />{property.favorite_count} saved</span>
                      </div>

                      {/* Creator card */}
                      <CreatorCard property={property} />

                      {/* Appointment widget */}
                      <AppointmentWidget propertyId={property.id} propertyTitle={property.title} />
                    </div>
                  </div>

                </div>
              )}
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
