"use client";
import { useEffect, useState, useCallback, Fragment } from "react";
import Link from "next/link";
import PhoneInput from "@/components/PhoneInput";
import {
  Plus, X, Users, Phone, Mail, Search, Calendar, ArrowUpRight,
  MessageSquare, Globe, UserPlus, Handshake, MapPin, Check,
  Sparkles, PhoneCall, ExternalLink, UserCheck, UserX, UserMinus,
  Trash2, AlertTriangle, Pill, ClipboardList, FileText, Loader2,
} from "lucide-react";

interface Lead {
  id: string; name: string; phone: string; email: string | null; source: string;
  status: string; treatmentInterest: string | null; notes: string | null; createdAt: string;
  appointments: { treatment: { name: string }; dateTime: string; status: string }[];
}

const STATUS: Record<string, { badge: string; label: string; color: string }> = {
  new:        { badge: "badge-new",       label: "New",       color: "#3b82f6" },
  contacted:  { badge: "badge-new",       label: "Contacted", color: "#60a5fa" },
  booked:     { badge: "badge-booked",    label: "Booked",    color: "#6366f1" },
  confirmed:  { badge: "badge-confirmed", label: "Confirmed", color: "#10b981" },
  arrived:    { badge: "badge-arrived",   label: "Arrived",   color: "#059669" },
  completed:  { badge: "badge-completed", label: "Completed", color: "#047857" },
  no_show:    { badge: "badge-no-show",   label: "No Show",   color: "#ef4444" },
  cancelled:  { badge: "badge-cancelled", label: "Cancelled", color: "#94a3b8" },
  lost:       { badge: "badge-cancelled", label: "Lost",      color: "#64748b" },
};

const JOURNEY_STEPS = [
  { key: "new", label: "New" }, { key: "booked", label: "Booked" },
  { key: "confirmed", label: "Confirmed" }, { key: "arrived", label: "Arrived" },
  { key: "completed", label: "Done" },
];
const JOURNEY_ORDER = ["new", "contacted", "booked", "confirmed", "arrived", "completed"];

const SOURCES = [
  { key: "manual", icon: UserPlus, label: "Manual", color: "bg-gray-100 text-gray-600" },
  { key: "whatsapp", icon: MessageSquare, label: "WhatsApp", color: "bg-green-50 text-green-600" },
  { key: "instagram", icon: Globe, label: "Instagram", color: "bg-pink-50 text-pink-600" },
  { key: "google", icon: Globe, label: "Google", color: "bg-blue-50 text-blue-600" },
  { key: "website", icon: Globe, label: "Website", color: "bg-indigo-50 text-indigo-600" },
  { key: "referral", icon: Handshake, label: "Referral", color: "bg-amber-50 text-amber-600" },
  { key: "walk_in", icon: MapPin, label: "Walk-in", color: "bg-purple-50 text-purple-600" },
];

function HighlightText({ text, search }: { text: string; search: string }) {
  if (!search || search.length < 2) return <>{text}</>;
  const idx = text.toLowerCase().indexOf(search.toLowerCase());
  if (idx === -1) return <>{text}</>;
  return <>{text.slice(0, idx)}<span className="search-highlight">{text.slice(idx, idx + search.length)}</span>{text.slice(idx + search.length)}</>;
}

function JourneyTimeline({ currentStatus }: { currentStatus: string }) {
  const currentIdx = JOURNEY_ORDER.indexOf(currentStatus);
  const isBad = ["cancelled", "lost", "no_show"].includes(currentStatus);
  return (
    <div className="flex items-center gap-0 py-3">
      {JOURNEY_STEPS.map((step, i) => {
        const stepIdx = JOURNEY_ORDER.indexOf(step.key);
        const reached = !isBad && currentIdx >= stepIdx;
        const isCurrent = !isBad && currentStatus === step.key;
        return (
          <Fragment key={step.key}>
            <div className="flex flex-col items-center gap-1.5 flex-1">
              <div className={`w-6 h-6 rounded-full flex items-center justify-center text-[9px] font-bold transition-all ${
                isCurrent ? "bg-primary-500 text-white shadow-md shadow-primary-500/30 scale-110" :
                reached ? "bg-primary-400 text-white" : "bg-gray-100 text-gray-400"
              }`}>
                {reached ? <Check size={10} strokeWidth={3} /> : i + 1}
              </div>
              <span className={`text-[9px] font-medium ${reached ? "text-primary-600" : "text-gray-400"}`}>{step.label}</span>
            </div>
            {i < JOURNEY_STEPS.length - 1 && (
              <div className={`h-0.5 flex-1 rounded-full -mt-4 ${reached && currentIdx > stepIdx ? "bg-primary-400" : "bg-gray-100"}`} />
            )}
          </Fragment>
        );
      })}
      {isBad && (
        <div className="flex flex-col items-center gap-1.5 flex-1">
          <div className="w-6 h-6 rounded-full bg-red-100 text-red-500 flex items-center justify-center">
            <X size={10} strokeWidth={3} />
          </div>
          <span className="text-[9px] font-medium text-red-500">{STATUS[currentStatus]?.label}</span>
        </div>
      )}
    </div>
  );
}

