'use client'

import { useState, useEffect } from 'react'
import { Plus, Trash2, Edit2, Mail, X, Code2, Copy, Check } from 'lucide-react'
import toast from 'react-hot-toast'
import {
  listEmailTemplates,
  createEmailTemplate,
  updateEmailTemplate,
  deleteEmailTemplate,
  type EmailTemplate,
  type EmailTemplateType,
  type CreateEmailTemplatePayload,
} from '@/lib/api/email-templates'

const TYPE_LABELS: Record<EmailTemplateType, string> = {
  BUILTIN: 'Built-in',
  CUSTOM_HTML: 'Custom HTML',
  SENDGRID: 'SendGrid',
  MAILCHIMP: 'Mailchimp',
  BREVO: 'Brevo',
}

const TYPE_COLORS: Record<EmailTemplateType, string> = {
  BUILTIN: 'bg-[#f2ece2] text-[#5f584f]',
  CUSTOM_HTML: 'bg-[#e6f5ee] text-[#2d8b69]',
  SENDGRID: 'bg-[#eaf5ee] text-[#317357]',
  MAILCHIMP: 'bg-[#fff1d8] text-[#8d6b2c]',
  BREVO: 'bg-[#fbe7de] text-[#a45c3c]',
}

const BUILTIN_LAYOUTS = [
  {
    value: 'editorial',
    label: 'Editorial',
    description: 'Magazine style, layered sections, warm premium look',
  },
  {
    value: 'minimal',
    label: 'Minimal',
    description: 'Clean digest, restrained hierarchy, light and readable',
  },
  {
    value: 'micromobility',
    label: 'Micromobility',
    description: 'OTORIDE-inspired operator dispatch branding for shared mobility briefings',
  },
  {
    value: 'data-engineering',
    label: 'Data Engineering',
    description: 'Operations report layout for pipelines, metrics, and technical briefings',
  },
] as const

const BUILTIN_LAYOUT_LABELS = Object.fromEntries(
  BUILTIN_LAYOUTS.map((layout) => [layout.value, layout.label])
) as Record<string, string>

const STARTER_TEMPLATE = `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Email</title>
  <style>
    body { margin: 0; padding: 0; background: #f4f4f5; font-family: Arial, sans-serif; }
    .wrapper { max-width: 600px; margin: 32px auto; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 4px rgba(0,0,0,0.08); }
    .header { background: #1e293b; padding: 24px 32px; }
    .header h1 { margin: 0; color: #ffffff; font-size: 20px; }
    .content { padding: 32px; color: #374151; font-size: 15px; line-height: 1.6; }
    .footer { background: #f8fafc; padding: 16px 32px; font-size: 12px; color: #9ca3af; border-top: 1px solid #e5e7eb; }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="header">
      <h1>Your Company</h1>
    </div>
    <div class="content">
      {{ body }}
    </div>
    <div class="footer">
      You received this email from Your Company &middot; Unsubscribe
    </div>
  </div>
</body>
</html>`

const VARIABLES_REFERENCE = [
  { variable: '{{ body }}', desc: 'Required — the email body generated by the agent is injected here.' },
  { variable: '{{ content }}', desc: 'Alias for {{ body }}. Either can be used.' },
]

const THIRD_PARTY_VARS: Record<string, { variable: string; desc: string }[]> = {
  SENDGRID: [
    { variable: '{{subject}}', desc: 'Email subject (SendGrid substitution tag)' },
    { variable: '{{first_name}}', desc: 'Recipient first name if passed via dynamic data' },
  ],
  MAILCHIMP: [
    { variable: '*|FNAME|*', desc: 'Recipient first name (Mailchimp merge tag)' },
    { variable: '*|EMAIL|*', desc: 'Recipient email address' },
  ],
  BREVO: [
    { variable: '{{params.name}}', desc: 'Custom param passed at send time' },
    { variable: '{{contact.EMAIL}}', desc: 'Recipient email from Brevo contact' },
  ],
}

function CopyButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false)
  return (
    <button
      onClick={() => { navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 1500) }}
      className="ml-1 inline-flex items-center text-gray-400 hover:text-gray-600"
      title="Copy"
    >
      {copied ? <Check size={12} className="text-green-500" /> : <Copy size={12} />}
    </button>
  )
}

