"use client";
import { useEffect, useState, useRef, useMemo, useCallback } from "react";
import PhoneInput from "@/components/PhoneInput";
import {
  Save, Clock, Bell, Eye, EyeOff, ChevronDown, ChevronUp, Check,
  Copy, CheckCircle, Info, Smartphone, Zap, ToggleLeft, ToggleRight,
  AlertTriangle, Undo2, GripVertical, Sparkles, ArrowRight, X,
  MessageSquare, Calendar, Send, Hash, Type, Shield, Search,
  Building2, Phone, Globe, Moon, Pencil,
} from "lucide-react";

interface Template {
  id: string; trigger: string; offsetMinutes: number; message: string; isActive: boolean; sortOrder: number;
}

const TRIGGERS: Record<string, { emoji: string; label: string; desc: string; phase: string; color: string }> = {
  booking_confirmed:       { emoji: "📋", label: "Booking Confirmation", desc: "Sent immediately when booked",            phase: "booking",   color: "#6366f1" },
  "3_days_before":         { emoji: "📅", label: "3 Days Before",       desc: "Prep instructions & reminder",            phase: "pre",       color: "#8b5cf6" },
  "1_day_before":          { emoji: "⏰", label: "1 Day Before",        desc: "Confirmation request + link",             phase: "pre",       color: "#f59e0b" },
  "2_hours_before":        { emoji: "🕐", label: "2 Hours Before",      desc: "Location details & final reminder",       phase: "pre",       color: "#f97316" },
  "30_min_before":         { emoji: "🔔", label: "30 Minutes Before",   desc: "Quick check — on the way?",              phase: "pre",       color: "#ef4444" },
  "1_hour_after_noshow":   { emoji: "😟", label: "1h After No-Show",    desc: "Caring check-in & concern",              phase: "noshow",    color: "#dc2626" },
  "1_day_after_noshow":    { emoji: "📞", label: "1d After No-Show",    desc: "Reschedule offer",                       phase: "noshow",    color: "#9f1239" },
  post_treatment_same_day: { emoji: "💊", label: "Post-Treatment",      desc: "Aftercare instructions same day",         phase: "post",      color: "#059669" },
  post_treatment_3_days:   { emoji: "💬", label: "3 Days After",        desc: "Recovery check-in & feedback",            phase: "post",      color: "#047857" },
  reschedule_followup:     { emoji: "🔄", label: "Reschedule Follow-Up", desc: "48h check if patient rebooked",          phase: "noshow",    color: "#be185d" },
};

const PHASE_META: Record<string, { label: string; color: string; bg: string; border: string; icon: React.ElementType }> = {
  booking: { label: "📋 Booking",  color: "text-primary-700", bg: "bg-primary-50",  border: "border-primary-100", icon: Calendar },
  pre:     { label: "⏳ Pre-Visit", color: "text-amber-700",   bg: "bg-amber-50",    border: "border-amber-100",   icon: Clock },
  noshow:  { label: "❌ No-Show",  color: "text-red-700",     bg: "bg-red-50",      border: "border-red-100",     icon: AlertTriangle },
  post:    { label: "✅ Post-Care", color: "text-emerald-700", bg: "bg-emerald-50",  border: "border-emerald-100", icon: Shield },
};

const VARS = [
  { key: "name", desc: "Patient name", icon: Type },
  { key: "treatment", desc: "Treatment name", icon: Sparkles },
  { key: "clinic", desc: "Clinic name", icon: MessageSquare },
  { key: "date", desc: "Appointment date", icon: Calendar },
  { key: "time", desc: "Appointment time", icon: Clock },
  { key: "prepInstructions", desc: "Prep instructions", icon: Info },
  { key: "aftercareInstructions", desc: "Aftercare", icon: Shield },
  { key: "confirmLink", desc: "Confirm link", icon: Check },
];

const PREVIEW_VARS: Record<string, string> = {
  name: "Sarah", treatment: "Botox — Forehead", clinic: "Glow Clinic",
  date: "Monday, Jan 15", time: "2:00 PM",
  prepInstructions: "Avoid blood thinners 48h before. Come with clean skin.",
  aftercareInstructions: "Don't touch treated area for 4 hours. Avoid exercise 24h.",
  confirmLink: "https://clinera.app/confirm/abc123",
};

/* ════════════════════════════════════════════════════════════
   UI #1 — TIMELINE FLOW: vertical visual timeline
   ════════════════════════════════════════════════════════════ */