function StatusBar({ leads }: { leads: Lead[] }) {
  const total = leads.length;
  if (total === 0) return null;
  const segments = Object.entries(STATUS)
    .map(([key, val]) => ({ key, ...val, count: leads.filter(l => l.status === key).length }))
    .filter(s => s.count > 0);
  const [mounted, setMounted] = useState(false);
  useEffect(() => { setTimeout(() => setMounted(true), 200); }, []);
  return (
    <div>
      <div className="flex gap-0.5 rounded-full overflow-hidden bg-gray-100 h-[6px]">
        {segments.map((seg, i) => (
          <div key={seg.key} className="status-bar-segment status-bar-animate"
            title={`${seg.label}: ${seg.count}`}
            style={{ width: mounted ? `${(seg.count / total) * 100}%` : "0%", backgroundColor: seg.color, animationDelay: `${i * 80}ms` }} />
        ))}
      </div>
      <div className="flex flex-wrap gap-x-3 gap-y-1 mt-2">
        {segments.map(seg => (
          <div key={seg.key} className="flex items-center gap-1.5">
            <div className="w-2 h-2 rounded-full" style={{ backgroundColor: seg.color }} />
            <span className="text-[10px] text-gray-500">{seg.label}</span>
            <span className="text-[10px] font-bold text-dark">{seg.count}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Medical Notes ─────────────────────────────────────────────────────────────

interface PatientNote {
  id: string; leadId: string; type: string; content: string; createdAt: string;
}

const NOTE_TYPES = [
  { key: "allergy",    label: "🚨 Allergies",   badge: "bg-red-50 border-red-200 text-red-700",     emptyIcon: AlertTriangle, emptyColor: "text-red-300" },
  { key: "medication", label: "💊 Medications",  badge: "bg-blue-50 border-blue-200 text-blue-700",  emptyIcon: Pill,          emptyColor: "text-blue-300" },
  { key: "history",    label: "📋 History",      badge: "bg-amber-50 border-amber-200 text-amber-700", emptyIcon: ClipboardList, emptyColor: "text-amber-300" },
  { key: "note",       label: "📝 Notes",        badge: "bg-gray-50 border-gray-200 text-gray-700",  emptyIcon: FileText,      emptyColor: "text-gray-300" },
];

function getNoteBadge(type: string) {
  return NOTE_TYPES.find(t => t.key === type) || NOTE_TYPES[3];
}

function MedicalNotesPanel({ leadId }: { leadId: string }) {
  const [notes, setNotes] = useState<PatientNote[]>([]);
  const [loading, setLoading] = useState(true);
  const [tab, setTab] = useState("all");
  const [addType, setAddType] = useState("note");
  const [addContent, setAddContent] = useState("");
  const [saving, setSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  const loadNotes = useCallback(() => {
    setLoading(true);
    fetch(`/api/leads/${leadId}/notes`).then(r => r.json()).then(setNotes).finally(() => setLoading(false));
  }, [leadId]);
  useEffect(() => { loadNotes(); }, [loadNotes]);

  const handleAdd = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!addContent.trim()) return;
    setSaving(true);
    const res = await fetch(`/api/leads/${leadId}/notes`, {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ type: addType, content: addContent }),
    });
    if (res.ok) { setAddContent(""); loadNotes(); }
    setSaving(false);
  };

  const handleDelete = async (noteId: string) => {
    setDeletingId(noteId);
    await fetch(`/api/leads/${leadId}/notes?noteId=${noteId}`, { method: "DELETE" });
    loadNotes();
    setDeletingId(null);
  };

  const filtered = tab === "all" ? notes : notes.filter(n => n.type === tab);
  const tabs = [{ key: "all", label: "All" }, ...NOTE_TYPES.map(t => ({ key: t.key, label: t.label }))];

  return (
    <div className="border-t border-gray-100 mt-4 pt-4">
      <p className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-3">Medical Notes</p>

      {/* Tabs */}
      <div className="flex gap-1 flex-wrap mb-3">
        {tabs.map(t => (
          <button key={t.key} onClick={() => setTab(t.key)}
            className={`px-2.5 py-1 rounded-lg text-[11px] font-medium transition-all ${
              tab === t.key ? "bg-primary-600 text-white shadow-sm" : "bg-gray-100 text-gray-500 hover:bg-gray-200"
            }`}>
            {t.label}
            {t.key !== "all" && <span className="ml-1 opacity-60">{notes.filter(n => n.type === t.key).length}</span>}
            {t.key === "all" && <span className="ml-1 opacity-60">{notes.length}</span>}
          </button>
        ))}
      </div>

      {/* Notes list */}
      {loading ? (
        <div className="flex items-center justify-center py-6"><Loader2 size={16} className="animate-spin text-gray-300" /></div>
      ) : filtered.length === 0 ? (
        <div className="text-center py-6">
          {(() => { const nt = NOTE_TYPES.find(t => t.key === tab); const Icon = nt?.emptyIcon || FileText; return (
            <><Icon size={24} className={nt?.emptyColor || "text-gray-300"} style={{ margin: "0 auto 8px" }} />
            <p className="text-xs text-gray-400">No {tab === "all" ? "notes" : tab === "allergy" ? "allergies" : tab + "s"} yet</p></>
          ); })()}
        </div>
      ) : (
        <div className="space-y-2 max-h-[240px] overflow-y-auto mb-3">
          {filtered.map(note => {
            const badge = getNoteBadge(note.type);
            return (
              <div key={note.id} className={`flex items-start gap-2 p-2.5 rounded-lg border ${
                note.type === "allergy" ? "bg-red-50 border-red-200" : "bg-white border-gray-100"
              }`}>
                <div className="flex-1 min-w-0">
                  <span className={`inline-block px-1.5 py-0.5 rounded text-[10px] font-semibold border ${badge.badge} mb-1`}>
                    {badge.key === "allergy" ? "🚨 Allergy" : badge.key === "medication" ? "💊 Med" : badge.key === "history" ? "📋 History" : "📝 Note"}
                  </span>
                  <p className="text-sm text-gray-700 whitespace-pre-line">{note.content}</p>
                  <p className="text-[10px] text-gray-400 mt-1">{new Date(note.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}</p>
                </div>
                <button onClick={() => handleDelete(note.id)} disabled={deletingId === note.id}
                  className="p-1.5 rounded-lg text-gray-300 hover:text-red-500 hover:bg-red-50 transition-colors shrink-0">
                  {deletingId === note.id ? <Loader2 size={12} className="animate-spin" /> : <Trash2 size={12} />}
                </button>
              </div>
            );
          })}
        </div>
      )}

      {/* Add form */}
      <form onSubmit={handleAdd} className="flex flex-col gap-2 mt-2">
        <div className="flex gap-2">
          <select value={addType} onChange={e => setAddType(e.target.value)}
            className="input py-1.5 text-xs w-[130px]">
            <option value="note">📝 Note</option>
            <option value="allergy">🚨 Allergy</option>
            <option value="medication">💊 Medication</option>
            <option value="history">📋 History</option>
          </select>
          <textarea value={addContent} onChange={e => setAddContent(e.target.value)}
            placeholder="Add a note..." rows={2} className="input flex-1 text-sm py-1.5" />
        </div>
        <button type="submit" disabled={saving || !addContent.trim()}
          className="btn-primary btn-sm self-end">
          {saving ? "Adding..." : "Add Note"}
        </button>
      </form>
    </div>
  );
}

export default function LeadsPage() {
  const [leads, setLeads] = useState<Lead[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAdd, setShowAdd] = useState(false);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [selectedLead, setSelectedLead] = useState<Lead | null>(null);
  const [form, setForm] = useState({ name: "", phone: "", email: "", source: "manual", treatmentInterest: "", notes: "" });
  const [saving, setSaving] = useState(false);
  const [toast, setToast] = useState<string | null>(null);

  const load = useCallback(() => {
    fetch("/api/leads").then(r => r.json()).then(setLeads).finally(() => setLoading(false));
  }, []);
  useEffect(() => { load(); }, [load]);

  const handleAdd = async (e: React.FormEvent) => {
    e.preventDefault(); setSaving(true);
    const res = await fetch("/api/leads", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(form) });
    if (res.ok) { setForm({ name: "", phone: "", email: "", source: "manual", treatmentInterest: "", notes: "" }); setShowAdd(false); setToast(`${form.name} added!`); setTimeout(() => setToast(null), 3000); load(); }
    setSaving(false);
  };

  const filtered = leads.filter(l => {
    if (search && !l.name.toLowerCase().includes(search.toLowerCase()) && !l.phone.includes(search)) return false;
    if (statusFilter !== "all" && l.status !== statusFilter) return false;
    return true;
  });

  const statusCounts = Object.keys(STATUS).reduce((acc, s) => {
    const c = leads.filter(l => l.status === s).length;
    if (c > 0) acc.push({ key: s, ...STATUS[s], count: c });
    return acc;
  }, [] as { key: string; badge: string; label: string; color: string; count: number }[]);

  const getSource = (key: string) => SOURCES.find(s => s.key === key) || SOURCES[0];
  const newCount = leads.filter(l => l.status === "new").length;
  const bookedCount = leads.filter(l => ["booked", "confirmed"].includes(l.status)).length;
  const completedCount = leads.filter(l => l.status === "completed").length;

  return (
    <>
      {/* ── Toast ── */}
      {toast && (
        <div className="success-toast"><div className="toast-check"><Check size={12} className="text-white" /></div>{toast}</div>
      )}

      {/* ── Add Modal ── */}
      {showAdd && (
        <div className="modal-overlay" onClick={() => setShowAdd(false)}>
          <div className="card p-6 w-full max-w-md animate-scale-in" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-5">
              <div className="flex items-center gap-2.5">
                <div className="w-8 h-8 rounded-lg bg-blue-50 flex items-center justify-center"><UserPlus size={16} className="text-blue-600" /></div>
                <h2 className="text-base font-bold">New Lead</h2>
              </div>
              <button onClick={() => setShowAdd(false)} className="p-1.5 hover:bg-gray-100 rounded-lg text-gray-400"><X size={18} /></button>
            </div>
            <form onSubmit={handleAdd} className="space-y-4">
              <div>
                <label className="block text-xs font-semibold text-gray-500 mb-1.5">Name *</label>
                <input type="text" value={form.name} onChange={e => setForm(p => ({ ...p, name: e.target.value }))} placeholder="Patient name" required className="input" autoFocus />
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-500 mb-1.5">WhatsApp Number *</label>
                <PhoneInput value={form.phone} onChange={v => setForm(p => ({ ...p, phone: v }))} variant="dashboard" height="h-[40px]" />
              </div>
              <div><label className="block text-xs font-semibold text-gray-500 mb-1.5">Email</label>
                <input type="email" value={form.email} onChange={e => setForm(p => ({ ...p, email: e.target.value }))} placeholder="Optional" className="input" /></div>
              <div>
                <label className="block text-xs font-semibold text-gray-500 mb-1.5">Source</label>
                <div className="flex flex-wrap gap-1.5">
                  {SOURCES.map(s => (
                    <button key={s.key} type="button" onClick={() => setForm(p => ({ ...p, source: s.key }))}
                      className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium border transition-all ${
                        form.source === s.key ? "border-primary-400 bg-primary-50 text-primary-700 shadow-sm" : "border-gray-200 text-gray-500 hover:border-gray-300"
                      }`}><s.icon size={11} /> {s.label}</button>
                  ))}
                </div>
              </div>
              <div><label className="block text-xs font-semibold text-gray-500 mb-1.5">Treatment Interest</label>
                <input type="text" value={form.treatmentInterest} onChange={e => setForm(p => ({ ...p, treatmentInterest: e.target.value }))} placeholder="e.g. Botox, fillers" className="input" /></div>
              <div><label className="block text-xs font-semibold text-gray-500 mb-1.5">Notes</label>
                <textarea value={form.notes} onChange={e => setForm(p => ({ ...p, notes: e.target.value }))} placeholder="Optional..." className="input" rows={2} /></div>
              <div className="flex gap-2 pt-1">
                <button type="button" onClick={() => setShowAdd(false)} className="btn-secondary flex-1">Cancel</button>
                <button type="submit" disabled={saving || !form.name || !form.phone} className="btn-primary flex-1">{saving ? "Saving..." : "Add Lead"}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ── Detail Drawer ── */}
      {selectedLead && (
        <div className="fixed inset-0 z-50 flex justify-end" onClick={() => setSelectedLead(null)}>
          <div className="absolute inset-0 bg-black/20 backdrop-blur-[2px]" style={{ animation: "overlay-in 0.25s ease" }} />
          <div className="relative w-full sm:max-w-sm bg-white h-full overflow-y-auto shadow-2xl drawer-morph-enter" onClick={e => e.stopPropagation()}>
            <div className="sticky top-0 bg-white/90 backdrop-blur-md z-10 flex items-center justify-between px-5 py-4 border-b border-gray-100">
              <h2 className="font-bold text-base">Lead Details</h2>
              <button onClick={() => setSelectedLead(null)} className="p-1.5 hover:bg-gray-100 rounded-lg text-gray-400 transition-colors"><X size={18} /></button>
            </div>
            <div className="p-5 space-y-5">
              <div className="drawer-section flex items-center gap-3">
                <div className="w-14 h-14 rounded-xl bg-gradient-to-br from-primary-50 to-primary-100 flex items-center justify-center avatar-bounce shadow-sm">
                  <span className="text-primary-700 text-xl font-bold">{selectedLead.name.charAt(0)}</span>
                </div>
                <div><p className="font-bold text-lg">{selectedLead.name}</p>
                  <span className={`badge ${STATUS[selectedLead.status]?.badge || "badge-new"}`}>{STATUS[selectedLead.status]?.label || selectedLead.status}</span></div>
              </div>
              <div className="drawer-section">
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1">Patient Journey</p>
                <JourneyTimeline currentStatus={selectedLead.status} />
              </div>
              <div className="drawer-section space-y-2">
                <a href={`tel:${selectedLead.phone}`} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg hover:bg-primary-50 border border-transparent hover:border-primary-200 transition-all group">
                  <Phone size={15} className="text-gray-400 group-hover:text-primary-500" /><span className="text-sm font-medium text-primary-600">{selectedLead.phone}</span>
                  <ExternalLink size={11} className="ml-auto text-gray-300 group-hover:text-primary-400" /></a>
                {selectedLead.email && <a href={`mailto:${selectedLead.email}`} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg hover:bg-blue-50 transition-all group">
                  <Mail size={15} className="text-gray-400 group-hover:text-blue-500" /><span className="text-sm">{selectedLead.email}</span></a>}
                <div className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">{(() => { const src = getSource(selectedLead.source); return <><src.icon size={15} className="text-gray-400" /><span className="text-sm capitalize">{src.label}</span></>; })()}</div>
              </div>
              {selectedLead.treatmentInterest && <div className="drawer-section"><p className="text-xs font-semibold text-gray-400 mb-1">Interest</p>
                <div className="flex items-center gap-2 px-3 py-2 bg-primary-50 rounded-lg border border-primary-100"><Sparkles size={12} className="text-primary-400" /><p className="text-sm font-medium text-primary-700">{selectedLead.treatmentInterest}</p></div></div>}
              {selectedLead.notes && <div className="drawer-section"><p className="text-xs font-semibold text-gray-400 mb-1">Notes</p>
                <p className="text-sm text-gray-600 whitespace-pre-line bg-gray-50 rounded-lg p-3">{selectedLead.notes}</p></div>}
              {selectedLead.appointments.length > 0 && <div className="drawer-section"><p className="text-xs font-semibold text-gray-400 mb-2">Appointments ({selectedLead.appointments.length})</p>
                <div className="space-y-2">{selectedLead.appointments.map((a, i) => (
                  <div key={i} className="flex items-center gap-3 p-3 border border-gray-100 rounded-lg hover:border-primary-200 hover:bg-primary-50/30 transition-all">
                    <Calendar size={14} className="text-gray-400 shrink-0" /><div className="flex-1 min-w-0"><p className="text-sm font-medium truncate">{a.treatment.name}</p>
                    <p className="text-[11px] text-gray-400">{new Date(a.dateTime).toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" })} at {new Date(a.dateTime).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true })}</p></div>
                    <span className={`badge ${STATUS[a.status]?.badge || "badge-scheduled"}`}>{STATUS[a.status]?.label || a.status}</span></div>))}</div></div>}
              <div className="drawer-section"><MedicalNotesPanel leadId={selectedLead.id} /></div>
              <div className="drawer-section"><Link href="/appointments" className="btn-primary w-full"><Calendar size={15} /> Book Appointment</Link></div>
              <p className="drawer-section text-[11px] text-gray-300 text-center">Added {new Date(selectedLead.createdAt).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })}</p>
            </div>
          </div>
        </div>
      )}

      {/* ═══════════════════════════════════════════ */}
      {/*                 PAGE CONTENT                */}
      {/* ═══════════════════════════════════════════ */}
      <div className="space-y-6 animate-fade-in">

        {/* ── Header ── */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
          <div className="flex items-center gap-3">
            <div className="w-10 sm:w-11 h-10 sm:h-11 rounded-xl bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center shadow-lg shadow-blue-500/20">
              <Users size={20} className="text-white" />
            </div>
            <div>
              <h1 className="text-xl sm:text-2xl font-bold tracking-tight text-dark">Leads</h1>
              <p className="text-xs sm:text-sm text-muted">{leads.length} total · {newCount} new</p>
            </div>
          </div>
          <button onClick={() => setShowAdd(true)} className="btn-primary btn-sm"><Plus size={15} /> Add Lead</button>
        </div>

        {/* ── Quick Stats ── */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4">
          {[
            { label: "Total", value: leads.length, icon: Users, color: "text-blue-600", bg: "bg-blue-50", border: "border-blue-100" },
            { label: "New", value: newCount, icon: UserPlus, color: "text-sky-600", bg: "bg-sky-50", border: "border-sky-100" },
            { label: "Booked", value: bookedCount, icon: UserCheck, color: "text-primary-600", bg: "bg-primary-50", border: "border-primary-100" },
            { label: "Completed", value: completedCount, icon: Check, color: "text-emerald-600", bg: "bg-emerald-50", border: "border-emerald-100" },
          ].map((s, i) => (
            <div key={i} className={`${s.bg} ${s.border} border rounded-2xl p-4 flex items-center gap-3 transition-transform hover:scale-[1.02]`}>
              <div className={`w-10 h-10 rounded-xl ${s.bg} flex items-center justify-center`}>
                <s.icon size={18} className={s.color} />
              </div>
              <div>
                <p className={`text-2xl font-bold ${s.color}`}>{s.value}</p>
                <p className="text-[11px] text-muted font-medium">{s.label}</p>
              </div>
            </div>
          ))}
        </div>

        {/* ── Status Distribution ── */}
        {leads.length > 0 && <StatusBar leads={leads} />}

        {/* ── Filters ── */}
        <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 sm:gap-4">
          <div className="relative flex-1">
            <Search size={15} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-gray-300" />
            <input type="text" value={search} onChange={e => setSearch(e.target.value)}
              placeholder="Search name or phone..." className="input pl-10 py-2.5 text-sm" />
            {search && <button onClick={() => setSearch("")} className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-300 hover:text-gray-500"><X size={14} /></button>}
          </div>
          {statusCounts.length > 1 && (
            <div className="flex gap-1 flex-wrap overflow-x-auto scrollbar-hide">
              <button onClick={() => setStatusFilter("all")}
                className={`btn-xs transition-all whitespace-nowrap ${statusFilter === "all" ? "bg-primary-600 text-white shadow-sm" : "bg-gray-100 text-gray-500 hover:bg-gray-200"}`}>All</button>
              {statusCounts.map(s => (
                <button key={s.key} onClick={() => setStatusFilter(statusFilter === s.key ? "all" : s.key)}
                  className={`btn-xs transition-all whitespace-nowrap ${statusFilter === s.key ? "bg-primary-600 text-white shadow-sm" : "bg-gray-100 text-gray-500 hover:bg-gray-200"}`}>
                  <span className="w-1.5 h-1.5 rounded-full inline-block mr-1" style={{ backgroundColor: s.color }} />{s.label} <span className="opacity-60 ml-0.5">{s.count}</span>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* ── Leads List ── */}
        {loading ? (
          <div className="flex flex-col items-center justify-center py-24 gap-3">
            <div className="w-8 h-8 border-[2.5px] border-primary-100 border-t-primary-500 rounded-full animate-spin" />
            <p className="text-xs text-gray-400">Loading leads...</p>
          </div>
        ) : filtered.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 text-center">
            <div className="w-16 h-16 bg-blue-50 rounded-2xl flex items-center justify-center mb-4 animate-float">
              <Users size={28} className="text-blue-300" />
            </div>
            <h3 className="text-lg font-bold text-dark mb-1">{search || statusFilter !== "all" ? "No matching leads" : "No leads yet"}</h3>
            <p className="text-sm text-gray-400 mb-6 max-w-xs">{search ? "Try a different search" : "Add your first patient lead to get started"}</p>
            {!search && statusFilter === "all" && <button onClick={() => setShowAdd(true)} className="btn-primary"><Plus size={15} /> Add First Lead</button>}
          </div>
        ) : (
          <div className="card card-flat overflow-hidden">
            {filtered.map((lead, idx) => {
              const src = getSource(lead.source);
              const st = STATUS[lead.status] || STATUS.new;
              return (
                <div key={lead.id}
                  className="lead-card table-row cursor-pointer group"
                  style={{ animation: `fade-in 0.35s ease both`, animationDelay: `${idx * 30}ms` }}>
                  <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary-50 to-primary-100 flex items-center justify-center shrink-0 group-hover:scale-110 group-hover:shadow-sm transition-all relative z-10"
                    onClick={() => setSelectedLead(lead)}>
                    <span className="text-primary-700 text-sm font-bold">{lead.name.charAt(0)}</span>
                  </div>
                  <div className="flex-1 min-w-0 relative z-10" onClick={() => setSelectedLead(lead)}>
                    <div className="flex items-center gap-2 mb-0.5">
                      <span className="text-[14px] font-semibold text-dark truncate"><HighlightText text={lead.name} search={search} /></span>
                      <span className={`badge ${st.badge}`}>{st.label}</span>
                    </div>
                    <div className="flex items-center gap-2 sm:gap-3 text-[11px] sm:text-[12px] text-gray-400 flex-wrap">
                      <span><HighlightText text={lead.phone} search={search} /></span>
                      <span className={`px-1.5 py-0.5 rounded text-[10px] font-medium ${src.color}`}>{src.label}</span>
                      {lead.treatmentInterest && <span className="truncate max-w-[100px] sm:max-w-[120px] text-primary-500/70 hidden sm:inline">{lead.treatmentInterest}</span>}
                    </div>
                  </div>
                  <div className="shrink-0 flex items-center gap-1.5 relative z-10">
                    <div className="lead-card-actions flex gap-1">
                      <a href={`tel:${lead.phone}`} className="action-btn-micro bg-emerald-50 text-emerald-600 hover:bg-emerald-100"
                        onClick={e => e.stopPropagation()} title="Call"><PhoneCall size={12} /></a>
                      <a href={`https://wa.me/${lead.phone.replace(/[^0-9]/g, "")}`} target="_blank" rel="noreferrer"
                        className="action-btn-micro bg-green-50 text-green-600 hover:bg-green-100"
                        onClick={e => e.stopPropagation()} title="WhatsApp"><MessageSquare size={12} /></a>
                    </div>
                    <div className="group-hover:hidden" onClick={() => setSelectedLead(lead)}>
                      {lead.appointments[0] ? (
                        <div className="text-right">
                          <p className="text-xs font-medium text-gray-600 truncate max-w-[120px]">{lead.appointments[0].treatment.name}</p>
                          <p className="text-[10px] text-gray-400">{new Date(lead.appointments[0].dateTime).toLocaleDateString("en-US", { month: "short", day: "numeric" })}</p>
                        </div>
                      ) : (
                        <span className="text-[11px] text-primary-600 font-medium flex items-center gap-1">Book <ArrowUpRight size={10} /></span>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </>
  );
}
