<div class="container-fluid py-4">
    <x-title :breadcrumbs="[
        ['link' => route('templates.index'), 'title' => 'Templates'],
        ['link' => '', 'title' => $template?->exists ? 'Edit' : 'Create'],
    ]">
        {{ $template?->exists ? 'Edit template' : 'Create template' }}
        <x-slot:buttons>
            <a wire:navigate href="{{ route('templates.index') }}" wire:navigate class="btn btn-outline-secondary me-2">
                <i class="mdi mdi-arrow-left me-1"></i>Back
            </a>
            @canany(['templates.create', 'templates.edit'])
                <button wire:click="save" class="btn btn-success px-4">Save Template</button>
            @endcanany
        </x-slot:buttons>
    </x-title>

    @if(session('template_saved'))
        <div class="alert alert-success">{{ session('template_saved') }}</div>
    @endif
    @if(session('template_error'))
        <div class="alert alert-warning">{{ session('template_error') }}</div>
    @endif
    @if(!empty($unknownAtSave))
        <div class="alert alert-warning">
            <strong>Unknown placeholders detected:</strong> {{ implode(', ', $unknownAtSave) }}
            <div class="small mt-1">
                These will render as empty strings for manual sends, and cause automatic triggers to fail and be logged.
            </div>
        </div>
    @endif

    <div class="row g-3">
        {{-- LEFT: editor form --}}
        <div class="col-lg-7">
            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h5 class="mb-3">Details</h5>

                    <div class="row g-3">
                        <div class="col-md-8">
                            <label class="form-label fw-bold">Name</label>
                            <input type="text" wire:model.live.debounce.500ms="name" class="form-control" placeholder="e.g. Welcome email">
                            @error('name') <small class="text-danger">{{ $message }}</small> @enderror
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold">Internal key</label>
                            <input type="text" wire:model="key" class="form-control" placeholder="welcome_email">
                            <small class="text-muted">Used by code-driven sends.</small>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label fw-bold">Channel</label>
                            <select wire:model.live="channel" class="form-select">
                                <option value="email">Email</option>
                                <option value="sms">SMS</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold">Category</label>
                            <select wire:model="category_id" class="form-select">
                                <option value="">—</option>
                                @foreach($categories as $c)
                                    <option value="{{ $c->id }}">{{ $c->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold">Applies to</label>
                            <select wire:model.live="applies_to_type" class="form-select">
                                <option value="">Any record</option>
                                <option value="App\Models\Client\Client">Client / Claim</option>
                            </select>
                            <small class="text-muted">Filters placeholders + triggers.</small>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold">Recipient</label>
                            <select wire:model.live="recipient_type" class="form-select">
                                <option value="client">Client</option>
                                <option value="scheme">Scheme (SCARS)</option>
                                <option value="user">User (staff)</option>
                                <option value="institution">Institution contact</option>
                                <option value="case_worker">Case worker (redress)</option>
                            </select>
                            <small class="text-muted">Who this template is sent to.</small>
                        </div>

                        @if($recipient_type === 'user')
                            <div class="col-12">
                                <label class="form-label fw-bold">Users to send to</label>
                                <div class="border rounded p-2 bg-white" style="max-height:180px;overflow-y:auto;">
                                    @forelse($solicitorUsers as $u)
                                        <div class="form-check form-check-sm">
                                            <input class="form-check-input" type="checkbox"
                                                   value="{{ $u->id }}"
                                                   wire:model="recipientUserIds"
                                                   id="ru_{{ $u->id }}">
                                            <label class="form-check-label small" for="ru_{{ $u->id }}">
                                                {{ trim($u->name_first . ' ' . $u->name_last) ?: 'User #' . $u->id }}
                                                @if($u->email_address)
                                                    <span class="text-muted">&lt;{{ $u->email_address }}&gt;</span>
                                                @endif
                                            </label>
                                        </div>
                                    @empty
                                        <span class="text-muted small">No staff users found.</span>
                                    @endforelse
                                </div>
                                <small class="text-muted">
                                    The message is sent to every selected user whenever this template is used.
                                </small>
                                @error('recipientUserIds.*') <small class="text-danger d-block">{{ $message }}</small> @enderror
                            </div>
                        @endif

                        <div class="col-12">
                            <label class="form-label fw-bold">Description <span class="text-muted">(optional)</span></label>
                            <input type="text" wire:model="description" class="form-control" placeholder="What this template is for...">
                        </div>
                    </div>

                    <hr class="my-4"/>
                    <h5 class="mb-3">
                        <i class="mdi {{ $channel === 'email' ? 'mdi-email-outline' : 'mdi-message-text-outline' }} me-1"></i>
                        Content
                    </h5>

                    @if($channel === 'email')
                        <div class="mb-3">
                            <label class="form-label fw-bold d-flex justify-content-between">
                                <span>Subject</span>
                                <small class="text-muted">Placeholders allowed</small>
                            </label>
                            <input type="text" wire:model.live.debounce.400ms="subject" class="form-control">
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold">HTML body</label>
                            {{-- Livewire binds to this hidden input; Trix pushes its HTML here on change --}}
                            <input type="hidden" id="tpl-html-sync" wire:model.live="body_html_template">
                            {{-- wire:ignore prevents Livewire from morphing the Trix DOM on re-renders --}}
                            <div wire:ignore class="border rounded" data-tpl-html-editor>
                                <input id="tpl-html-trix-input" type="hidden" value="{{ $body_html_template ?? '' }}">
                                <trix-editor input="tpl-html-trix-input"
                                             class="trix-content bg-white"
                                             style="min-height: 220px; font-size: 0.9rem;">
                                </trix-editor>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold d-flex justify-content-between">
                                <span>Plain text body</span>
                                <small class="text-muted">Sent as fallback + basis for signature text</small>
                            </label>
                            <textarea wire:model.live.debounce.500ms="body_text_template"
                                      class="form-control"
                                      rows="5"></textarea>
                        </div>
                    @else
                        <div class="mb-3">
                            <label class="form-label fw-bold">SMS body</label>
                            <textarea wire:model.live.debounce.400ms="body_text_template"
                                      class="form-control" rows="5"></textarea>
                            @if($smsLength !== null)
                                <div class="small text-muted mt-1">
                                    <i class="mdi mdi-counter me-1"></i>
                                    {{ $smsLength }} chars &middot;
                                    {{ $smsSegments }} segment{{ $smsSegments === 1 ? '' : 's' }}
                                    &middot; {{ $smsEncoding }}
                                    @if($smsSegments > 1)
                                        <span class="text-warning">— will be sent as multiple parts</span>
                                    @endif
                                </div>
                            @endif
                        </div>
                    @endif
                </div>
            </div>

            {{-- Sender + flags --}}
            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h5 class="mb-3">Sender &amp; flags</h5>

                    <div class="row g-3">
                        @if($channel === 'email')
                            <div class="col-md-8">
                                <label class="form-label fw-bold">Default email sender</label>
                                <select wire:model.live="default_sender_email_id" class="form-select">
                                    <option value="">— use solicitor default —</option>
                                    @foreach($emailSenders as $s)
                                        <option value="{{ $s->id }}">{{ $s->label() }}</option>
                                    @endforeach
                                </select>
                                <small class="text-muted">If blank, falls back to the solicitor's general sender.</small>
                            </div>
                            <div class="col-md-4 d-flex align-items-end">
                                <div class="form-check form-switch">
                                    <input type="checkbox" class="form-check-input" id="inc_sig"
                                           wire:model.live="include_signature">
                                    <label class="form-check-label" for="inc_sig">Include signature</label>
                                </div>
                            </div>
                        @else
                            <div class="col-md-12">
                                <label class="form-label fw-bold">Default SMS sender</label>
                                <select wire:model.live="default_sms_sender_id" class="form-select">
                                    <option value="">— use solicitor default —</option>
                                    @foreach($smsSenders as $s)
                                        <option value="{{ $s->id }}">{{ $s->label() }}</option>
                                    @endforeach
                                </select>
                                @if($smsSenders->isEmpty())
                                    <small class="text-warning">
                                        No SMS senders are whitelisted yet. Add one under Solicitor → SMS Senders.
                                    </small>
                                @endif
                            </div>
                        @endif

                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input type="checkbox" class="form-check-input" id="tpl_active"
                                       wire:model.live="is_active">
                                <label class="form-check-label" for="tpl_active">Active</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input type="checkbox" class="form-check-input" id="tpl_manual"
                                       wire:model.live="allow_manual_send">
                                <label class="form-check-label" for="tpl_manual">Available for manual send</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input type="checkbox" class="form-check-input" id="tpl_auto"
                                       wire:model.live="allow_automatic_send">
                                <label class="form-check-label" for="tpl_auto">Usable by triggers</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {{-- Attachments --}}
            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h5 class="mb-1">
                        <i class="mdi mdi-paperclip me-1"></i>Attachments
                    </h5>
                    <p class="small text-muted mb-3">
                        Select document types to automatically attach when this template is sent.
                        The latest document of each type on the client will be used.
                    </p>

                    @if($documentTypes->isEmpty())
                        <div class="text-muted small">No document types configured.</div>
                    @else
                        <div class="row g-1">
                            @foreach($documentTypes as $dt)
                                <div class="col-md-6">
                                    <div class="form-check">
                                        <input class="form-check-input"
                                               type="checkbox"
                                               value="{{ $dt->id }}"
                                               wire:model.live="documentTypeIds"
                                               id="dt_{{ $dt->id }}">
                                        <label class="form-check-label small" for="dt_{{ $dt->id }}">
                                            {{ $dt->display_name }}
                                        </label>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @endif

                    @if(!empty($documentTypeIds))
                        <div class="mt-2 d-flex flex-wrap gap-1">
                            @foreach($documentTypes->whereIn('id', array_map('intval', $documentTypeIds)) as $dt)
                                <span class="badge bg-secondary">
                                    <i class="mdi mdi-paperclip me-1"></i>{{ $dt->display_name }}
                                </span>
                            @endforeach
                        </div>
                    @endif
                </div>
            </div>

            {{-- Triggers section (only once the template exists) --}}
            @if($template?->exists)
                <div class="card shadow-sm mb-3">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="mb-0">
                                <i class="mdi mdi-robot-outline me-1"></i>Automatic triggers
                            </h5>
                            @can('communications.triggers.manage')
                                <button type="button" class="btn btn-primary btn-sm"
                                        wire:click="openTriggerForm(null)"
                                        @disabled(!$allow_automatic_send)>
                                    <i class="mdi mdi-plus me-1"></i>Add trigger
                                </button>
                            @endcan
                        </div>

                        @if(!$allow_automatic_send)
                            <div class="alert alert-light small mb-3">
                                Enable <em>"Usable by triggers"</em> above to allow this template to fire automatically.
                            </div>
                        @endif

                        @if($triggers->isEmpty())
                            <div class="text-muted small">No triggers configured.</div>
                        @else
                            <table class="table table-sm align-middle">
                                <thead>
                                    <tr>
                                        <th>Event</th>
                                        <th>Applies to</th>
                                        <th>Condition</th>
                                        <th>Dedupe</th>
                                        <th>Active</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($triggers as $trig)
                                        <tr wire:key="trg-{{ $trig->id }}">
                                            <td><span class="badge bg-secondary">{{ $trig->trigger_type->label() }}</span></td>
                                            <td class="small">{{ $availableModels[$trig->model_type] ?? class_basename($trig->model_type ?? 'Any') }}</td>
                                            <td class="small">
                                                @php
                                                    $parts = [];
                                                    $resolveNames = fn($ids, $map) => collect((array)$ids)
                                                        ->map(fn($id) => $map[$id] ?? "#{$id}")
                                                        ->implode(', ');
                                                    if (!empty($trig->conditions['to_status_id'])) {
                                                        $parts[] = 'To: ' . $resolveNames($trig->conditions['to_status_id'], $statusMap);
                                                    }
                                                    if (!empty($trig->conditions['from_status_id'])) {
                                                        $parts[] = 'From: ' . $resolveNames($trig->conditions['from_status_id'], $statusMap);
                                                    }
                                                    if (!empty($trig->conditions['tag_id'])) {
                                                        $parts[] = 'Tag: ' . $resolveNames($trig->conditions['tag_id'], $tagMap);
                                                    }
                                                @endphp
                                                {{ implode(' · ', $parts) ?: '—' }}
                                            </td>
                                            <td class="small">{{ $trig->dedupe_window_minutes }}m</td>
                                            <td>
                                                @if($trig->is_active)
                                                    <span class="badge bg-success">on</span>
                                                @else
                                                    <span class="badge bg-secondary">off</span>
                                                @endif
                                            </td>
                                            <td class="text-end">
                                                @can('communications.triggers.manage')
                                                    <button class="btn btn-sm btn-outline-primary"
                                                            wire:click="openTriggerForm({{ $trig->id }})">Edit</button>
                                                    <button class="btn btn-sm btn-outline-danger"
                                                            wire:click="deleteTrigger({{ $trig->id }})"
                                                            wire:confirm="Delete this trigger?">
                                                        <i class="mdi mdi-delete"></i>
                                                    </button>
                                                @endcan
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        @endif

                        @if($showTriggerForm)
                            <div class="border rounded p-3 mt-3 bg-light">
                                <h6>{{ $editingTriggerId ? 'Edit trigger' : 'New trigger' }}</h6>
                                <div class="row g-2">
                                    <div class="col-md-4">
                                        <label class="form-label small">When this happens</label>
                                        <select wire:model.live="triggerForm.trigger_type" class="form-select form-select-sm">
                                            @foreach($triggerTypes as $tt)
                                                <option value="{{ $tt->value }}">{{ $tt->label() }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label small">Applies to</label>
                                        <select wire:model="triggerForm.model_type" class="form-select form-select-sm">
                                            @foreach($availableModels as $class => $label)
                                                <option value="{{ $class }}">{{ $label }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label small">Don't resend within (minutes)</label>
                                        <input type="number" wire:model="triggerForm.dedupe_window_minutes"
                                               class="form-control form-control-sm" min="0">
                                    </div>

                                    {{-- Contextual condition builder --}}
                                    <div class="col-12">
                                        @if($triggerForm['trigger_type'] === 'status_changed')
                                            <label class="form-label small fw-semibold">
                                                Condition
                                                <span class="text-muted fw-normal ms-1">(optional — tick nothing to fire on any status change)</span>
                                            </label>
                                            <div class="row g-2">
                                                <div class="col-6">
                                                    <p class="form-label small text-muted mb-1">From status</p>
                                                    <div class="border rounded p-2 bg-white" style="max-height:160px;overflow-y:auto;">
                                                        @forelse($statuses as $s)
                                                            <div class="form-check form-check-sm">
                                                                <input class="form-check-input" type="checkbox"
                                                                       value="{{ $s->id }}"
                                                                       wire:model="triggerConditionFromStatusIds"
                                                                       id="te_from_s_{{ $s->id }}">
                                                                <label class="form-check-label small" for="te_from_s_{{ $s->id }}">
                                                                    {{ $s->display_name }}
                                                                </label>
                                                            </div>
                                                        @empty
                                                            <span class="text-muted small">No statuses configured.</span>
                                                        @endforelse
                                                    </div>
                                                </div>
                                                <div class="col-6">
                                                    <p class="form-label small text-muted mb-1">To status</p>
                                                    <div class="border rounded p-2 bg-white" style="max-height:160px;overflow-y:auto;">
                                                        @forelse($statuses as $s)
                                                            <div class="form-check form-check-sm">
                                                                <input class="form-check-input" type="checkbox"
                                                                       value="{{ $s->id }}"
                                                                       wire:model="triggerConditionToStatusIds"
                                                                       id="te_to_s_{{ $s->id }}">
                                                                <label class="form-check-label small" for="te_to_s_{{ $s->id }}">
                                                                    {{ $s->display_name }}
                                                                </label>
                                                            </div>
                                                        @empty
                                                            <span class="text-muted small">No statuses configured.</span>
                                                        @endforelse
                                                    </div>
                                                </div>
                                            </div>

                                        @elseif(in_array($triggerForm['trigger_type'], ['tag_added', 'tag_removed']))
                                            <label class="form-label small fw-semibold">
                                                Condition
                                                <span class="text-muted fw-normal ms-1">(optional — tick nothing to fire on any tag)</span>
                                            </label>
                                            <div class="border rounded p-2 bg-white" style="max-height:160px;overflow-y:auto;">
                                                @forelse($tags as $tag)
                                                    <div class="form-check form-check-sm">
                                                        <input class="form-check-input" type="checkbox"
                                                               value="{{ $tag->id }}"
                                                               wire:model="triggerConditionTagIds"
                                                               id="te_tag_{{ $tag->id }}">
                                                        <label class="form-check-label small" for="te_tag_{{ $tag->id }}">
                                                            {{ $tag->name }}
                                                        </label>
                                                    </div>
                                                @empty
                                                    <span class="text-muted small">No tags configured.</span>
                                                @endforelse
                                            </div>

                                        @else
                                            <p class="text-muted small mb-0">
                                                <i class="mdi mdi-information-outline me-1"></i>No conditions available for this trigger type.
                                            </p>
                                        @endif

                                        <button type="button"
                                                class="btn btn-link btn-sm p-0 mt-1 text-muted text-decoration-none"
                                                wire:click="toggleAdvancedTriggerConditions">
                                            <i class="mdi mdi-code-braces me-1"></i>
                                            {{ $triggerShowAdvancedConditions ? 'Hide JSON editor' : 'Advanced: edit conditions as JSON' }}
                                        </button>

                                        @if($triggerShowAdvancedConditions)
                                            <textarea wire:model="triggerForm.conditions"
                                                      class="form-control form-control-sm font-monospace mt-1"
                                                      rows="3"
                                                      placeholder='{"to_status_id": [5]}'></textarea>
                                            @error('triggerForm.conditions')
                                                <small class="text-danger">{{ $message }}</small>
                                            @enderror
                                            <small class="text-muted">Editing JSON directly overrides the checkboxes above when saving.</small>
                                        @endif
                                    </div>

                                    <div class="col-12">
                                        <div class="form-check form-switch">
                                            <input type="checkbox" class="form-check-input"
                                                   id="trg_active_edit"
                                                   wire:model="triggerForm.is_active">
                                            <label class="form-check-label" for="trg_active_edit">Active</label>
                                        </div>
                                    </div>
                                    <div class="col-12 text-end">
                                        <button class="btn btn-outline-secondary btn-sm" wire:click="cancelTrigger">Cancel</button>
                                        @can('communications.triggers.manage')
                                            <button class="btn btn-success btn-sm" wire:click="saveTrigger">Save trigger</button>
                                        @endcan
                                    </div>
                                </div>
                            </div>
                        @endif
                    </div>
                </div>
            @else
                <div class="alert alert-info small">
                    <i class="mdi mdi-information-outline me-1"></i>
                    Save the template first to configure automatic triggers.
                </div>
            @endif
        </div>

        {{-- RIGHT: placeholders + preview --}}
        <div class="col-lg-5">
            <div class="card shadow-sm mb-3">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span class="fw-bold">
                        <i class="mdi mdi-code-braces me-1"></i>Available placeholders
                    </span>
                    <small class="text-muted">click to insert</small>
                </div>
                <div class="card-body" style="max-height: 320px; overflow-y: auto;">
                    @foreach($placeholdersByPrefix as $prefix => $group)
                        <div class="mb-2">
                            <div class="small text-uppercase text-muted fw-bold">{{ $prefix }}</div>
                            @foreach($group as $p)
                                @php $displayToken = '{' . '{ ' . $p->token . ' }' . '}'; @endphp
                                <div class="d-flex justify-content-between align-items-center py-1 border-bottom">
                                    <div>
                                        <code class="small">{{ $displayToken }}</code>
                                        @if($p->description)
                                            <div class="small text-muted">{{ $p->description }}</div>
                                        @endif
                                    </div>
                                    <div class="btn-group btn-group-sm">
                                        @if($channel === 'email')
                                            <button class="btn btn-outline-secondary btn-sm"
                                                    wire:click="insertPlaceholder('{{ $p->token }}', 'subject')"
                                                    title="Insert into subject">Subj</button>
                                            <button class="btn btn-outline-secondary btn-sm"
                                                    onclick="window.dispatchEvent(new CustomEvent('tpl-insert-html', {detail: {token: '{{ $p->token }}'}}))"
                                                    title="Insert into HTML body">HTML</button>
                                            <button class="btn btn-outline-secondary btn-sm"
                                                    wire:click="insertPlaceholder('{{ $p->token }}', 'text')"
                                                    title="Insert into plain text">Text</button>
                                        @else
                                            <button class="btn btn-outline-secondary btn-sm"
                                                    wire:click="insertPlaceholder('{{ $p->token }}', 'text')">
                                                Insert
                                            </button>
                                        @endif
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @endforeach

                    @if($placeholdersByPrefix->isEmpty())
                        <div class="text-muted small">No placeholders registered.</div>
                    @endif
                </div>
            </div>

            <div class="card shadow-sm">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span class="fw-bold"><i class="mdi mdi-eye-outline me-1"></i>Live preview</span>
                    <select wire:model.live="previewClientId" class="form-select form-select-sm" style="width:auto;">
                        <option value="">Sample client...</option>
                        @foreach($previewClients as $c)
                            <option value="{{ $c->id }}">{{ $c->name_first }} {{ $c->name_last }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="card-body">
                    @if(!empty($previewUnknown))
                        <div class="alert alert-warning py-2 small mb-2">
                            Unknown placeholders: {{ implode(', ', $previewUnknown) }}
                        </div>
                    @endif

                    @if($channel === 'email')
                        @if($previewSubject)
                            <div class="border rounded mb-2 p-2 bg-light">
                                <small class="text-muted">Subject</small>
                                <div class="fw-semibold">{{ $previewSubject }}</div>
                            </div>
                        @endif
                        <div class="border rounded bg-white p-3" style="min-height: 260px; max-height: 460px; overflow:auto;">
                            {!! $previewBodyHtml ?: '<em class="text-muted">Start typing to see a preview...</em>' !!}
                        </div>
                        @if($previewBodyText)
                            <details class="mt-2">
                                <summary class="small text-muted">Plain text version</summary>
                                <pre class="small p-2 bg-light rounded mt-1" style="white-space: pre-wrap;">{{ $previewBodyText }}</pre>
                            </details>
                        @endif
                    @else
                        <div class="border rounded bg-white p-3" style="min-height: 180px;">
                            <pre class="mb-0" style="white-space: pre-wrap; font-family: inherit;">{{ $previewBodyText ?: '—' }}</pre>
                        </div>
                        @if($smsLength !== null)
                            <div class="small text-muted mt-2">
                                {{ $smsLength }} chars &middot; {{ $smsSegments }} segment(s) &middot; {{ $smsEncoding }}
                            </div>
                        @endif
                    @endif

                    @if(!empty($previewPlaceholdersUsed))
                        <details class="mt-3">
                            <summary class="small text-muted">
                                {{ count($previewPlaceholdersUsed) }} placeholder(s) resolved
                            </summary>
                            <table class="table table-sm mt-2 small">
                                <tbody>
                                    @foreach($previewPlaceholdersUsed as $token => $value)
                                        <tr>
                                            <td><code>{{ $token }}</code></td>
                                            <td>{{ $value !== '' ? $value : '(empty)' }}</td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </details>
                    @endif
                </div>
            </div>
        </div>
    </div>

    @once
    <style>
        [data-tpl-html-editor] .trix-button--icon-attach { display: none !important; }
        [data-tpl-html-editor] trix-editor { border: none !important; outline: none !important; }
    </style>
    <script>
    (function () {
        if (window._tplHtmlEditorInit) return;
        window._tplHtmlEditorInit = true;

        function initEditor(wrapper) {
            const trix = wrapper.querySelector('trix-editor');
            const innerInput = wrapper.querySelector('input[type="hidden"]');
            const syncInput = document.getElementById('tpl-html-sync');
            let debounce;

            function loadContent() {
                trix.editor.loadHTML(innerInput?.value || '');
            }

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

            trix.addEventListener('trix-change', () => {
                clearTimeout(debounce);
                debounce = setTimeout(() => {
                    if (syncInput) {
                        syncInput.value = trix.value;
                        syncInput.dispatchEvent(new Event('input', { bubbles: true }));
                    }
                }, 500);
            });
        }

        const observer = new MutationObserver(() => {
            document.querySelectorAll('[data-tpl-html-editor]:not([data-tpl-ready])').forEach(el => {
                el.setAttribute('data-tpl-ready', '');
                initEditor(el);
            });
        });
        observer.observe(document.body, { childList: true, subtree: true });

        window.addEventListener('tpl-insert-html', e => {
            const trix = document.querySelector('[data-tpl-html-editor] trix-editor');
            if (trix) {
                trix.editor.insertString('{' + '{ ' + e.detail.token + ' }' + '}');
                trix.focus();
            }
        });

        document.querySelectorAll('[data-tpl-html-editor]:not([data-tpl-ready])').forEach(el => {
            el.setAttribute('data-tpl-ready', '');
            initEditor(el);
        });
    })();
    </script>
    @endonce
</div>
