import { useEffect, useMemo, useRef, useState } from "react";
import SectionCard from "../components/SectionCard";
import { api, requestBlob } from "../lib/api";

const emptyForm = {
  title: "",
  category: "meeting_protocol",
  description: "",
  content_format: "html",
  content: "<h1>Betriebsrat {{committee_name}}</h1>\n<p>{{template_logo}}</p>\n<h2>Protokoll der BR-Sitzung am {{meeting_date}}</h2>\n<p>{{meeting_title_block}}</p>\n<h2>Organisatorisches und Feststellungen</h2>\n<p>Sitzungsnummer: {{meeting_number}}<br>Sitzungsart: {{meeting_type}}<br>Sitzungsbeginn: {{start_time}}<br>Sitzungsort: {{location}}<br>Sitzungsleitung: {{chair_name}}<br>Schriftführung: {{secretary_name}}</p>\n<p>{{quorum_statement}}</p>\n<p>{{attendees_block}}</p>\n<h2>Protokollnotizen</h2>\n<p>{{protocol_notes}}</p>\n<h2>Tagesordnung und Beratung</h2>\n<p>{{agenda_sections}}</p>\n<h2>Sitzungsende</h2>\n<p>Schließung der Sitzung um {{end_time}} Uhr.</p>\n<p>{{signature_place}}</p>",
  version_label: "v1",
  is_active: true,
  logo_asset_id: "",
};

const sampleValues = {
  committee_name: "Betriebsrat Beispiel GmbH",
  meeting_number: "BR-2026-04",
  meeting_date: "12.05.2026",
  meeting_title_block: "Titel: Ordentliche BR-Sitzung",
  meeting_type: "Ordentlich",
  start_time: "09:00",
  end_time: "11:30",
  location: "Besprechungsraum 1",
  chair_name: "Max Mustermann",
  secretary_name: "Erika Beispiel",
  quorum_statement: "Die Sitzung ist Beschlussfähig.",
  attendees_block: "Anwesende Betriebsratsmitglieder\n- Max Mustermann (Vorsitz)\n- Erika Beispiel (Schriftführung)",
  protocol_notes: "Keine zusätzlichen Protokollnotizen hinterlegt.",
  agenda_sections: "TOP 1: Beispiel-TOP\nBeschreibung und Beratung.\nBeschluss: Beispielbeschluss.",
  signature_place: "Musterstadt, den 12.05.2026",
};

function normalizeTemplate(row) {
  return {
    ...emptyForm,
    ...row,
    description: row?.description || "",
    content_format: row?.content_format || "markdown",
    logo_asset_id: row?.logo_asset_id ? String(row.logo_asset_id) : "",
    is_active: row?.is_active !== false,
  };
}

function stripUnsafeHtml(html) {
  return String(html || "")
    .replace(/<\s*script[^>]*>[\s\S]*?<\s*\/\s*script\s*>/gi, "")
    .replace(/<\s*style[^>]*>[\s\S]*?<\s*\/\s*style\s*>/gi, "")
    .replace(/\son[a-z]+\s*=\s*"[^"]*"/gi, "")
    .replace(/\son[a-z]+\s*=\s*'[^']*'/gi, "")
    .replace(/javascript:/gi, "");
}

