"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  FileText,
  Mail,
  CheckSquare,
  Calendar,
  Search,
  Plus,
  Eye,
  Briefcase,
  Copy,
  CheckCircle2,
  AlertCircle,
  X,
  ShieldCheck,
  Send,
  Pencil,
  Trash2,
  Save,
  GripVertical,
  ChevronUp,
  ChevronDown,
} from "lucide-react";

interface LibraryTemplate {
  id: number;
  name: string;
  type: "form" | "message" | "task" | "event";
  category: string;
  description: string;
  content: any;
  isOfficial: boolean;
  createdAt: string;
}

interface Job {
  id: number;
  title: string;
  location: string;
}

const TAB_CONFIGS = [
  { id: "form" as const, label: "Application Forms", icon: FileText, desc: "Pre-built application questionnaires and knockout form templates" },
  { id: "message" as const, label: "Message Templates", icon: Mail, desc: "Standardized candidate emails and automated SMS sequences" },
  { id: "task" as const, label: "Tasks & Checklists", icon: CheckSquare, desc: "Recruiter screening protocols and paperless onboarding workflows" },
  { id: "event" as const, label: "Interviews & Events", icon: Calendar, desc: "Structured multi-session interview loops and career fair blocks" },
];

const FIELD_TYPES = [
  { value: "short_text", label: "Short Text" },
  { value: "long_text", label: "Paragraph" },
  { value: "email", label: "Email" },
  { value: "phone", label: "Phone" },
  { value: "number", label: "Number" },
  { value: "dropdown", label: "Dropdown" },
  { value: "radio", label: "Radio Buttons" },
  { value: "checkbox", label: "Checkbox" },
  { value: "file", label: "File Upload" },
  { value: "date", label: "Date" },
];