function TimelineDot({ color, active, idx }: { color: string; active: boolean; idx: number }) {
  return (
    <div className="flex flex-col items-center shrink-0 relative" style={{ animation: `fade-in 0.4s ease both`, animationDelay: `${idx * 60}ms` }}>
      <div className={`w-4 h-4 rounded-full border-[2.5px] transition-all duration-300 ${
        active ? "scale-110 shadow-md" : "scale-90 opacity-40"
      }`} style={{ borderColor: color, backgroundColor: active ? color : "transparent", boxShadow: active ? `0 0 12px ${color}40` : "none" }} />
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   UI #2 — WHATSAPP PREVIEW: phone frame with typing
   ════════════════════════════════════════════════════════════ */
function WaPreview({ message, trigger }: { message: string; trigger: string }) {
  const [typed, setTyped] = useState("");
  const [phase, setPhase] = useState<"typing" | "done">("typing");

  useEffect(() => {
    setTyped(""); setPhase("typing");
    const t1 = setTimeout(() => {
      setPhase("done");
      let i = 0;
      const iv = setInterval(() => {
        if (i < message.length) { setTyped(message.slice(0, i + 1)); i++; }
        else clearInterval(iv);
      }, 6);
      return () => clearInterval(iv);
    }, 1200);
    return () => clearTimeout(t1);
  }, [message]);

  const cfg = TRIGGERS[trigger];
  const time = new Date().toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true });

  // Highlight variables in rendered text
  const renderText = (text: string) => {
    const parts = text.split(/({{[^}]+}})/g);
    return parts.map((part, i) => {
      if (part.match(/^{{[^}]+}}$/)) {
        const v = part.replace(/[{}]/g, "");
        return <span key={i} className="wa-var-highlight">{PREVIEW_VARS[v] || part}</span>;
      }
      const bold = part.split(/(\*[^*]+\*)/g);
      return bold.map((b, j) => {
        if (b.match(/^\*[^*]+\*$/)) return <strong key={`${i}-${j}`} className="text-white font-bold">{b.replace(/\*/g, "")}</strong>;
        return <span key={`${i}-${j}`}>{b}</span>;
      });
    });
  };

  return (
    <div className="wa-phone-frame">
      <div className="wa-screen">
        <div className="wa-header">
          <div className="w-8 h-8 rounded-full flex items-center justify-center" style={{ backgroundColor: cfg?.color || "#6366f1" }}>
            <span className="text-white text-xs font-bold">{cfg?.emoji || "📨"}</span>
          </div>
          <div className="flex-1">
            <p className="text-white text-sm font-semibold">Glow Clinic</p>
            <p className="text-gray-400 text-[10px]">{phase === "typing" ? "typing…" : "online"}</p>
          </div>
        </div>
        <div className="wa-chat-bg">
          <div className="text-center mb-3">
            <span className="text-[10px] text-gray-500 bg-[#1a2530] px-3 py-1 rounded-lg">{cfg?.label || trigger}</span>
          </div>
          {phase === "typing" ? (
            <div className="wa-typing-dots"><span /><span /><span /></div>
          ) : (
            <div className="wa-bubble">
              <p className="text-[13px] text-white whitespace-pre-line leading-relaxed">{renderText(typed)}</p>
              <div className="flex items-center justify-end gap-1 mt-1">
                <span className="text-[9px] text-gray-300">{time}</span>
                <CheckCircle size={10} className="text-blue-400" />
              </div>
            </div>
          )}
        </div>
        <div className="bg-[#1f2c34] px-3 py-2 flex items-center gap-2">
          <div className="flex-1 bg-[#2a3942] rounded-full px-4 py-2"><span className="text-gray-500 text-xs">Type a message</span></div>
          <div className="w-9 h-9 rounded-full bg-[#00a884] flex items-center justify-center"><Send size={14} className="text-white" /></div>
        </div>
      </div>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   UI #3 — CHAR COUNTER RING: circular character limit
   ════════════════════════════════════════════════════════════ */
function CharRing({ count, max = 1024 }: { count: number; max?: number }) {
  const pct = Math.min(count / max, 1);
  const r = 10; const circ = 2 * Math.PI * r;
  const offset = circ - pct * circ;
  const color = pct > 0.9 ? "#ef4444" : pct > 0.7 ? "#f59e0b" : "#10b981";
  return (
    <div className="flex items-center gap-1.5">
      <svg width="24" height="24" className="-rotate-90">
        <circle cx="12" cy="12" r={r} fill="none" stroke="#f0f0f5" strokeWidth="2.5" />
        <circle cx="12" cy="12" r={r} fill="none" stroke={color} strokeWidth="2.5"
          strokeLinecap="round" strokeDasharray={circ} strokeDashoffset={offset}
          style={{ transition: "stroke-dashoffset 0.3s ease" }} />
      </svg>
      <span className="text-[10px] tabular-nums" style={{ color }}>{count}</span>
    </div>
  );
}

/* ════════════════════════════════════════════════════════════
   MAIN PAGE
   ════════════════════════════════════════════════════════════ */
/* ── Timezone options ── */
const TIMEZONES = [
  "Asia/Riyadh", "Asia/Dubai", "Asia/Kuwait", "Asia/Bahrain", "Asia/Qatar",
  "Asia/Muscat", "Asia/Amman", "Asia/Beirut", "Asia/Damascus", "Asia/Baghdad",
  "Africa/Cairo", "Africa/Casablanca", "Africa/Tripoli", "Africa/Tunis",
  "Europe/Istanbul", "Europe/London", "Europe/Paris", "Europe/Berlin",
  "America/New_York", "America/Chicago", "America/Los_Angeles",
  "Asia/Kuala_Lumpur", "Asia/Singapore", "Asia/Jakarta", "Asia/Karachi",
  "Asia/Kolkata", "Pacific/Auckland", "Australia/Sydney",
];

interface ClinicSettings {
  id: string; name: string; slug: string; email: string; phone: string | null;
  timezone: string; quietHoursStart: number; quietHoursEnd: number;
  wahaStatus: string;
}

export default function SettingsPage() {
  const [templates, setTemplates] = useState<Template[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState<string | null>(null);
  const [editId, setEditId] = useState<string | null>(null);
  const [editText, setEditText] = useState("");
  const [editOriginal, setEditOriginal] = useState("");
  const [preview, setPreview] = useState(false);
  const [openId, setOpenId] = useState<string | null>(null);
  const [copiedVar, setCopiedVar] = useState<string | null>(null);
  const [savedId, setSavedId] = useState<string | null>(null);
  const [waPreviewId, setWaPreviewId] = useState<string | null>(null);
  /* UX #1 — Undo toggle */
  const [undoAction, setUndoAction] = useState<{ id: string; wasActive: boolean } | null>(null);
  /* UX #4 — Bulk toggle */
  const [bulkAction, setBulkAction] = useState<"enableAll" | "disableAll" | null>(null);
  /* UX #7 — Search/filter */
  const [searchTerm, setSearchTerm] = useState("");
  const [phaseFilter, setPhaseFilter] = useState<string | null>(null);
  /* UX #9 — Toast */
  const [toast, setToast] = useState<string | null>(null);

  /* ── Clinic Settings state ── */
  const [clinic, setClinic] = useState<ClinicSettings | null>(null);
  const [clinicEdit, setClinicEdit] = useState(false);
  const [clinicForm, setClinicForm] = useState<Partial<ClinicSettings>>({});
  const [clinicSaving, setClinicSaving] = useState(false);

  const loadClinic = useCallback(() => {
    fetch("/api/clinic").then(r => r.json()).then((data) => {
      if (!data.error) setClinic(data);
    });
  }, []);

  useEffect(() => {
    fetch("/api/reminders").then(r => r.json()).then(setTemplates).finally(() => setLoading(false));
    loadClinic();
  }, [loadClinic]);

  const showToast = (msg: string) => { setToast(msg); setTimeout(() => setToast(null), 3000); };

  /* ── Clinic save ── */
  const saveClinic = async () => {
    if (!clinic) return;
    setClinicSaving(true);
    try {
      const res = await fetch("/api/clinic", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(clinicForm),
      });
      const data = await res.json();
      if (res.ok) {
        setClinic(data);
        setClinicEdit(false);
        setClinicForm({});
        showToast("✅ Clinic settings saved — changes are live everywhere");
      } else {
        showToast(`❌ ${data.error || "Failed to save"}`);
      }
    } catch {
      showToast("❌ Failed to save clinic settings");
    }
    setClinicSaving(false);
  };

  const startClinicEdit = () => {
    if (!clinic) return;
    setClinicForm({
      name: clinic.name,
      phone: clinic.phone || "",
      timezone: clinic.timezone,
      quietHoursStart: clinic.quietHoursStart,
      quietHoursEnd: clinic.quietHoursEnd,
    });
    setClinicEdit(true);
  };

  const formatHour = (h: number) => {
    const ampm = h >= 12 ? "PM" : "AM";
    const h12 = h % 12 || 12;
    return `${h12}:00 ${ampm}`;
  };

  const toggle = async (id: string, active: boolean) => {
    const prev = templates.find(t => t.id === id);
    setSaving(id);
    await fetch(`/api/reminders/${id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ isActive: active }) });
    setTemplates(prev2 => prev2.map(t => t.id === id ? { ...t, isActive: active } : t));
    setSaving(null);
    /* UX #1 — Set undo */
    if (prev) { setUndoAction({ id, wasActive: prev.isActive }); setTimeout(() => setUndoAction(null), 5000); }
    showToast(active ? "Reminder enabled" : "Reminder disabled");
  };

  const handleUndo = async () => {
    if (!undoAction) return;
    await fetch(`/api/reminders/${undoAction.id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ isActive: undoAction.wasActive }) });
    setTemplates(prev => prev.map(t => t.id === undoAction.id ? { ...t, isActive: undoAction.wasActive } : t));
    setUndoAction(null); showToast("Undone");
  };

  /* UX #4 — Bulk toggle all */
  const handleBulk = async (enable: boolean) => {
    setBulkAction(enable ? "enableAll" : "disableAll");
    await Promise.all(templates.map(t =>
      fetch(`/api/reminders/${t.id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ isActive: enable }) })
    ));
    setTemplates(prev => prev.map(t => ({ ...t, isActive: enable })));
    setBulkAction(null);
    showToast(enable ? "All reminders enabled" : "All reminders disabled");
  };

  const startEdit = (t: Template) => {
    setEditId(t.id); setEditText(t.message); setEditOriginal(t.message); setOpenId(t.id);
  };

  const save = async (id: string) => {
    setSaving(id);
    await fetch(`/api/reminders/${id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: editText }) });
    setTemplates(prev => prev.map(t => t.id === id ? { ...t, message: editText } : t));
    setEditId(null); setSaving(null);
    setSavedId(id); setTimeout(() => setSavedId(null), 2500);
    showToast("Template saved!");
  };

  /* UX #3 — Undo edit (revert) */
  const revertEdit = () => { setEditText(editOriginal); };

  const insertVar = (v: string) => {
    if (editId) setEditText(prev => prev + `{{${v}}}`);
    setCopiedVar(v); setTimeout(() => setCopiedVar(null), 1500);
  };

  const renderPreview = (msg: string) => {
    let result = msg;
    for (const [key, value] of Object.entries(PREVIEW_VARS)) result = result.replaceAll(`{{${key}}}`, value);
    return result;
  };

  const activeCount = templates.filter(t => t.isActive).length;

  /* UX #7 — Filter templates */
  const filteredTemplates = useMemo(() => {
    return templates
      .sort((a, b) => a.sortOrder - b.sortOrder)
      .filter(t => {
        if (searchTerm && !TRIGGERS[t.trigger]?.label.toLowerCase().includes(searchTerm.toLowerCase()) && !t.message.toLowerCase().includes(searchTerm.toLowerCase())) return false;
        if (phaseFilter && TRIGGERS[t.trigger]?.phase !== phaseFilter) return false;
        return true;
      });
  }, [templates, searchTerm, phaseFilter]);

  /* UX #8 — Group by phase */
  const groupedByPhase = useMemo(() => {
    const groups: Record<string, Template[]> = {};
    filteredTemplates.forEach(t => {
      const phase = TRIGGERS[t.trigger]?.phase || "other";
      (groups[phase] ??= []).push(t);
    });
    return groups;
  }, [filteredTemplates]);

  /* UI #5 — Coverage score */
  const coverageScore = Math.round((activeCount / templates.length) * 100) || 0;

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

      {/* UX #1 — Undo toast */}
      {undoAction && (
        <div className="fixed bottom-5 left-1/2 -translate-x-1/2 z-[9999] bg-gray-900 text-white px-5 py-3 rounded-xl shadow-2xl flex items-center gap-3 animate-slide-up text-sm">
          <CheckCircle size={14} className="text-emerald-400" /> Toggle updated
          <button onClick={handleUndo} className="flex items-center gap-1 px-3 py-1 bg-white/10 hover:bg-white/20 rounded-lg text-xs font-semibold transition-colors">
            <Undo2 size={12} /> Undo
          </button>
        </div>
      )}

      {/* WA Preview Drawer */}
      {waPreviewId && (
        <div className="fixed inset-0 z-50 flex justify-end" onClick={() => setWaPreviewId(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-sm 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">
              <div className="flex items-center gap-2">
                <Smartphone size={16} className="text-green-500" />
                <h2 className="font-bold text-sm">WhatsApp Preview</h2>
              </div>
              <button onClick={() => setWaPreviewId(null)} className="p-1.5 hover:bg-gray-100 rounded-lg text-gray-400"><X size={18} /></button>
            </div>
            <div className="p-5">
              <WaPreview
                message={renderPreview(templates.find(t => t.id === waPreviewId)?.message || "")}
                trigger={templates.find(t => t.id === waPreviewId)?.trigger || ""}
              />
              <div className="mt-4 p-3 bg-gray-50 rounded-xl border border-gray-100">
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1.5">Raw Template</p>
                <p className="text-[11px] text-gray-600 font-mono whitespace-pre-line leading-relaxed">
                  {templates.find(t => t.id === waPreviewId)?.message || ""}
                </p>
              </div>
            </div>
          </div>
        </div>
      )}

      <div className="space-y-6 animate-fade-in">

        {/* ═══════════════════════════════════════════════════════
            CLINIC SETTINGS SECTION
            ═══════════════════════════════════════════════════════ */}
        {clinic && (
          <div className="card p-6">
            <div className="flex items-center justify-between mb-5">
              <div className="flex items-center gap-3">
                <div className="w-11 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">
                  <Building2 size={20} className="text-white" />
                </div>
                <div>
                  <h2 className="text-lg font-bold tracking-tight text-dark">Clinic Settings</h2>
                  <p className="text-xs text-muted">Changes apply instantly to chatbot, reminders & messages</p>
                </div>
              </div>
              {!clinicEdit ? (
                <button onClick={startClinicEdit}
                  className="px-3 py-2 rounded-xl text-xs font-semibold bg-white border border-gray-200 text-gray-600 hover:border-primary-200 hover:bg-primary-50 transition-all flex items-center gap-1.5">
                  <Pencil size={13} /> Edit
                </button>
              ) : (
                <div className="flex gap-2">
                  <button onClick={() => { setClinicEdit(false); setClinicForm({}); }}
                    className="px-3 py-2 rounded-xl text-xs font-semibold bg-white border border-gray-200 text-gray-500 hover:bg-gray-50 transition-all">
                    Cancel
                  </button>
                  <button onClick={saveClinic} disabled={clinicSaving}
                    className="px-3 py-2 rounded-xl text-xs font-semibold bg-primary-600 text-white hover:bg-primary-700 transition-all flex items-center gap-1.5 disabled:opacity-50">
                    {clinicSaving ? <div className="w-3 h-3 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <Save size={13} />}
                    Save
                  </button>
                </div>
              )}
            </div>

            {!clinicEdit ? (
              /* ── View mode ── */
              <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
                <div className="bg-gray-50 rounded-xl p-4">
                  <div className="flex items-center gap-2 text-xs text-muted mb-1"><Building2 size={12} /> Clinic Name</div>
                  <p className="text-sm font-semibold text-dark">{clinic.name}</p>
                </div>
                <div className="bg-gray-50 rounded-xl p-4">
                  <div className="flex items-center gap-2 text-xs text-muted mb-1"><Phone size={12} /> Phone</div>
                  <p className="text-sm font-semibold text-dark">{clinic.phone || "—"}</p>
                </div>
                <div className="bg-gray-50 rounded-xl p-4">
                  <div className="flex items-center gap-2 text-xs text-muted mb-1"><Globe size={12} /> Timezone</div>
                  <p className="text-sm font-semibold text-dark">{clinic.timezone}</p>
                </div>
                <div className="bg-gray-50 rounded-xl p-4">
                  <div className="flex items-center gap-2 text-xs text-muted mb-1"><Moon size={12} /> Quiet Hours</div>
                  <p className="text-sm font-semibold text-dark">{formatHour(clinic.quietHoursStart)} — {formatHour(clinic.quietHoursEnd)}</p>
                  <p className="text-[10px] text-muted mt-0.5">No messages during this window</p>
                </div>
              </div>
            ) : (
              /* ── Edit mode ── */
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4">
                {/* Clinic Name */}
                <div>
                  <label className="text-xs font-semibold text-gray-600 mb-1.5 flex items-center gap-1.5">
                    <Building2 size={12} /> Clinic Name
                  </label>
                  <input
                    type="text"
                    value={clinicForm.name || ""}
                    onChange={(e) => setClinicForm(prev => ({ ...prev, name: e.target.value }))}
                    className="w-full px-3 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary-400 focus:ring-2 focus:ring-primary-100 outline-none transition-all"
                    placeholder="Your clinic name"
                  />
                  <p className="text-[10px] text-muted mt-1">Used in WhatsApp messages, reminders, and chatbot replies</p>
                </div>

                {/* Phone */}
                <div>
                  <label className="text-xs font-semibold text-gray-600 mb-1.5 flex items-center gap-1.5">
                    <Phone size={12} /> Clinic Phone
                  </label>
                  <PhoneInput
                    value={(clinicForm.phone as string) || ""}
                    onChange={(v) => setClinicForm(prev => ({ ...prev, phone: v }))}
                    variant="dashboard"
                    height="h-[40px]"
                  />
                  <p className="text-[10px] text-muted mt-1">Shown when patients ask for contact info</p>
                </div>

                {/* Timezone */}
                <div>
                  <label className="text-xs font-semibold text-gray-600 mb-1.5 flex items-center gap-1.5">
                    <Globe size={12} /> Timezone
                  </label>
                  <select
                    value={clinicForm.timezone || "Asia/Riyadh"}
                    onChange={(e) => setClinicForm(prev => ({ ...prev, timezone: e.target.value }))}
                    className="w-full px-3 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary-400 focus:ring-2 focus:ring-primary-100 outline-none transition-all bg-white"
                  >
                    {TIMEZONES.map(tz => <option key={tz} value={tz}>{tz.replace(/_/g, " ")}</option>)}
                  </select>
                  <p className="text-[10px] text-muted mt-1">Used for scheduling reminders & formatting dates in messages</p>
                </div>

                {/* Quiet Hours */}
                <div>
                  <label className="text-xs font-semibold text-gray-600 mb-1.5 flex items-center gap-1.5">
                    <Moon size={12} /> Quiet Hours
                  </label>
                  <div className="flex items-center gap-2">
                    <select
                      value={clinicForm.quietHoursStart ?? 22}
                      onChange={(e) => setClinicForm(prev => ({ ...prev, quietHoursStart: parseInt(e.target.value) }))}
                      className="flex-1 px-3 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary-400 outline-none transition-all bg-white"
                    >
                      {Array.from({ length: 24 }, (_, i) => (
                        <option key={i} value={i}>{formatHour(i)}</option>
                      ))}
                    </select>
                    <span className="text-xs text-muted">to</span>
                    <select
                      value={clinicForm.quietHoursEnd ?? 8}
                      onChange={(e) => setClinicForm(prev => ({ ...prev, quietHoursEnd: parseInt(e.target.value) }))}
                      className="flex-1 px-3 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary-400 outline-none transition-all bg-white"
                    >
                      {Array.from({ length: 24 }, (_, i) => (
                        <option key={i} value={i}>{formatHour(i)}</option>
                      ))}
                    </select>
                  </div>
                  <p className="text-[10px] text-muted mt-1">No reminders or bot replies during this window</p>
                </div>
              </div>
            )}

            {/* Live indicator */}
            <div className="mt-4 pt-3 border-t border-gray-100 flex items-center gap-2 text-[11px] text-muted">
              <Zap size={11} className="text-amber-500" />
              <span>Changes are <strong className="text-dark">instant</strong> — chatbot, reminders, and all messages use live data from the database</span>
            </div>
          </div>
        )}

        {/* ── 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-amber-400 to-orange-500 flex items-center justify-center shadow-lg shadow-amber-500/20">
              <Bell size={20} className="text-white" />
            </div>
            <div>
              <h1 className="text-xl sm:text-2xl font-bold tracking-tight text-dark">Reminder Sequence</h1>
              <p className="text-xs sm:text-sm text-muted">{activeCount}/{templates.length} active · WhatsApp automation</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button onClick={() => setPreview(!preview)}
              className={`px-3 py-2 rounded-xl text-xs font-semibold transition-all flex items-center gap-1.5 border ${
                preview ? "bg-primary-600 text-white border-primary-600 shadow-lg shadow-primary-500/20" : "bg-white text-gray-600 border-gray-200 hover:border-primary-200 hover:bg-primary-50"
              }`}>
              {preview ? <EyeOff size={13} /> : <Eye size={13} />}
              {preview ? "Exit" : "Preview"}
            </button>
          </div>
        </div>

        {/* ── UI #5: Coverage + Stats ── */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4">
          {/* Coverage ring */}
          <div className="bg-white/80 border border-gray-100 rounded-2xl p-4 flex items-center gap-4 col-span-1">
            <div className="relative">
              <svg width="56" height="56" className="-rotate-90">
                <circle cx="28" cy="28" r="22" fill="none" stroke="#f0f0f5" strokeWidth="5" />
                <circle cx="28" cy="28" r="22" fill="none"
                  stroke={coverageScore > 80 ? "#10b981" : coverageScore > 50 ? "#f59e0b" : "#ef4444"}
                  strokeWidth="5" strokeLinecap="round"
                  strokeDasharray={2 * Math.PI * 22}
                  strokeDashoffset={2 * Math.PI * 22 - (coverageScore / 100) * 2 * Math.PI * 22}
                  className="msg-ring-draw" />
              </svg>
              <div className="absolute inset-0 flex items-center justify-center">
                <span className="text-sm font-bold text-dark">{coverageScore}%</span>
              </div>
            </div>
            <div>
              <p className="text-sm font-bold text-dark">Coverage</p>
              <p className="text-[10px] text-muted">{activeCount} of {templates.length} active</p>
            </div>
          </div>

          {/* Phase breakdown */}
          {Object.entries(PHASE_META).map(([key, meta], i) => {
            const count = templates.filter(t => TRIGGERS[t.trigger]?.phase === key && t.isActive).length;
            const total = templates.filter(t => TRIGGERS[t.trigger]?.phase === key).length;
            return (
              <button key={key} onClick={() => setPhaseFilter(phaseFilter === key ? null : key)}
                className={`${meta.bg} ${meta.border} border rounded-2xl p-4 flex items-center gap-3 transition-all hover:scale-[1.02] text-left ${
                  phaseFilter === key ? "ring-2 ring-primary-400 ring-offset-2" : ""
                }`}
                style={{ animation: `fade-in 0.4s ease both`, animationDelay: `${(i + 1) * 60}ms` }}>
                <div className={`w-10 h-10 rounded-xl ${meta.bg} flex items-center justify-center`}>
                  <meta.icon size={18} className={meta.color} />
                </div>
                <div>
                  <p className={`text-lg font-bold ${meta.color}`}>{count}/{total}</p>
                  <p className="text-[10px] text-muted font-medium">{meta.label}</p>
                </div>
              </button>
            );
          })}
        </div>

        {/* ── UI #6: Visual journey flow ── */}
        <div className="bg-white/60 backdrop-blur-sm border border-gray-100 rounded-2xl p-4">
          <div className="flex items-center gap-2 mb-3">
            <Zap size={13} className="text-amber-500" />
            <span className="text-[11px] font-bold text-gray-500 uppercase tracking-wider">Patient Journey Flow</span>
          </div>
          <div className="flex items-center gap-0">
            {templates.sort((a, b) => a.sortOrder - b.sortOrder).map((t, i) => {
              const cfg = TRIGGERS[t.trigger];
              if (!cfg) return null;
              return (
                <div key={t.id} className="flex items-center flex-1 min-w-0" style={{ animation: `fade-in 0.3s ease both`, animationDelay: `${i * 50}ms` }}>
                  <div className="flex flex-col items-center gap-1 flex-1">
                    <TimelineDot color={cfg.color} active={t.isActive} idx={i} />
                    <span className={`text-[8px] font-bold text-center leading-tight px-0.5 ${t.isActive ? "text-gray-600" : "text-gray-300 line-through"}`}>
                      {cfg.label.replace(" Before", "").replace(" After", "").replace("Post-", "Post ")}
                    </span>
                  </div>
                  {i < templates.length - 1 && (
                    <div className={`h-[2px] flex-1 -mt-3 rounded-full transition-colors ${
                      t.isActive ? "bg-gradient-to-r from-current to-current" : "bg-gray-100"
                    }`} style={{ color: t.isActive ? cfg.color : undefined }} />
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* ── UX #4: Bulk actions + UX #7: Search ── */}
        <div className="flex items-center gap-3">
          <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={searchTerm} onChange={e => setSearchTerm(e.target.value)}
              placeholder="Search templates..." className="input pl-10 py-2.5 text-sm" />
            {searchTerm && <button onClick={() => setSearchTerm("")} className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-300 hover:text-gray-500"><X size={14} /></button>}
          </div>

          {phaseFilter && (
            <button onClick={() => setPhaseFilter(null)}
              className="px-3 py-2 rounded-xl text-[11px] font-semibold text-primary-600 bg-primary-50 border border-primary-100 hover:bg-primary-100 transition-colors flex items-center gap-1">
              <X size={10} /> {PHASE_META[phaseFilter]?.label}
            </button>
          )}

          <div className="flex gap-1.5 shrink-0">
            <button onClick={() => handleBulk(true)} disabled={bulkAction !== null}
              className="px-3 py-2 rounded-xl text-[11px] font-semibold text-emerald-600 bg-emerald-50 border border-emerald-100 hover:bg-emerald-100 transition-all flex items-center gap-1">
              <ToggleRight size={12} /> Enable All
            </button>
            <button onClick={() => handleBulk(false)} disabled={bulkAction !== null}
              className="px-3 py-2 rounded-xl text-[11px] font-semibold text-gray-500 bg-gray-50 border border-gray-200 hover:bg-gray-100 transition-all flex items-center gap-1">
              <ToggleLeft size={12} /> Disable All
            </button>
          </div>
        </div>

        {/* ── Variables panel ── */}
        {editId && (
          <div className="bg-primary-50/50 border border-primary-100 rounded-2xl p-4 animate-fade-in">
            <div className="flex items-center gap-1.5 mb-2.5">
              <Hash size={12} className="text-primary-500" />
              <span className="text-[11px] font-bold text-primary-600 uppercase tracking-wider">Insert Variable</span>
              <span className="text-[10px] text-primary-400 ml-1">— click to insert at cursor</span>
            </div>
            <div className="flex flex-wrap gap-1.5">
              {VARS.map(v => (
                <button key={v.key} onClick={() => insertVar(v.key)}
                  className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-mono border transition-all ${
                    copiedVar === v.key
                      ? "bg-emerald-50 text-emerald-600 border-emerald-200"
                      : "bg-white text-gray-500 border-gray-200 hover:border-primary-300 hover:bg-primary-50 hover:text-primary-700"
                  }`}>
                  {copiedVar === v.key ? <Check size={10} /> : <v.icon size={10} />}
                  {`{{${v.key}}}`}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* ── Template List — UI #8: grouped by phase ── */}
        {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 templates...</p>
          </div>
        ) : (
          <div className="space-y-5">
            {Object.entries(groupedByPhase).map(([phase, items]) => {
              const meta = PHASE_META[phase] || PHASE_META.booking;
              return (
                <div key={phase}>
                  {/* Phase header */}
                  <div className="flex items-center gap-2 mb-2">
                    <span className={`text-[11px] font-bold uppercase tracking-wider ${meta.color}`}>{meta.label}</span>
                    <div className="h-px flex-1 bg-gray-100" />
                    <span className="text-[10px] text-gray-400">{items.filter(t => t.isActive).length}/{items.length} active</span>
                  </div>

                  <div className="card card-flat overflow-hidden">
                    {items.map((t, idx) => {
                      const cfg = TRIGGERS[t.trigger] || { emoji: "📨", label: t.trigger, desc: "", phase: "other", color: "#6b7294" };
                      const editing = editId === t.id;
                      const open = openId === t.id || editing;
                      const hasUnsavedChanges = editing && editText !== editOriginal;

                      return (
                        <div key={t.id}
                          className={`border-b border-gray-50 last:border-0 transition-all duration-300 ${!t.isActive ? "opacity-40" : ""}`}
                          style={{ animation: `fade-in 0.35s ease both`, animationDelay: `${idx * 40}ms` }}>

                          {/* Row */}
                          <div className="flex items-center gap-3.5 px-5 py-3.5 cursor-pointer hover:bg-gray-50/50 transition-colors group"
                            onClick={() => !editing && setOpenId(open ? null : t.id)}>

                            {/* UI #1: Timeline dot */}
                            <div className="w-3 h-3 rounded-full shrink-0 shadow-sm" style={{ backgroundColor: t.isActive ? cfg.color : "#d1d5db" }} />

                            {/* Emoji */}
                            <span className="text-lg shrink-0">{cfg.emoji}</span>

                            {/* Info */}
                            <div className="flex-1 min-w-0">
                              <div className="flex items-center gap-2">
                                <span className="text-[14px] font-semibold text-dark">{cfg.label}</span>
                                {/* UI #4: Offset badge */}
                                <span className="text-[9px] font-bold px-1.5 py-0.5 rounded-md bg-gray-100 text-gray-500 tabular-nums">
                                  {t.offsetMinutes === 0 ? "⚡ Instant" : t.offsetMinutes > 0 ? `+${Math.round(t.offsetMinutes / 60)}h after` : `${Math.round(Math.abs(t.offsetMinutes) / 60)}h before`}
                                </span>
                                {/* UI #10: Char count badge */}
                                <span className="text-[9px] text-gray-300 tabular-nums">{t.message.length} chars</span>
                                {savedId === t.id && (
                                  <span className="text-[10px] text-emerald-500 font-semibold animate-fade-in flex items-center gap-0.5">
                                    <CheckCircle size={10} /> Saved
                                  </span>
                                )}
                              </div>
                              <p className="text-[11px] text-gray-400 mt-0.5">{cfg.desc}</p>
                            </div>

                            {/* Actions */}
                            <div className="flex items-center gap-2 shrink-0" onClick={e => e.stopPropagation()}>
                              {/* UI #2: WA Preview button */}
                              {!editing && t.isActive && (
                                <button onClick={() => setWaPreviewId(waPreviewId === t.id ? null : t.id)}
                                  className={`px-2 py-1.5 rounded-lg text-[10px] font-semibold transition-all flex items-center gap-1 ${
                                    waPreviewId === t.id ? "bg-green-100 text-green-700" : "text-gray-400 hover:text-green-600 hover:bg-green-50"
                                  }`}>
                                  <Smartphone size={11} /> Preview
                                </button>
                              )}
                              {!editing && (
                                <button onClick={() => startEdit(t)}
                                  className="px-2 py-1.5 rounded-lg text-[10px] font-semibold text-gray-400 hover:text-primary-600 hover:bg-primary-50 transition-all">
                                  Edit
                                </button>
                              )}
                              <button onClick={() => toggle(t.id, !t.isActive)} disabled={saving === t.id}
                                className={`toggle ${t.isActive ? "active" : ""} ${saving === t.id ? "opacity-50" : ""}`} />
                            </div>

                            {!editing && (
                              <ChevronDown size={15} className={`text-gray-300 transition-transform duration-300 shrink-0 ${open ? "rotate-180" : ""}`} />
                            )}
                          </div>

                          {/* Expanded content */}
                          {open && (
                            <div className="px-5 pb-4 animate-fade-in">
                              <div className="ml-[52px]">
                                {editing ? (
                                  <div className="space-y-3">
                                    {/* UI #9: Rich editor */}
                                    <div className="relative">
                                      <textarea value={editText} onChange={e => setEditText(e.target.value)}
                                        className="input font-mono text-xs leading-relaxed !rounded-xl !border-primary-200 focus:!border-primary-400"
                                        rows={Math.max(4, editText.split("\n").length + 1)}
                                        placeholder="Write your reminder template..." />
                                      {/* UX #10: Variable hint overlay */}
                                      {editText.includes("{{") && !editText.includes("}}") && (
                                        <div className="absolute bottom-2 right-2 text-[9px] text-amber-500 bg-amber-50 px-2 py-0.5 rounded-md border border-amber-200">
                                          ⚠️ Close with {"}}"}
                                        </div>
                                      )}
                                    </div>

                                    {/* UI #3: Char counter + actions */}
                                    <div className="flex items-center justify-between">
                                      <div className="flex items-center gap-3">
                                        <CharRing count={editText.length} />
                                        {hasUnsavedChanges && (
                                          <span className="text-[10px] text-amber-500 font-semibold flex items-center gap-1">
                                            <AlertTriangle size={10} /> Unsaved changes
                                          </span>
                                        )}
                                      </div>
                                      <div className="flex gap-2">
                                        {/* UX #3: Revert button */}
                                        {hasUnsavedChanges && (
                                          <button onClick={revertEdit}
                                            className="px-2.5 py-1.5 rounded-lg text-[11px] font-semibold text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition-all flex items-center gap-1">
                                            <Undo2 size={11} /> Revert
                                          </button>
                                        )}
                                        <button onClick={() => { setEditId(null); setOpenId(null); }}
                                          className="px-3 py-1.5 rounded-lg text-[11px] font-semibold text-gray-500 bg-gray-100 hover:bg-gray-200 transition-all">
                                          Cancel
                                        </button>
                                        <button onClick={() => save(t.id)} disabled={saving === t.id || !hasUnsavedChanges}
                                          className="btn-primary btn-sm disabled:opacity-40">
                                          {saving === t.id ? "Saving..." : <><Save size={11} /> Save Template</>}
                                        </button>
                                      </div>
                                    </div>

                                    {/* UX #5: Live side-by-side preview while editing */}
                                    <div className="bg-[#ECE5DD] rounded-xl p-3.5 border border-[#d4cfc4]">
                                      <p className="text-[9px] font-bold text-gray-500 uppercase tracking-wider mb-1.5">💬 Live Preview</p>
                                      <p className="text-[12px] text-gray-800 whitespace-pre-line leading-relaxed">
                                        {renderPreview(editText)}
                                      </p>
                                      <div className="flex items-center justify-end gap-1 mt-1.5">
                                        <span className="text-[9px] text-gray-400">2:14 PM</span>
                                        <CheckCircle size={10} className="text-blue-400" />
                                      </div>
                                    </div>
                                  </div>
                                ) : (
                                  <div className={`rounded-xl p-3.5 border ${
                                    preview ? "bg-[#ECE5DD] border-[#d4cfc4]" : "bg-gray-50/80 border-gray-100"
                                  }`}>
                                    <p className="text-[12.5px] text-gray-700 whitespace-pre-line leading-relaxed">
                                      {preview ? renderPreview(t.message) : t.message}
                                    </p>
                                    {preview && (
                                      <div className="flex items-center justify-end gap-1 mt-1.5">
                                        <span className="text-[9px] text-gray-400">2:14 PM</span>
                                        <CheckCircle size={10} className="text-blue-400" />
                                      </div>
                                    )}
                                  </div>
                                )}
                              </div>
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {/* ── Quiet Hours ── */}
        <div className="bg-white/80 backdrop-blur-sm border border-gray-100 rounded-2xl p-5">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-xl bg-gray-100 flex items-center justify-center">
              <Clock size={18} className="text-gray-500" />
            </div>
            <div>
              <p className="text-sm font-bold text-dark">Quiet Hours</p>
              <p className="text-[11px] text-gray-400">Messages queued during quiet hours are sent at 8:00 AM</p>
            </div>
          </div>
          <div className="flex items-center gap-4 bg-gray-50 rounded-xl p-4 border border-gray-100">
            <div className="text-center">
              <p className="text-xl font-bold text-dark">10 PM</p>
              <p className="text-[9px] text-gray-400 font-medium">START</p>
            </div>
            <div className="flex-1 relative h-3 bg-gray-200 rounded-full overflow-hidden">
              <div className="absolute inset-0 bg-gradient-to-r from-indigo-400 via-violet-500 to-indigo-400 rounded-full opacity-40 animate-gradient" style={{ backgroundSize: "200% auto" }} />
              <div className="absolute top-1/2 -translate-y-1/2 left-0 w-full flex items-center justify-between px-1">
                <div className="w-2 h-2 rounded-full bg-white shadow-sm" />
                <span className="text-[8px] font-bold text-white drop-shadow-sm">🌙 Sleep Mode</span>
                <div className="w-2 h-2 rounded-full bg-white shadow-sm" />
              </div>
            </div>
            <div className="text-center">
              <p className="text-xl font-bold text-dark">8 AM</p>
              <p className="text-[9px] text-gray-400 font-medium">END</p>
            </div>
          </div>
        </div>

      </div>
    </>
  );
}
