"use client";
import { useEffect, useState, useRef, useCallback, useMemo } from "react";
import {
  MessageSquare, ArrowUpRight, ArrowDownLeft, CheckCheck, Check,
  Clock, XCircle, Search, Copy, CheckCircle, X, Phone, ChevronDown,
  RefreshCw, TrendingUp, Activity, BarChart3, Zap, Send,
  ExternalLink, PhoneCall, Eye, EyeOff,
} from "lucide-react";

interface Message {
  id: string; phone: string; direction: string; message: string;
  status: string; sentAt: string | null; createdAt: string;
  appointmentId?: string | null;
}

/* ════════════════════════════════════════════════════════════
   #1 — DELIVERY RING: SVG circular progress instead of bars
   ════════════════════════════════════════════════════════════ */
function DeliveryRing({ status }: { status: string }) {
  const stages: Record<string, { pct: number; color: string; label: string }> = {
    queued:    { pct: 10,  color: "#d1d5db", label: "Queued" },
    sent:     { pct: 40,  color: "#10b981", label: "Sent" },
    delivered:{ pct: 75,  color: "#10b981", label: "Delivered" },
    read:     { pct: 100, color: "#3b82f6", label: "Read" },
    failed:   { pct: 100, color: "#ef4444", label: "Failed" },
  };
  const s = stages[status] || stages.queued;
  const r = 7; const circ = 2 * Math.PI * r;
  const offset = circ - (s.pct / 100) * circ;

  return (
    <div className="flex items-center gap-1.5 shrink-0" title={s.label}>
      <svg width="18" height="18" className="-rotate-90">
        <circle cx="9" cy="9" r={r} fill="none" stroke="#f0f0f5" strokeWidth="2" />
        <circle cx="9" cy="9" r={r} fill="none" stroke={s.color} strokeWidth="2"
          strokeLinecap="round" strokeDasharray={circ} strokeDashoffset={offset}
          className="msg-ring-draw" />
      </svg>
      <span className="text-[9px] font-semibold" style={{ color: s.color }}>{s.label}</span>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   #2 — ANIMATED COUNTER with spring effect
   ════════════════════════════════════════════════════════════ */
function AnimCounter({ value, duration = 900 }: { value: number; duration?: number }) {
  const [display, setDisplay] = useState(0);
  const prev = useRef(0);
  useEffect(() => {
    const from = prev.current;
    const start = Date.now();
    const tick = () => {
      const p = Math.min((Date.now() - start) / duration, 1);
      const ease = 1 - Math.pow(1 - p, 4); // quartic ease-out
      setDisplay(Math.round(from + (value - from) * ease));
      if (p < 1) requestAnimationFrame(tick);
      else prev.current = value;
    };
    requestAnimationFrame(tick);
  }, [value, duration]);
  return <>{display}</>;
}

/* ════════════════════════════════════════════════════════════
   #3 — EXPANDABLE MESSAGE with gradient reveal
   ════════════════════════════════════════════════════════════ */
function ExpandableMessage({ text }: { text: string }) {
  const [expanded, setExpanded] = useState(false);
  const isLong = text.length > 180;

  return (
    <div className="relative">
      <p className={`text-[13.5px] text-gray-800 whitespace-pre-line leading-relaxed ${isLong && !expanded ? "msg-truncated" : ""}`}>
        {text}
      </p>
      {isLong && !expanded && (
        <div className="absolute bottom-0 left-0 right-0 h-8 bg-gradient-to-t from-white/95 to-transparent flex items-end justify-center pb-0.5 cursor-pointer"
          onClick={e => { e.stopPropagation(); setExpanded(true); }}>
          <span className="text-[10px] font-bold text-primary-600 bg-white/80 px-2 py-0.5 rounded-full border border-primary-100 backdrop-blur-sm hover:bg-primary-50 transition-colors">
            Show more ↓
          </span>
        </div>
      )}
      {isLong && expanded && (
        <button className="text-[10px] font-bold text-primary-600 mt-1.5 bg-primary-50 px-2 py-0.5 rounded-full border border-primary-100 hover:bg-primary-100 transition-colors"
          onClick={e => { e.stopPropagation(); setExpanded(false); }}>
          Show less ↑
        </button>
      )}
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   #4 — CHAT BUBBLE MESSAGE CARD — full redesign with
        gradient direction stripe, hover actions dock
   ════════════════════════════════════════════════════════════ */
function MessageCard({ msg, onCopy, copied, onPhoneFilter }: {
  msg: Message;
  onCopy: (id: string, text: string) => void;
  copied: boolean;
  onPhoneFilter: (phone: string) => void;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const [visible, setVisible] = useState(false);
  const out = msg.direction === "outgoing";

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) { setVisible(true); observer.unobserve(el); } },
      { threshold: 0.08 }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  const time = new Date(msg.sentAt || msg.createdAt);

  return (
    <div ref={ref}
      className={`msg-card group ${visible ? (out ? "msg-bubble-out" : "msg-bubble-in") : "opacity-0"}`}>

      {/* Direction stripe */}
      <div className={`msg-stripe ${out ? "msg-stripe-out" : "msg-stripe-in"}`} />

      <div className="flex items-start gap-3 px-4 py-3">
        {/* Avatar / direction */}
        <div className={`w-9 h-9 rounded-xl flex items-center justify-center shrink-0 ${
          out ? "bg-gradient-to-br from-primary-100 to-primary-50" : "bg-gradient-to-br from-blue-100 to-blue-50"
        }`}>
          {out
            ? <ArrowUpRight size={15} className="text-primary-600" />
            : <ArrowDownLeft size={15} className="text-blue-600" />
          }
        </div>

        <div className="flex-1 min-w-0">
          {/* Meta row */}
          <div className="flex items-center gap-2 mb-1.5">
            <button onClick={e => { e.stopPropagation(); onPhoneFilter(msg.phone); }}
              className="text-[12px] font-semibold text-dark hover:text-primary-600 transition-colors">
              {msg.phone}
            </button>
            <span className={`text-[10px] font-medium px-1.5 py-0.5 rounded-md ${
              out ? "bg-primary-50 text-primary-600" : "bg-blue-50 text-blue-600"
            }`}>
              {out ? "Outgoing" : "Incoming"}
            </span>
            {out && <DeliveryRing status={msg.status} />}
            <span className="text-[10px] text-gray-400 ml-auto tabular-nums">
              {time.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true })}
            </span>
          </div>

          {/* Message body */}
          <ExpandableMessage text={msg.message} />

          {/* Ticks for outgoing */}
          {out && (
            <div className="flex items-center gap-1 mt-1.5">
              {msg.status === "read" ? <CheckCheck size={13} className="text-blue-500" /> :
               msg.status === "delivered" ? <CheckCheck size={13} className="text-gray-400" /> :
               msg.status === "sent" ? <Check size={13} className="text-gray-400" /> :
               msg.status === "failed" ? <XCircle size={13} className="text-red-400" /> :
               <Clock size={13} className="text-gray-300 animate-pulse-soft" />}
            </div>
          )}
        </div>

        {/* Hover action dock */}
        <div className="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity flex flex-col gap-1 -mt-0.5">
          <button onClick={() => onCopy(msg.id, msg.message)}
            className="msg-action-btn" title="Copy">
            {copied ? <CheckCircle size={12} className="text-emerald-500" /> : <Copy size={12} />}
          </button>
          <a href={`https://wa.me/${msg.phone.replace(/[^0-9]/g, "")}`} target="_blank" rel="noreferrer"
            className="msg-action-btn" title="WhatsApp" onClick={e => e.stopPropagation()}>
            <ExternalLink size={12} />
          </a>
          <a href={`tel:${msg.phone}`} className="msg-action-btn" title="Call" onClick={e => e.stopPropagation()}>
            <PhoneCall size={12} />
          </a>
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   #5 — THREAD CARD — redesigned with activity sparkline,
        gradient avatar, and inline chat preview
   ════════════════════════════════════════════════════════════ */
function ThreadCard({ phone, messages: msgs, onPhoneFilter }: {
  phone: string;
  messages: Message[];
  onPhoneFilter: (phone: string) => void;
}) {
  const [expanded, setExpanded] = useState(false);
  const lastMsg = msgs[0];
  const outCount = msgs.filter(m => m.direction === "outgoing").length;
  const inCount = msgs.filter(m => m.direction === "incoming").length;
  const last5 = msgs.slice(0, 5);

  // Mini sparkline: last 7 days activity
  const spark = useMemo(() => {
    const days = Array(7).fill(0);
    const now = Date.now();
    msgs.forEach(m => {
      const age = Math.floor((now - new Date(m.sentAt || m.createdAt).getTime()) / 86400000);
      if (age < 7) days[6 - age]++;
    });
    const max = Math.max(...days, 1);
    return days.map(d => d / max);
  }, [msgs]);

  return (
    <div className="msg-card overflow-hidden">
      {/* Header */}
      <div className="flex items-center gap-3.5 px-5 py-4 cursor-pointer hover:bg-gray-50/50 transition-colors"
        onClick={() => setExpanded(!expanded)}>
        {/* Gradient avatar */}
        <div className="w-11 h-11 rounded-xl bg-gradient-to-br from-primary-500 to-violet-500 flex items-center justify-center shrink-0 shadow-md shadow-primary-500/15">
          <span className="text-white text-sm font-bold">{phone.slice(-2)}</span>
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-0.5">
            <span className="text-[14px] font-semibold text-dark">{phone}</span>
            <span className="text-[10px] font-bold bg-primary-50 text-primary-700 px-1.5 py-0.5 rounded-md">{msgs.length}</span>
          </div>
          <div className="flex items-center gap-1 text-[11px] text-gray-400">
            {lastMsg.direction === "outgoing" ? <ArrowUpRight size={10} className="text-primary-400" /> : <ArrowDownLeft size={10} className="text-blue-400" />}
            <span className="truncate">{lastMsg.message.slice(0, 50)}{lastMsg.message.length > 50 ? "…" : ""}</span>
          </div>
        </div>

        {/* Mini sparkline */}
        <div className="flex items-end gap-[3px] h-5 shrink-0" title="7-day activity">
          {spark.map((v, i) => (
            <div key={i} className="w-[4px] rounded-full bg-primary-400/60 transition-all"
              style={{ height: `${Math.max(v * 100, 10)}%`, opacity: 0.3 + v * 0.7 }} />
          ))}
        </div>

        {/* Stats */}
        <div className="flex items-center gap-3 shrink-0 text-[11px]">
          <span className="flex items-center gap-1 text-primary-500 font-semibold"><ArrowUpRight size={10} />{outCount}</span>
          <span className="flex items-center gap-1 text-blue-500 font-semibold"><ArrowDownLeft size={10} />{inCount}</span>
          <span className="text-[10px] text-gray-400 tabular-nums w-[55px] text-right">
            {new Date(lastMsg.sentAt || lastMsg.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
          </span>
        </div>

        <ChevronDown size={16} className={`text-gray-300 transition-transform duration-300 shrink-0 ${expanded ? "rotate-180" : ""}`} />
      </div>

      {/* Inline chat preview */}
      {expanded && (
        <div className="border-t border-gray-100 bg-gradient-to-b from-gray-50/80 to-white px-5 py-4 space-y-2 animate-fade-in">
          {last5.map(m => {
            const out = m.direction === "outgoing";
            return (
              <div key={m.id} className={`flex ${out ? "justify-end" : "justify-start"}`}>
                <div className={`max-w-[75%] rounded-2xl px-3.5 py-2 shadow-sm ${
                  out
                    ? "bg-gradient-to-br from-primary-500 to-primary-600 text-white rounded-br-md"
                    : "bg-white text-gray-800 border border-gray-100 rounded-bl-md"
                }`}>
                  <p className="text-[12.5px] leading-relaxed whitespace-pre-line">
                    {m.message.length > 150 ? m.message.slice(0, 150) + "…" : m.message}
                  </p>
                  <div className="flex items-center justify-end gap-1 mt-1">
                    <span className={`text-[9px] ${out ? "text-white/60" : "text-gray-400"}`}>
                      {new Date(m.sentAt || m.createdAt).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true })}
                    </span>
                    {out && (
                      m.status === "read" ? <CheckCheck size={11} className="text-blue-200" /> :
                      m.status === "delivered" ? <CheckCheck size={11} className="text-white/50" /> :
                      <Check size={11} className="text-white/50" />
                    )}
                  </div>
                </div>
              </div>
            );
          })}
          {msgs.length > 5 && (
            <button className="w-full text-center py-1.5 text-[11px] font-semibold text-primary-600 hover:text-primary-500 transition-colors"
              onClick={e => { e.stopPropagation(); onPhoneFilter(phone); }}>
              View all {msgs.length} messages →
            </button>
          )}
        </div>
      )}
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   #6 — DELIVERY RATE RING — big SVG ring for overview
   ════════════════════════════════════════════════════════════ */
function RateRing({ label, value, color, icon: Icon }: {
  label: string; value: number; color: string; icon: React.ElementType;
}) {
  const r = 22; const circ = 2 * Math.PI * r;
  const offset = circ - (value / 100) * circ;
  return (
    <div className="flex flex-col items-center gap-1.5">
      <div className="relative">
        <svg width="56" height="56" className="-rotate-90">
          <circle cx="28" cy="28" r={r} fill="none" stroke="#f0f0f5" strokeWidth="4" />
          <circle cx="28" cy="28" r={r} fill="none" stroke={color} strokeWidth="4"
            strokeLinecap="round" strokeDasharray={circ} strokeDashoffset={offset}
            className="msg-ring-draw" />
        </svg>
        <div className="absolute inset-0 flex items-center justify-center">
          <span className="text-[13px] font-bold text-dark">{value}%</span>
        </div>
      </div>
      <div className="flex items-center gap-1 text-[10px] font-semibold text-gray-500">
        <Icon size={10} style={{ color }} />
        {label}
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   MAIN PAGE
   ════════════════════════════════════════════════════════════ */
export default function MessagesPage() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState("");
  const [dirFilter, setDirFilter] = useState<"all" | "outgoing" | "incoming">("all");
  const [phoneFilter, setPhoneFilter] = useState<string | null>(null);
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const [viewMode, setViewMode] = useState<"timeline" | "threads">("timeline");
  const [refreshing, setRefreshing] = useState(false);
  /* #7 — STATUS FILTER: quick-filter by delivery status */
  const [statusFilter, setStatusFilter] = useState<string | null>(null);
  /* #8 — PREVIEW PANEL: selected message detail */
  const [previewId, setPreviewId] = useState<string | null>(null);

  const fetchMessages = useCallback(() => {
    fetch("/api/messages")
      .then(r => { if (!r.ok) throw new Error("Failed"); return r.json(); })
      .then(setMessages)
      .catch(() => setError("Failed to load messages"))
      .finally(() => { setLoading(false); setRefreshing(false); });
  }, []);

  useEffect(() => { fetchMessages(); }, [fetchMessages]);
  useEffect(() => { const i = setInterval(fetchMessages, 20000); return () => clearInterval(i); }, [fetchMessages]);

  const handleRefresh = () => { setRefreshing(true); fetchMessages(); };

  const copy = (id: string, text: string) => {
    navigator.clipboard.writeText(text); setCopiedId(id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  const handlePhoneFilter = (phone: string) => {
    setPhoneFilter(phoneFilter === phone ? null : phone);
    setViewMode("timeline");
  };

  const filtered = messages.filter(m => {
    if (dirFilter !== "all" && m.direction !== dirFilter) return false;
    if (phoneFilter && m.phone !== phoneFilter) return false;
    if (statusFilter && m.status !== statusFilter) return false;
    if (search && !m.phone.includes(search) && !m.message.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  const outgoing = messages.filter(m => m.direction === "outgoing").length;
  const incoming = messages.filter(m => m.direction === "incoming").length;
  const delivered = messages.filter(m => ["delivered", "read"].includes(m.status)).length;
  const readCount = messages.filter(m => m.status === "read").length;
  const failed = messages.filter(m => m.status === "failed").length;
  const deliveryRate = outgoing > 0 ? Math.round((delivered / outgoing) * 100) : 0;
  const readRate = outgoing > 0 ? Math.round((readCount / outgoing) * 100) : 0;

  /* #9 — UNIQUE CONTACTS count */
  const uniquePhones = useMemo(() => new Set(messages.map(m => m.phone)).size, [messages]);

  /* #10 — RESPONSE RATE: % of contacts that replied */
  const responseRate = useMemo(() => {
    const phonesContacted = new Set(messages.filter(m => m.direction === "outgoing").map(m => m.phone));
    const phonesReplied = new Set(messages.filter(m => m.direction === "incoming").map(m => m.phone));
    if (phonesContacted.size === 0) return 0;
    let replied = 0;
    phonesContacted.forEach(p => { if (phonesReplied.has(p)) replied++; });
    return Math.round((replied / phonesContacted.size) * 100);
  }, [messages]);

  // Group by date for timeline
  const grouped: Record<string, Message[]> = {};
  filtered.forEach(m => {
    const d = new Date(m.sentAt || m.createdAt).toLocaleDateString("en-US", { weekday: "long", month: "short", day: "numeric" });
    (grouped[d] ??= []).push(m);
  });

  // Group by phone for threads
  const threads: Record<string, Message[]> = {};
  filtered.forEach(m => { (threads[m.phone] ??= []).push(m); });
  const sortedThreads = Object.entries(threads).sort((a, b) =>
    new Date(b[1][0].sentAt || b[1][0].createdAt).getTime() - new Date(a[1][0].sentAt || a[1][0].createdAt).getTime()
  );

  const previewMsg = previewId ? messages.find(m => m.id === previewId) : null;

  return (
    <>
      {/* Error toast */}
      {error && (
        <div className="clinera-toast fixed top-5 right-5 z-[9999] bg-red-500 text-white px-5 py-3 rounded-xl shadow-lg text-sm font-semibold animate-slide-up cursor-pointer"
          onClick={() => setError(null)}>
          ❌ {error}
        </div>
      )}

      {/* #8 — PREVIEW PANEL (slide-in drawer) */}
      {previewMsg && (
        <div className="fixed inset-0 z-50 flex justify-end" onClick={() => setPreviewId(null)}>
          <div className="absolute inset-0 bg-black/15 backdrop-blur-[2px]" style={{ animation: "overlay-in 0.2s ease" }} />
          <div className="relative w-full sm:max-w-md bg-white h-full overflow-y-auto shadow-2xl drawer-morph-enter" onClick={e => e.stopPropagation()}>
            <div className="sticky top-0 bg-white/95 backdrop-blur-md z-10 flex items-center justify-between px-5 py-4 border-b border-gray-100">
              <h2 className="font-bold text-sm">Message Detail</h2>
              <button onClick={() => setPreviewId(null)} className="p-1.5 hover:bg-gray-100 rounded-lg text-gray-400"><X size={18} /></button>
            </div>
            <div className="p-5 space-y-5">
              <div className="drawer-section flex items-center gap-3">
                <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${
                  previewMsg.direction === "outgoing" ? "bg-gradient-to-br from-primary-100 to-primary-50" : "bg-gradient-to-br from-blue-100 to-blue-50"
                }`}>
                  {previewMsg.direction === "outgoing" ? <ArrowUpRight size={20} className="text-primary-600" /> : <ArrowDownLeft size={20} className="text-blue-600" />}
                </div>
                <div>
                  <p className="font-bold text-base">{previewMsg.phone}</p>
                  <span className={`text-[10px] font-bold px-2 py-0.5 rounded-md ${
                    previewMsg.direction === "outgoing" ? "bg-primary-50 text-primary-600" : "bg-blue-50 text-blue-600"
                  }`}>{previewMsg.direction === "outgoing" ? "Outgoing" : "Incoming"}</span>
                </div>
              </div>
              <div className="drawer-section">
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-2">Status</p>
                <DeliveryRing status={previewMsg.status} />
              </div>
              <div className="drawer-section">
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-2">Timestamp</p>
                <p className="text-sm text-gray-600">
                  {new Date(previewMsg.sentAt || previewMsg.createdAt).toLocaleString("en-US", {
                    weekday: "long", month: "long", day: "numeric", year: "numeric",
                    hour: "numeric", minute: "2-digit", hour12: true,
                  })}
                </p>
              </div>
              <div className="drawer-section">
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-2">Full Message</p>
                <div className="bg-gray-50 rounded-xl p-4 border border-gray-100">
                  <p className="text-sm text-gray-800 whitespace-pre-line leading-relaxed">{previewMsg.message}</p>
                </div>
              </div>
              <div className="drawer-section flex gap-2">
                <button onClick={() => copy(previewMsg.id, previewMsg.message)} className="btn-secondary flex-1 btn-sm">
                  <Copy size={13} /> Copy
                </button>
                <a href={`https://wa.me/${previewMsg.phone.replace(/[^0-9]/g, "")}`} target="_blank" rel="noreferrer"
                  className="btn-primary flex-1 btn-sm"><Send size={13} /> WhatsApp</a>
              </div>
            </div>
          </div>
        </div>
      )}

      <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-green-500 to-emerald-600 flex items-center justify-center shadow-lg shadow-green-500/20">
              <MessageSquare size={20} className="text-white" />
            </div>
            <div>
              <h1 className="text-xl sm:text-2xl font-bold tracking-tight text-dark">Messages</h1>
              <p className="text-xs sm:text-sm text-muted">{messages.length} messages · {uniquePhones} contacts</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <div className="flex items-center gap-1.5 px-2.5 py-1.5 bg-emerald-50 border border-emerald-100 rounded-xl">
              <div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse-soft" />
              <span className="text-[10px] sm:text-[11px] font-semibold text-emerald-600">Live</span>
            </div>
            <button onClick={handleRefresh} disabled={refreshing}
              className={`p-2 sm:p-2.5 rounded-xl border border-gray-200 text-gray-400 hover:text-primary-600 hover:border-primary-200 hover:bg-primary-50 transition-all ${refreshing ? "animate-spin" : ""}`}>
              <RefreshCw size={15} />
            </button>
          </div>
        </div>

        {/* ── Stats Row + Rate Rings ── */}
        {messages.length > 0 && (
          <div className="flex flex-col lg:flex-row gap-4 items-stretch">
            {/* Stat cards */}
            <div className="flex-1 grid grid-cols-3 sm:grid-cols-5 gap-2 sm:gap-3">
              {[
                { label: "Sent", value: outgoing, color: "text-primary-600", bg: "bg-primary-50", border: "border-primary-100", icon: ArrowUpRight, statusKey: null },
                { label: "Received", value: incoming, color: "text-blue-600", bg: "bg-blue-50", border: "border-blue-100", icon: ArrowDownLeft, statusKey: null },
                { label: "Delivered", value: delivered, color: "text-emerald-600", bg: "bg-emerald-50", border: "border-emerald-100", icon: CheckCheck, statusKey: "delivered" },
                { label: "Read", value: readCount, color: "text-blue-500", bg: "bg-sky-50", border: "border-sky-100", icon: Eye, statusKey: "read" },
                { label: "Failed", value: failed, color: failed > 0 ? "text-red-500" : "text-gray-300", bg: failed > 0 ? "bg-red-50" : "bg-gray-50", border: failed > 0 ? "border-red-100" : "border-gray-100", icon: XCircle, statusKey: "failed" },
              ].map((s, i) => (
                <button key={i}
                  onClick={() => s.statusKey ? setStatusFilter(statusFilter === s.statusKey ? null : s.statusKey) : null}
                  className={`${s.bg} ${s.border} border rounded-2xl p-3.5 flex flex-col items-center gap-1 transition-all hover:scale-[1.03] ${
                    statusFilter === s.statusKey ? "ring-2 ring-primary-400 ring-offset-2" : ""
                  } ${s.statusKey ? "cursor-pointer" : "cursor-default"}`}
                  style={{ animation: `fade-in 0.4s ease both`, animationDelay: `${i * 50}ms` }}>
                  <s.icon size={16} className={s.color} />
                  <p className={`text-xl font-bold ${s.color} leading-none`}>
                    <AnimCounter value={s.value} />
                  </p>
                  <p className="text-[10px] text-muted font-medium">{s.label}</p>
                </button>
              ))}
            </div>

            {/* #6 — Rate rings panel */}
            <div className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-2xl px-5 py-3 flex items-center gap-6 shrink-0 shadow-sm"
              style={{ animation: "fade-in 0.5s ease both", animationDelay: "300ms" }}>
              <RateRing label="Delivery" value={deliveryRate} color="#10b981" icon={TrendingUp} />
              <div className="w-px h-10 bg-gray-100" />
              <RateRing label="Read" value={readRate} color="#3b82f6" icon={Eye} />
              <div className="w-px h-10 bg-gray-100" />
              <RateRing label="Response" value={responseRate} color="#8b5cf6" icon={Activity} />
            </div>
          </div>
        )}

        {/* ── Toolbar: Filters + Search ── */}
        <div className="flex items-center gap-3">
          {/* Direction */}
          <div className="flex gap-1 bg-gray-100/80 rounded-xl p-1">
            {([["all", "All"], ["outgoing", "Sent"], ["incoming", "Received"]] as const).map(([k, l]) => (
              <button key={k} onClick={() => setDirFilter(k)}
                className={`px-4 py-2 rounded-lg text-xs font-semibold transition-all ${
                  dirFilter === k ? "bg-white text-dark shadow-sm" : "text-gray-400 hover:text-gray-600"
                }`}>
                {l}
              </button>
            ))}
          </div>

          {/* View mode */}
          <div className="flex gap-1 bg-gray-100/80 rounded-xl p-1">
            {([["timeline", "Timeline"], ["threads", "Threads"]] as const).map(([k, l]) => (
              <button key={k} onClick={() => setViewMode(k)}
                className={`px-4 py-2 rounded-lg text-xs font-semibold transition-all ${
                  viewMode === k ? "bg-white text-dark shadow-sm" : "text-gray-400 hover:text-gray-600"
                }`}>
                {l}
              </button>
            ))}
          </div>

          {/* Search */}
          <div className="relative flex-1">
            <Search size={14} 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 messages 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>

          {/* Clear all filters */}
          {(phoneFilter || statusFilter || search || dirFilter !== "all") && (
            <button onClick={() => { setPhoneFilter(null); setStatusFilter(null); setSearch(""); setDirFilter("all"); }}
              className="px-3 py-2 rounded-xl text-[11px] font-semibold text-red-500 bg-red-50 hover:bg-red-100 border border-red-100 transition-colors">
              Clear All
            </button>
          )}
        </div>

        {/* ── Active filter chips ── */}
        {(phoneFilter || statusFilter) && (
          <div className="flex items-center gap-2">
            {phoneFilter && (
              <div className="phone-filter-chip bg-primary-50 text-primary-700 border border-primary-200">
                <Phone size={11} /><span>{phoneFilter}</span>
                <button onClick={() => setPhoneFilter(null)} className="ml-0.5 p-0.5 rounded-full hover:bg-primary-200"><X size={10} /></button>
              </div>
            )}
            {statusFilter && (
              <div className="phone-filter-chip bg-amber-50 text-amber-700 border border-amber-200">
                <Zap size={11} /><span className="capitalize">{statusFilter}</span>
                <button onClick={() => setStatusFilter(null)} className="ml-0.5 p-0.5 rounded-full hover:bg-amber-200"><X size={10} /></button>
              </div>
            )}
            <span className="text-[11px] text-gray-400">{filtered.length} result{filtered.length !== 1 ? "s" : ""}</span>
          </div>
        )}

        {/* ── Content ── */}
        {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 messages...</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-green-50 rounded-2xl flex items-center justify-center mb-4 animate-float">
              <MessageSquare size={28} className="text-green-300" />
            </div>
            <h3 className="text-lg font-bold text-dark mb-1">
              {search || phoneFilter || statusFilter ? "No messages found" : "No messages yet"}
            </h3>
            <p className="text-sm text-gray-400 mb-6 max-w-xs">
              {search ? "Try a different search" : "Messages appear here once reminders are sent via WhatsApp"}
            </p>
            {(search || phoneFilter || statusFilter) && (
              <button onClick={() => { setSearch(""); setPhoneFilter(null); setStatusFilter(null); }} className="btn-secondary btn-sm">
                Clear Filters
              </button>
            )}
          </div>
        ) : viewMode === "threads" ? (
          <div className="space-y-3">
            {sortedThreads.map(([phone, msgs], i) => (
              <div key={phone} style={{ animation: `fade-in 0.4s ease both`, animationDelay: `${i * 40}ms` }}>
                <ThreadCard phone={phone} messages={msgs} onPhoneFilter={handlePhoneFilter} />
              </div>
            ))}
          </div>
        ) : (
          <div className="space-y-6">
            {Object.entries(grouped).map(([date, msgs]) => (
              <div key={date}>
                {/* Date separator */}
                <div className="flex items-center gap-3 mb-3 sticky top-0 z-10 py-1.5">
                  <div className="h-px flex-1 bg-gradient-to-r from-transparent via-gray-200 to-transparent" />
                  <span className="text-[11px] font-bold text-gray-400 bg-surface/90 backdrop-blur-sm px-4 py-1 rounded-full border border-gray-100 shadow-sm tracking-wide uppercase">
                    {date}
                  </span>
                  <div className="h-px flex-1 bg-gradient-to-r from-transparent via-gray-200 to-transparent" />
                </div>
                <div className="space-y-2">
                  {msgs.map(msg => (
                    <div key={msg.id} onClick={() => setPreviewId(msg.id)} className="cursor-pointer">
                      <MessageCard
                        msg={msg}
                        onCopy={copy}
                        copied={copiedId === msg.id}
                        onPhoneFilter={handlePhoneFilter}
                      />
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </>
  );
}
