"use client";

import React, { useState, useEffect, useMemo } from "react";
import Link from "next/link";
import { useAuth } from "@/context/AuthContext";
import {
  getSavedProperties,
  removeSavedProperty,
  updateSavedPropertyNotes,
  SavedPropertyItem
} from "@/services/savedPropertyService";
import { resolveImageUrl } from "@/services/propertyService";
import AgentContactModal from "@/components/AgentContactModal";
import PropertyShareModal from "@/components/PropertyShareModal";
import {
  Heart,
  Search,
  SlidersHorizontal,
  Building2,
  MapPin,
  Bed,
  Bath,
  Maximize2,
  Trash2,
  ArrowUpRight,
  Phone,
  MessageSquare,
  Sparkles,
  ShieldCheck,
  Calendar,
  Lock,
  ArrowRight,
  Edit3,
  Check,
  X,
  Share2,
  Compass,
  FileText
} from "lucide-react";

export default function SavedPropertiesPage() {
  const { user, isLoggedIn, openAuthModal, toggleSaveProperty, savedPropertyIds } = useAuth();
  
  const [savedItems, setSavedItems] = useState<SavedPropertyItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedCategory, setSelectedCategory] = useState<string>("All");
  const [sortBy, setSortBy] = useState<"recent" | "price_low" | "price_high">("recent");

  // Notes Modal state
  const [editingNotesItem, setEditingNotesItem] = useState<SavedPropertyItem | null>(null);
  const [notesText, setNotesText] = useState("");
  const [isSavingNotes, setIsSavingNotes] = useState(false);

  // Modals & Feedback state
  const [contactProperty, setContactProperty] = useState<any | null>(null);
  const [copiedId, setCopiedId] = useState<number | string | null>(null);

  const handleCopyLink = (p: any) => {
    const url = typeof window !== "undefined"
      ? `${window.location.origin}/properties/${p.slug || p.id}`
      : `https://dreamhomes.lk/properties/${p.slug || p.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);
    }
    setCopiedId(p.id);
    setTimeout(() => setCopiedId(null), 2500);
  };

  // Load saved properties
  const loadData = async () => {
    if (!isLoggedIn) {
      setIsLoading(false);
      return;
    }
    setIsLoading(true);
    try {
      const data = await getSavedProperties();
      setSavedItems(data);
    } catch (err) {
      console.error("Failed to load saved properties", err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [isLoggedIn, savedPropertyIds.length]);

  // Handle Remove
  const handleRemove = async (propertyId: number, title: string) => {
    setSavedItems((prev) => prev.filter((item) => item.property.id !== propertyId));
    await toggleSaveProperty(propertyId, title);
  };

  // Handle Save Notes
  const handleSaveNotes = async () => {
    if (!editingNotesItem) return;
    setIsSavingNotes(true);
    try {
      await updateSavedPropertyNotes(editingNotesItem.property.id, notesText);
      setSavedItems((prev) =>
        prev.map((item) =>
          item.property.id === editingNotesItem.property.id
            ? { ...item, notes: notesText }
            : item
        )
      );
      setEditingNotesItem(null);
    } catch (err) {
      console.error("Failed to update notes", err);
    } finally {
      setIsSavingNotes(false);
    }
  };

  // Filtered & Sorted items
  const categories = useMemo(() => {
    const cats = new Set<string>();
    savedItems.forEach((item) => {
      if (item.property.category?.name) {
        cats.add(item.property.category.name);
      }
    });
    return ["All", ...Array.from(cats)];
  }, [savedItems]);

  const filteredItems = useMemo(() => {
    return savedItems
      .filter((item) => {
        const matchesCat =
          selectedCategory === "All" ||
          item.property.category?.name === selectedCategory;

        const q = searchQuery.toLowerCase();
        const matchesSearch =
          !q ||
          item.property.title.toLowerCase().includes(q) ||
          (item.property.address && item.property.address.toLowerCase().includes(q)) ||
          (item.property.location?.name && item.property.location.name.toLowerCase().includes(q)) ||
          (item.notes && item.notes.toLowerCase().includes(q));

        return matchesCat && matchesSearch;
      })
      .sort((a, b) => {
        if (sortBy === "price_low") {
          return Number(a.property.price || 0) - Number(b.property.price || 0);
        }
        if (sortBy === "price_high") {
          return Number(b.property.price || 0) - Number(a.property.price || 0);
        }
        return new Date(b.saved_at).getTime() - new Date(a.saved_at).getTime();
      });
  }, [savedItems, selectedCategory, searchQuery, sortBy]);

  const formatPriceLKR = (price: number | string) => {
    const num = Number(price);
    if (!num) return "Price on Request";
    if (num >= 1000000) {
      return `LKR ${(num / 1000000).toFixed(1)} Million`;
    }
    if (num >= 1 && num < 100000) {
      return `LKR ${num} Million`;
    }
    return `LKR ${num.toLocaleString()}`;
  };

  return (
    <div className="min-h-screen py-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-8 text-white">

      {/* ------------------------------------------------------------- */}
      {/* HEADER & HERO BAR */}
      {/* ------------------------------------------------------------- */}
      <div className="bg-[#0e0e10] rounded-3xl p-6 sm:p-10 border border-[#FFE259]/30 shadow-2xl flex flex-col md:flex-row md:items-center justify-between gap-6 relative overflow-hidden">
        <div className="space-y-3 relative z-10">
          <div className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full bg-[#0A0A0A] border border-[#FFA726]/40 text-[#FFE259] text-xs font-bold shadow-sm">
            <Heart className="w-3.5 h-3.5 fill-[#FFE259] text-[#FFE259]" />
            <span>Customer Wishlist &amp; Portfolio</span>
          </div>
          <h1 className="text-3xl sm:text-4xl md:text-5xl font-extrabold text-white font-display-lg tracking-tight">
            My Saved <span className="text-[#FFE259]">Properties</span>
          </h1>
          <p className="text-xs sm:text-sm text-slate-400 max-w-xl leading-relaxed">
            Track your shortlisted luxury residences, download floor plans, add personal inspection notes, and connect directly with assigned sales advisors.
          </p>
        </div>

        <div className="flex items-center gap-3 relative z-10 shrink-0">
          <div className="bg-[#18181b] px-5 py-3.5 rounded-2xl border border-zinc-800 text-center">
            <span className="block text-2xl font-extrabold text-[#FFE259] font-mono leading-none">
              {savedItems.length}
            </span>
            <span className="text-[11px] font-bold text-slate-400 uppercase tracking-wider">
              Saved Items
            </span>
          </div>

          <Link
            href="/properties"
            className="bg-[#059669] hover:bg-[#047857] text-white px-5 py-3.5 rounded-2xl text-xs font-bold shadow-lg shadow-[#059669]/25 transition-all flex items-center gap-2 cursor-pointer"
          >
            <Compass className="w-4 h-4 text-white" />
            <span>Explore Properties</span>
          </Link>
        </div>

        {/* Ambient Glow */}
        <div className="absolute -right-20 -bottom-20 w-80 h-80 bg-[#FFE259]/10 rounded-full blur-3xl pointer-events-none" />
      </div>

      {/* ------------------------------------------------------------- */}
      {/* UNAUTHENTICATED STATE PROMPT */}
      {/* ------------------------------------------------------------- */}
      {!isLoggedIn && (
        <div className="bg-[#0e0e10] rounded-3xl p-10 sm:p-14 border border-[#FFE259]/30 text-center space-y-5 shadow-2xl max-w-2xl mx-auto my-12">
          <div className="w-16 h-16 rounded-2xl bg-[#18181b] text-[#FFE259] border border-[#FFE259]/40 flex items-center justify-center mx-auto shadow-inner">
            <Lock className="w-8 h-8" />
          </div>
          <div className="space-y-2">
            <h2 className="text-2xl font-extrabold text-white font-display-lg">
              Sign In to Access Your Saved Wishlist
            </h2>
            <p className="text-xs sm:text-sm text-slate-400 max-w-md mx-auto">
              Sign in with your DreamHomes customer account to view your saved villas, inspection notes, and schedule exclusive viewings.
            </p>
          </div>
          <div className="pt-3 flex items-center justify-center gap-3">
            <button
              onClick={() => openAuthModal("Sign in to view your saved properties.")}
              className="bg-[#059669] hover:bg-[#047857] text-white font-extrabold text-xs px-6 py-3.5 rounded-xl shadow-lg shadow-[#059669]/25 transition-all flex items-center gap-2 cursor-pointer"
            >
              <span>Sign In to Account</span>
              <ArrowRight className="w-4 h-4" />
            </button>
            <Link
              href="/auth?mode=signup&redirect=/saved-properties"
              className="bg-[#18181b] border border-zinc-700 hover:border-[#FFE259] text-slate-300 hover:text-white font-bold text-xs px-5 py-3.5 rounded-xl transition-all"
            >
              Create Free Account
            </Link>
          </div>
        </div>
      )}

      {/* ------------------------------------------------------------- */}
      {/* LOGGED IN: CONTROLS & SEARCH BAR */}
      {/* ------------------------------------------------------------- */}
      {isLoggedIn && (
        <div className="bg-[#0e0e10] rounded-2xl p-4 border border-zinc-800 shadow-lg space-y-4">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            
            {/* Search Bar */}
            <div className="relative flex-1 max-w-md">
              <Search className="w-4 h-4 text-[#FFE259] absolute left-3.5 top-1/2 -translate-y-1/2" />
              <input
                type="text"
                placeholder="Filter saved by title, location, notes..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full bg-[#18181b] border border-zinc-700 focus:border-[#FFE259] text-white placeholder-slate-400 rounded-xl pl-10 pr-4 py-2.5 text-xs outline-none transition-all font-medium"
              />
              {searchQuery && (
                <button
                  onClick={() => setSearchQuery("")}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white"
                >
                  <X className="w-3.5 h-3.5" />
                </button>
              )}
            </div>

            {/* Sort Dropdown */}
            <div className="flex items-center gap-2">
              <span className="text-xs font-semibold text-slate-400 whitespace-nowrap">Sort By:</span>
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value as any)}
                className="bg-[#18181b] border border-zinc-700 text-white rounded-xl px-3 py-2 text-xs font-bold outline-none focus:border-[#FFE259] cursor-pointer"
              >
                <option value="recent">Recently Saved</option>
                <option value="price_low">Price: Low to High</option>
                <option value="price_high">Price: High to Low</option>
              </select>
            </div>

          </div>

          {/* Category Filter Pills */}
          {categories.length > 1 && (
            <div className="flex items-center gap-1.5 overflow-x-auto pb-1 pt-1 scrollbar-none border-t border-zinc-800/80">
              {categories.map((cat) => (
                <button
                  key={cat}
                  onClick={() => setSelectedCategory(cat)}
                  className={`px-3.5 py-1.5 rounded-xl text-xs font-bold whitespace-nowrap transition-all cursor-pointer ${
                    selectedCategory === cat
                      ? "bg-[#FFE259] text-black font-extrabold shadow-md border border-[#FFE259] scale-[1.02]"
                      : "bg-[#18181b] text-slate-300 border border-zinc-800 hover:text-white hover:border-[#FFE259]/50 hover:bg-[#202024]"
                  }`}
                >
                  {cat}
                </button>
              ))}
            </div>
          )}
        </div>
      )}

      {/* ------------------------------------------------------------- */}
      {/* PROPERTY LISTING GRID */}
      {/* ------------------------------------------------------------- */}
      {isLoggedIn && (
        <div>
          {isLoading ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 py-8">
              {[1, 2, 3].map((n) => (
                <div key={n} className="bg-[#0e0e10] rounded-3xl border border-zinc-800 overflow-hidden animate-pulse">
                  <div className="h-48 bg-zinc-800" />
                  <div className="p-6 space-y-3">
                    <div className="h-4 bg-zinc-800 rounded w-1/3" />
                    <div className="h-6 bg-zinc-800 rounded w-3/4" />
                    <div className="h-4 bg-zinc-800 rounded w-1/2" />
                  </div>
                </div>
              ))}
            </div>
          ) : filteredItems.length === 0 ? (
            /* Empty State */
            <div className="bg-[#0e0e10] rounded-3xl p-12 text-center space-y-5 border border-zinc-800 max-w-lg mx-auto my-8">
              <div className="w-16 h-16 rounded-full bg-rose-500/10 text-rose-400 border border-rose-500/20 flex items-center justify-center mx-auto">
                <Heart className="w-8 h-8" />
              </div>
              <div className="space-y-1.5">
                <h3 className="text-xl font-extrabold text-white font-display-lg">
                  {savedItems.length === 0
                    ? "No Saved Properties Yet"
                    : "No Matching Properties Found"}
                </h3>
                <p className="text-xs text-slate-400 max-w-sm mx-auto leading-relaxed">
                  {savedItems.length === 0
                    ? "You haven't saved any properties to your wishlist yet. Explore our portfolio and click the heart icon on any residence to save it here."
                    : "Try adjusting your search query or category filter to find what you're looking for."}
                </p>
              </div>
              <div className="pt-2">
                <Link
                  href="/properties"
                  className="inline-flex items-center gap-2 bg-[#059669] hover:bg-[#047857] text-white text-xs font-bold px-6 py-3 rounded-xl shadow-lg shadow-[#059669]/25 transition-all"
                >
                  <span>Browse Luxury Properties</span>
                  <ArrowRight className="w-3.5 h-3.5" />
                </Link>
              </div>
            </div>
          ) : (
            /* Grid of Saved Properties */
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredItems.map((item) => {
                const p = item.property;
                const heroImg = p.primary_image
                  ? resolveImageUrl(p.primary_image)
                  : p.images?.[0]?.image_url
                  ? resolveImageUrl(p.images[0].image_url)
                  : "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=1000&q=80";

                const locationName = p.location?.name || p.address || "Sri Lanka";
                const categoryName = p.category?.name || "Luxury Residence";
                const propertySlug = p.slug || String(p.id);

                return (
                  <div
                    key={item.saved_id}
                    className="group bg-[#0e0e10] rounded-3xl overflow-hidden border border-[#FFE259]/25 shadow-xl hover:border-[#FFE259]/60 hover:shadow-2xl transition-all duration-300 flex flex-col justify-between"
                  >
                    {/* Top Image & Floating Badges */}
                    <div>
                      <div className="relative aspect-[16/10] overflow-hidden bg-zinc-900">
                        <img
                          src={heroImg}
                          alt={p.title}
                          className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500 ease-out opacity-90 group-hover:opacity-100"
                          onError={(e) => {
                            (e.target as HTMLImageElement).src =
                              "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=1000&q=80";
                          }}
                        />
                        <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-black/30" />

                        {/* Top Badges */}
                        <div className="absolute top-3.5 left-3.5 right-3.5 flex items-center justify-between gap-2">
                          <span className="px-3 py-1 rounded-full text-[11px] font-extrabold bg-[#FFE259] text-black shadow-md border border-[#FFE259]/80">
                            {categoryName}
                          </span>

                          {/* Remove Bookmark Button */}
                          <button
                            onClick={() => handleRemove(p.id, p.title)}
                            className="w-8 h-8 rounded-full bg-rose-500 hover:bg-rose-600 text-white flex items-center justify-center shadow-md transition-transform hover:scale-110 cursor-pointer"
                            title="Remove from saved properties"
                            aria-label="Remove property"
                          >
                            <Heart className="w-3.5 h-3.5 fill-current" />
                          </button>
                        </div>

                        {/* Bottom Price on Image */}
                        <div className="absolute bottom-3 left-3.5 right-3.5 flex items-end justify-between">
                          <div>
                            <span className="text-[#FFE259] text-xl font-extrabold block leading-none font-display-lg drop-shadow-md">
                              {formatPriceLKR(p.price)}
                            </span>
                          </div>
                          <span className="text-[11px] px-2 py-0.5 rounded-full bg-[#0A0A0A]/80 backdrop-blur-md text-[#FFE259] border border-[#FFE259]/30 font-medium">
                            {p.status || "For Sale"}
                          </span>
                        </div>
                      </div>

                      {/* Card Body */}
                      <div className="p-5 space-y-3">
                        {/* Location */}
                        <div className="flex items-center gap-1.5 text-xs text-slate-400 font-semibold">
                          <MapPin className="w-3.5 h-3.5 text-[#FFE259] shrink-0" />
                          <span className="truncate text-slate-300">{locationName}</span>
                        </div>

                        {/* Title */}
                        <Link href={`/properties/${propertySlug}`}>
                          <h3 className="text-base font-bold text-white group-hover:text-[#FFE259] transition-colors leading-snug line-clamp-1 font-headline-md">
                            {p.title}
                          </h3>
                        </Link>

                        {/* Specs Bar */}
                        <div className="grid grid-cols-3 gap-1.5 py-2 px-3 bg-[#18181b] rounded-xl border border-zinc-800 text-slate-300 text-xs font-semibold">
                          <div className="flex items-center gap-1">
                            <Bed className="w-3.5 h-3.5 text-[#FFE259] shrink-0" />
                            <span>{p.bedrooms || 0} Beds</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <Bath className="w-3.5 h-3.5 text-[#FFE259] shrink-0" />
                            <span>{p.bathrooms || 0} Baths</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <Maximize2 className="w-3.5 h-3.5 text-[#FFE259] shrink-0" />
                            <span>{Number(p.area_sqft || 0).toLocaleString()} SqFt</span>
                          </div>
                        </div>

                        {/* Private Notes Section */}
                        <div className="bg-[#18181b] rounded-xl p-3 border border-zinc-800 text-xs space-y-1.5">
                          <div className="flex items-center justify-between text-slate-300 font-bold">
                            <div className="flex items-center gap-1 text-[11px] text-[#FFE259]">
                              <FileText className="w-3 h-3 text-[#FFE259]" />
                              <span>Private Notes</span>
                            </div>
                            <button
                              onClick={() => {
                                setEditingNotesItem(item);
                                setNotesText(item.notes || "");
                              }}
                              className="text-[10px] text-[#FFE259] hover:underline font-bold flex items-center gap-0.5 cursor-pointer"
                            >
                              <Edit3 className="w-2.5 h-2.5" />
                              <span>{item.notes ? "Edit" : "Add Notes"}</span>
                            </button>
                          </div>
                          <p className="text-[11px] text-slate-400 italic line-clamp-2">
                            {item.notes || "No notes added yet. Click Add Notes to record viewing notes."}
                          </p>
                        </div>
                      </div>
                    </div>

                    {/* Card Footer: Action Buttons */}
                    <div className="p-5 pt-0 space-y-2 border-t border-zinc-800 mt-2">
                      {p.agent && (
                        <div className="flex items-center justify-between text-[11px] text-slate-400 pt-2">
                          <span>Advisor: <strong className="text-white">{p.agent.name}</strong></span>
                          <span className="text-[10px] text-slate-500 font-mono">
                            Saved {new Date(item.saved_at).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                          </span>
                        </div>
                      )}

                      <div className="flex items-center gap-2 pt-1">
                        <Link
                          href={`/properties/${propertySlug}`}
                          className="flex-1 bg-[#059669] hover:bg-[#047857] text-white text-xs font-bold py-2.5 rounded-xl text-center transition-colors flex items-center justify-center gap-1 shadow-md shadow-[#059669]/20"
                        >
                          <span>Explore Details</span>
                          <ArrowUpRight className="w-3.5 h-3.5" />
                        </Link>

                        <button
                          onClick={() => setContactProperty(p)}
                          className="px-3.5 py-2.5 rounded-xl bg-[#18181b] border border-[#FFE259]/30 hover:border-[#FFE259] text-slate-300 hover:text-white text-xs font-bold transition-colors flex items-center gap-1 cursor-pointer"
                          title="Contact Agent & Schedule Viewing"
                        >
                          <Phone className="w-3.5 h-3.5 text-[#FFE259]" />
                          <span className="hidden sm:inline">Contact</span>
                        </button>

                        <button
                          onClick={() => handleCopyLink(p)}
                          className={`p-2.5 rounded-xl border border-zinc-700 transition-all cursor-pointer shadow-xs ${
                            copiedId === p.id
                              ? "bg-[#059669] border-[#059669] text-white shadow-[#059669]/30 scale-105"
                              : "bg-[#18181b] text-slate-300 hover:text-[#FFE259] hover:border-[#FFE259]"
                          }`}
                          title={copiedId === p.id ? "Link Copied to Clipboard!" : "Copy Property Link to share"}
                        >
                          {copiedId === p.id ? (
                            <Check className="w-3.5 h-3.5 text-white" />
                          ) : (
                            <Share2 className="w-3.5 h-3.5" />
                          )}
                        </button>

                        <button
                          onClick={() => handleRemove(p.id, p.title)}
                          className="p-2.5 rounded-xl bg-[#18181b] border border-zinc-700 hover:border-rose-400 text-slate-400 hover:text-rose-400 transition-colors cursor-pointer"
                          title="Remove from Saved Wishlist"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                        </button>
                      </div>
                    </div>

                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* ------------------------------------------------------------- */}
      {/* MODAL: EDIT CUSTOMER NOTES */}
      {/* ------------------------------------------------------------- */}
      {editingNotesItem && (
        <div className="fixed inset-0 z-50 bg-black/80 backdrop-blur-md flex items-center justify-center p-4 animate-in fade-in">
          <div className="bg-[#0e0e10] rounded-3xl max-w-lg w-full p-6 sm:p-8 shadow-2xl border border-[#FFE259]/30 space-y-4 text-white">
            <div className="flex items-center justify-between pb-3 border-b border-zinc-800">
              <div className="flex items-center gap-2.5">
                <div className="w-8 h-8 rounded-xl bg-[#18181b] text-[#FFE259] border border-[#FFE259]/30 flex items-center justify-center">
                  <FileText className="w-4 h-4" />
                </div>
                <div>
                  <h3 className="text-base font-extrabold text-white">Personal Inspection Notes</h3>
                  <p className="text-[11px] text-slate-400 truncate max-w-xs">{editingNotesItem.property.title}</p>
                </div>
              </div>
              <button
                onClick={() => setEditingNotesItem(null)}
                className="p-1.5 rounded-lg bg-white/10 hover:bg-white/20 text-slate-300 hover:text-white"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-slate-300">
                Your Private Notes (Only visible to you)
              </label>
              <textarea
                rows={4}
                value={notesText}
                onChange={(e) => setNotesText(e.target.value)}
                placeholder="e.g. Schedule Saturday morning viewing. Inquire about swimming pool heating and deed status..."
                className="w-full bg-[#18181b] border border-zinc-700 rounded-2xl p-3.5 text-xs text-white outline-none focus:border-[#FFE259] transition-all resize-none"
              />
              <p className="text-[10px] text-slate-500">
                Tip: Notes help you keep track of pros, cons, and questions before calling the assigned advisor.
              </p>
            </div>

            <div className="flex items-center justify-end gap-2 pt-3 border-t border-zinc-800">
              <button
                type="button"
                onClick={() => setEditingNotesItem(null)}
                className="px-4 py-2 rounded-xl bg-[#18181b] border border-zinc-700 text-slate-300 text-xs font-bold hover:bg-zinc-800 cursor-pointer"
              >
                Cancel
              </button>
              <button
                type="button"
                disabled={isSavingNotes}
                onClick={handleSaveNotes}
                className="px-5 py-2 rounded-xl bg-[#059669] hover:bg-[#047857] text-white text-xs font-bold shadow-md shadow-[#059669]/25 transition-all flex items-center gap-1.5 cursor-pointer"
              >
                <Check className="w-3.5 h-3.5" />
                <span>{isSavingNotes ? "Saving..." : "Save Notes"}</span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ------------------------------------------------------------- */}
      {/* AGENT CONTACT MODAL */}
      {/* ------------------------------------------------------------- */}
      {contactProperty && (
        <AgentContactModal
          isOpen={true}
          onClose={() => setContactProperty(null)}
          agent={
            contactProperty.agent || {
              name: "DreamHomes Premier Real Estate",
              phone: "+94 77 123 4567",
              email: "sales@dreamhomes.lk",
              avatar: "/logo.png",
              division: "Luxury Portfolio Specialist"
            }
          }
          propertyTitle={contactProperty.title}
          propertyId={contactProperty.id}
        />
      )}

    </div>
  );
}
