"use client";
import { useEffect, useState, useCallback, useRef, useMemo } from "react";
import Link from "next/link";
import {
  Users, Calendar, TrendingUp, MessageSquare, Plus, Smartphone,
  CheckCircle, XCircle, AlertTriangle, Clock, Zap, ArrowUpRight,
  ArrowDownRight, Send, Activity, Bell, ChevronRight, Sparkles,
  Command, Search, Bot, RefreshCw, X,
} from "lucide-react";

/* ── Types ── */
interface DashboardData {
  clinicName: string; wahaStatus: string;
  stats: {
    totalLeads: number; bookedLeads: number; confirmedLeads: number;
    arrivedLeads: number; completedLeads: number; noShowLeads: number;
    cancelledLeads: number; totalAppointments: number; upcomingAppointments: number;
    conversionRate: number; showUpRate: number; confirmationRate: number; noShowRate: number;
    messagesSent: number; messagesDelivered: number; messagesRead: number; messagesFailed: number;
    leadTrend: number; leadsThisWeek: number; appointmentsThisWeek: number; totalRevenue: number;
  };
  todayAppointments: Apt[];
  unconfirmedUpcoming: Apt[];
  recentReminders: Rem[];
  next7Days: Day[];
  treatmentBreakdown: Tx[];
  systemHealth?: { cronStatus: string; pendingReminders: number; failedReminders: number; alerts: { level: string; message: string }[] };
}
interface Apt { id: string; dateTime: string; status: string; lead: { name: string; phone: string }; treatment: { name: string }; }
interface Rem { id: string; status: string; template: { trigger: string }; appointment: { lead: { name: string } }; }
interface Day { date: string; label: string; dayNum: number; count: number; isToday: boolean; }
interface Tx { name: string; count: number; price: number; }
interface FailedReminder {
  id: string;
  failureReason: string | null;
  scheduledFor: string;
  retryCount: number;
  template: { trigger: string };
  appointment: { dateTime: string; lead: { name: string; phone: string } };
}

const SL = (s: string) => s.replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase());
const TE: Record<string, string> = { booking_confirmed:"📋","3_days_before":"📅","1_day_before":"⏰","2_hours_before":"🕐","30_min_before":"🔔","1_hour_after_noshow":"😟","1_day_after_noshow":"📞",post_treatment_same_day:"💊",post_treatment_3_days:"💬" };

/* ══════════════════════════════════════════════════
   UPGRADE #1 — 3D TILT STAT CARD
══════════════════════════════════════════════════ */
function TiltCard({ children, className = "", style = {} }: { children: React.ReactNode; className?: string; style?: React.CSSProperties }) {
  const ref = useRef<HTMLDivElement>(null);
  const [tilt, setTilt] = useState({ x: 0, y: 0, gx: 50, gy: 50 });
  const [hovered, setHovered] = useState(false);

  const onMove = (e: React.MouseEvent) => {
    if (!ref.current) return;
    const { left, top, width, height } = ref.current.getBoundingClientRect();
    const x = ((e.clientY - top) / height - 0.5) * 18;
    const y = -((e.clientX - left) / width - 0.5) * 18;
    const gx = ((e.clientX - left) / width) * 100;
    const gy = ((e.clientY - top) / height) * 100;
    setTilt({ x, y, gx, gy });
  };

  return (
    <div ref={ref}
      onMouseMove={onMove}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => { setHovered(false); setTilt({ x: 0, y: 0, gx: 50, gy: 50 }); }}
      className={`card relative overflow-hidden cursor-default select-none ${className}`}
      style={{
        transform: hovered ? `perspective(600px) rotateX(${tilt.x}deg) rotateY(${tilt.y}deg) translateZ(8px)` : "perspective(600px) rotateX(0) rotateY(0)",
        transition: hovered ? "transform 0.05s ease" : "transform 0.4s cubic-bezier(0.23,1,0.32,1)",
        boxShadow: hovered ? `0 24px 48px #0000001a, 0 0 0 1px #ffffff10` : undefined,
        ...style,
      }}
    >
      {/* Holographic sheen */}
      {hovered && (
        <div className="absolute inset-0 pointer-events-none z-10 rounded-2xl"
          style={{ background: `radial-gradient(circle at ${tilt.gx}% ${tilt.gy}%, rgba(255,255,255,0.12) 0%, transparent 60%)` }} />
      )}
      {children}
    </div>
  );
}

