{{ define "fragments/markdownEditor" }}
    {{ $name        := .Name        }}
    {{ $value       := .Value       }}
    {{ $blobName    := .BlobName    }}
    {{ $blobValues  := .BlobValues  }}
    {{ $rows        := (or .Rows 5) }}
    {{ $required    := .Required    }}
    {{ $autofocus   := .AutoFocus   }}
    {{ $placeholder := .Placeholder }}
    <div
        class="flex flex-col gap-2"
        data-md-editor
        hx-disinherit="*"
        hx-include="this"
    >
        <div class="btn-group self-start text-gray-600 dark:text-gray-300">
            <button type="button" data-md-mode="write"
                class="btn-group-item active group">
                {{ i "pencil" "w-3.5 h-3.5" }}
                Write
            </button>
            <button type="button" data-md-mode="preview"
                hx-post="/markup/preview"
                hx-target="next [data-md-preview]"
                hx-swap="innerHTML"
                hx-indicator="this"
                hx-disabled-elt="this"
                class="btn-group-item group">
                {{ i "eye" "w-3.5 h-3.5 inline group-[.htmx-request]:hidden" }}
                {{ i "loader-circle" "w-3.5 h-3.5 animate-spin hidden group-[.htmx-request]:inline" }}
                Preview
            </button>
        </div>
        <div data-md-panel="write">
            <textarea
                name="{{ $name }}"
                rows="{{ $rows }}"
                class="w-full resize-y dark:bg-gray-800 dark:text-white dark:border-gray-700"
                {{if $required}}required{{end}}
                {{if $autofocus}}autofocus{{end}}
                placeholder="{{ $placeholder }}"
            >{{with $value}}{{.}}{{end}}</textarea>
        </div>
        <div data-md-panel="preview" class="hidden">
            <div data-md-preview class="min-h-[6rem] p-3 border border-gray-200 dark:border-gray-700 rounded bg-gray-50 dark:bg-gray-900/30">
                <span class="text-gray-400 dark:text-gray-500 italic">Loading preview...</span>
            </div>
        </div>
    </div>
    <script>
    (() => {
        if (window.__mdEditorWired) return;
        window.__mdEditorWired = true;
        document.body.addEventListener('click', (e) => {
            const btn = e.target.closest('[data-md-mode]');
            if (!btn) return;
            const editor = btn.closest('[data-md-editor]');
            if (!editor) return;
            const mode = btn.dataset.mdMode;
            editor.querySelectorAll('[data-md-panel]').forEach(p => {
                p.classList.toggle('hidden', p.dataset.mdPanel !== mode);
            });
            editor.querySelectorAll('[data-md-mode]').forEach(b => {
                b.classList.toggle('active', b === btn);
            });
        });
    })();
    </script>
{{ end }}