const inputCls = 'w-full rounded-[1.15rem] border border-[#e2d7c8] bg-white/90 px-4 py-3.5 text-sm text-gray-900 outline-none transition-all placeholder:text-[#8a8175] focus:border-[#2d8b69] focus:bg-white focus:ring-4 focus:ring-[#7de5c1]/25'
const labelCls = 'mb-2 block text-sm font-semibold text-gray-700'

function TemplateModal({
  editTarget, form, setForm, saving, onSave, onClose,
}: {
  editTarget: EmailTemplate | null
  form: CreateEmailTemplatePayload
  setForm: React.Dispatch<React.SetStateAction<CreateEmailTemplatePayload>>
  saving: boolean
  onSave: () => void
  onClose: () => void
}) {
  const isThirdParty = ['SENDGRID', 'MAILCHIMP', 'BREVO'].includes(form.template_type)
  const isCustom = form.template_type === 'CUSTOM_HTML'
  const modalWidth = isCustom ? 'max-w-6xl' : 'max-w-2xl'
  const typeOptionLabel =
    form.template_type === 'BUILTIN'
      ? 'Platform managed'
      : form.template_type === 'CUSTOM_HTML'
        ? 'Full control'
        : 'External provider'
  const typeSummary =
    form.template_type === 'BUILTIN'
      ? 'Use a clean built-in newsletter layout managed by the platform.'
      : form.template_type === 'CUSTOM_HTML'
        ? 'Wrap generated content inside your own HTML structure and branding.'
        : 'Connect this template to a third-party provider while keeping agent-generated content reusable.'

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-[rgba(28,22,16,0.34)] p-4 backdrop-blur-[8px]">
      <div className={`flex max-h-[92vh] w-full flex-col overflow-hidden rounded-[2rem] border border-[#e5d9ca] bg-[linear-gradient(180deg,_rgba(255,255,255,0.985),_rgba(249,245,239,0.965))] shadow-[0_36px_110px_-44px_rgba(73,45,23,0.36)] ${modalWidth}`}>
        <div className="relative overflow-hidden border-b border-[#ece2d6] px-6 py-5">
          <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_left,_rgba(255,255,255,0.92),_rgba(247,240,231,0.78)_48%,_rgba(236,228,216,0.56)_100%)]" />
          <div className="absolute right-8 top-2 h-24 w-24 rounded-full bg-[radial-gradient(circle,_rgba(125,229,193,0.22),_transparent_70%)]" />
          <div className="absolute left-8 bottom-0 h-16 w-40 rounded-full bg-[radial-gradient(circle,_rgba(246,199,148,0.18),_transparent_72%)]" />

          <div className="relative flex items-start justify-between gap-4">
            <div>
              <div className="mb-3 inline-flex items-center gap-2 rounded-full border border-black/10 bg-white/70 px-3.5 py-1.5 text-[11px] font-semibold uppercase tracking-[0.22em] text-[#5f584f] shadow-[0_12px_30px_-24px_rgba(30,22,14,0.45)]">
                <Mail className="h-3.5 w-3.5 text-[#2d8b69]" />
                Email Template
              </div>
              <h2 className="text-[2rem] font-semibold tracking-[-0.04em] text-gray-900">
                {editTarget ? 'Edit Template' : 'New Email Template'}
              </h2>
              <p className="mt-2 max-w-2xl text-sm leading-relaxed text-[#6b645a]">
                {typeSummary}
              </p>
            </div>
            <button
              onClick={onClose}
              className="rounded-full border border-[#ddd2c4] bg-white/78 p-2.5 text-[#7a7267] shadow-[0_16px_30px_-24px_rgba(30,22,14,0.4)] transition-colors hover:bg-white hover:text-[#171717]"
            >
            <X size={18} />
            </button>
          </div>
        </div>

        <div className={`min-h-0 flex-1 overflow-y-auto ${isCustom ? 'grid xl:grid-cols-[minmax(0,1fr)_320px]' : ''}`}>
          <div className="space-y-5 px-6 py-6">
            <div className="rounded-[1.5rem] border border-white/70 bg-white/75 px-4 py-3 shadow-[0_20px_45px_-38px_rgba(77,51,28,0.4)] backdrop-blur">
              <div className="flex flex-wrap items-center gap-3">
                <span className="text-xs font-semibold uppercase tracking-[0.18em] text-[#766e63]">Template mode</span>
                <span className="rounded-full bg-[#171717] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-[#f7f2e7]">
                  {TYPE_LABELS[form.template_type]}
                </span>
                <span className="rounded-full border border-[#dfd3c4] bg-[#f8f2e8] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-[#7a6651]">
                  {typeOptionLabel}
                </span>
              </div>
            </div>

            <div>
              <label className={labelCls}>Name *</label>
              <input
                type="text"
                value={form.name}
                onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
                placeholder="e.g. Weekly Report"
                className={inputCls}
              />
            </div>

            <div>
              <label className={labelCls}>Description</label>
              <input
                type="text"
                value={form.description}
                onChange={e => setForm(f => ({ ...f, description: e.target.value }))}
                placeholder="Optional description"
                className={inputCls}
              />
            </div>

            <div>
              <label className={labelCls}>Template Type</label>
              <select
                value={form.template_type}
                onChange={e => setForm(f => ({ ...f, template_type: e.target.value as EmailTemplateType }))}
                className={inputCls}
              >
                <option value="BUILTIN">Built-in (editorial / minimal / micromobility / data engineering)</option>
                <option value="CUSTOM_HTML">Custom HTML</option>
                <option value="SENDGRID">SendGrid Dynamic Template</option>
                <option value="MAILCHIMP">Mailchimp Template</option>
                <option value="BREVO">Brevo Template</option>
              </select>
            </div>

            {form.template_type === 'BUILTIN' && (
              <div className="rounded-[1.5rem] border border-[#e5d9ca] bg-[linear-gradient(180deg,_rgba(255,255,255,0.9),_rgba(247,241,234,0.88))] p-5 shadow-[0_20px_45px_-40px_rgba(30,22,14,0.32)]">
                <label className={labelCls}>Built-in layout</label>
                <select
                  value={form.builtin_name}
                  onChange={e => setForm(f => ({ ...f, builtin_name: e.target.value }))}
                  className={inputCls}
                >
                  {BUILTIN_LAYOUTS.map((layout) => (
                    <option key={layout.value} value={layout.value}>
                      {layout.label} — {layout.description}
                    </option>
                  ))}
                </select>
                <div className="mt-4 rounded-[1.15rem] border border-[#e7dac8] bg-white/80 px-4 py-3 text-sm leading-relaxed text-[#71695e]">
                  Built-in layouts are managed by the platform. The agent's generated content is automatically rendered inside the chosen layout — no variables needed.
                </div>
              </div>
            )}

            {isCustom && (
              <div className="rounded-[1.65rem] border border-[#e5d9ca] bg-[linear-gradient(180deg,_rgba(255,255,255,0.94),_rgba(247,241,234,0.9))] p-5 shadow-[0_20px_45px_-40px_rgba(30,22,14,0.32)]">
                <div className="mb-3 flex items-center justify-between gap-3">
                  <label className="block text-sm font-semibold text-gray-700">HTML Content *</label>
                  {!form.html_content && (
                    <button
                      type="button"
                      onClick={() => setForm(f => ({ ...f, html_content: STARTER_TEMPLATE }))}
                      className="inline-flex items-center gap-1.5 rounded-full border border-[#dfd3c4] bg-white/80 px-3 py-1.5 text-xs font-semibold text-[#2d8b69] transition-colors hover:bg-white hover:text-[#236b50]"
                    >
                      <Code2 size={12} />
                      Insert starter template
                    </button>
                  )}
                </div>
                <textarea
                  value={form.html_content}
                  onChange={e => setForm(f => ({ ...f, html_content: e.target.value }))}
                  rows={22}
                  spellCheck={false}
                  placeholder={'<!DOCTYPE html>\n<html>\n<body>\n  {{ body }}\n</body>\n</html>'}
                  className={`${inputCls} min-h-[28rem] resize-none font-mono text-xs leading-relaxed`}
                />
              </div>
            )}

            {isThirdParty && (
              <div className="space-y-4 rounded-[1.5rem] border border-[#e5d9ca] bg-[linear-gradient(180deg,_rgba(255,255,255,0.9),_rgba(247,241,234,0.88))] p-5 shadow-[0_20px_45px_-40px_rgba(30,22,14,0.32)]">
                <div>
                  <label className={labelCls}>Template ID</label>
                  <input
                    type="text"
                    value={form.external_template_id}
                    onChange={e => setForm(f => ({ ...f, external_template_id: e.target.value }))}
                    placeholder={
                      form.template_type === 'SENDGRID' ? 'd-xxxxxxxxxxxxxxxxxxxx' :
                      form.template_type === 'MAILCHIMP' ? 'template_id or campaign name' :
                      'Template ID in Brevo'
                    }
                    className={inputCls}
                  />
                </div>
                <div>
                  <label className={labelCls}>
                    From Email <span className="font-normal text-gray-400">(optional)</span>
                  </label>
                  <input
                    type="email"
                    value={(form.external_config as any)?.from_email ?? ''}
                    onChange={e => setForm(f => ({ ...f, external_config: { ...(f.external_config || {}), from_email: e.target.value } }))}
                    placeholder="sender@yourdomain.com"
                    className={inputCls}
                  />
                  <p className="mt-2 text-sm text-[#71695e]">Credentials are pulled from the matching integration in your account settings.</p>
                </div>
              </div>
            )}
          </div>

          {isCustom && (
            <div className="border-t border-[#ece2d6] bg-[linear-gradient(180deg,_rgba(247,241,234,0.88),_rgba(243,236,226,0.92))] px-5 py-6 xl:max-h-[92vh] xl:overflow-y-auto xl:border-l xl:border-t-0">
              <div className="xl:sticky xl:top-0">
                <div className="mb-5 rounded-[1.5rem] border border-white/70 bg-white/80 p-4 shadow-[0_18px_40px_-36px_rgba(30,22,14,0.36)] backdrop-blur">
                  <p className="text-xs font-semibold uppercase tracking-[0.2em] text-[#766e63]">Template Variables</p>
                  <p className="mt-2 text-sm leading-relaxed text-[#6e675d]">
                    Use these placeholders and Jinja expressions to shape the final email output.
                  </p>
                </div>

                <div className="mb-5 space-y-3">
                  {VARIABLES_REFERENCE.map(v => (
                    <div key={v.variable} className="rounded-[1.2rem] border border-[#e5d9ca] bg-white/85 p-3.5 shadow-[0_16px_34px_-34px_rgba(30,22,14,0.35)]">
                      <div className="mb-1.5 flex items-center gap-1">
                        <code className="text-xs font-semibold text-[#2d8b69]">{v.variable}</code>
                        <CopyButton text={v.variable} />
                      </div>
                      <p className="text-xs leading-relaxed text-[#6e675d]">{v.desc}</p>
                    </div>
                  ))}
                </div>

                <p className="mb-3 text-xs font-semibold uppercase tracking-[0.2em] text-[#766e63]">How it works</p>
                <div className="space-y-2 text-xs leading-relaxed text-[#6e675d]">
                  <p>When the agent calls <code className="rounded border border-[#e5d9ca] bg-white px-1.5 py-0.5 font-mono text-[#4b453d]">internal_send_email</code>, it writes the email content. Your template wraps that content automatically.</p>
                  <p>Place <code className="rounded border border-[#d8ecdf] bg-white px-1.5 py-0.5 font-mono text-[#2d8b69]">{`{{ body }}`}</code> exactly where you want the agent&apos;s content to appear.</p>
                  <p>The template is rendered using <strong>Jinja2</strong>, so you can use any Jinja2 expression:</p>
                </div>

                <div className="mt-3 space-y-2">
                  {[
                    ['Conditional block', `{% if subject %}\n<h2>{{ subject }}</h2>\n{% endif %}`],
                    ['Loop', `{% for item in items %}\n<li>{{ item }}</li>\n{% endfor %}`],
                    ['Filter', `{{ body | safe }}`],
                  ].map(([label, code]) => (
                    <div key={label} className="rounded-[1.2rem] border border-[#e5d9ca] bg-white/85 p-3.5 shadow-[0_16px_34px_-34px_rgba(30,22,14,0.35)]">
                      <p className="mb-1.5 text-xs font-semibold text-[#5e584f]">{label}</p>
                      <div className="flex items-start justify-between gap-2">
                        <pre className="whitespace-pre-wrap text-xs leading-relaxed text-[#6e675d]">{code}</pre>
                        <CopyButton text={code} />
                      </div>
                    </div>
                  ))}
                </div>

                <div className="mt-4 rounded-[1.25rem] border border-[#ecd8b6] bg-[linear-gradient(180deg,_rgba(255,248,235,0.95),_rgba(252,243,221,0.92))] p-4">
                  <p className="mb-1.5 text-xs font-semibold uppercase tracking-[0.18em] text-[#8f6d36]">Tips</p>
                  <ul className="space-y-1.5 text-xs leading-relaxed text-[#7f6336]">
                    <li>Always include <code className="font-mono">{`{{ body }}`}</code> or the generated email content will not appear.</li>
                    <li>Use inline CSS for the best email-client compatibility.</li>
                    <li>Keep the layout near 600px width for a safer default.</li>
                    <li>Test the final output across multiple clients before going live.</li>
                  </ul>
                </div>
              </div>
            </div>
          )}
        </div>

        <div className="sticky bottom-0 flex justify-end gap-3 border-t border-[#ece2d6] bg-[rgba(252,249,244,0.96)] px-6 py-4 backdrop-blur">
          <button
            onClick={onClose}
            className="rounded-[1.15rem] border border-[#ddd2c4] bg-white/88 px-5 py-3 text-sm font-semibold text-[#5f584f] transition-colors hover:bg-white"
          >
            Cancel
          </button>
          <button
            onClick={onSave}
            disabled={saving}
            className="rounded-[1.15rem] bg-[#191919] px-5 py-3 text-sm font-semibold text-[#f7f2e7] shadow-[0_20px_34px_-24px_rgba(0,0,0,0.45)] transition-colors hover:bg-[#0f0f0f] disabled:opacity-60"
          >
            {saving ? 'Saving…' : editTarget ? 'Save Changes' : 'Create Template'}
          </button>
        </div>
      </div>
    </div>
  )
}

