@props([
    'name',                   // Livewire property name for HTML signature, e.g. "signature"
    'textName' => null,       // Optional Livewire property name for plain-text signature
    'label' => 'Email signature',
    'help' => 'Appended to outgoing emails.',
    'rows' => 5,
])

@php
    $editorId = 'sig-' . md5($name . uniqid('', true));
@endphp

<div class="mb-3 signature-editor" data-signature-editor>
    <label class="form-label fw-semibold">{{ $label }}</label>

    {{--
        Hidden input that Livewire actually binds to.  The Trix editor pushes
        its HTML value into this input on every change via a native 'input'
        event so wire:model.live picks it up.
    --}}
    <input type="hidden" wire:model.live="{{ $name }}" data-signature-sync>

    {{-- wire:ignore prevents Livewire from morphing Trix's DOM --}}
    <div data-signature-trix wire:ignore class="trix-signature-wrapper">
        <input id="{{ $editorId }}" type="hidden" value="{{ $attributes->get('initial', '') }}">
        <trix-editor input="{{ $editorId }}"
                     class="bg-white trix-content"
                     style="min-height:160px; border-radius:.375rem; border:1px solid #dee2e6;">
        </trix-editor>
    </div>

    @if($help)
        <small class="form-text text-muted">{{ $help }}</small>
    @endif

    @if($textName)
        <details class="mt-3">
            <summary class="small text-muted">
                Plain-text version <span class="text-muted">(optional, used when no HTML is rendered)</span>
            </summary>
            <textarea class="form-control mt-2"
                      rows="{{ $rows }}"
                      wire:model.lazy="{{ $textName }}"
                      placeholder="Plain text signature&#10;Lines are preserved as-is."></textarea>
            <small class="form-text text-muted">
                Leave blank to auto-derive from the HTML above when sending.
            </small>
        </details>
    @endif

    @once
        <link rel="stylesheet" href="https://unpkg.com/trix@2.1.1/dist/trix.css">
        <script src="https://unpkg.com/trix@2.1.1/dist/trix.umd.min.js"></script>
        <style>
            trix-editor.trix-content { border: none !important; outline: none !important; }
            trix-toolbar .trix-button-group { margin-bottom: 0; }
        </style>
        <script>
            (function () {
                function initSignatureEditor(wrapper) {
                    if (wrapper._trixInit) return;
                    wrapper._trixInit = true;

                    const editorEl = wrapper.querySelector('trix-editor');
                    if (!editorEl) return;

                    // Find the [data-signature-sync] hidden input within the
                    // shared parent .signature-editor wrapper.
                    const root = wrapper.closest('[data-signature-editor]');
                    const syncEl = root?.querySelector('[data-signature-sync]');

                    const innerInput = wrapper.querySelector('input[type="hidden"]');
                    const initialHtml = innerInput ? innerInput.value : '';

                    function loadInitialContent() {
                        editorEl.editor.loadHTML(initialHtml);
                    }

                    if (editorEl.editor) {
                        loadInitialContent();
                    } else {
                        editorEl.addEventListener('trix-initialize', loadInitialContent, { once: true });
                    }

                    editorEl.addEventListener('trix-change', () => {
                        if (syncEl) {
                            syncEl.value = editorEl.value;
                            syncEl.dispatchEvent(new Event('input', { bubbles: true }));
                        }
                    });
                }

                const observer = new MutationObserver(() => {
                    document.querySelectorAll('[data-signature-trix]:not([data-trix-ready])').forEach(el => {
                        el.setAttribute('data-trix-ready', '');
                        initSignatureEditor(el);
                    });
                });

                observer.observe(document.body, { childList: true, subtree: true });
                document.querySelectorAll('[data-signature-trix]:not([data-trix-ready])').forEach(el => {
                    el.setAttribute('data-trix-ready', '');
                    initSignatureEditor(el);
                });
            })();
        </script>
    @endonce
</div>
