<div
    x-data="{
        open: false,
        sending: false,
        preview: null,
        showPreview: false,

        toggle() {
            this.open = !this.open;
            if (this.open) {
                this.$nextTick(() => {
                    const ed = this.$refs.editor;
                    if (!ed) return;
                    ed.focus();
                    const range = document.createRange();
                    range.selectNodeContents(ed);
                    range.collapse(true);
                    const sel = window.getSelection();
                    sel.removeAllRanges();
                    sel.addRange(range);
                });
            } else {
                this.showPreview = false;
            }
        },

        fmt(cmd, val = null) {
            document.execCommand(cmd, false, val);
            this.$refs.editor.focus();
        },

        insertLink() {
            const url = prompt('Enter URL:', 'https://');
            if (url) this.fmt('createLink', url);
        },

        applyFromPreview() {
            if (!this.preview) return;
            if ($refs.editor) {
                $refs.editor.innerHTML = this.preview.bodyHtml;
                $refs.editor.focus();
            }
            this.showPreview = false;
        },

        async doSend() {
            if (this.sending) return;
            const html = this.$refs.editor?.innerHTML ?? '';
            const stripped = html.replace(/<[^>]+>/g, '').trim();
            if (!stripped) {
                alert('Please write your reply before sending.');
                return;
            }
            this.sending = true;
            await $wire.set('bodyHtml', html);
            await $wire.call('send');
            this.sending = false;
        },
    }"
    x-on:open-reply-panel.window="open = true; $nextTick(() => $refs.editor?.focus())"
    x-on:reply-sent.window="
        open = false;
        showPreview = false;
        if (this.$refs.editor) this.$refs.editor.innerHTML = '';
    "
    x-on:ct-template-applied.window="
        if ($refs.editor && $event.detail.bodyHtml) {
            $refs.editor.innerHTML = $event.detail.bodyHtml;
            $refs.editor.focus();
        }
        showPreview = false;
    "
    x-on:ct-template-preview.window="
        preview = $event.detail;
        showPreview = true;
    "
    class="border-top flex-shrink-0"
    style="background:#fff;"