const EMPTY: CreateEmailTemplatePayload = {
  name: '',
  description: '',
  template_type: 'BUILTIN',
  builtin_name: 'editorial',
  html_content: '',
  external_provider: '',
  external_template_id: '',
  external_config: {},
}

export default function EmailTemplatesPage() {
  const [templates, setTemplates] = useState<EmailTemplate[]>([])
  const [loading, setLoading] = useState(true)
  const [showModal, setShowModal] = useState(false)
  const [editTarget, setEditTarget] = useState<EmailTemplate | null>(null)
  const [form, setForm] = useState<CreateEmailTemplatePayload>(EMPTY)
  const [saving, setSaving] = useState(false)
  const [previewId, setPreviewId] = useState<string | null>(null)

  useEffect(() => { fetchTemplates() }, [])

  const fetchTemplates = async () => {
    try {
      setLoading(true)
      const data = await listEmailTemplates()
      setTemplates(data)
    } catch (e) {
      toast.error('Failed to load email templates')
    } finally {
      setLoading(false)
    }
  }

  const openCreate = () => {
    setEditTarget(null)
    setForm(EMPTY)
    setShowModal(true)
  }

  const openEdit = (t: EmailTemplate) => {
    setEditTarget(t)
    setForm({
      name: t.name,
      description: t.description ?? '',
      template_type: t.template_type,
      builtin_name: t.builtin_name ?? 'editorial',
      html_content: t.html_content ?? '',
      external_provider: t.external_provider ?? '',
      external_template_id: t.external_template_id ?? '',
      external_config: t.external_config ?? {},
    })
    setShowModal(true)
  }

  const handleSave = async () => {
    if (!form.name.trim()) { toast.error('Name is required'); return }
    setSaving(true)
    try {
      const payload: CreateEmailTemplatePayload = {
        name: form.name.trim(),
        description: form.description || undefined,
        template_type: form.template_type,
        builtin_name: form.template_type === 'BUILTIN' ? form.builtin_name : undefined,
        html_content: form.template_type === 'CUSTOM_HTML' ? form.html_content : undefined,
        external_provider: ['SENDGRID', 'MAILCHIMP', 'BREVO'].includes(form.template_type) ? form.external_provider : undefined,
        external_template_id: ['SENDGRID', 'MAILCHIMP', 'BREVO'].includes(form.template_type) ? form.external_template_id : undefined,
        external_config: ['SENDGRID', 'MAILCHIMP', 'BREVO'].includes(form.template_type) ? form.external_config : undefined,
      }

      if (editTarget) {
        await updateEmailTemplate(editTarget.id, payload)
        toast.success('Template updated')
      } else {
        await createEmailTemplate(payload)
        toast.success('Template created')
      }
      setShowModal(false)
      fetchTemplates()
    } catch (e: any) {
      toast.error(e.message || 'Failed to save template')
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async (id: string, name: string) => {
    if (!confirm(`Delete "${name}"?`)) return
    try {
      await deleteEmailTemplate(id)
      toast.success('Template deleted')
      fetchTemplates()
    } catch (e) {
      toast.error('Failed to delete template')
    }
  }

  const isThirdParty = ['SENDGRID', 'MAILCHIMP', 'BREVO'].includes(form.template_type)

  return (
    <div className="dashboard-resource-page min-h-screen">
      <div className="max-w-5xl mx-auto px-4 md:px-6 py-8">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-2xl md:text-3xl font-extrabold text-gray-900 tracking-tight">Email Templates</h1>
            <p className="text-gray-500 mt-1 text-sm">
              Manage reusable templates for agent emails. Assign a template to an agent from its edit page.
            </p>
          </div>
          <button
            onClick={openCreate}
            className="inline-flex items-center gap-2 px-4 py-2 bg-red-600 text-white text-sm font-medium rounded-lg hover:bg-red-700 transition-colors"
          >
            <Plus size={18} />
            New Template
          </button>
        </div>

        {/* List */}
        {loading ? (
          <div className="space-y-3">
            {[...Array(3)].map((_, i) => (
              <div key={i} className="bg-white rounded-xl border border-gray-200 p-5 animate-pulse">
                <div className="h-4 bg-gray-200 rounded w-40 mb-2" />
                <div className="h-3 bg-gray-100 rounded w-64" />
              </div>
            ))}
          </div>
        ) : templates.length === 0 ? (
          <div className="text-center py-20">
            <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <Mail className="w-8 h-8 text-red-500" />
            </div>
            <h3 className="text-lg font-semibold text-gray-900 mb-2">No email templates yet</h3>
            <p className="text-gray-500 text-sm mb-6">Create a template to assign to your agents</p>
            <button onClick={openCreate} className="inline-flex items-center gap-2 px-5 py-2 bg-red-600 text-white text-sm font-medium rounded-lg hover:bg-red-700 transition-colors">
              <Plus size={16} /> New Template
            </button>
          </div>
        ) : (
          <div className="space-y-3">
            {templates.map((t) => (
              <div key={t.id} className="bg-white rounded-xl border border-gray-200 p-5 hover:shadow-sm transition-shadow">
                <div className="flex items-start justify-between gap-4">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <span className="font-semibold text-gray-900">{t.name}</span>
                      <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${TYPE_COLORS[t.template_type]}`}>
                        {TYPE_LABELS[t.template_type]}
                      </span>
                    </div>
                    {t.description && <p className="text-sm text-gray-500 mb-2">{t.description}</p>}
                    <div className="text-xs text-gray-400">
                      {t.template_type === 'BUILTIN' && `Layout: ${BUILTIN_LAYOUT_LABELS[t.builtin_name || 'editorial'] || (t.builtin_name || 'editorial')}`}
                      {t.template_type === 'CUSTOM_HTML' && 'Custom HTML layout'}
                      {['SENDGRID', 'MAILCHIMP', 'BREVO'].includes(t.template_type) && (
                        <span>Template ID: <code className="bg-gray-100 px-1 rounded">{t.external_template_id || '—'}</code></span>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-2 flex-shrink-0">
                    {t.preview_html && (
                      <button
                        onClick={() => setPreviewId(previewId === t.id ? null : t.id)}
                        className="px-3 py-1.5 text-xs font-medium text-gray-600 border border-gray-200 rounded-lg hover:bg-gray-50"
                      >
                        Preview
                      </button>
                    )}
                    <button onClick={() => openEdit(t)} className="p-1.5 text-gray-400 hover:text-gray-700 rounded-lg hover:bg-gray-100 transition-colors">
                      <Edit2 size={15} />
                    </button>
                    <button onClick={() => handleDelete(t.id, t.name)} className="p-1.5 text-gray-400 hover:text-red-600 rounded-lg hover:bg-red-50 transition-colors">
                      <Trash2 size={15} />
                    </button>
                  </div>
                </div>
                {previewId === t.id && t.preview_html && (
                  <div className="mt-4 border border-gray-200 rounded-lg overflow-hidden">
                    <iframe
                      srcDoc={t.preview_html}
                      className="w-full h-80"
                      sandbox="allow-same-origin"
                      title="Template preview"
                    />
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Create / Edit Modal */}
      {showModal && (
        <TemplateModal
          editTarget={editTarget}
          form={form}
          setForm={setForm}
          saving={saving}
          onSave={handleSave}
          onClose={() => setShowModal(false)}
        />
      )}
    </div>
  )
}