function htmlEscape(value) {
  return String(value ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

function markdownToPreviewHtml(markdown) {
  const lines = String(markdown || "").replace(/\r\n/g, "\n").split("\n");
  return lines.map((line) => {
    const trimmed = line.trim();
    if (!trimmed) return "<br>";
    if (trimmed.startsWith("### ")) return `<h3>${htmlEscape(trimmed.slice(4))}</h3>`;
    if (trimmed.startsWith("## ")) return `<h2>${htmlEscape(trimmed.slice(3))}</h2>`;
    if (trimmed.startsWith("# ")) return `<h1>${htmlEscape(trimmed.slice(2))}</h1>`;
    if (trimmed.startsWith("- ")) return `<p>• ${htmlEscape(trimmed.slice(2))}</p>`;
    return `<p>${htmlEscape(line)}</p>`;
  }).join("\n");
}

function renderPreviewContent(content, format, logoUrl) {
  const logoMarkup = logoUrl
    ? `<div class="template-preview-logo"><img src="${logoUrl}" alt="Template-Logo" /></div>`
    : `<span class="template-placeholder-missing">{{template_logo}}</span>`;

  let html = format === "html" ? stripUnsafeHtml(content) : markdownToPreviewHtml(content);
  html = html.replace(/\{\{\s*template_logo\s*\}\}/g, logoMarkup);

  Object.entries(sampleValues).forEach(([key, value]) => {
    const safe = htmlEscape(value).replace(/\n/g, "<br>");
    html = html.replace(new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`, "g"), safe);
  });

  return html.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, '<span class="template-token">{{$1}}</span>');
}

export default function TemplatesPage() {
  const [templates, setTemplates] = useState([]);
  const [assets, setAssets] = useState([]);
  const [placeholders, setPlaceholders] = useState([]);
  const [selectedId, setSelectedId] = useState("");
  const [form, setForm] = useState(emptyForm);
  const [mode, setMode] = useState("editor");
  const [assetFile, setAssetFile] = useState(null);
  const [assetTitle, setAssetTitle] = useState("");
  const [logoPreviewUrl, setLogoPreviewUrl] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const editorRef = useRef(null);
  const textareaRef = useRef(null);
  const editorSelectionRef = useRef(null);

  async function loadTemplates() {
    const rows = await api.get("/templates");
    setTemplates(rows || []);
  }

  async function loadAssets() {
    const rows = await api.get("/templates/assets");
    setAssets(rows || []);
  }

  async function loadPlaceholders() {
    const rows = await api.get("/templates/placeholders");
    setPlaceholders(rows || []);
  }

  async function loadAll() {
    setLoading(true);
    setError("");
    try {
      await Promise.all([loadTemplates(), loadAssets(), loadPlaceholders()]);
    } catch (err) {
      setError(err.message || "Vorlagen konnten nicht geladen werden.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    loadAll();
  }, []);

  useEffect(() => {
    if (form.content_format !== "html") return;
    if (mode !== "editor") return;
    if (editorRef.current && editorRef.current.innerHTML !== form.content) {
      editorRef.current.innerHTML = form.content || "";
    }
  }, [form.content_format, form.content, mode, selectedId]);

  useEffect(() => {
    let cancelled = false;
    let objectUrl = "";

    async function loadLogoPreview() {
      if (!form.logo_asset_id) {
        setLogoPreviewUrl("");
        return;
      }
      try {
        const response = await requestBlob(`/templates/assets/${form.logo_asset_id}/view`);
        const blob = await response.blob();
        objectUrl = URL.createObjectURL(blob);
        if (!cancelled) setLogoPreviewUrl(objectUrl);
      } catch {
        if (!cancelled) setLogoPreviewUrl("");
      }
    }

    loadLogoPreview();

    return () => {
      cancelled = true;
      if (objectUrl) URL.revokeObjectURL(objectUrl);
    };
  }, [form.logo_asset_id]);

  const selectedAsset = useMemo(
    () => assets.find((asset) => String(asset.id) === String(form.logo_asset_id)),
    [assets, form.logo_asset_id]
  );

  const previewHtml = useMemo(
    () => renderPreviewContent(form.content, form.content_format, logoPreviewUrl),
    [form.content, form.content_format, logoPreviewUrl]
  );

  function updateField(field, value) {
    setForm((prev) => ({ ...prev, [field]: value }));
  }

  function startCreate() {
    editorSelectionRef.current = null;
    setSelectedId("");
    setForm(emptyForm);
    setMode("editor");
    setMessage("");
    setError("");
  }

  async function selectTemplate(id) {
    editorSelectionRef.current = null;
    setMessage("");
    setError("");
    setSelectedId(String(id));
    try {
      const row = await api.get(`/templates/${id}`);
      setForm(normalizeTemplate(row));
      setMode(row?.content_format === "html" ? "editor" : "source");
    } catch (err) {
      setError(err.message || "Vorlage konnte nicht geladen werden.");
    }
  }

  function keepEditorFocus(event) {
    event.preventDefault();
  }

  function selectionIsInsideEditor(range) {
    if (!range || !editorRef.current) return false;
    return editorRef.current.contains(range.commonAncestorContainer);
  }

  function rememberEditorSelection() {
    if (form.content_format !== "html" || mode !== "editor") return;
    const selection = window.getSelection?.();
    if (!selection?.rangeCount) return;
    const range = selection.getRangeAt(0);
    if (selectionIsInsideEditor(range)) {
      editorSelectionRef.current = range.cloneRange();
    }
  }

  function restoreEditorSelection() {
    const selection = window.getSelection?.();
    const range = editorSelectionRef.current;
    if (!selection || !selectionIsInsideEditor(range)) return;
    selection.removeAllRanges();
    selection.addRange(range);
  }

  function syncEditorContent() {
    if (form.content_format === "html" && mode === "editor" && editorRef.current) {
      updateField("content", editorRef.current.innerHTML);
    }
  }

  function exec(command, value = null) {
    if (form.content_format !== "html") return;
    editorRef.current?.focus();
    restoreEditorSelection();
    document.execCommand(command, false, value);
    syncEditorContent();
    rememberEditorSelection();
  }

  function insertHtmlAtCursor(html) {
    if (form.content_format === "html" && mode === "editor") {
      editorRef.current?.focus();
      restoreEditorSelection();
      document.execCommand("insertHTML", false, html);
      syncEditorContent();
      rememberEditorSelection();
      return;
    }

    const el = textareaRef.current;
    const tokenText = html.replace(/<[^>]+>/g, "");
    if (!el) {
      updateField("content", `${form.content || ""}${tokenText}`);
      return;
    }
    const start = el.selectionStart ?? form.content.length;
    const end = el.selectionEnd ?? form.content.length;
    const next = `${form.content.slice(0, start)}${tokenText}${form.content.slice(end)}`;
    updateField("content", next);
    window.requestAnimationFrame(() => {
      el.focus();
      el.setSelectionRange(start + tokenText.length, start + tokenText.length);
    });
  }

  function insertPlaceholder(token) {
    insertHtmlAtCursor(`<span>${token}</span>`);
  }

  function insertLogoPlaceholder() {
    insertPlaceholder("{{template_logo}}");
  }

  async function saveTemplate(event) {
    event.preventDefault();
    setMessage("");
    setError("");

    let content = form.content;
    if (form.content_format === "html" && mode === "editor" && editorRef.current) {
      content = editorRef.current.innerHTML;
    }

    const payload = {
      title: form.title,
      category: form.category,
      description: form.description || null,
      content,
      content_format: form.content_format,
      logo_asset_id: form.logo_asset_id ? Number(form.logo_asset_id) : null,
      version_label: form.version_label || "v1",
      is_active: Boolean(form.is_active),
    };

    try {
      let saved;
      if (selectedId) {
        saved = await api.put(`/templates/${selectedId}`, payload);
        setMessage("Vorlage gespeichert.");
      } else {
        saved = await api.post("/templates", payload);
        setSelectedId(String(saved.id));
        setMessage("Vorlage angelegt.");
      }
      setForm(normalizeTemplate(saved));
      await loadTemplates();
    } catch (err) {
      setError(err.message || "Vorlage konnte nicht gespeichert werden.");
    }
  }

  async function deleteTemplate(template) {
    if (!window.confirm(`Vorlage „${template.title}“ wirklich löschen?`)) return;
    setMessage("");
    setError("");
    try {
      await api.delete(`/templates/${template.id}`);
      setMessage("Vorlage gelöscht.");
      if (String(selectedId) === String(template.id)) startCreate();
      await loadTemplates();
    } catch (err) {
      setError(err.message || "Vorlage konnte nicht gelöscht werden.");
    }
  }

  async function uploadLogo(event) {
    event.preventDefault();
    setMessage("");
    setError("");

    if (!assetFile) {
      setError("Bitte zuerst eine PNG- oder JPEG-Datei auswählen.");
      return;
    }

    try {
      const data = new FormData();
      data.append("file", assetFile);
      data.append("title", assetTitle || assetFile.name);
      const asset = await api.post("/templates/assets/upload", data);
      setAssetFile(null);
      setAssetTitle("");
      updateField("logo_asset_id", String(asset.id));
      await loadAssets();
      setMessage("Logo/Bild wurde hochgeladen und der Vorlage zugeordnet.");
    } catch (err) {
      setError(err.message || "Logo/Bild konnte nicht hochgeladen werden.");
    }
  }

  return (
    <>
      <style>{`
        .templates-layout { display: grid; grid-template-columns: 1fr; gap: 18px; align-items: start; }
        .templates-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 10px; }
        .template-list-item { width: 100%; text-align: left; border: 1px solid rgba(148,164,184,.28); background: #fff; border-radius: 16px; padding: 12px; cursor: pointer; display: grid; gap: 4px; }
        .template-list-item.active { border-color: rgba(37,99,235,.6); background: rgba(37,99,235,.06); }
        .template-list-item strong { color: #0f172a; }
        .template-list-item small { color: var(--muted); }
        .template-editor-shell { display: grid; gap: 16px; }
        .template-editor-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
        .template-toolbar { display: flex; gap: 6px; flex-wrap: wrap; padding: 10px; border: 1px solid rgba(148,164,184,.28); border-radius: 16px; background: #f8fafc; }
        .template-toolbar button, .template-mode-btn { border: 1px solid rgba(148,164,184,.36); background: #fff; color: #0f172a; border-radius: 10px; min-height: 34px; padding: 6px 10px; cursor: pointer; font-weight: 700; }
        .template-toolbar button:hover, .template-mode-btn:hover { background: #f1f5f9; }
        .template-mode-btn.active { color: #1d4ed8; border-color: rgba(37,99,235,.55); background: rgba(37,99,235,.08); }
        .template-editor { min-height: 520px; border: 1px solid rgba(148,164,184,.36); border-radius: 18px; padding: 18px; background: #fff; color: #0f172a; line-height: 1.55; overflow: auto; }
        .template-editor:focus { outline: 3px solid rgba(37,99,235,.16); border-color: rgba(37,99,235,.5); }
        .template-editor h1, .template-preview h1 { font-size: 1.7rem; margin: .3rem 0 .8rem; }
        .template-editor h2, .template-preview h2 { font-size: 1.25rem; margin: 1.2rem 0 .5rem; }
        .template-editor h3, .template-preview h3 { font-size: 1.05rem; margin: 1rem 0 .4rem; }
        .template-source { min-height: 520px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: pre; }
        .template-preview { min-height: 520px; border: 1px solid rgba(148,164,184,.28); border-radius: 18px; padding: 22px; background: #fff; color: #0f172a; line-height: 1.55; }
        .template-preview-logo { text-align: center; margin: 0 0 18px; }
        .template-preview-logo img { max-width: 260px; max-height: 96px; object-fit: contain; }
        .template-token { display: inline-block; padding: 1px 6px; border-radius: 999px; background: rgba(37,99,235,.10); color: #1d4ed8; font-weight: 700; }
        .template-placeholder-missing { display: inline-block; padding: 4px 8px; border-radius: 10px; background: #fff7ed; color: #c2410c; font-weight: 700; }
        .template-placeholder-panel { border: 1px solid rgba(148,164,184,.28); background: #fff; border-radius: 16px; padding: 12px; display: grid; gap: 8px; max-height: 240px; overflow: auto; }
        .template-placeholder-panel-top { margin-top: 12px; }
        .template-placeholder-grid { display: flex; gap: 6px; flex-wrap: wrap; }
        .template-placeholder-grid button { border: 1px solid rgba(37,99,235,.26); background: rgba(37,99,235,.06); color: #1d4ed8; border-radius: 999px; padding: 5px 9px; cursor: pointer; font-weight: 700; }
        .template-logo-card { border: 1px solid rgba(148,164,184,.28); background: #fff; border-radius: 16px; padding: 14px; display: grid; gap: 12px; }
        .template-logo-preview { min-height: 104px; border: 1px dashed rgba(148,164,184,.55); border-radius: 14px; display: grid; place-items: center; background: #f8fafc; padding: 12px; }
        .template-logo-preview img { max-width: 260px; max-height: 90px; object-fit: contain; }
        .template-mode-tabs { display: flex; gap: 8px; flex-wrap: wrap; }
        .template-delete-btn { margin-left: auto; }
        @media (max-width: 1150px) { .template-editor-grid { grid-template-columns: 1fr; } }
      `}</style>

      {error ? <div className="alert error">{error}</div> : null}
      {message ? <div className="alert success">{message}</div> : null}

      <div className="templates-layout">
        <SectionCard
          title="Vorlagen"
          subtitle="HTML5/WYSIWYG-Editor für Protokoll- und Berichtsvorlagen. Platzhalter bleiben als {{platzhalter}} erhalten."
          actions={<button className="btn" type="button" onClick={startCreate}>Neue Vorlage</button>}
        >
          <div className="templates-list">
            {templates.map((template) => (
              <button
                key={template.id}
                className={`template-list-item ${String(selectedId) === String(template.id) ? "active" : ""}`}
                type="button"
                onClick={() => selectTemplate(template.id)}
              >
                <strong>{template.title}</strong>
                <small>{template.category} · {template.version_label || "v1"} · {template.content_format || "markdown"}</small>
                <small>{template.is_active ? "Aktiv" : "Inaktiv"}{template.logo_title ? ` · Logo: ${template.logo_title}` : ""}</small>
              </button>
            ))}
            {!templates.length ? <p>Noch keine Vorlagen vorhanden.</p> : null}
          </div>

          <div className="template-placeholder-panel template-placeholder-panel-top">
            <strong>Platzhalter einfügen</strong>
            <small>Per Klick an der aktuellen Cursorposition in „Vorlage bearbeiten“ einfügen.</small>
            <div className="template-placeholder-grid">
              {placeholders.map((placeholder) => (
                <button key={placeholder.token} type="button" onMouseDown={keepEditorFocus} onClick={() => insertPlaceholder(placeholder.token)} title={placeholder.label}>
                  {placeholder.token}
                </button>
              ))}
            </div>
          </div>
        </SectionCard>

        <form onSubmit={saveTemplate} className="template-editor-shell">
          <SectionCard
            title={selectedId ? "Vorlage bearbeiten" : "Vorlage anlegen"}
            subtitle="Für Sitzungsprotokolle wird die aktive Vorlage mit Kategorie meeting_protocol verwendet. Bilder werden über {{template_logo}} eingefügt."
            actions={
              <div className="row-actions">
                <button className="btn secondary" type="button" onClick={loadAll} disabled={loading}>{loading ? "Lade…" : "Aktualisieren"}</button>
                <button className="btn" type="submit">{selectedId ? "Speichern" : "Anlegen"}</button>
              </div>
            }
          >
            <div className="form-grid">
              <div className="template-editor-grid">
                <label>
                  <span>Titel</span>
                  <input className="input" required value={form.title} onChange={(event) => updateField("title", event.target.value)} />
                </label>
                <label>
                  <span>Kategorie</span>
                  <input className="input" required value={form.category} onChange={(event) => updateField("category", event.target.value)} placeholder="meeting_protocol" />
                </label>
              </div>

              <div className="template-editor-grid">
                <label>
                  <span>Format</span>
                  <select className="input" value={form.content_format} onChange={(event) => { updateField("content_format", event.target.value); setMode(event.target.value === "html" ? "editor" : "source"); }}>
                    <option value="html">HTML5/WYSIWYG</option>
                    <option value="markdown">Text/Markdown-kompatibel</option>
                  </select>
                </label>
                <label>
                  <span>Version</span>
                  <input className="input" required value={form.version_label} onChange={(event) => updateField("version_label", event.target.value)} />
                </label>
              </div>

              <label>
                <span>Beschreibung</span>
                <textarea className="textarea" value={form.description} onChange={(event) => updateField("description", event.target.value)} />
              </label>

              <label className="check-row">
                <input type="checkbox" checked={form.is_active} onChange={(event) => updateField("is_active", event.target.checked)} />
                <span>Vorlage aktiv</span>
              </label>
            </div>
          </SectionCard>

          <SectionCard title="Logo / Bild" subtitle="PNG oder JPEG hochladen, auswählen und über {{template_logo}} in die Vorlage einfügen.">
            <div className="template-logo-card">
              <label>
                <span>Vorhandenes Logo/Bild</span>
                <select className="input" value={form.logo_asset_id} onChange={(event) => updateField("logo_asset_id", event.target.value)}>
                  <option value="">Kein Logo/Bild</option>
                  {assets.map((asset) => (
                    <option key={asset.id} value={asset.id}>{asset.title} · {asset.file_name}</option>
                  ))}
                </select>
              </label>
              <div className="template-logo-preview">
                {logoPreviewUrl ? <img src={logoPreviewUrl} alt="Template-Logo" /> : <span>Kein Logo/Bild ausgewählt</span>}
              </div>
              {selectedAsset ? <small>Ausgewählt: {selectedAsset.title} · {selectedAsset.mime_type}</small> : null}
              <button className="btn secondary" type="button" onMouseDown={keepEditorFocus} onClick={insertLogoPlaceholder}>{"{{template_logo}}"} einfügen</button>
              <div className="form-grid">
                <label>
                  <span>Neues Logo/Bild hochladen</span>
                  <input className="input" type="file" accept="image/png,image/jpeg" onChange={(event) => setAssetFile(event.target.files?.[0] || null)} />
                </label>
                <label>
                  <span>Titel des Bildes</span>
                  <input className="input" value={assetTitle} onChange={(event) => setAssetTitle(event.target.value)} placeholder="z. B. BR-Logo" />
                </label>
                <button className="btn secondary" type="button" onClick={uploadLogo}>Logo/Bild hochladen</button>
              </div>
            </div>
          </SectionCard>

          <SectionCard
            title="Inhalt"
            subtitle="Editor, Quelltext und Vorschau können jederzeit gewechselt werden. Gespeichert wird der HTML-/Textinhalt mit unveränderten Platzhaltern."
            actions={
              <div className="template-mode-tabs">
                {form.content_format === "html" ? <button className={`template-mode-btn ${mode === "editor" ? "active" : ""}`} type="button" onClick={() => setMode("editor")}>Editor</button> : null}
                <button className={`template-mode-btn ${mode === "source" ? "active" : ""}`} type="button" onClick={() => { syncEditorContent(); setMode("source"); }}>HTML/Text</button>
                <button className={`template-mode-btn ${mode === "preview" ? "active" : ""}`} type="button" onClick={() => { syncEditorContent(); setMode("preview"); }}>Vorschau</button>
              </div>
            }
          >
            {form.content_format === "html" && mode === "editor" ? (
              <>
                <div className="template-toolbar">
                  <button type="button" onMouseDown={keepEditorFocus} onClick={() => exec("formatBlock", "H1")}>H1</button>
                  <button type="button" onMouseDown={keepEditorFocus} onClick={() => exec("formatBlock", "H2")}>H2</button>
                  <button type="button" onMouseDown={keepEditorFocus} onClick={() => exec("formatBlock", "H3")}>H3</button>
                  <button type="button" onMouseDown={keepEditorFocus} onClick={() => exec("bold")}>Fett</button>
                  <button type="button" onMouseDown={keepEditorFocus} onClick={() => exec("italic")}>Kursiv</button>
                  <button type="button" onMouseDown={keepEditorFocus} onClick={() => exec("insertUnorderedList")}>Liste</button>
                  <button type="button" onMouseDown={keepEditorFocus} onClick={() => exec("insertOrderedList")}>Nummernliste</button>
                  <button type="button" onMouseDown={keepEditorFocus} onClick={() => exec("insertHorizontalRule")}>Trennlinie</button>
                  <button type="button" onMouseDown={keepEditorFocus} onClick={() => insertHtmlAtCursor('<table border="1"><tbody><tr><td>Spalte 1</td><td>Spalte 2</td></tr></tbody></table>')}>Tabelle</button>
                  <button type="button" onMouseDown={keepEditorFocus} onClick={() => exec("removeFormat")}>Format löschen</button>
                </div>
                <div
                  ref={editorRef}
                  className="template-editor"
                  contentEditable
                  suppressContentEditableWarning
                  onInput={() => {
                    updateField("content", editorRef.current?.innerHTML || "");
                    rememberEditorSelection();
                  }}
                  onKeyUp={rememberEditorSelection}
                  onMouseUp={rememberEditorSelection}
                  onFocus={rememberEditorSelection}
                />
              </>
            ) : null}

            {mode === "source" ? (
              <textarea
                ref={textareaRef}
                className="textarea template-source"
                value={form.content}
                onChange={(event) => updateField("content", event.target.value)}
              />
            ) : null}

            {mode === "preview" ? (
              <div className="template-preview" dangerouslySetInnerHTML={{ __html: previewHtml }} />
            ) : null}

            <div className="row-actions" style={{ marginTop: 14 }}>
              <button className="btn" type="submit">{selectedId ? "Vorlage speichern" : "Vorlage anlegen"}</button>
              {selectedId ? (
                <button
                  className="btn danger template-delete-btn"
                  type="button"
                  onClick={() => deleteTemplate({ id: selectedId, title: form.title })}
                >
                  Vorlage löschen
                </button>
              ) : null}
            </div>
          </SectionCard>
        </form>
      </div>
    </>
  );
}