>
    {{-- ── Collapsed toggle bar ──────────────────────────────────────── --}}
    <div class="d-flex align-items-center px-3 py-2 gap-2" style="cursor:default;">

        @if($sent)
            <div class="d-flex align-items-center gap-2 text-success small flex-grow-1">
                <i class="mdi mdi-check-circle-outline"></i>
                Reply sent successfully.
            </div>
        @endif

        @if($error)
            <div class="d-flex align-items-center gap-2 text-danger small flex-grow-1">
                <i class="mdi mdi-alert-outline"></i>{{ $error }}
            </div>
        @endif

        <button
            type="button"
            class="btn btn-sm btn-outline-primary ms-auto d-flex align-items-center gap-1"
            x-on:click="toggle()"
            style="font-size:.82rem;"
        >
            <i class="mdi mdi-reply me-1"></i>
            <span x-text="open ? 'Close reply' : 'Reply'"></span>
            <i class="mdi" x-bind:class="open ? 'mdi-chevron-down' : 'mdi-chevron-up'"></i>
        </button>
    </div>

    {{-- ── Compose panel ─────────────────────────────────────────────── --}}
    <div x-show="open" x-cloak
         x-transition:enter="transition-all duration-150"
         x-transition:enter-start="opacity-0 transform translate-y-2"
         x-transition:enter-end="opacity-100 transform translate-y-0"
         class="border-top"
         x-bind:style="{ maxHeight: showPreview ? '90vh' : '600px' }"
         style="display:flex; flex-direction:column;">

        {{-- Header fields --}}
        <div class="px-3 pt-2 pb-1 border-bottom bg-light flex-shrink-0" style="font-size:.83rem;">
            @error('to') <div class="text-danger mb-1" style="font-size:.75rem;">{{ $message }}</div> @enderror
            @error('subject') <div class="text-danger mb-1" style="font-size:.75rem;">{{ $message }}</div> @enderror
            @error('bodyHtml') <div class="text-danger mb-1" style="font-size:.75rem;">Please write a reply before sending.</div> @enderror

            <div class="d-flex align-items-center gap-2 mb-1">
                <span class="text-muted flex-shrink-0" style="width:52px;">From</span>
                <select class="form-select form-select-sm border-0 bg-transparent p-0 fw-medium"
                        style="font-size:.83rem; flex:1; box-shadow:none;"
                        wire:model.live="senderId">
                    @foreach($senders as $s)
                        <option value="{{ $s->id }}">{{ $s->label() }}</option>
                    @endforeach
                </select>
            </div>

            <div class="d-flex align-items-center gap-2 mb-1">
                <span class="text-muted flex-shrink-0" style="width:52px;">To</span>
                <input type="email"
                       class="form-control form-control-sm border-0 bg-transparent p-0 fw-medium"
                       style="font-size:.83rem; box-shadow:none; flex:1;"
                       wire:model="to"
                       placeholder="recipient@example.com">
            </div>

            <div class="d-flex align-items-center gap-2 mb-1">
                <span class="text-muted flex-shrink-0" style="width:52px;">Subject</span>
                <input type="text"
                       class="form-control form-control-sm border-0 bg-transparent p-0"
                       style="font-size:.83rem; box-shadow:none; flex:1;"
                       wire:model="subject"
                       placeholder="Subject">
            </div>

            {{-- Template picker --}}
            <div class="d-flex align-items-center gap-2 pt-1 mt-1 border-top">
                <span class="text-muted flex-shrink-0" style="width:52px;">Template</span>
                <div class="d-flex align-items-center gap-1 flex-grow-1">
                    @if($templates->isEmpty())
                        <span class="text-muted fst-italic" style="font-size:.78rem;">No templates available</span>
                    @else
                        <select class="form-select form-select-sm border-0 bg-transparent p-0"
                                style="font-size:.83rem; flex:1; box-shadow:none;"
                                wire:model="templateId">
                            <option value="">— select a template —</option>
                            @foreach($templates as $tpl)
                                <option value="{{ $tpl->id }}">{{ $tpl->name }}</option>
                            @endforeach
                        </select>
                        <button type="button"
                                class="btn btn-sm btn-outline-secondary py-0 px-2 flex-shrink-0"
                                style="font-size:.76rem;"
                                wire:click="previewTemplate()"
                                wire:loading.attr="disabled"
                                wire:target="previewTemplate"
                                @if(!$templateId) disabled @endif
                                title="Preview rendered template">
                            <span wire:loading.remove wire:target="previewTemplate">
                                <i class="mdi mdi-eye-outline me-1"></i>Preview
                            </span>
                            <span wire:loading wire:target="previewTemplate">
                                <span class="spinner-border spinner-border-sm" role="status"></span>
                            </span>
                        </button>
                        <button type="button"
                                class="btn btn-sm btn-primary py-0 px-2 flex-shrink-0"
                                style="font-size:.76rem;"
                                wire:click="applyTemplate()"
                                wire:loading.attr="disabled"
                                wire:target="applyTemplate"
                                @if(!$templateId) disabled @endif
                                title="Apply template to editor">
                            <span wire:loading.remove wire:target="applyTemplate">
                                <i class="mdi mdi-lightning-bolt me-1"></i>Apply
                            </span>
                            <span wire:loading wire:target="applyTemplate">
                                <span class="spinner-border spinner-border-sm" role="status"></span>
                            </span>
                        </button>
                    @endif
                </div>
            </div>
        </div>

        {{-- ── Template preview panel ──────────────────────────────────────── --}}
        <div x-show="showPreview" x-cloak
             x-transition:enter="transition-all duration-150"
             x-transition:enter-start="opacity-0"
             x-transition:enter-end="opacity-100"
             class="border-bottom flex-shrink-0 bg-white"
             style="max-height:420px; display:flex; flex-direction:column;">

            {{-- Preview header --}}
            <div class="d-flex align-items-center justify-content-between px-3 py-2 bg-light border-bottom flex-shrink-0">
                <div class="d-flex align-items-center gap-2">
                    <i class="mdi mdi-eye-outline text-muted"></i>
                    <span class="fw-semibold" style="font-size:.82rem;">Template Preview</span>
                    <span class="text-muted fst-italic text-truncate" style="font-size:.8rem; max-width:260px;"
                          x-text="preview?.subject ?? ''"></span>
                </div>
                <div class="d-flex align-items-center gap-2">
                    {{-- Unknown placeholders warning --}}
                    <template x-if="preview?.unknownPlaceholders?.length > 0">
                        <span class="badge bg-warning-subtle text-warning border border-warning-subtle"
                              style="font-size:.68rem;"
                              x-bind:title="'Unresolved: ' + preview.unknownPlaceholders.join(', ')">
                            <i class="mdi mdi-alert-outline me-1"></i>
                            <span x-text="preview.unknownPlaceholders.length + ' unresolved'"></span>
                        </span>
                    </template>
                    <button type="button"
                            class="btn btn-sm btn-primary py-0 px-2"
                            style="font-size:.76rem;"
                            x-on:click="applyFromPreview()">
                        <i class="mdi mdi-lightning-bolt me-1"></i>Use this
                    </button>
                    <button type="button"
                            class="btn btn-sm btn-outline-secondary py-0 px-2"
                            style="font-size:.76rem;"
                            x-on:click="showPreview = false">
                        <i class="mdi mdi-close"></i>
                    </button>
                </div>
            </div>

            {{-- Preview body in iframe --}}
            <div class="flex-grow-1 overflow-auto p-0">
                <iframe
                    x-ref="previewFrame"
                    x-effect="
                        if (showPreview && preview?.bodyHtml && $refs.previewFrame) {
                            const doc = $refs.previewFrame.contentDocument || $refs.previewFrame.contentWindow.document;
                            doc.open(); doc.write(preview.bodyHtml); doc.close();
                        }
                    "
                    sandbox="allow-same-origin"
                    style="width:100%; height:320px; border:0; display:block;"
                ></iframe>
            </div>
        </div>

        {{-- WYSIWYG toolbar --}}
        <div class="d-flex align-items-center gap-1 px-2 py-1 border-bottom bg-light flex-shrink-0"
             style="font-size:.8rem;">
            <button type="button" class="btn btn-sm btn-light py-0 px-1 fw-bold" title="Bold"
                    x-on:click.prevent="fmt('bold')" style="font-size:.78rem; min-width:26px;">B</button>
            <button type="button" class="btn btn-sm btn-light py-0 px-1 fst-italic" title="Italic"
                    x-on:click.prevent="fmt('italic')" style="font-size:.78rem; min-width:26px;">I</button>
            <button type="button" class="btn btn-sm btn-light py-0 px-1" title="Underline"
                    x-on:click.prevent="fmt('underline')" style="font-size:.78rem; min-width:26px; text-decoration:underline;">U</button>
            <div class="vr mx-1" style="height:16px;"></div>
            <button type="button" class="btn btn-sm btn-light py-0 px-1" title="Bullet list"
                    x-on:click.prevent="fmt('insertUnorderedList')">
                <i class="mdi mdi-format-list-bulleted" style="font-size:.85rem;"></i>
            </button>
            <button type="button" class="btn btn-sm btn-light py-0 px-1" title="Numbered list"
                    x-on:click.prevent="fmt('insertOrderedList')">
                <i class="mdi mdi-format-list-numbered" style="font-size:.85rem;"></i>
            </button>
            <div class="vr mx-1" style="height:16px;"></div>
            <button type="button" class="btn btn-sm btn-light py-0 px-1" title="Insert link"
                    x-on:click.prevent="insertLink()">
                <i class="mdi mdi-link-variant" style="font-size:.85rem;"></i>
            </button>
            <button type="button" class="btn btn-sm btn-light py-0 px-1" title="Remove formatting"
                    x-on:click.prevent="fmt('removeFormat')">
                <i class="mdi mdi-format-clear" style="font-size:.85rem;"></i>
            </button>

            {{-- Active template indicator --}}
            @if($templateId)
                @php $activeTpl = $templates->firstWhere('id', $templateId); @endphp
                @if($activeTpl)
                    <div class="ms-auto d-flex align-items-center gap-1 text-muted" style="font-size:.73rem;">
                        <i class="mdi mdi-file-document-outline text-primary"></i>
                        <span class="text-primary">{{ $activeTpl->name }}</span>
                        <button type="button"
                                class="btn btn-sm btn-link p-0 text-muted ms-1"
                                style="font-size:.73rem; line-height:1;"
                                wire:click="$set('templateId', null)"
                                title="Clear template">
                            <i class="mdi mdi-close"></i>
                        </button>
                    </div>
                @endif
            @endif
        </div>

        {{-- Editable body --}}
        <div class="flex-grow-1 overflow-auto" style="min-height:0;">
            <div
                contenteditable="true"
                x-ref="editor"
                class="h-100 px-3 pt-2"
                style="outline:none; font-size:.88rem; line-height:1.6; min-height:120px;"
                data-placeholder="Write your reply here…"
                x-on:focus="$el.classList.remove('editor-empty')"
                x-on:blur="if (!$el.innerText.trim()) $el.classList.add('editor-empty')"
            ></div>

            @if($signature)
                <div class="px-3 pb-2 text-muted"
                     style="font-size:.82rem; border-top:1px solid #dee2e6; margin-top:8px; padding-top:8px;">
                    {!! $signature !!}
                </div>
            @endif
        </div>

        {{-- Footer --}}
        <div class="d-flex align-items-center gap-2 px-3 py-2 border-top flex-shrink-0 bg-light">
            <button
                type="button"
                class="btn btn-primary btn-sm d-flex align-items-center gap-1"
                x-on:click="doSend()"
                x-bind:disabled="sending"
            >
                <span x-show="!sending"><i class="mdi mdi-send me-1"></i>Send reply</span>
                <span x-show="sending" x-cloak>
                    <span class="spinner-border spinner-border-sm me-1" role="status"></span>Sending…
                </span>
            </button>
            <button type="button"
                    class="btn btn-sm btn-outline-secondary"
                    x-on:click="toggle()">
                Cancel
            </button>
            <span class="text-muted ms-auto" style="font-size:.72rem;">
                Sending via {{ $senders->firstWhere('id', $senderId)?->email_address ?? '—' }}
            </span>
        </div>
    </div>

    <style>
    [contenteditable][data-placeholder]:empty:before {
        content: attr(data-placeholder);
        color: #adb5bd;
        pointer-events: none;
    }
    </style>
</div>