export default function TemplateLibraryPage() {
  const [activeTab, setActiveTab] = useState<"form" | "message" | "task" | "event">("form");
  const [templates, setTemplates] = useState<LibraryTemplate[]>([]);
  const [jobs, setJobs] = useState<Job[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("All");

  // Preview / Apply modals
  const [previewTemplate, setPreviewTemplate] = useState<LibraryTemplate | null>(null);
  const [applyModalTemplate, setApplyModalTemplate] = useState<LibraryTemplate | null>(null);
  const [selectedJobId, setSelectedJobId] = useState("");
  const [applying, setApplying] = useState(false);
  const [applySuccess, setApplySuccess] = useState("");
  const [applyError, setApplyError] = useState("");
  const [copiedId, setCopiedId] = useState<number | null>(null);

  // Edit / Create modal
  const [editTemplate, setEditTemplate] = useState<LibraryTemplate | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState("");

  // Delete confirmation
  const [deleteTarget, setDeleteTarget] = useState<LibraryTemplate | null>(null);
  const [deleting, setDeleting] = useState(false);

  useEffect(() => { fetchLibrary(); fetchJobs(); }, []);

  async function fetchLibrary() {
    setLoading(true);
    try { const res = await fetch("/api/library"); setTemplates(await res.json()); }
    catch (e) { console.error(e); }
    finally { setLoading(false); }
  }

  async function fetchJobs() {
    try { const res = await fetch("/api/jobs?status=open"); const data = await res.json(); setJobs(data); if (data.length > 0) setSelectedJobId(String(data[0].id)); }
    catch (e) { console.error(e); }
  }

  const currentConfig = TAB_CONFIGS.find((t) => t.id === activeTab)!;

  const filteredTemplates = templates
    .filter((t) => t.type === activeTab)
    .filter((t) => {
      const s = searchTerm.toLowerCase();
      return (t.name.toLowerCase().includes(s) || t.description.toLowerCase().includes(s)) && (selectedCategory === "All" || t.category === selectedCategory);
    });

  const categories = ["All", ...Array.from(new Set(templates.filter((t) => t.type === activeTab).map((t) => t.category)))];

  // ── Apply form to job ──
  async function handleApplyToJob() {
    if (!applyModalTemplate || !selectedJobId) return;
    setApplying(true); setApplyError(""); setApplySuccess("");
    try {
      const res = await fetch("/api/forms", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ jobId: parseInt(selectedJobId), title: applyModalTemplate.content?.title || applyModalTemplate.name, description: applyModalTemplate.content?.description || applyModalTemplate.description, fields: applyModalTemplate.content?.fields || [], isActive: true }),
      });
      const data = await res.json();
      if (res.ok) { setApplySuccess("Form applied!"); setTimeout(() => { setApplyModalTemplate(null); setApplySuccess(""); }, 1800); }
      else setApplyError(data.error || "Failed");
    } catch { setApplyError("Network error"); }
    finally { setApplying(false); }
  }

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

  // ── Create / Edit save ──
  function openCreate() {
    const emptyContent: any =
      activeTab === "form" ? { title: "", description: "", fields: [] } :
      activeTab === "message" ? { subject: "", body: "", channel: "email" } :
      activeTab === "task" ? { tasks: [] } :
      { format: "", durationMins: 60, sessions: [] };
    setEditTemplate({ id: 0, name: "", type: activeTab, category: "", description: "", content: emptyContent, isOfficial: false, createdAt: "" });
    setIsCreating(true);
    setSaveError("");
  }

  function openEdit(t: LibraryTemplate) {
    setEditTemplate(JSON.parse(JSON.stringify(t)));
    setIsCreating(false);
    setSaveError("");
  }

  async function handleSave() {
    if (!editTemplate) return;
    if (!editTemplate.name.trim()) { setSaveError("Template name is required."); return; }
    setSaving(true); setSaveError("");
    try {
      const url = isCreating ? "/api/library" : `/api/library/${editTemplate.id}`;
      const method = isCreating ? "POST" : "PUT";
      const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(editTemplate) });
      const data = await res.json();
      if (res.ok) { setEditTemplate(null); fetchLibrary(); }
      else setSaveError(data.error || "Failed to save template.");
    } catch { setSaveError("Network error."); }
    finally { setSaving(false); }
  }

  // ── Delete ──
  async function handleDelete() {
    if (!deleteTarget) return;
    setDeleting(true);
    try { await fetch(`/api/library/${deleteTarget.id}`, { method: "DELETE" }); setDeleteTarget(null); fetchLibrary(); }
    catch { /* ignore */ }
    finally { setDeleting(false); }
  }

  // ── Content editor helpers ──
  function updateContent(patch: any) { if (editTemplate) setEditTemplate({ ...editTemplate, content: { ...editTemplate.content, ...patch } }); }

  function addFormField() {
    if (!editTemplate) return;
    const fields = [...(editTemplate.content.fields || [])];
    fields.push({ id: `f_${Date.now()}`, type: "short_text", label: "New Field", required: false, order: fields.length, placeholder: "", options: undefined, helpText: "" });
    updateContent({ fields });
  }

  function updateFormField(idx: number, patch: any) {
    if (!editTemplate) return;
    const fields = [...(editTemplate.content.fields || [])];
    fields[idx] = { ...fields[idx], ...patch };
    updateContent({ fields });
  }

  function removeFormField(idx: number) {
    if (!editTemplate) return;
    const fields = (editTemplate.content.fields || []).filter((_: any, i: number) => i !== idx);
    updateContent({ fields });
  }

  function moveFormField(idx: number, dir: -1 | 1) {
    if (!editTemplate) return;
    const fields = [...(editTemplate.content.fields || [])];
    const target = idx + dir;
    if (target < 0 || target >= fields.length) return;
    [fields[idx], fields[target]] = [fields[target], fields[idx]];
    updateContent({ fields });
  }

  function addTask() {
    if (!editTemplate) return;
    const tasks = [...(editTemplate.content.tasks || [])];
    tasks.push({ title: "New task", estimatedMins: 10, required: false });
    updateContent({ tasks });
  }

  function updateTask(idx: number, patch: any) {
    if (!editTemplate) return;
    const tasks = [...(editTemplate.content.tasks || [])];
    tasks[idx] = { ...tasks[idx], ...patch };
    updateContent({ tasks });
  }

  function removeTask(idx: number) {
    if (!editTemplate) return;
    updateContent({ tasks: (editTemplate.content.tasks || []).filter((_: any, i: number) => i !== idx) });
  }

  function addSession() {
    if (!editTemplate) return;
    const sessions = [...(editTemplate.content.sessions || [])];
    sessions.push({ title: "New Session", mins: 30, interviewerType: "Recruiter" });
    updateContent({ sessions });
  }

  function updateSession(idx: number, patch: any) {
    if (!editTemplate) return;
    const sessions = [...(editTemplate.content.sessions || [])];
    sessions[idx] = { ...sessions[idx], ...patch };
    updateContent({ sessions });
  }

  function removeSession(idx: number) {
    if (!editTemplate) return;
    updateContent({ sessions: (editTemplate.content.sessions || []).filter((_: any, i: number) => i !== idx) });
  }

  // ── Render ──
  return (
    <div className="p-6 max-w-7xl mx-auto">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">📚 Template Library Hub</h1>
          <p className="text-gray-500 mt-1">Browse, preview, edit, and apply professional recruiting templates</p>
        </div>
        <button onClick={openCreate} className="px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl transition-colors text-sm font-medium flex items-center gap-2 shadow-sm">
          <Plus className="w-4 h-4" /> New {currentConfig.label.replace(/s$/, "")}
        </button>
      </div>

      {/* Tabs */}
      <div className="flex flex-wrap items-center gap-2 border-b border-gray-200 mb-6 bg-white p-1 rounded-xl shadow-sm">
        {TAB_CONFIGS.map((tab) => {
          const Icon = tab.icon;
          const isActive = activeTab === tab.id;
          return (
            <button key={tab.id} onClick={() => { setActiveTab(tab.id); setSelectedCategory("All"); setSearchTerm(""); }}
              className={`flex items-center gap-2.5 px-5 py-3 rounded-lg text-sm font-medium transition-all ${isActive ? "bg-blue-600 text-white shadow-sm" : "text-gray-600 hover:text-gray-900 hover:bg-gray-50"}`}>
              <Icon className="w-4 h-4" /><span>{tab.label}</span>
              <span className={`text-xs px-2 py-0.5 rounded-full font-semibold ${isActive ? "bg-blue-500 text-white" : "bg-gray-100 text-gray-500"}`}>
                {templates.filter((t) => t.type === tab.id).length}
              </span>
            </button>
          );
        })}
      </div>

      {/* Filters */}
      <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5 mb-6 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          <div className="p-2.5 bg-blue-50 text-blue-600 rounded-xl"><currentConfig.icon className="w-6 h-6" /></div>
          <div><h2 className="font-semibold text-gray-900">{currentConfig.label}</h2><p className="text-sm text-gray-500">{currentConfig.desc}</p></div>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          <div className="relative min-w-[240px]">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input type="text" placeholder={`Search…`} value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-full pl-9 pr-4 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" />
          </div>
          <div className="flex items-center gap-1.5 overflow-x-auto">
            {categories.map((cat) => (
              <button key={cat} onClick={() => setSelectedCategory(cat)} className={`px-3 py-1.5 rounded-lg text-xs font-medium whitespace-nowrap transition-colors ${selectedCategory === cat ? "bg-slate-900 text-white" : "bg-gray-100 text-gray-600 hover:bg-gray-200"}`}>{cat}</button>
            ))}
          </div>
        </div>
      </div>

      {/* Grid */}
      {loading ? (
        <div className="flex items-center justify-center py-20"><div className="animate-spin rounded-full h-10 w-10 border-b-2 border-blue-600" /></div>
      ) : filteredTemplates.length === 0 ? (
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-12 text-center text-gray-500 space-y-3">
          <AlertCircle className="w-12 h-12 text-gray-300 mx-auto" />
          <h3 className="text-lg font-semibold text-gray-800">No {currentConfig.label.toLowerCase()} found</h3>
          <p className="text-sm max-w-sm mx-auto">Try a different category or search term, or create a new template.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredTemplates.map((template) => (
            <div key={template.id} className="bg-white rounded-2xl border border-gray-200 shadow-sm hover:shadow-md transition-shadow flex flex-col justify-between overflow-hidden">
              <div className="p-5">
                <div className="flex items-start justify-between gap-2 mb-3">
                  <span className="text-xs px-2.5 py-1 rounded-full font-semibold bg-blue-50 text-blue-700 border border-blue-100">{template.category}</span>
                  {template.isOfficial && (<span className="flex items-center gap-1 text-xs text-emerald-700 font-medium bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-100"><ShieldCheck className="w-3.5 h-3.5" /> Approved</span>)}
                </div>
                <h3 className="font-bold text-gray-900 text-lg mb-1">{template.name}</h3>
                <p className="text-sm text-gray-600 line-clamp-2 leading-relaxed mb-4">{template.description}</p>

                {/* Compact preview digest */}
                <div className="p-3.5 bg-gray-50 rounded-xl border border-gray-100 text-xs text-gray-700 space-y-1">
                  {activeTab === "form" && (<><p className="font-semibold text-gray-800 truncate">📋 {template.content?.title || "Application Form"}</p><p className="text-gray-500">{template.content?.fields?.length || 0} fields</p></>)}
                  {activeTab === "message" && (<><p className="font-semibold text-gray-800 truncate">Subject: {template.content?.subject || "—"}</p><p className="text-gray-500 line-clamp-2 italic">&quot;{(template.content?.body || "").slice(0, 100)}&quot;</p></>)}
                  {activeTab === "task" && (<><p className="font-semibold text-gray-800">⚡ {template.content?.tasks?.length || 0} tasks</p>{template.content?.tasks?.slice(0, 2).map((tsk: any, i: number) => <p key={i} className="text-gray-500 truncate">✓ {tsk.title}</p>)}</>)}
                  {activeTab === "event" && (<><p className="font-semibold text-gray-800">⏰ {template.content?.format} · {template.content?.durationMins}m</p><p className="text-gray-500">{template.content?.sessions?.length || 0} sessions</p></>)}
                </div>
              </div>

              {/* Card actions */}
              <div className="px-5 py-3 bg-gray-50 border-t border-gray-100 flex items-center gap-2 flex-wrap">
                <button onClick={() => setPreviewTemplate(template)} className="px-3 py-1.5 text-xs font-semibold text-gray-700 hover:bg-gray-200 rounded-lg transition-colors flex items-center gap-1.5"><Eye className="w-3.5 h-3.5" /> Preview</button>
                <button onClick={() => openEdit(template)} className="px-3 py-1.5 text-xs font-semibold text-blue-700 hover:bg-blue-100 rounded-lg transition-colors flex items-center gap-1.5"><Pencil className="w-3.5 h-3.5" /> Edit</button>
                <button onClick={() => setDeleteTarget(template)} className="px-3 py-1.5 text-xs font-semibold text-red-600 hover:bg-red-50 rounded-lg transition-colors flex items-center gap-1.5"><Trash2 className="w-3.5 h-3.5" /> Delete</button>
                <div className="flex-1" />
                {activeTab === "form" && (<button onClick={() => setApplyModalTemplate(template)} className="px-3 py-1.5 text-xs font-bold text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors flex items-center gap-1.5 shadow-sm"><Briefcase className="w-3.5 h-3.5" /> Use in Job</button>)}
                {activeTab === "message" && (<button onClick={() => copyToClipboard(template.content?.body || "", template.id)} className="px-3 py-1.5 text-xs font-bold text-white bg-slate-900 hover:bg-slate-800 rounded-lg transition-colors flex items-center gap-1.5 shadow-sm">{copiedId === template.id ? <><CheckCircle2 className="w-3.5 h-3.5 text-green-400" /> Copied!</> : <><Copy className="w-3.5 h-3.5" /> Copy</>}</button>)}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* ═══════════ EDIT / CREATE MODAL ═══════════ */}
      {editTemplate && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[92vh] flex flex-col overflow-hidden border border-gray-100">
            <div className="px-6 py-4 bg-slate-900 text-white flex items-center justify-between shrink-0">
              <h2 className="font-bold text-lg">{isCreating ? "Create New Template" : "Edit Template"}</h2>
              <button onClick={() => setEditTemplate(null)} className="p-2 text-slate-400 hover:text-white hover:bg-slate-800 rounded-xl"><X className="w-5 h-5" /></button>
            </div>
            <div className="flex-1 overflow-y-auto p-6 space-y-5">
              {/* Meta */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Template Name *</label>
                  <input value={editTemplate.name} onChange={(e) => setEditTemplate({ ...editTemplate, name: e.target.value })} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm" placeholder="e.g. Engineering Application" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Category</label>
                  <input value={editTemplate.category} onChange={(e) => setEditTemplate({ ...editTemplate, category: e.target.value })} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm" placeholder="e.g. Engineering & Tech" />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
                <textarea value={editTemplate.description} onChange={(e) => setEditTemplate({ ...editTemplate, description: e.target.value })} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm h-16 resize-none" placeholder="Brief description of this template…" />
              </div>
              <div className="flex items-center gap-3">
                <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={editTemplate.isOfficial} onChange={(e) => setEditTemplate({ ...editTemplate, isOfficial: e.target.checked })} className="rounded border-gray-300" /> Mark as officially approved</label>
              </div>

              <hr className="border-gray-200" />

              {/* ── FORM content editor ── */}
              {editTemplate.type === "form" && (
                <div className="space-y-4">
                  <h3 className="font-semibold text-gray-900">Form Configuration</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div><label className="block text-sm font-medium text-gray-700 mb-1">Form Title</label><input value={editTemplate.content.title || ""} onChange={(e) => updateContent({ title: e.target.value })} className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" /></div>
                    <div><label className="block text-sm font-medium text-gray-700 mb-1">Form Intro</label><input value={editTemplate.content.description || ""} onChange={(e) => updateContent({ description: e.target.value })} className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" /></div>
                  </div>
                  <div className="flex items-center justify-between">
                    <h4 className="text-sm font-semibold text-gray-800">Fields ({(editTemplate.content.fields || []).length})</h4>
                    <button onClick={addFormField} className="flex items-center gap-1.5 text-sm text-blue-600 hover:text-blue-700 font-medium"><Plus className="w-4 h-4" /> Add Field</button>
                  </div>
                  <div className="space-y-3">
                    {(editTemplate.content.fields || []).map((f: any, idx: number) => (
                      <div key={f.id || idx} className="p-4 border border-gray-200 rounded-xl bg-gray-50 space-y-3">
                        <div className="flex items-center gap-2">
                          <div className="flex flex-col gap-0.5">
                            <button onClick={() => moveFormField(idx, -1)} disabled={idx === 0} className="text-gray-400 hover:text-gray-600 disabled:opacity-30"><ChevronUp className="w-4 h-4" /></button>
                            <button onClick={() => moveFormField(idx, 1)} disabled={idx === (editTemplate.content.fields || []).length - 1} className="text-gray-400 hover:text-gray-600 disabled:opacity-30"><ChevronDown className="w-4 h-4" /></button>
                          </div>
                          <input value={f.label} onChange={(e) => updateFormField(idx, { label: e.target.value })} className="flex-1 px-3 py-1.5 border border-gray-300 rounded-lg text-sm font-medium focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="Field label" />
                          <select value={f.type} onChange={(e) => updateFormField(idx, { type: e.target.value, options: ["dropdown", "radio", "checkbox"].includes(e.target.value) ? (f.options || ["Option 1", "Option 2"]) : undefined })} className="px-2 py-1.5 border border-gray-300 rounded-lg text-xs focus:ring-2 focus:ring-blue-500 focus:outline-none">
                            {FIELD_TYPES.map((ft) => <option key={ft.value} value={ft.value}>{ft.label}</option>)}
                          </select>
                          <label className="flex items-center gap-1 text-xs text-gray-700"><input type="checkbox" checked={f.required} onChange={(e) => updateFormField(idx, { required: e.target.checked })} className="rounded border-gray-300" /> Req</label>
                          <button onClick={() => removeFormField(idx)} className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg"><Trash2 className="w-4 h-4" /></button>
                        </div>
                        <div className="grid grid-cols-2 gap-3">
                          <input value={f.placeholder || ""} onChange={(e) => updateFormField(idx, { placeholder: e.target.value })} className="px-2 py-1.5 border border-gray-200 rounded-lg text-xs focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="Placeholder text" />
                          <input value={f.helpText || ""} onChange={(e) => updateFormField(idx, { helpText: e.target.value })} className="px-2 py-1.5 border border-gray-200 rounded-lg text-xs focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="Help text" />
                        </div>
                        {["dropdown", "radio", "checkbox"].includes(f.type) && (
                          <div><label className="block text-xs text-gray-500 mb-1">Options (one per line)</label><textarea value={(f.options || []).join("\n")} onChange={(e) => updateFormField(idx, { options: e.target.value.split("\n") })} className="w-full px-2 py-1.5 border border-gray-200 rounded-lg text-xs h-16 resize-none focus:ring-2 focus:ring-blue-500 focus:outline-none" /></div>
                        )}
                      </div>
                    ))}
                    {(editTemplate.content.fields || []).length === 0 && <p className="text-sm text-gray-400 text-center py-4">No fields yet. Click &quot;Add Field&quot; above.</p>}
                  </div>
                </div>
              )}

              {/* ── MESSAGE content editor ── */}
              {editTemplate.type === "message" && (
                <div className="space-y-4">
                  <h3 className="font-semibold text-gray-900">Message Configuration</h3>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Channel</label>
                    <select value={editTemplate.content.channel || "email"} onChange={(e) => updateContent({ channel: e.target.value })} className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none">
                      <option value="email">Email</option><option value="sms">SMS</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Subject</label>
                    <input value={editTemplate.content.subject || ""} onChange={(e) => updateContent({ subject: e.target.value })} className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="Subject line…" />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Body</label>
                    <textarea value={editTemplate.content.body || ""} onChange={(e) => updateContent({ body: e.target.value })} className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm h-40 resize-none font-mono focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="Dear {{candidate_name}},…" />
                    <p className="text-xs text-gray-400 mt-1">Variables: {"{{candidate_name}}"}, {"{{job_title}}"}, {"{{recruiter_name}}"}, {"{{company_name}}"}</p>
                  </div>
                </div>
              )}

              {/* ── TASK content editor ── */}
              {editTemplate.type === "task" && (
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <h3 className="font-semibold text-gray-900">Task Checklist</h3>
                    <button onClick={addTask} className="flex items-center gap-1.5 text-sm text-blue-600 hover:text-blue-700 font-medium"><Plus className="w-4 h-4" /> Add Task</button>
                  </div>
                  <div className="space-y-2">
                    {(editTemplate.content.tasks || []).map((tsk: any, idx: number) => (
                      <div key={idx} className="flex items-center gap-3 p-3 border border-gray-200 rounded-xl bg-gray-50">
                        <input value={tsk.title} onChange={(e) => updateTask(idx, { title: e.target.value })} className="flex-1 px-2 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="Task description" />
                        <input type="number" value={tsk.estimatedMins} onChange={(e) => updateTask(idx, { estimatedMins: parseInt(e.target.value) || 0 })} className="w-16 px-2 py-1.5 border border-gray-300 rounded-lg text-sm text-center focus:ring-2 focus:ring-blue-500 focus:outline-none" />
                        <span className="text-xs text-gray-400">min</span>
                        <label className="flex items-center gap-1 text-xs"><input type="checkbox" checked={tsk.required} onChange={(e) => updateTask(idx, { required: e.target.checked })} className="rounded border-gray-300" /> Req</label>
                        <button onClick={() => removeTask(idx)} className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg"><Trash2 className="w-4 h-4" /></button>
                      </div>
                    ))}
                    {(editTemplate.content.tasks || []).length === 0 && <p className="text-sm text-gray-400 text-center py-4">No tasks yet. Click &quot;Add Task&quot; above.</p>}
                  </div>
                </div>
              )}

              {/* ── EVENT content editor ── */}
              {editTemplate.type === "event" && (
                <div className="space-y-4">
                  <h3 className="font-semibold text-gray-900">Event / Interview Loop</h3>
                  <div className="grid grid-cols-2 gap-4">
                    <div><label className="block text-sm font-medium text-gray-700 mb-1">Format</label><input value={editTemplate.content.format || ""} onChange={(e) => updateContent({ format: e.target.value })} className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="e.g. Onsite Loop" /></div>
                    <div><label className="block text-sm font-medium text-gray-700 mb-1">Total Duration (mins)</label><input type="number" value={editTemplate.content.durationMins || ""} onChange={(e) => updateContent({ durationMins: parseInt(e.target.value) || 0 })} className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" /></div>
                  </div>
                  <div className="flex items-center justify-between">
                    <h4 className="text-sm font-semibold text-gray-800">Sessions ({(editTemplate.content.sessions || []).length})</h4>
                    <button onClick={addSession} className="flex items-center gap-1.5 text-sm text-blue-600 hover:text-blue-700 font-medium"><Plus className="w-4 h-4" /> Add Session</button>
                  </div>
                  <div className="space-y-2">
                    {(editTemplate.content.sessions || []).map((sess: any, idx: number) => (
                      <div key={idx} className="flex items-center gap-3 p-3 border border-gray-200 rounded-xl bg-gray-50">
                        <input value={sess.title} onChange={(e) => updateSession(idx, { title: e.target.value })} className="flex-1 px-2 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="Session title" />
                        <input type="number" value={sess.mins} onChange={(e) => updateSession(idx, { mins: parseInt(e.target.value) || 0 })} className="w-16 px-2 py-1.5 border border-gray-300 rounded-lg text-sm text-center focus:ring-2 focus:ring-blue-500 focus:outline-none" />
                        <span className="text-xs text-gray-400">min</span>
                        <input value={sess.interviewerType || ""} onChange={(e) => updateSession(idx, { interviewerType: e.target.value })} className="w-36 px-2 py-1.5 border border-gray-300 rounded-lg text-xs focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="Interviewer type" />
                        <button onClick={() => removeSession(idx)} className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg"><Trash2 className="w-4 h-4" /></button>
                      </div>
                    ))}
                    {(editTemplate.content.sessions || []).length === 0 && <p className="text-sm text-gray-400 text-center py-4">No sessions yet. Click &quot;Add Session&quot; above.</p>}
                  </div>
                </div>
              )}

              {saveError && <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">{saveError}</div>}
            </div>
            <div className="px-6 py-4 bg-gray-50 border-t border-gray-100 flex items-center justify-end gap-3 shrink-0">
              <button onClick={() => setEditTemplate(null)} className="px-5 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-200 rounded-xl transition-colors">Cancel</button>
              <button onClick={handleSave} disabled={saving} className="px-6 py-2.5 text-sm font-bold text-white bg-blue-600 hover:bg-blue-700 rounded-xl transition-colors disabled:opacity-50 shadow-sm flex items-center gap-2">
                <Save className="w-4 h-4" />{saving ? "Saving…" : isCreating ? "Create Template" : "Save Changes"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ═══════════ DELETE CONFIRMATION ═══════════ */}
      {deleteTarget && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6 space-y-4">
            <h2 className="font-bold text-lg text-gray-900">Delete Template</h2>
            <p className="text-sm text-gray-600">Are you sure you want to delete <strong>{deleteTarget.name}</strong>? This action cannot be undone.</p>
            <div className="flex items-center justify-end gap-3 pt-2">
              <button onClick={() => setDeleteTarget(null)} className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg">Cancel</button>
              <button onClick={handleDelete} disabled={deleting} className="px-5 py-2 text-sm font-bold text-white bg-red-600 hover:bg-red-700 rounded-lg disabled:opacity-50">{deleting ? "Deleting…" : "Delete"}</button>
            </div>
          </div>
        </div>
      )}

      {/* ═══════════ PREVIEW MODAL ═══════════ */}
      {previewTemplate && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col overflow-hidden">
            <div className="px-6 py-4 bg-slate-900 text-white flex items-center justify-between shrink-0">
              <div><h2 className="font-bold text-lg">{previewTemplate.name}</h2><p className="text-xs text-slate-400 capitalize">{previewTemplate.category}</p></div>
              <button onClick={() => setPreviewTemplate(null)} className="p-2 text-slate-400 hover:text-white hover:bg-slate-800 rounded-xl"><X className="w-5 h-5" /></button>
            </div>
            <div className="flex-1 overflow-y-auto p-6 space-y-5">
              <p className="text-sm text-gray-800 bg-blue-50 p-4 rounded-xl border border-blue-100">{previewTemplate.description}</p>

              {previewTemplate.type === "form" && (
                <div className="space-y-3">{previewTemplate.content?.fields?.map((f: any, i: number) => (
                  <div key={i} className="p-3 bg-gray-50 rounded-xl border border-gray-200 flex items-start justify-between gap-3">
                    <div><p className="text-sm font-semibold text-gray-900">{i + 1}. {f.label} {f.required && <span className="text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded-full ml-1">Required</span>}</p><p className="text-xs text-gray-500 mt-0.5">Type: {f.type?.replace("_", " ")}</p>{f.helpText && <p className="text-xs text-gray-600 mt-1 italic">{f.helpText}</p>}</div>
                    {f.options && <div className="flex flex-wrap gap-1 max-w-xs justify-end">{f.options.map((opt: string, oi: number) => <span key={oi} className="text-[10px] bg-white px-2 py-0.5 rounded-md border border-gray-200">{opt}</span>)}</div>}
                  </div>
                ))}</div>
              )}

              {previewTemplate.type === "message" && (
                <div className="space-y-3">
                  <div className="p-3 bg-gray-50 rounded-xl border border-gray-200"><p className="text-xs text-gray-400 uppercase font-bold mb-1">Subject</p><p className="font-bold text-gray-900">{previewTemplate.content?.subject}</p></div>
                  <div className="p-4 bg-slate-900 text-emerald-400 font-mono rounded-xl whitespace-pre-line text-sm">{previewTemplate.content?.body}</div>
                </div>
              )}

              {previewTemplate.type === "task" && (
                <div className="space-y-2">{previewTemplate.content?.tasks?.map((tsk: any, i: number) => (
                  <div key={i} className="flex items-center justify-between p-3 bg-gray-50 rounded-xl border border-gray-200">
                    <div className="flex items-center gap-2"><CheckSquare className="w-4 h-4 text-blue-600" /><span className="text-sm font-semibold text-gray-900">{tsk.title}</span></div>
                    <div className="flex items-center gap-2"><span className="text-xs bg-white px-2 py-1 rounded-lg border border-gray-200">⏱ {tsk.estimatedMins}m</span>{tsk.required && <span className="text-xs px-2 py-0.5 bg-blue-100 text-blue-700 rounded-full font-semibold">Req</span>}</div>
                  </div>
                ))}</div>
              )}

              {previewTemplate.type === "event" && (
                <div className="space-y-3">
                  <p className="text-sm text-gray-700"><strong>Format:</strong> {previewTemplate.content?.format} · <strong>Total:</strong> {previewTemplate.content?.durationMins} mins</p>
                  {previewTemplate.content?.sessions?.map((sess: any, i: number) => (
                    <div key={i} className="p-3 bg-gray-50 rounded-xl border border-gray-200 flex items-center justify-between">
                      <div><p className="text-sm font-bold text-gray-900">Session {i + 1}: {sess.title}</p><p className="text-xs text-gray-500">Interviewer: {sess.interviewerType}</p></div>
                      <span className="px-3 py-1 bg-blue-600 text-white font-bold text-xs rounded-xl">{sess.mins}m</span>
                    </div>
                  ))}
                </div>
              )}
            </div>
            <div className="px-6 py-4 bg-gray-50 border-t border-gray-100 flex items-center justify-between shrink-0">
              <button onClick={() => { setPreviewTemplate(null); openEdit(previewTemplate); }} className="px-4 py-2 text-sm font-semibold text-blue-700 hover:bg-blue-50 rounded-lg flex items-center gap-1.5"><Pencil className="w-3.5 h-3.5" /> Edit this template</button>
              <button onClick={() => setPreviewTemplate(null)} className="px-5 py-2.5 bg-slate-900 text-white font-bold text-sm rounded-xl hover:bg-slate-800 shadow-sm">Close</button>
            </div>
          </div>
        </div>
      )}

      {/* ═══════════ APPLY FORM TO JOB MODAL ═══════════ */}
      {applyModalTemplate && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg overflow-hidden flex flex-col">
            <div className="px-6 py-4 bg-blue-600 text-white flex items-center justify-between"><h2 className="font-bold text-lg">💼 Apply Form to Job</h2><button onClick={() => setApplyModalTemplate(null)} className="p-2 text-blue-100 hover:text-white hover:bg-blue-700 rounded-xl"><X className="w-5 h-5" /></button></div>
            <div className="p-6 space-y-4">
              <p className="text-sm text-gray-600">Deploy <strong>{applyModalTemplate.name}</strong> to an open job posting.</p>
              <select value={selectedJobId} onChange={(e) => setSelectedJobId(e.target.value)} className="w-full px-4 py-3 border border-gray-300 rounded-xl font-medium text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none">
                {jobs.length === 0 ? <option value="">No open jobs</option> : jobs.map((j) => <option key={j.id} value={j.id}>{j.title} — {j.location}</option>)}
              </select>
              {applySuccess && <div className="p-3 bg-emerald-50 text-emerald-800 border border-emerald-200 rounded-lg text-sm font-bold flex items-center gap-2"><CheckCircle2 className="w-4 h-4" /> {applySuccess}</div>}
              {applyError && <div className="p-3 bg-red-50 text-red-800 border border-red-200 rounded-lg text-sm flex items-center gap-2"><AlertCircle className="w-4 h-4" /> {applyError}</div>}
            </div>
            <div className="px-6 py-4 bg-gray-50 border-t border-gray-100 flex items-center justify-end gap-3">
              <button onClick={() => setApplyModalTemplate(null)} className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-200 rounded-lg">Cancel</button>
              <button onClick={handleApplyToJob} disabled={applying || !selectedJobId || Boolean(applySuccess)} className="px-5 py-2 text-sm font-bold text-white bg-blue-600 hover:bg-blue-700 rounded-lg disabled:opacity-50 flex items-center gap-2"><Send className="w-4 h-4" />{applying ? "Applying…" : "Deploy"}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