/* ══════════════════════════════════════════════════
   UPGRADE #2 — ANIMATED FLIP COUNTER
══════════════════════════════════════════════════ */
function FlipCounter({ value, suffix = "", prefix = "" }: { value: number; suffix?: string; prefix?: string }) {
  const [display, setDisplay] = useState(0);
  const prev = useRef(0);
  useEffect(() => {
    const from = prev.current; prev.current = value;
    const start = Date.now(); const dur = 1000;
    const tick = () => {
      const p = Math.min((Date.now() - start) / dur, 1);
      const ease = 1 - Math.pow(1 - p, 4);
      setDisplay(Math.round(from + (value - from) * ease));
      if (p < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  }, [value]);

  return (
    <span className="tabular-nums">
      {prefix}{display.toLocaleString()}{suffix}
    </span>
  );
}

/* ══════════════════════════════════════════════════
   UPGRADE #3 — PARTICLE BURST
══════════════════════════════════════════════════ */
type Particle = { id: number; x: number; y: number; vx: number; vy: number; color: string; size: number; life: number };
function ParticleBurst({ trigger }: { trigger: number }) {
  const [particles, setParticles] = useState<Particle[]>([]);
  useEffect(() => {
    if (!trigger) return;
    const cols = ["#10b981","#6366f1","#f59e0b","#ec4899","#06b6d4","#84cc16"];
    setParticles(Array.from({ length: 40 }, (_, i) => ({
      id: Date.now() + i,
      x: 50, y: 30,
      vx: (Math.random() - 0.5) * 14,
      vy: -(Math.random() * 10 + 3),
      color: cols[i % cols.length],
      size: Math.random() * 8 + 4,
      life: 1,
    })));
  }, [trigger]);

  useEffect(() => {
    if (!particles.length) return;
    const id = setInterval(() => {
      setParticles(ps => {
        const next = ps.map(p => ({ ...p, x: p.x + p.vx, y: p.y + p.vy + 0.4, vy: p.vy + 0.4, life: p.life - 0.03 }))
          .filter(p => p.life > 0);
        if (!next.length) clearInterval(id);
        return next;
      });
    }, 16);
    return () => clearInterval(id);
  }, [particles.length]);

  if (!particles.length) return null;
  return (
    <div className="fixed inset-0 pointer-events-none z-50">
      {particles.map(p => (
        <div key={p.id} className="absolute rounded-full"
          style={{ left: `${p.x}%`, top: `${p.y}%`, width: p.size, height: p.size, background: p.color, opacity: p.life, transform: `scale(${p.life})`, transition: "none" }} />
      ))}
    </div>
  );
}

/* ══════════════════════════════════════════════════
   UPGRADE #4 — LIVE ACTIVITY PULSE FEED
══════════════════════════════════════════════════ */
type FeedItem = { id: string; icon: string; text: string; time: string; color: string };
function LiveFeed({ reminders, apts }: { reminders: Rem[]; apts: Apt[] }) {
  const items = useMemo<FeedItem[]>(() => {
    const out: FeedItem[] = [];
    reminders.slice(0, 5).forEach((r, i) => out.push({
      id: `reminder-${i}-${r.appointment.lead.name}`,
      icon: TE[r.template.trigger] || "📨",
      text: `${r.appointment.lead.name} · ${r.template.trigger.replace(/_/g, " ")}`,
      time: "just now",
      color: r.status === "sent" ? "#10b981" : "#ef4444",
    }));
    apts.slice(0, 3).forEach((a, i) => out.push({
      id: `apt-${i}-${a.id}`,
      icon: a.status === "confirmed" ? "✅" : a.status === "completed" ? "🎉" : "📅",
      text: `${a.lead.name} — ${SL(a.status)}`,
      time: new Date(a.dateTime).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
      color: "#6366f1",
    }));
    return out.sort(() => Math.random() - 0.5).slice(0, 6);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [reminders.length, apts.length]);

  const [visible, setVisible] = useState<FeedItem[]>([]);
  useEffect(() => {
    setVisible([]);
    const timers: ReturnType<typeof setTimeout>[] = [];
    items.forEach((item, i) => {
      const t = setTimeout(() => setVisible(v => {
        // prevent duplicates if a stale timer fires
        if (v.some(x => x.id === item.id)) return v;
        return [item, ...v].slice(0, 6);
      }), i * 400);
      timers.push(t);
    });
    return () => timers.forEach(clearTimeout);
  }, [items]);

  return (
    <div className="space-y-2 overflow-hidden">
      {visible.map((item, i) => (
        <div key={item.id}
          className="flex items-center gap-3 px-3 py-2.5 rounded-xl bg-white/50 border border-gray-100 feed-item-enter"
          style={{ animationDelay: `${i * 80}ms` }}>
          <div className="relative flex-shrink-0">
            <span className="text-base">{item.icon}</span>
            <span className="absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full animate-ping"
              style={{ background: item.color }} />
          </div>
          <p className="text-[11px] font-semibold text-gray-700 flex-1 truncate">{item.text}</p>
          <span className="text-[9px] text-gray-400 flex-shrink-0">{item.time}</span>
        </div>
      ))}
    </div>
  );
}

/* ══════════════════════════════════════════════════
   UPGRADE #5 — MORPHING HEALTH ORB
══════════════════════════════════════════════════ */
function HealthOrb({ score, label, connected }: { score: number; label: string; connected: boolean }) {
  const color = score >= 80 ? "#10b981" : score >= 60 ? "#f59e0b" : "#ef4444";
  const glow  = score >= 80 ? "#10b98140" : score >= 60 ? "#f59e0b40" : "#ef444440";
  return (
    <div className="flex flex-col items-center gap-2">
      <div className="relative w-32 h-32">
        {/* Pulsing rings */}
        {[1, 2, 3].map(i => (
          <div key={i} className="absolute inset-0 rounded-full orb-ring"
            style={{ border: `2px solid ${color}`, opacity: 0.3 / i, animationDelay: `${i * 0.4}s`, animationDuration: `${2 + i * 0.5}s` }} />
        ))}
        {/* Main orb */}
        <div className="absolute inset-4 rounded-full orb-blob flex flex-col items-center justify-center"
          style={{ background: `radial-gradient(circle at 35% 35%, ${color}cc, ${color})`, boxShadow: `0 0 40px ${glow}, 0 0 80px ${glow}40, inset 0 2px 8px rgba(255,255,255,0.3)` }}>
          <span className="text-2xl font-black text-white">{score}%</span>
          <span className="text-[9px] text-white/70 font-semibold">health</span>
        </div>
        {/* Connected indicator */}
        {connected && (
          <div className="absolute top-3 right-3 w-4 h-4 rounded-full bg-emerald-400 border-2 border-white shadow-sm status-dot-live" />
        )}
      </div>
      <div className="text-center">
        <p className="text-[12px] font-bold text-gray-700">{label}</p>
        <p className="text-[10px] font-semibold" style={{ color }}>{score >= 80 ? "Excellent" : score >= 60 ? "Good" : "Needs attention"}</p>
      </div>
    </div>
  );
}

/* ══════════════════════════════════════════════════
   UPGRADE #6 — NEON PROGRESS RING
══════════════════════════════════════════════════ */
function NeonRing({ value, color, label, size = 72 }: { value: number; color: string; label: string; size?: number }) {
  const [filled, setFilled] = useState(0);
  const sw = 5; const r = (size - sw * 2) / 2; const c = 2 * Math.PI * r;
  useEffect(() => { const t = setTimeout(() => setFilled(value), 200); return () => clearTimeout(t); }, [value]);

  return (
    <div className="flex flex-col items-center gap-1.5">
      <div className="relative" style={{ width: size, height: size }}>
        <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
          <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="#f1f5f9" strokeWidth={sw} />
          <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={color} strokeWidth={sw}
            strokeDasharray={c} strokeDashoffset={c * (1 - Math.min(filled / 100, 1))}
            strokeLinecap="round"
            style={{ transition: "stroke-dashoffset 1.2s cubic-bezier(0.34,1.56,0.64,1)", filter: `drop-shadow(0 0 6px ${color}80)` }} />
        </svg>
        <div className="absolute inset-0 flex items-center justify-center flex-col">
          <span className="text-[14px] font-black text-gray-800">{value}%</span>
        </div>
      </div>
      <span className="text-[10px] text-gray-500 font-semibold">{label}</span>
    </div>
  );
}

/* ══════════════════════════════════════════════════
   UPGRADE #7 — COMMAND PALETTE (⌘K)
══════════════════════════════════════════════════ */
const CMD_ITEMS = [
  { icon:"📅", label:"Book Appointment",     href:"/appointments", shortcut:"B" },
  { icon:"👤", label:"Add New Lead",         href:"/leads",        shortcut:"L" },
  { icon:"🌳", label:"Open Canvas Builder", href:"/chatbot-canvas",shortcut:"C" },
  { icon:"📊", label:"View Appointments",    href:"/appointments",  shortcut:"A" },
  { icon:"📱", label:"WhatsApp Connect",     href:"/connect",       shortcut:"W" },
  { icon:"🤖", label:"AI Tree Builder",      href:"/admin/ai-tree-builder", shortcut:"T" },
];
function CommandPalette({ open, onClose }: { open: boolean; onClose: () => void }) {
  const [q, setQ] = useState("");
  const filtered = CMD_ITEMS.filter(i => i.label.toLowerCase().includes(q.toLowerCase()));
  useEffect(() => { if (!open) setQ(""); }, [open]);
  useEffect(() => {
    const h = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", h); return () => window.removeEventListener("keydown", h);
  }, [onClose]);

  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[100] flex items-start justify-center pt-24 px-4">
      <div className="absolute inset-0 bg-black/40 backdrop-blur-md" onClick={onClose} />
      <div className="relative w-full max-w-md bg-white/90 backdrop-blur-xl rounded-3xl shadow-2xl border border-white/50 overflow-hidden cmd-enter">
        <div className="flex items-center gap-3 px-5 py-4 border-b border-gray-100">
          <Search size={16} className="text-gray-400 flex-shrink-0" />
          <input autoFocus value={q} onChange={e => setQ(e.target.value)}
            className="flex-1 bg-transparent text-[14px] text-gray-800 placeholder-gray-400 outline-none font-medium"
            placeholder="Search commands, pages, actions…" />
          <kbd className="text-[10px] bg-gray-100 text-gray-500 px-2 py-1 rounded-lg font-mono">ESC</kbd>
        </div>
        <div className="p-2 max-h-80 overflow-y-auto">
          {filtered.length === 0 ? (
            <p className="text-center text-[12px] text-gray-400 py-6">No commands found</p>
          ) : filtered.map(item => (
            <Link key={item.label} href={item.href} onClick={onClose}
              className="flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-indigo-50 transition group cmd-item">
              <span className="text-xl w-8 text-center">{item.icon}</span>
              <span className="flex-1 text-[13px] font-semibold text-gray-700 group-hover:text-indigo-700">{item.label}</span>
              <kbd className="text-[9px] bg-gray-100 group-hover:bg-indigo-100 text-gray-400 group-hover:text-indigo-500 px-2 py-0.5 rounded font-mono">⌘{item.shortcut}</kbd>
            </Link>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ══════════════════════════════════════════════════
   UPGRADE #8 — WHATSAPP RADAR
══════════════════════════════════════════════════ */
function WARadar({ sent, delivered, read }: { sent: number; delivered: number; read: number }) {
  const total = sent || 1;
  const rings = [
    { label: "Sent",      value: sent,      pct: 100,                        color: "#6366f1" },
    { label: "Delivered", value: delivered, pct: Math.round((delivered/total)*100), color: "#10b981" },
    { label: "Read",      value: read,      pct: Math.round((read/total)*100),      color: "#06b6d4" },
  ];
  return (
    <div className="relative flex items-center justify-center" style={{ height: 160 }}>
      {rings.map((ring, i) => {
        const size = 140 - i * 36;
        const delay = i * 0.6;
        return (
          <div key={ring.label} className="absolute rounded-full radar-ring"
            style={{ width: size, height: size, border: `2px solid ${ring.color}30`, boxShadow: `0 0 12px ${ring.color}20`, animationDelay: `${delay}s` }}>
            <div className="absolute inset-0 rounded-full overflow-hidden">
              <div className="absolute inset-0 rounded-full radar-fill"
                style={{ background: `conic-gradient(${ring.color}30 ${ring.pct * 3.6}deg, transparent 0deg)`, animationDelay: `${delay}s` }} />
            </div>
          </div>
        );
      })}
      {/* Sweeping beam */}
      <div className="absolute w-full h-full rounded-full radar-sweep" style={{ background: "conic-gradient(transparent 340deg, #6366f120 350deg, transparent 360deg)" }} />
      {/* Center dot */}
      <div className="relative z-10 flex flex-col items-center">
        <div className="w-8 h-8 rounded-full bg-indigo-600 flex items-center justify-center shadow-lg" style={{ boxShadow: "0 0 20px #6366f160" }}>
          <Smartphone size={14} className="text-white" />
        </div>
      </div>
      {/* Legend */}
      <div className="absolute right-0 top-0 space-y-1.5">
        {rings.map(r => (
          <div key={r.label} className="flex items-center gap-1.5">
            <div className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: r.color }} />
            <span className="text-[9px] font-semibold text-gray-500">{r.label} {r.pct}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ══════════════════════════════════════════════════
   UPGRADE #9 — AI INSIGHT CARDS
══════════════════════════════════════════════════ */
function AIInsights({ s }: { s: DashboardData["stats"] }) {
  const insights = useMemo(() => {
    const out: { icon: string; title: string; body: string; color: string; bg: string }[] = [];
    if (s.noShowRate > 25) out.push({ icon:"🚨", title:"High No-Show Alert", body:`${s.noShowRate}% of patients didn't show up. Enable Smart Retry blocks in Canvas to auto-recover them.`, color:"#dc2626", bg:"#fef2f2" });
    if (s.showUpRate >= 80) out.push({ icon:"🏆", title:"Excellent Attendance!", body:`${s.showUpRate}% show-up rate — your reminders are working. Consider adding post-treatment follow-ups.`, color:"#059669", bg:"#f0fdf4" });
    if (s.messagesRead > 0 && s.messagesSent > 0) {
      const readRate = Math.round((s.messagesRead / s.messagesSent) * 100);
      if (readRate > 70) out.push({ icon:"📈", title:`${readRate}% Message Read Rate`, body:"Patients are reading your messages. Try adding interactive buttons to get replies.", color:"#6366f1", bg:"#eef2ff" });
    }
    if (s.upcomingAppointments > 5) out.push({ icon:"📅", title:`${s.upcomingAppointments} Upcoming`, body:"You have a busy schedule ahead. Make sure reminders are set up for all of them.", color:"#d97706", bg:"#fffbeb" });
    if (s.confirmationRate < 50) out.push({ icon:"⚡", title:"Low Confirmation Rate", body:`Only ${s.confirmationRate}% confirmed. Add a Buttons block in Canvas to make confirming one tap.`, color:"#7c3aed", bg:"#f5f3ff" });
    if (out.length === 0) out.push({ icon:"✨", title:"All Systems Go!", body:"Your clinic is running smoothly. Check the Canvas Builder to level up patient engagement.", color:"#059669", bg:"#f0fdf4" });
    return out.slice(0, 3);
  }, [s]);

  return (
    <div className="space-y-2.5">
      {insights.map((ins, i) => (
        <div key={i} className="flex gap-3 p-3.5 rounded-2xl border insight-card"
          style={{ background: ins.bg, borderColor: ins.color + "30", animationDelay: `${i * 150}ms` }}>
          <span className="text-xl flex-shrink-0 mt-0.5">{ins.icon}</span>
          <div>
            <p className="text-[12px] font-bold mb-0.5" style={{ color: ins.color }}>{ins.title}</p>
            <p className="text-[11px] text-gray-600 leading-relaxed">{ins.body}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

/* ══════════════════════════════════════════════════
   UPGRADE #10 — ANIMATED HEAT CALENDAR
══════════════════════════════════════════════════ */
function HeatCalendar({ days }: { days: Day[] }) {
  const [hover, setHover] = useState<number | null>(null);
  const max = Math.max(...days.map(d => d.count), 1);
  return (
    <div>
      <div className="grid grid-cols-7 gap-1.5">
        {days.map((day, i) => {
          const intensity = day.count / max;
          const bg = day.count === 0 ? "#f8fafc"
            : intensity < 0.33 ? "#dbeafe"
            : intensity < 0.66 ? "#6366f1"
            : "#3730a3";
          const text = intensity >= 0.33 ? "#fff" : "#1e293b";
          return (
            <div key={i} className="relative"
              onMouseEnter={() => setHover(i)}
              onMouseLeave={() => setHover(null)}>
              <div className="rounded-xl p-1.5 text-center cal-cell"
                style={{
                  background: bg, color: text,
                  boxShadow: day.isToday ? "0 0 0 2px #6366f1, 0 0 12px #6366f140" : undefined,
                  transform: hover === i ? "scale(1.15) translateY(-2px)" : undefined,
                  transition: "transform 0.2s cubic-bezier(0.34,1.56,0.64,1), box-shadow 0.2s",
                  animationDelay: `${i * 0.06}s`,
                }}>
                <p className="text-[8px] font-bold opacity-70">{day.label}</p>
                <p className="text-[15px] font-black leading-tight">{day.dayNum}</p>
                <p className="text-[9px] font-semibold opacity-80">{day.count > 0 ? day.count : "·"}</p>
              </div>
              {hover === i && day.count > 0 && (
                <div className="absolute -top-10 left-1/2 -translate-x-1/2 bg-gray-900 text-white text-[9px] font-bold px-2 py-1.5 rounded-xl whitespace-nowrap shadow-xl z-20 cal-tooltip-enter">
                  {day.count} appt{day.count > 1 ? "s" : ""}
                </div>
              )}
            </div>
          );
        })}
      </div>
      <div className="flex items-center gap-1 mt-2 justify-end">
        <span className="text-[8px] text-gray-400">Less</span>
        {["#f8fafc","#dbeafe","#6366f1","#3730a3"].map((c,i) => <div key={i} className="w-3 h-3 rounded-sm" style={{background:c}}/>)}
        <span className="text-[8px] text-gray-400">More</span>
      </div>
    </div>
  );
}

/* ══════════════════════════════════════════════════
   MAIN PAGE
══════════════════════════════════════════════════ */
export default function DashboardPage() {
  const [data, setData]       = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);
  const [now, setNow]         = useState(new Date());
  const [burst, setBurst]     = useState(0);
  const [cmdOpen, setCmdOpen] = useState(false);
  const [statusMap, setStatusMap] = useState<Record<string,string>>({});
  const [failedReminders, setFailedReminders] = useState<FailedReminder[]>([]);
  const [showFailed, setShowFailed] = useState(false);
  const [retrying, setRetrying] = useState(false);
  const [retryResult, setRetryResult] = useState<string | null>(null);

  const load = useCallback(() => {
    const controller = new AbortController();
    // 15-second client-side timeout so the spinner never hangs forever
    const timer = setTimeout(() => controller.abort(), 15_000);

    fetch("/api/dashboard", { signal: controller.signal })
      .then(r => {
        if (r.status === 401) {
          // Session expired — redirect to login
          window.location.href = "/login";
          return null;
        }
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then(d => { if (d) setData(d); })
      .catch(err => {
        if (err.name !== "AbortError") console.error("Dashboard load failed:", err);
      })
      .finally(() => { clearTimeout(timer); setLoading(false); });
  }, []);

  useEffect(() => { load(); }, [load]);
  useEffect(() => { const i = setInterval(() => setNow(new Date()), 60000); return () => clearInterval(i); }, []);

  // ⌘K shortcut
  useEffect(() => {
    const h = (e: KeyboardEvent) => { if ((e.metaKey || e.ctrlKey) && e.key === "k") { e.preventDefault(); setCmdOpen(o => !o); } };
    window.addEventListener("keydown", h); return () => window.removeEventListener("keydown", h);
  }, []);

  const loadFailedReminders = async () => {
    const res = await fetch("/api/reminders/failed");
    if (res.ok) setFailedReminders(await res.json());
  };

  useEffect(() => {
    if (showFailed) loadFailedReminders();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [showFailed]);

  const handleRetryAll = async () => {
    setRetrying(true);
    const res = await fetch("/api/reminders/retry-failed", { method: "POST" });
    if (res.ok) {
      const d = await res.json();
      setRetryResult(`✅ ${d.reset} reminders queued for retry`);
      setFailedReminders([]);
      load();
    }
    setRetrying(false);
  };

  const updateStatus = async (id: string, status: string) => {
    setStatusMap(m => ({ ...m, [id]: status }));
    if (["confirmed","completed"].includes(status)) setBurst(b => b + 1);
    await fetch(`/api/appointments/${id}/status`, { method:"PUT", headers:{"Content-Type":"application/json"}, body:JSON.stringify({ status }) });
    load();
  };

  if (loading) return (
    <div className="flex items-center justify-center h-[70vh] flex-col gap-4">
      <div className="relative w-16 h-16">
        {[0,1,2].map(i => <div key={i} className="absolute inset-0 rounded-full border-2 border-indigo-500/30 loader-ring" style={{animationDelay:`${i*0.2}s`}}/>)}
        <div className="absolute inset-3 rounded-full bg-gradient-to-br from-indigo-500 to-violet-600 flex items-center justify-center animate-pulse">
          <Sparkles size={16} className="text-white" />
        </div>
      </div>
      <p className="text-[13px] font-semibold text-gray-400 animate-pulse">Loading dashboard…</p>
    </div>
  );
  if (!data) return <div className="text-red-500 p-8">Failed to load data</div>;

  const { stats: s, todayAppointments, unconfirmedUpcoming, recentReminders, next7Days, treatmentBreakdown } = data;
  const greeting = now.getHours() < 12 ? "Good morning" : now.getHours() < 18 ? "Good afternoon" : "Good evening";
  const healthScore = Math.round((s.showUpRate * 0.4) + (s.confirmationRate * 0.3) + ((100 - s.noShowRate) * 0.3));

  const STAT_CARDS = [
    { label:"Total Leads",    value:s.totalLeads,           suffix:"",  prefix:"", icon:Users,        grad:"from-indigo-500 to-violet-600", sub:`${s.leadsThisWeek} this week`,  trend:s.leadTrend },
    { label:"Upcoming Appts", value:s.upcomingAppointments, suffix:"",  prefix:"", icon:Calendar,     grad:"from-sky-500 to-blue-600",      sub:`${s.appointmentsThisWeek} this week`, trend:null },
    { label:"Show-up Rate",   value:s.showUpRate,           suffix:"%", prefix:"", icon:TrendingUp,   grad:"from-emerald-500 to-teal-600",  sub:s.showUpRate>=80?"🔥 Excellent":"Needs work", trend:null },
    { label:"Messages Sent",  value:s.messagesSent,         suffix:"",  prefix:"", icon:MessageSquare,grad:"from-rose-500 to-pink-600",     sub:`${s.messagesRead} read`,         trend:null },
  ];

  return (
    <div className="space-y-6 pb-8">
      <ParticleBurst trigger={burst} />
      <CommandPalette open={cmdOpen} onClose={() => setCmdOpen(false)} />

      {/* ── Header ── */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-black text-gray-900 flex items-center gap-2.5">
            {greeting} <span className="wave-hand inline-block">👋</span>
          </h1>
          <p className="text-[13px] text-gray-500 mt-1">
            <span className="font-semibold text-indigo-600">{data.clinicName}</span> ·{" "}
            {now.toLocaleDateString("en-US", { weekday:"long", month:"long", day:"numeric" })}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={() => setCmdOpen(true)}
            className="flex items-center gap-2 px-3 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 transition text-[12px] font-semibold text-gray-500 border border-gray-200">
            <Command size={13} /><span className="hidden sm:inline">Quick Actions</span>
            <kbd className="text-[10px] bg-white px-1.5 py-0.5 rounded-md font-mono border border-gray-200">⌘K</kbd>
          </button>
          <Link href="/leads" className="btn-secondary btn-sm text-xs"><Users size={13} /> Lead</Link>
          <Link href="/appointments" className="btn-primary btn-sm text-xs"><Plus size={13} /> Book</Link>
        </div>
      </div>

      {/* ── Alerts ── */}
      {data.systemHealth?.alerts && data.systemHealth.alerts.length > 0 && (
        <div className="space-y-2">
          {data.systemHealth.alerts.map((a, i) => (
            <div key={i} className={`flex items-center gap-3 px-4 py-3 rounded-2xl border text-[13px] font-semibold alert-slide-in ${a.level==="critical"?"bg-red-50 border-red-200 text-red-700":a.level==="warning"?"bg-amber-50 border-amber-200 text-amber-700":"bg-blue-50 border-blue-200 text-blue-700"}`}>
              {a.level==="critical"?<XCircle size={15} className="shrink-0"/>:<AlertTriangle size={15} className="shrink-0"/>}
              <span className="flex-1">{a.message}</span>
            </div>
          ))}
        </div>
      )}

      {/* ── Failed Reminders Banner ── */}
      {(data.systemHealth?.failedReminders ?? 0) > 0 && (
        <div className="rounded-2xl border border-red-100 bg-red-50 p-4 flex items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-xl bg-red-100 flex items-center justify-center shrink-0">
              <AlertTriangle size={18} className="text-red-500" />
            </div>
            <div>
              <p className="font-bold text-sm text-red-700">
                {data.systemHealth!.failedReminders} reminder{data.systemHealth!.failedReminders !== 1 ? "s" : ""} permanently failed
              </p>
              <p className="text-xs text-red-500 mt-0.5">
                These exhausted all 3 retries — usually caused by WhatsApp being disconnected
              </p>
            </div>
          </div>
          <button
            onClick={() => { setShowFailed(true); loadFailedReminders(); }}
            className="shrink-0 px-4 py-2 text-xs font-bold rounded-xl bg-red-600 hover:bg-red-700 text-white transition-colors flex items-center gap-2"
          >
            <RefreshCw size={13} /> View &amp; Retry
          </button>
        </div>
      )}

      {/* ── Failed Reminders Panel ── */}
      {showFailed && (
        <div className="card p-5 animate-fade-in border border-red-100">
          <div className="flex items-center justify-between mb-4">
            <div>
              <h3 className="font-bold text-base">Failed Reminders</h3>
              <p className="text-xs text-muted mt-0.5">Reminders that exhausted all retries</p>
            </div>
            <div className="flex items-center gap-2">
              {retryResult && <span className="text-xs text-emerald-600 font-semibold">{retryResult}</span>}
              <button
                onClick={handleRetryAll}
                disabled={retrying || failedReminders.length === 0}
                className="px-4 py-2 text-xs font-bold rounded-xl bg-emerald-600 hover:bg-emerald-700 disabled:opacity-50 text-white transition-colors flex items-center gap-2"
              >
                <RefreshCw size={13} className={retrying ? "animate-spin" : ""} />
                {retrying ? "Retrying..." : `Retry All (${failedReminders.length})`}
              </button>
              <button onClick={() => { setShowFailed(false); setRetryResult(null); }}
                className="p-2 hover:bg-gray-100 rounded-lg text-gray-400">
                <X size={16} />
              </button>
            </div>
          </div>
          {failedReminders.length === 0 ? (
            <div className="text-center py-8 text-sm text-muted">
              {retryResult ? "All reminders queued for retry ✅" : "No failed reminders"}
            </div>
          ) : (
            <div className="space-y-2">
              {failedReminders.map((r, i) => (
                <div key={r.id} className="flex items-center gap-3 p-3 rounded-xl bg-gray-50 border border-gray-100 text-sm"
                  style={{ animation: `fade-in 0.3s ease both`, animationDelay: `${i * 30}ms` }}>
                  <div className="w-8 h-8 rounded-lg bg-red-50 flex items-center justify-center shrink-0">
                    <span className="text-base">{TE[r.template.trigger] || "📨"}</span>
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="font-semibold text-dark truncate">{r.appointment.lead.name}</p>
                    <p className="text-xs text-muted truncate">
                      {r.template.trigger.replace(/_/g, " ")} · {r.appointment.lead.phone}
                    </p>
                  </div>
                  <div className="text-right shrink-0">
                    <p className="text-xs text-red-500 font-medium">{r.failureReason || "Unknown error"}</p>
                    <p className="text-[11px] text-muted">
                      {new Date(r.scheduledFor).toLocaleDateString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* ══ UPGRADE #1 + #2 — 3D TILT + FLIP COUNTER STAT CARDS ══ */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {STAT_CARDS.map((c, i) => (
          <TiltCard key={i} className="p-5" style={{ animationDelay: `${i * 80}ms` }}>
            {/* Gradient orb background */}
            <div className={`absolute -top-8 -right-8 w-24 h-24 rounded-full bg-gradient-to-br ${c.grad} opacity-10 blur-xl group-hover:opacity-20 transition-opacity duration-500`} />
            <div className="relative z-10">
              <div className={`w-10 h-10 rounded-2xl bg-gradient-to-br ${c.grad} flex items-center justify-center mb-3 shadow-lg`}>
                <c.icon size={17} className="text-white" />
              </div>
              <div className="text-2xl font-black text-gray-900 mb-0.5">
                <FlipCounter value={c.value} suffix={c.suffix} prefix={c.prefix} />
              </div>
              <p className="text-[11px] font-bold text-gray-500">{c.label}</p>
              <div className="flex items-center gap-1.5 mt-2">
                {c.trend !== null && c.trend !== 0 && (
                  <span className={`flex items-center gap-0.5 text-[10px] font-black px-1.5 py-0.5 rounded-full ${c.trend > 0 ? "bg-emerald-100 text-emerald-600" : "bg-red-100 text-red-500"}`}>
                    {c.trend > 0 ? <ArrowUpRight size={10} /> : <ArrowDownRight size={10} />}{Math.abs(c.trend)}%
                  </span>
                )}
                <span className="text-[10px] text-gray-400">{c.sub}</span>
              </div>
            </div>
          </TiltCard>
        ))}
      </div>

      {/* ══ ROW 2 — Orb + Insights + Rings ══ */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">

        {/* UPGRADE #5 — Health Orb */}
        <div className="card p-6 flex flex-col items-center justify-center gap-4">
          <div className="flex items-center gap-2 self-start w-full">
            <div className="w-7 h-7 rounded-lg bg-violet-100 flex items-center justify-center"><Activity size={14} className="text-violet-600"/></div>
            <p className="text-[13px] font-bold text-gray-800">Clinic Health</p>
            <span className={`ml-auto text-[10px] font-bold px-2 py-0.5 rounded-full ${data.wahaStatus==="connected"?"bg-emerald-100 text-emerald-600":"bg-red-100 text-red-500"}`}>
              WA {data.wahaStatus==="connected"?"Live":"Offline"}
            </span>
          </div>
          <HealthOrb score={healthScore} label={data.clinicName} connected={data.wahaStatus==="connected"} />
          <div className="grid grid-cols-3 gap-2 w-full">
            {[
              {label:"Leads",     value:s.totalLeads,          color:"#6366f1"},
              {label:"Today",     value:todayAppointments.length, color:"#f59e0b"},
              {label:"Pending",   value:s.upcomingAppointments, color:"#10b981"},
            ].map(m => (
              <div key={m.label} className="text-center p-2 rounded-xl bg-gray-50 border border-gray-100">
                <p className="text-[15px] font-black" style={{color:m.color}}>{m.value}</p>
                <p className="text-[9px] text-gray-400 font-semibold">{m.label}</p>
              </div>
            ))}
          </div>
        </div>

        {/* UPGRADE #9 — AI Insights */}
        <div className="card p-6">
          <div className="flex items-center gap-2 mb-4">
            <div className="w-7 h-7 rounded-lg bg-gradient-to-br from-violet-500 to-fuchsia-600 flex items-center justify-center"><Bot size={13} className="text-white"/></div>
            <p className="text-[13px] font-bold text-gray-800">AI Insights</p>
            <span className="ml-auto text-[9px] font-black text-violet-500 bg-violet-50 px-2 py-0.5 rounded-full border border-violet-100 animate-pulse">LIVE</span>
          </div>
          <AIInsights s={s} />
          <Link href="/chatbot-canvas"
            className="mt-4 w-full flex items-center justify-center gap-2 py-2.5 rounded-xl text-[12px] font-bold text-white transition hover:opacity-90"
            style={{background:"linear-gradient(135deg,#7c3aed,#ec4899)"}}>
            <Sparkles size={13}/> Open Canvas Builder
          </Link>
        </div>

        {/* UPGRADE #6 — Neon Performance Rings */}
        <div className="card p-6">
          <div className="flex items-center gap-2 mb-5">
            <div className="w-7 h-7 rounded-lg bg-emerald-100 flex items-center justify-center"><TrendingUp size={14} className="text-emerald-600"/></div>
            <p className="text-[13px] font-bold text-gray-800">Performance Rings</p>
          </div>
          <div className="grid grid-cols-2 gap-5">
            {[
              {v:s.conversionRate,   color:"#6366f1", label:"Conversion"},
              {v:s.showUpRate,       color:"#10b981", label:"Show-up"},
              {v:s.confirmationRate, color:"#f59e0b", label:"Confirmed"},
              {v:100-s.noShowRate,   color:s.noShowRate>20?"#ef4444":"#10b981", label:"Attendance"},
            ].map((r,i) => <NeonRing key={i} value={r.v} color={r.color} label={r.label} />)}
          </div>
        </div>
      </div>

      {/* ══ ROW 3 — Pipeline ══ */}
      <div className="card p-6">
        <div className="flex items-center justify-between mb-5">
          <div className="flex items-center gap-2.5">
            <div className="w-8 h-8 rounded-xl bg-indigo-100 flex items-center justify-center"><Activity size={15} className="text-indigo-600"/></div>
            <div><p className="text-[13px] font-bold text-gray-800">Conversion Pipeline</p><p className="text-[10px] text-gray-400">Lead → Patient journey</p></div>
          </div>
          <Link href="/leads" className="text-[11px] text-indigo-600 font-bold hover:text-indigo-500 flex items-center gap-1">View all <ChevronRight size={12}/></Link>
        </div>
        <div className="flex items-stretch gap-1 overflow-x-auto pb-1">
          {[
            {label:"Leads",     count:s.totalLeads,       color:"#6366f1", bg:"#eef2ff"},
            {label:"Booked",    count:s.bookedLeads+s.confirmedLeads+s.arrivedLeads+s.completedLeads, color:"#0284c7", bg:"#e0f2fe"},
            {label:"Confirmed", count:s.confirmedLeads+s.arrivedLeads+s.completedLeads, color:"#059669", bg:"#d1fae5"},
            {label:"Showed Up", count:s.arrivedLeads+s.completedLeads, color:"#d97706", bg:"#fef3c7"},
            {label:"Completed", count:s.completedLeads,  color:"#7c3aed", bg:"#ede9fe"},
          ].map((stage, i, arr) => {
            const pct = s.totalLeads > 0 ? Math.round((stage.count/s.totalLeads)*100) : 0;
            return (
              <div key={i} className="flex items-center flex-1 min-w-0">
                <div className="flex-1 rounded-2xl py-5 px-2 text-center pipeline-stage-enter border"
                  style={{background:stage.bg, borderColor:stage.color+"30", animationDelay:`${i*100}ms`}}>
                  <p className="text-[22px] font-black" style={{color:stage.color}}><FlipCounter value={stage.count}/></p>
                  <p className="text-[10px] font-bold text-gray-500 mt-1">{stage.label}</p>
                  {i > 0 && <p className="text-[9px] font-semibold mt-0.5" style={{color:stage.color}}>{pct}%</p>}
                </div>
                {i < arr.length - 1 && (
                  <div className="w-5 flex items-center justify-center flex-shrink-0">
                    <ChevronRight size={12} className="text-gray-300"/>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* ══ ROW 4 — Schedule + Feed ══ */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">

        {/* Today's Schedule */}
        <div className="lg:col-span-2 card p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2.5">
              <div className="w-8 h-8 rounded-xl bg-amber-100 flex items-center justify-center"><Clock size={15} className="text-amber-600"/></div>
              <div><p className="text-[13px] font-bold text-gray-800">Today&apos;s Schedule</p><p className="text-[10px] text-gray-400">{todayAppointments.length} appointments</p></div>
            </div>
            <Link href="/appointments" className="text-[11px] text-indigo-600 font-bold hover:text-indigo-500">All →</Link>
          </div>
          {todayAppointments.length === 0 ? (
            <div className="text-center py-12 text-gray-400">
              <div className="text-5xl mb-3 animate-bounce">📅</div>
              <p className="text-[13px] font-semibold">No appointments today</p>
              <Link href="/appointments" className="text-[11px] text-indigo-600 font-bold mt-2 inline-block">Book one →</Link>
            </div>
          ) : (
            <div className="space-y-2">
              {todayAppointments.map((apt, i) => {
                const dt = new Date(apt.dateTime);
                const past = dt < now;
                const next = !past && (i === 0 || new Date(todayAppointments[i-1].dateTime) < now);
                const status = statusMap[apt.id] || apt.status;
                const statusColors: Record<string,string> = { confirmed:"#059669", completed:"#7c3aed", arrived:"#0284c7", no_show:"#dc2626", scheduled:"#6366f1" };
                return (
                  <div key={apt.id}
                    className={`flex items-center gap-3 px-4 py-3 rounded-2xl border transition-all apt-row-enter ${next?"border-indigo-200 bg-indigo-50/50 shadow-sm":past?"opacity-40 border-gray-100":"border-gray-100 hover:border-gray-200 hover:bg-gray-50/50"}`}
                    style={{ animationDelay: `${i * 60}ms` }}>
                    <div className="text-center w-14 flex-shrink-0">
                      <p className="text-[13px] font-black text-gray-700">{dt.toLocaleTimeString([],{hour:"numeric",minute:"2-digit",hour12:true})}</p>
                      {next && <p className="text-[9px] font-black text-indigo-500 animate-pulse">NEXT</p>}
                    </div>
                    <div className="w-2.5 h-2.5 rounded-full flex-shrink-0" style={{background: statusColors[status] ?? "#9ca3af"}} />
                    <div className="flex-1 min-w-0">
                      <p className="text-[13px] font-bold text-gray-800 truncate">{apt.lead.name}</p>
                      <p className="text-[10px] text-gray-400">{apt.treatment.name}</p>
                    </div>
                    <span className="text-[10px] font-bold px-2.5 py-1 rounded-full flex-shrink-0"
                      style={{background:(statusColors[status]??"#9ca3af")+"18", color:statusColors[status]??"#9ca3af"}}>
                      {SL(status)}
                    </span>
                    <div className="flex gap-1.5 flex-shrink-0">
                      {status==="scheduled"  && <button onClick={()=>updateStatus(apt.id,"confirmed")}  className="text-[10px] font-bold px-2.5 py-1.5 rounded-xl bg-emerald-500 text-white hover:bg-emerald-600 transition active:scale-95">Confirm</button>}
                      {status==="confirmed"  && <button onClick={()=>updateStatus(apt.id,"arrived")}   className="text-[10px] font-bold px-2.5 py-1.5 rounded-xl bg-blue-500 text-white hover:bg-blue-600 transition active:scale-95">Arrived</button>}
                      {status==="arrived"    && <button onClick={()=>updateStatus(apt.id,"completed")} className="text-[10px] font-bold px-2.5 py-1.5 rounded-xl bg-violet-500 text-white hover:bg-violet-600 transition active:scale-95">Done ✓</button>}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* UPGRADE #4 — Live Feed */}
        <div className="card p-6">
          <div className="flex items-center gap-2.5 mb-4">
            <div className="w-7 h-7 rounded-xl bg-pink-100 flex items-center justify-center"><Zap size={13} className="text-pink-600"/></div>
            <p className="text-[13px] font-bold text-gray-800">Live Activity</p>
            <span className="ml-auto flex items-center gap-1 text-[9px] font-black text-emerald-600">
              <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-ping"/>LIVE
            </span>
          </div>
          <LiveFeed reminders={recentReminders} apts={todayAppointments} />
        </div>
      </div>

      {/* ══ ROW 5 — Radar + Calendar + Treatments ══ */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">

        {/* UPGRADE #8 — WA Radar */}
        <div className="card p-6">
          <div className="flex items-center gap-2.5 mb-2">
            <div className="w-7 h-7 rounded-xl bg-emerald-100 flex items-center justify-center"><Smartphone size={13} className="text-emerald-600"/></div>
            <p className="text-[13px] font-bold text-gray-800">WhatsApp Radar</p>
            <span className={`ml-auto text-[10px] font-bold px-2 py-0.5 rounded-full ${data.wahaStatus==="connected"?"bg-emerald-100 text-emerald-700":"bg-red-100 text-red-600"}`}>
              {data.wahaStatus==="connected"?"● Live":"○ Offline"}
            </span>
          </div>
          <WARadar sent={s.messagesSent} delivered={s.messagesDelivered} read={s.messagesRead} />
          {data.wahaStatus !== "connected" && (
            <Link href="/connect" className="mt-3 w-full flex items-center justify-center gap-1.5 py-2 rounded-xl bg-red-500 text-white text-[11px] font-bold hover:bg-red-600 transition">Connect WhatsApp →</Link>
          )}
        </div>

        {/* UPGRADE #10 — Heat Calendar */}
        <div className="card p-6">
          <div className="flex items-center gap-2.5 mb-4">
            <div className="w-7 h-7 rounded-xl bg-indigo-100 flex items-center justify-center"><Calendar size={13} className="text-indigo-600"/></div>
            <p className="text-[13px] font-bold text-gray-800">Next 7 Days</p>
          </div>
          <HeatCalendar days={next7Days} />
        </div>

        {/* Treatments */}
        <div className="card p-6">
          <div className="flex items-center gap-2.5 mb-4">
            <div className="w-7 h-7 rounded-xl bg-rose-100 flex items-center justify-center"><TrendingUp size={13} className="text-rose-600"/></div>
            <p className="text-[13px] font-bold text-gray-800">Treatments</p>
          </div>
          {s.totalRevenue > 0 && (
            <div className="rounded-2xl p-3.5 mb-4 bg-gradient-to-br from-indigo-600 to-violet-700">
              <p className="text-[10px] text-indigo-200 font-semibold uppercase tracking-wider">Revenue</p>
              <p className="text-2xl font-black text-white mt-0.5"><FlipCounter value={s.totalRevenue} prefix="$"/></p>
            </div>
          )}
          <div className="space-y-3">
            {treatmentBreakdown.slice(0, 5).map((t, i) => {
              const pct = treatmentBreakdown[0]?.count > 0 ? (t.count / treatmentBreakdown[0].count) * 100 : 0;
              return (
                <div key={i}>
                  <div className="flex justify-between mb-1">
                    <span className="text-[12px] font-semibold text-gray-700 truncate">{t.name}</span>
                    <span className="text-[11px] text-gray-400 flex-shrink-0 ml-2">{t.count}</span>
                  </div>
                  <div className="h-1.5 bg-gray-100 rounded-full overflow-hidden">
                    <div className="h-full rounded-full treatment-bar"
                      style={{ width:`${pct}%`, background:`linear-gradient(90deg,#6366f1,#8b5cf6)`, animationDelay:`${i*80}ms` }}/>
                  </div>
                </div>
              );
            })}
            {treatmentBreakdown.length === 0 && <p className="text-[12px] text-gray-400 text-center py-4">No treatments yet</p>}
          </div>
        </div>
      </div>

      {/* ══ Unconfirmed Alerts ══ */}
      {unconfirmedUpcoming.length > 0 && (
        <div className="card p-6">
          <div className="flex items-center gap-2.5 mb-4">
            <div className="w-7 h-7 rounded-xl bg-amber-100 flex items-center justify-center"><Bell size={13} className="text-amber-600"/></div>
            <p className="text-[13px] font-bold text-gray-800">Needs Confirmation</p>
            <span className="ml-auto text-[10px] font-black px-2 py-0.5 rounded-full bg-amber-100 text-amber-700">{unconfirmedUpcoming.length}</span>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
            {unconfirmedUpcoming.slice(0, 6).map(apt => (
              <div key={apt.id} className="flex items-center gap-3 p-3 rounded-xl bg-amber-50 border border-amber-100">
                <div className="w-8 h-8 rounded-xl bg-amber-200 flex items-center justify-center text-sm font-black text-amber-700 flex-shrink-0">
                  {apt.lead.name[0]}
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-[12px] font-bold truncate">{apt.lead.name}</p>
                  <p className="text-[10px] text-amber-600">{new Date(apt.dateTime).toLocaleDateString([],{month:"short",day:"numeric"})}</p>
                </div>
                <button onClick={() => updateStatus(apt.id, "confirmed")}
                  className="text-[10px] font-bold px-2 py-1.5 rounded-lg bg-amber-500 text-white hover:bg-amber-600 transition active:scale-95 flex-shrink-0">
                  Confirm
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ══ Onboarding (only if new) ══ */}
      {s.totalLeads === 0 && (
        <div className="rounded-3xl p-7 relative overflow-hidden" style={{background:"linear-gradient(135deg,#4f46e5,#7c3aed,#ec4899)"}}>
          <div className="absolute inset-0 opacity-20" style={{backgroundImage:"radial-gradient(circle at 20% 50%,#fff 1px,transparent 1px),radial-gradient(circle at 80% 20%,#fff 1px,transparent 1px)",backgroundSize:"48px 48px"}}/>
          <div className="relative flex items-start gap-5">
            <div className="w-12 h-12 rounded-2xl bg-white/20 flex items-center justify-center flex-shrink-0"><Zap size={22} className="text-white"/></div>
            <div className="flex-1">
              <h3 className="text-lg font-black text-white mb-1">Get Started in 3 Steps</h3>
              <p className="text-[13px] text-white/60 mb-5">5 minutes to automatic WhatsApp patient reminders</p>
              <div className="grid grid-cols-3 gap-3">
                {[{n:1,t:"Add Treatments",d:"Your clinic services",h:"/treatments"},{n:2,t:"Connect WhatsApp",d:"Scan QR code",h:"/connect",done:data.wahaStatus==="connected"},{n:3,t:"Book Appointment",d:"Reminders auto-fire",h:"/appointments"}].map((step:any) => (
                  <Link key={step.n} href={step.h} className={`p-4 rounded-2xl border transition hover:scale-[1.03] ${step.done?"bg-white/20 border-white/30":"bg-white/10 border-white/15 hover:bg-white/15"}`}>
                    <div className={`w-6 h-6 rounded-full flex items-center justify-center text-[11px] font-black mb-2 ${step.done?"bg-emerald-400 text-white":"bg-white/20 text-white"}`}>{step.done?"✓":step.n}</div>
                    <p className="text-[13px] font-bold text-white">{step.t}</p>
                    <p className="text-[10px] text-white/50">{step.d}</p>
                  </Link>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
