"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Property } from "@/data/portalData";
import { getPropertyBySlug } from "@/services/propertyService";
import TourModal from "@/components/TourModal";
import AgentContactModal from "@/components/AgentContactModal";
import PropertyShareModal from "@/components/PropertyShareModal";
import { useAuth } from "@/context/AuthContext";
import { 
  Bed, 
  Bath, 
  Maximize2, 
  MapPin, 
  Heart, 
  Share2, 
  ShieldCheck, 
  CheckCircle2, 
  Eye, 
  Calculator, 
  Phone, 
  Mail, 
  ArrowLeft, 
  Play, 
  Layers, 
  Compass, 
  Sparkles,
  Download,
  Calendar,
  Lock,
  MessageSquare,
  Check
} from "lucide-react";

interface PropertyDetailClientProps {
  id: string;
  initialProperty?: Property | null;
}

export default function PropertyDetailClient({
  id,
  initialProperty,
}: PropertyDetailClientProps) {
  const router = useRouter();
  const { isLoggedIn, user, isPropertySaved, toggleSaveProperty } = useAuth();

  const [property, setProperty] = useState<Property | null>(initialProperty || null);
  const [isLoading, setIsLoading] = useState(!initialProperty);
  const [viewsCount, setViewsCount] = useState<number>(initialProperty?.viewsCount || 0);
  const [activeMediaTab, setActiveMediaTab] = useState<"gallery" | "360" | "floorplan">("gallery");
  const [activeImageIndex, setActiveImageIndex] = useState(0);
  const [activeFloorPlanIndex, setActiveFloorPlanIndex] = useState(0);
  const [isTourModalOpen, setIsTourModalOpen] = useState(false);
  const [isContactModalOpen, setIsContactModalOpen] = useState(false);
  const [isShareModalOpen, setIsShareModalOpen] = useState(false);
  const [copied, setCopied] = useState(false);

  const isFavorite = property?.id ? isPropertySaved(property.id) : false;

  const handleCopyLink = () => {
    if (!property) return;
    const url = typeof window !== "undefined"
      ? `${window.location.origin}/properties/${property.slug || property.id}`
      : `https://dreamhomes.lk/properties/${property.slug || property.id}`;

    if (navigator.clipboard) {
      navigator.clipboard.writeText(url);
    } else {
      const input = document.createElement("input");
      input.value = url;
      document.body.appendChild(input);
      input.select();
      document.execCommand("copy");
      document.body.removeChild(input);
    }
    setCopied(true);
    setTimeout(() => setCopied(false), 3000);
  };

  // Load property dynamically if not provided as SSR initialProperty
  useEffect(() => {
    let isMounted = true;
    if (!initialProperty) {
      setIsLoading(true);
      getPropertyBySlug(id).then((data) => {
        if (isMounted) {
          if (data) {
            setProperty(data);
            if (typeof data.viewsCount === "number") {
              setViewsCount(data.viewsCount);
            }
          } else {
            setProperty(null);
          }
          setIsLoading(false);
        }
      }).catch(() => {
        if (isMounted) {
          setProperty(null);
          setIsLoading(false);
        }
      });
    } else {
      setProperty(initialProperty);
      if (typeof initialProperty.viewsCount === "number") {
        setViewsCount(initialProperty.viewsCount);
      }
      setIsLoading(false);
    }
    return () => {
      isMounted = false;
    };
  }, [id, initialProperty]);

  // Mortgage Calculator Widget State
  const [downPaymentPercent, setDownPaymentPercent] = useState(30);
  const [interestRate, setInterestRate] = useState(12.5); // Sri Lanka bank loan rate
  const [loanTermYears, setLoanTermYears] = useState(15);

  const calculateMonthlyPayment = () => {
    if (!property) return 0;
    const principalLKR = (property.priceLKR * 1000000) * (1 - downPaymentPercent / 100);
    const monthlyRate = (interestRate / 100) / 12;
    const numPayments = loanTermYears * 12;
    if (monthlyRate === 0) return principalLKR / numPayments;
    const monthlyPayment = (principalLKR * monthlyRate * Math.pow(1 + monthlyRate, numPayments)) / (Math.pow(1 + monthlyRate, numPayments) - 1);
    return Math.round(monthlyPayment);
  };

  const monthlyPaymentLKR = calculateMonthlyPayment();

  if (isLoading) {
    return (
      <div className="min-h-screen py-12 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 animate-pulse space-y-8">
        <div className="h-6 bg-slate-200 rounded w-1/4" />
        <div className="aspect-[21/9] bg-slate-200 rounded-3xl" />
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2 space-y-4">
            <div className="h-10 bg-slate-200 rounded w-3/4" />
            <div className="h-6 bg-slate-200 rounded w-1/2" />
            <div className="h-40 bg-slate-200 rounded" />
          </div>
          <div className="h-80 bg-slate-200 rounded-3xl" />
        </div>
      </div>
    );
  }

  if (!property) {
    return (
      <div className="min-h-[70vh] flex flex-col items-center justify-center p-6 text-center">
        <h2 className="text-3xl font-extrabold text-slate-900 mb-2 font-display-lg">Property Not Found</h2>
        <p className="text-slate-500 mb-6 max-w-md">
          The requested luxury listing may have been sold or is currently private.
        </p>
        <Link
          href="/properties"
          className="bg-[#4223de] text-white px-6 py-3 rounded-full font-bold text-xs shadow-lg shadow-[#4223de]/30 hover:bg-[#3912d8] transition-all"
        >
          Explore Available Properties
        </Link>
      </div>
    );
  }

  const galleryList = (property.galleryImages && property.galleryImages.length > 0)
    ? property.galleryImages
    : [property.heroImage];

  return (
    <div className="min-h-screen py-8 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      
      {/* Top Breadcrumb & Share */}
      <div className="flex items-center justify-between mb-6">
        <Link
          href="/properties"
          className="inline-flex items-center gap-2 text-xs font-bold text-slate-600 hover:text-[#4223de] transition-colors"
        >
          <ArrowLeft className="w-4 h-4" />
          <span>Back to Property Explorer</span>
        </Link>

        <div className="flex items-center gap-2">
          {/* Wishlist Heart Button */}
          <button
            onClick={() => toggleSaveProperty(property.id, property.title)}
            className={`p-2.5 rounded-full border transition-all cursor-pointer ${
              isFavorite
                ? "bg-rose-500 text-white border-rose-500 shadow-md shadow-rose-500/30 scale-105"
                : "bg-white text-slate-700 border-slate-200 hover:bg-slate-50 hover:text-rose-500"
            }`}
            title={isFavorite ? "Remove from Saved Properties" : "Save Property to Wishlist"}
            aria-label={isFavorite ? "Remove from Saved Properties" : "Save Property"}
          >
            <Heart className={`w-4 h-4 ${isFavorite ? "fill-current" : ""}`} />
          </button>

          {/* 1-Click Copy & Share Button */}
          <button
            onClick={handleCopyLink}
            className={`p-2.5 sm:px-4 rounded-full border transition-all cursor-pointer flex items-center gap-1.5 text-xs font-bold shadow-xs ${
              copied
                ? "bg-emerald-600 border-emerald-600 text-white shadow-emerald-600/30 scale-105"
                : "bg-white border-slate-200 text-slate-700 hover:text-[#4223de] hover:border-[#4223de] hover:bg-slate-50"
            }`}
            title="Copy Property Link to share on WhatsApp or Facebook"
          >
            {copied ? (
              <>
                <Check className="w-4 h-4 text-white" />
                <span className="text-white">Link Copied!</span>
              </>
            ) : (
              <>
                <Share2 className="w-4 h-4 text-[#4223de]" />
                <span className="hidden sm:inline">Share Link</span>
              </>
            )}
          </button>
        </div>
      </div>

      {/* ------------------------------------------------------------- */}
      {/* IMMERSIVE MEDIA SHOWCASE VIEWER (Gallery, 360 VR, Floor Plan) */}
      {/* ------------------------------------------------------------- */}
      <div className="bg-slate-900 rounded-[2.5rem] overflow-hidden shadow-2xl mb-10 border border-slate-800">
        
        {/* Media Switcher Tab Header */}
        <div className="flex items-center justify-between p-4 sm:px-8 border-b border-white/10 bg-slate-950/60 backdrop-blur-md">
          <div className="flex items-center gap-2">
            <button
              onClick={() => setActiveMediaTab("gallery")}
              className={`px-4 py-2 rounded-full text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${
                activeMediaTab === "gallery"
                  ? "bg-[#4223de] text-white shadow-lg shadow-[#4223de]/40"
                  : "text-slate-300 hover:text-white hover:bg-white/10"
              }`}
            >
              <Layers className="w-3.5 h-3.5" />
              <span>HD Gallery ({galleryList.length})</span>
            </button>

            <button
              onClick={() => setActiveMediaTab("360")}
              className={`px-4 py-2 rounded-full text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${
                activeMediaTab === "360"
                  ? "bg-[#4223de] text-white shadow-lg shadow-[#4223de]/40"
                  : "text-slate-300 hover:text-white hover:bg-white/10"
              }`}
            >
              <Eye className="w-3.5 h-3.5" />
              <span>360° Virtual Tour</span>
            </button>

            <button
              onClick={() => setActiveMediaTab("floorplan")}
              className={`px-4 py-2 rounded-full text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${
                activeMediaTab === "floorplan"
                  ? "bg-[#4223de] text-white shadow-lg shadow-[#4223de]/40"
                  : "text-slate-300 hover:text-white hover:bg-white/10"
              }`}
            >
              <Compass className="w-3.5 h-3.5" />
              <span>2D/3D Floor Plans</span>
            </button>
          </div>

          <div className="hidden sm:flex items-center gap-2 text-xs text-slate-300 font-semibold bg-white/5 px-3.5 py-1.5 rounded-full border border-white/10">
            <Eye className="w-3.5 h-3.5 text-[#c5c0ff]" />
            <span>{viewsCount.toLocaleString()} Verified Client Views</span>
          </div>
        </div>

        {/* Media Content Display Area */}
        <div className="relative aspect-[16/10] sm:aspect-[21/9] w-full bg-black flex items-center justify-center overflow-hidden">
          
          {/* 1. HD Gallery Mode */}
          {activeMediaTab === "gallery" && (
            <div className="relative w-full h-full">
              <img
                src={galleryList[activeImageIndex] || property.heroImage}
                alt={property.title}
                className="w-full h-full object-cover"
              />
              <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-black/20 pointer-events-none" />

              {/* Photo Label Pill */}
              <div className="absolute top-4 left-4 sm:top-6 sm:left-6 z-10">
                <span className="px-3 py-1 rounded-full text-xs font-bold bg-black/60 backdrop-blur-md text-white border border-white/20">
                  {property.labeledImages?.[activeImageIndex]?.label || `Photo ${activeImageIndex + 1} of ${galleryList.length}`}
                </span>
              </div>

              {/* Floating Headline inside Viewer */}
              <div className="absolute bottom-4 left-4 right-4 sm:bottom-6 sm:left-8 sm:right-8 flex flex-col sm:flex-row sm:items-end justify-between gap-4 pointer-events-none">
                <div className="space-y-1 max-w-2xl">
                  <div className="flex items-center gap-2">
                    <span className="px-3 py-1 rounded-full text-[11px] font-extrabold bg-[#4223de] text-white">
                      {property.category}
                    </span>
                    <span className="px-3 py-1 rounded-full text-[11px] font-extrabold bg-emerald-600/90 text-white flex items-center gap-1">
                      <ShieldCheck className="w-3 h-3" /> Verified Title
                    </span>
                  </div>
                  <h1 className="text-2xl sm:text-4xl font-extrabold text-white font-display-lg leading-tight drop-shadow-md">
                    {property.title}
                  </h1>
                  <p className="text-xs sm:text-sm text-slate-300 flex items-center gap-1.5 font-medium drop-shadow">
                    <MapPin className="w-4 h-4 text-[#c5c0ff] shrink-0" />
                    <span>{property.location}</span>
                  </p>
                </div>

                <div className="text-left sm:text-right shrink-0">
                  <span className="block text-2xl sm:text-3xl font-extrabold text-white font-display-lg leading-none drop-shadow">
                    {property.priceDisplayLKR}
                  </span>
                  <span className="text-xs font-bold text-[#c5c0ff] drop-shadow">
                    Approx. ${property.priceUSD.toLocaleString()} USD
                  </span>
                </div>
              </div>
            </div>
          )}

          {/* 2. 360 VR Mode */}
          {activeMediaTab === "360" && (
            <div className="relative w-full h-full flex flex-col items-center justify-center p-6 text-center bg-slate-950">
              <img
                src={property.panoramas[0]?.url || property.heroImage}
                alt="360 Panorama"
                className="absolute inset-0 w-full h-full object-cover opacity-35 blur-xs"
              />
              <div className="relative z-10 max-w-md space-y-4">
                <div className="w-16 h-16 rounded-full bg-[#4223de] text-white flex items-center justify-center mx-auto shadow-xl shadow-[#4223de]/50 animate-pulse">
                  <Eye className="w-8 h-8" />
                </div>
                <div className="space-y-1">
                  <h3 className="text-xl sm:text-2xl font-extrabold text-white font-display-lg">
                    Interactive 360° VR Spatial Tour
                  </h3>
                  <p className="text-xs text-slate-300">
                    Step inside {property.title} and explore high-definition 360 panoramic views.
                  </p>
                </div>
                <button
                  onClick={() => setIsTourModalOpen(true)}
                  className="bg-[#4223de] hover:bg-[#3912d8] text-white text-xs font-extrabold px-6 py-3.5 rounded-full shadow-lg shadow-[#4223de]/40 transition-all flex items-center gap-2 mx-auto cursor-pointer"
                >
                  <Play className="w-4 h-4 fill-current" />
                  <span>Launch Fullscreen 360 Tour</span>
                </button>
              </div>
            </div>
          )}

          {/* 3. Floor Plan Mode */}
          {activeMediaTab === "floorplan" && (
            <div className="relative w-full h-full flex items-center justify-center p-4 sm:p-8 bg-slate-950">
              <div className="max-w-4xl w-full h-full flex flex-col items-center justify-center relative">
                <img
                  src={property.floorPlans[activeFloorPlanIndex]?.imageUrl || property.heroImage}
                  alt={property.floorPlans[activeFloorPlanIndex]?.level || "Floor Plan"}
                  className="max-h-[80%] max-w-full object-contain rounded-2xl border border-white/10"
                />
                
                {/* Level switcher pills */}
                <div className="absolute bottom-2 sm:bottom-4 flex items-center gap-2 bg-black/70 backdrop-blur-md p-1.5 rounded-full border border-white/20">
                  {property.floorPlans.map((fp, idx) => (
                    <button
                      key={fp.level}
                      onClick={() => setActiveFloorPlanIndex(idx)}
                      className={`px-4 py-1.5 rounded-full text-xs font-bold transition-all ${
                        activeFloorPlanIndex === idx
                          ? "bg-[#4223de] text-white"
                          : "text-slate-300 hover:text-white"
                      }`}
                    >
                      {fp.level} ({fp.sqft.toLocaleString()} SqFt)
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

        </div>

        {/* Thumbnail Filmstrip Bar (For Gallery Mode) */}
        {activeMediaTab === "gallery" && galleryList.length > 1 && (
          <div className="p-4 bg-slate-950/80 border-t border-white/10 flex items-center gap-3 overflow-x-auto scrollbar-thin">
            {galleryList.map((img, index) => (
              <button
                key={index}
                onClick={() => setActiveImageIndex(index)}
                className={`relative shrink-0 w-20 h-14 sm:w-28 sm:h-18 rounded-xl overflow-hidden border-2 transition-all cursor-pointer ${
                  activeImageIndex === index
                    ? "border-[#4223de] scale-105 shadow-md shadow-[#4223de]/40"
                    : "border-transparent opacity-60 hover:opacity-100"
                }`}
              >
                <img src={img} alt={`Thumb ${index + 1}`} className="w-full h-full object-cover" />
              </button>
            ))}
          </div>
        )}

      </div>

      {/* ------------------------------------------------------------- */}
      {/* 2-COLUMN MAIN CONTENT (Specs, Highlights, Calculator vs Sidebar) */}
      {/* ------------------------------------------------------------- */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">

        {/* LEFT COLUMN: SPECS & BLUEPRINT SPECS (8 Cols) */}
        <div className="lg:col-span-8 space-y-10">
          
          {/* Key Specs Pill Matrix */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 p-6 bg-white rounded-3xl border border-slate-100 shadow-[0_4px_25px_rgba(0,0,0,0.03)]">
            <div className="flex items-center gap-3.5 p-3 rounded-2xl bg-slate-50 border border-slate-100">
              <div className="p-3 rounded-xl bg-[#4223de]/10 text-[#4223de]">
                <Bed className="w-5 h-5" />
              </div>
              <div>
                <span className="text-[11px] font-bold text-slate-400 uppercase tracking-wider block">Bedrooms</span>
                <span className="text-base font-extrabold text-slate-900">{property.bedrooms} Ensuite</span>
              </div>
            </div>

            <div className="flex items-center gap-3.5 p-3 rounded-2xl bg-slate-50 border border-slate-100">
              <div className="p-3 rounded-xl bg-[#4223de]/10 text-[#4223de]">
                <Bath className="w-5 h-5" />
              </div>
              <div>
                <span className="text-[11px] font-bold text-slate-400 uppercase tracking-wider block">Bathrooms</span>
                <span className="text-base font-extrabold text-slate-900">{property.bathrooms} Luxury</span>
              </div>
            </div>

            <div className="flex items-center gap-3.5 p-3 rounded-2xl bg-slate-50 border border-slate-100">
              <div className="p-3 rounded-xl bg-[#4223de]/10 text-[#4223de]">
                <Maximize2 className="w-5 h-5" />
              </div>
              <div>
                <span className="text-[11px] font-bold text-slate-400 uppercase tracking-wider block">Total Area</span>
                <span className="text-base font-extrabold text-slate-900">{Number(property.sqft).toLocaleString()} SqFt</span>
              </div>
            </div>

            <div className="flex items-center gap-3.5 p-3 rounded-2xl bg-slate-50 border border-slate-100">
              <div className="p-3 rounded-xl bg-[#4223de]/10 text-[#4223de]">
                <MapPin className="w-5 h-5" />
              </div>
              <div>
                <span className="text-[11px] font-bold text-slate-400 uppercase tracking-wider block">Land Extent</span>
                <span className="text-base font-extrabold text-slate-900">{property.perches ? `${property.perches} Perches` : "Prime Plot"}</span>
              </div>
            </div>
          </div>

          {/* Property Overview Narrative */}
          <div className="space-y-4 bg-white p-8 rounded-3xl border border-slate-100 shadow-[0_4px_25px_rgba(0,0,0,0.03)]">
            <h3 className="text-xl sm:text-2xl font-extrabold text-slate-900 font-display-lg">
              Property Architectural Narrative
            </h3>
            <p className="text-sm text-slate-600 leading-relaxed font-body whitespace-pre-line">
              {property.description || "Designed to the highest architectural standards, this residence seamlessly blends indoor and outdoor luxury living."}
            </p>
          </div>

          {/* Architectural Highlights & Amenities */}
          <div className="space-y-6 bg-white p-8 rounded-3xl border border-slate-100 shadow-[0_4px_25px_rgba(0,0,0,0.03)]">
            <h3 className="text-xl sm:text-2xl font-extrabold text-slate-900 font-display-lg">
              Signature Amenities &amp; Features
            </h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3.5">
              {property.amenities.map((amenity, index) => (
                <div
                  key={index}
                  className="flex items-center gap-3 p-3.5 rounded-2xl bg-slate-50 border border-slate-100 text-xs font-bold text-slate-800"
                >
                  <div className="w-6 h-6 rounded-full bg-emerald-100 text-emerald-700 flex items-center justify-center shrink-0">
                    <CheckCircle2 className="w-4 h-4" />
                  </div>
                  <span>{amenity}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Mortgage & Loan Calculator Card */}
          <div className="p-8 rounded-3xl bg-[#edf1f8] border border-slate-200/80 space-y-6">
            <div className="flex items-center justify-between">
              <div className="space-y-1">
                <div className="flex items-center gap-2 text-[#4223de] text-xs font-bold">
                  <Calculator className="w-4 h-4" />
                  <span>Financial Estimator</span>
                </div>
                <h3 className="text-xl font-extrabold text-slate-900 font-display-lg">
                  Mortgage &amp; Monthly Payment Calculator
                </h3>
              </div>
              <div className="text-right">
                <span className="text-xs text-slate-500 font-semibold block">Estimated Monthly</span>
                <span className="text-xl sm:text-2xl font-extrabold text-[#4223de] font-mono">
                  LKR {monthlyPaymentLKR.toLocaleString()} / mo
                </span>
              </div>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-3 gap-6 pt-2">
              <div className="space-y-2">
                <div className="flex justify-between text-xs font-bold text-slate-700">
                  <span>Down Payment</span>
                  <span className="text-[#4223de]">{downPaymentPercent}%</span>
                </div>
                <input
                  type="range"
                  min={10}
                  max={60}
                  step={5}
                  value={downPaymentPercent}
                  onChange={(e) => setDownPaymentPercent(Number(e.target.value))}
                  className="w-full accent-[#4223de]"
                />
              </div>

              <div className="space-y-2">
                <div className="flex justify-between text-xs font-bold text-slate-700">
                  <span>Bank Interest Rate</span>
                  <span className="text-[#4223de]">{interestRate}%</span>
                </div>
                <input
                  type="range"
                  min={8}
                  max={20}
                  step={0.5}
                  value={interestRate}
                  onChange={(e) => setInterestRate(Number(e.target.value))}
                  className="w-full accent-[#4223de]"
                />
              </div>

              <div className="space-y-2">
                <div className="flex justify-between text-xs font-bold text-slate-700">
                  <span>Loan Term</span>
                  <span className="text-[#4223de]">{loanTermYears} Years</span>
                </div>
                <input
                  type="range"
                  min={5}
                  max={30}
                  step={5}
                  value={loanTermYears}
                  onChange={(e) => setLoanTermYears(Number(e.target.value))}
                  className="w-full accent-[#4223de]"
                />
              </div>
            </div>
          </div>

        </div>

        {/* RIGHT COLUMN: STICKY CONTACT & VIEWING SIDEBAR (4 Cols) */}
        <aside className="lg:col-span-4">
          <div className="sticky top-24 bg-white rounded-3xl p-6 sm:p-8 border border-slate-100 shadow-[0_10px_40px_rgba(0,0,0,0.06)] space-y-6">
            
            {/* Price Banner */}
            <div className="pb-4 border-b border-slate-100 space-y-1">
              <span className="text-xs font-bold text-slate-400 uppercase tracking-wider block">Official Asking Price</span>
              <span className="text-2xl sm:text-3xl font-extrabold text-slate-900 font-display-lg block">
                {property.priceDisplayLKR}
              </span>
              <span className="text-xs font-semibold text-[#4223de]">
                Approx. ${property.priceUSD.toLocaleString()} USD
              </span>
            </div>

            {/* Schedule Viewing CTA Button */}
            {isLoggedIn ? (
              <button
                onClick={() => setIsTourModalOpen(true)}
                className="w-full bg-[#4223de] hover:bg-[#3912d8] text-white font-extrabold text-xs uppercase tracking-wider py-4 rounded-full shadow-lg shadow-[#4223de]/30 transition-all flex items-center justify-center gap-2 cursor-pointer"
              >
                <Calendar className="w-4 h-4" />
                <span>Schedule Property Tour</span>
              </button>
            ) : (
              <Link
                href={`/auth?redirect=/properties/${property.slug}&mode=signup&reason=viewing`}
                className="w-full bg-[#4223de] hover:bg-[#3912d8] text-white font-extrabold text-xs uppercase tracking-wider py-4 rounded-full shadow-lg shadow-[#4223de]/30 transition-all flex items-center justify-center gap-2 text-center"
              >
                <Lock className="w-4 h-4" />
                <span>Sign Up to Schedule Viewing</span>
              </Link>
            )}

            {/* Assigned Executive Agent Profile */}
            <div className="p-4 bg-slate-50 rounded-2xl border border-slate-100 space-y-3">
              <Link href={`/agents/${property.agent.slug}`} className="flex items-center gap-3 group/agent">
                <img
                  src={property.agent.image}
                  alt={property.agent.name}
                  className="w-14 h-14 rounded-full object-cover border-2 border-white shadow-md group-hover/agent:scale-105 transition-transform"
                />
                <div>
                  <h5 className="font-bold text-slate-900 text-sm font-headline-md group-hover/agent:text-[#4223de] transition-colors">
                    {property.agent.name}
                  </h5>
                  <p className="text-[11px] text-[#4223de] font-semibold">{property.agent.role}</p>
                  <p className="text-[10px] text-slate-400">{property.agent.division || "DreamHomes Realty"}</p>
                </div>
              </Link>

              <div className="pt-2 space-y-2">
                <button
                  type="button"
                  onClick={() => setIsContactModalOpen(true)}
                  className="w-full py-3 px-4 rounded-xl bg-[#4223de] hover:bg-[#381dd0] text-white text-xs font-extrabold flex items-center justify-center gap-2 transition-all shadow-md shadow-[#4223de]/20 cursor-pointer"
                >
                  <MessageSquare className="w-3.5 h-3.5" />
                  <span>Contact Agent Regarding Property</span>
                </button>

                <button
                  type="button"
                  onClick={handleCopyLink}
                  className={`w-full py-3 px-4 rounded-xl border text-xs font-bold flex items-center justify-center gap-2 transition-all cursor-pointer shadow-xs ${
                    copied
                      ? "bg-emerald-600 border-emerald-600 text-white shadow-emerald-600/30 scale-[1.02]"
                      : "border-slate-200 hover:border-[#4223de] text-slate-700 hover:text-[#4223de] bg-white hover:bg-slate-50"
                  }`}
                >
                  {copied ? (
                    <>
                      <Check className="w-4 h-4 text-white" />
                      <span className="text-white">Link Copied! Paste on WhatsApp / FB</span>
                    </>
                  ) : (
                    <>
                      <Share2 className="w-3.5 h-3.5 text-[#4223de]" />
                      <span>Copy Share Link (WhatsApp &amp; FB)</span>
                    </>
                  )}
                </button>
              </div>
            </div>

            {/* Neighborhood Ratings */}
            <div className="space-y-2 pt-2 border-t border-slate-100">
              <span className="text-xs font-bold text-slate-700 uppercase tracking-wider block">
                Neighborhood Scores
              </span>
              <div className="space-y-1.5 text-xs">
                <div className="flex justify-between font-semibold text-slate-600">
                  <span>Lifestyle &amp; Coast:</span>
                  <span className="text-[#4223de] font-bold">{property.neighborhoodScores.lifestyle}/100</span>
                </div>
                <div className="flex justify-between font-semibold text-slate-600">
                  <span>Walkability &amp; Cafes:</span>
                  <span className="text-[#4223de] font-bold">{property.neighborhoodScores.walkability}/100</span>
                </div>
                <div className="flex justify-between font-semibold text-slate-600">
                  <span>Highway / Transit Access:</span>
                  <span className="text-[#4223de] font-bold">{property.neighborhoodScores.transit}/100</span>
                </div>
              </div>
            </div>

          </div>
        </aside>

      </div>

      {/* ------------------------------------------------------------- */}
      {/* POPUP MODALS */}
      {/* ------------------------------------------------------------- */}

      {/* Virtual Tour Modal */}
      <TourModal
        isOpen={isTourModalOpen}
        onClose={() => setIsTourModalOpen(false)}
        property={property}
      />

      {/* Agent Contact Modal */}
      <AgentContactModal
        isOpen={isContactModalOpen}
        onClose={() => setIsContactModalOpen(false)}
        agent={property.agent}
        propertyTitle={property.title}
        propertyId={property.id}
      />

      {/* Floating Copied Toast Banner */}
      {copied && (
        <div className="fixed bottom-6 right-6 z-50 bg-slate-900 text-white px-5 py-3.5 rounded-2xl shadow-2xl border border-slate-700/80 flex items-center gap-3 animate-in slide-in-from-bottom-5 duration-200">
          <div className="w-8 h-8 rounded-full bg-emerald-500 text-white flex items-center justify-center shrink-0 shadow-md">
            <Check className="w-4 h-4" />
          </div>
          <div className="text-xs">
            <p className="font-extrabold text-white">Property Link Copied to Clipboard!</p>
            <p className="text-[11px] text-slate-300">Paste directly in WhatsApp or Facebook to show property preview.</p>
          </div>
        </div>
      )}

    </div>
  );
}
