<div
    x-data="{
        open: false,
        minimized: false,
        sending: false,
        preview: null,
        showPreview: false,
        resizing: false,
        panelHeight: Math.min(600, (window.innerHeight || 800) - 96),

        startResize(e) {
            e.preventDefault();
            this.resizing = true;
            const startY = e.clientY;
            const startH = this.panelHeight;
            const onMove = (ev) => {
                const next = startH + (startY - ev.clientY); // drag up = taller
                this.panelHeight = Math.max(260, Math.min(next, window.innerHeight - 72));
            };
            const onUp = () => {
                this.resizing = false;
                document.body.style.userSelect = '';
                window.removeEventListener('mousemove', onMove);
                window.removeEventListener('mouseup', onUp);
            };
            document.body.style.userSelect = 'none';
            window.addEventListener('mousemove', onMove);
            window.addEventListener('mouseup', onUp);
        },

        close() {
            this.open = false;
            this.minimized = false;
            this.showPreview = false;
            if (this.$refs.editor) this.$refs.editor.innerHTML = '';
        },

        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 (this.$refs.editor) {
                this.$refs.editor.innerHTML = this.preview.bodyHtml;
                this.$refs.editor.focus();
            }
            this.showPreview = false;
        },

        async doSend() {
            if (this.sending) return;
            const html = this.$refs.editor?.innerHTML ?? '';
            if (!html.replace(/<[^>]+>/g, '').trim()) {
                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; minimized = false; $nextTick(() => $refs.editor?.focus())"
    x-on:reply-sent.window="
        open = false;
        minimized = false;
        showPreview = false;
        if ($refs.editor) $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;
    "
    x-show="open"
    x-cloak
    x-transition:enter="transition-all duration-200"
    x-transition:enter-start="opacity-0 translate-y-3"
    x-transition:enter-end="opacity-100 translate-y-0"
    style="position:fixed; bottom:0; right:24px; z-index:1050; width:520px;"
>
    {{-- ── Resize handle (drag the top edge) ──────────────────────────────── --}}
    <div x-show="!minimized"
         x-on:mousedown="startResize($event)"
         title="Drag to resize"
         style="height:9px; background:#404040; border-radius:.5rem .5rem 0 0;
                cursor:ns-resize; display:flex; align-items:center; justify-content:center;">
        <span style="width:36px; height:3px; border-radius:3px; background:rgba(255,255,255,.4);"></span>
    </div>

    {{-- ── Title bar ──────────────────────────────────────────────────────── --}}
    <div
        x-on:click="minimized = !minimized"
        :style="minimized ? 'border-radius:.5rem .5rem 0 0' : 'border-radius:0'"
        style="background:#404040; padding:.45rem .75rem;
               display:flex; align-items:center; gap:.5rem; cursor:pointer; user-select:none;"
    >
        <i class="mdi mdi-reply" style="color:rgba(255,255,255,.8); font-size:.9rem;"></i>
        <span style="color:#fff; font-size:.84rem; font-weight:600; flex:1; overflow:hidden; white-space:nowrap; text-overflow:ellipsis;">
            @if(!empty($to))
                Reply to {{ $to }}
            @else
                Reply
            @endif
        </span>

        @if($sent)
            <span style="font-size:.72rem; color:#86efac; display:flex; align-items:center; gap:.25rem; flex-shrink:0;">
                <i class="mdi mdi-check-circle-outline"></i> Sent
            </span>
        @endif
        @if($error)
            <span style="font-size:.72rem; color:#fca5a5; flex-shrink:0;" title="{{ $error }}">
                <i class="mdi mdi-alert-circle-outline"></i> Error
            </span>
        @endif

        <button type="button"
                x-on:click.stop="minimized = !minimized"
                :title="minimized ? 'Expand' : 'Minimise'"
                style="background:none; border:none; color:rgba(255,255,255,.65); padding:.15rem .35rem;
                       line-height:1; border-radius:.3rem; cursor:pointer;"
                onmouseover="this.style.background='rgba(255,255,255,.15)'"
                onmouseout="this.style.background='none'">
            <i class="mdi" :class="minimized ? 'mdi-window-restore' : 'mdi-minus'" style="font-size:1rem;"></i>
        </button>
        <button type="button"
                x-on:click.stop="close()"
                title="Close"
                style="background:none; border:none; color:rgba(255,255,255,.65); padding:.15rem .35rem;
                       line-height:1; border-radius:.3rem; cursor:pointer;"
                onmouseover="this.style.background='rgba(255,255,255,.15)'"
                onmouseout="this.style.background='none'">
            <i class="mdi mdi-close" style="font-size:1rem;"></i>
        </button>
    </div>

    {{-- ── Compose body ────────────────────────────────────────────────────── --}}
    <div
        x-show="!minimized"
        x-cloak
        x-transition:enter="transition-all duration-150"
        x-transition:enter-start="opacity-0"
        x-transition:enter-end="opacity-100"
        :style="{ height: panelHeight + 'px' }"
        style="background:#fff; border:1px solid #c4c4c4; border-top:0;
               border-radius:0 0 .5rem .5rem; box-shadow:0 6px 32px rgba(0,0,0,.22);
               display:flex; flex-direction:column;
               max-height:calc(100vh - 72px);"
    >

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

            <div style="display:flex; align-items:center; gap:.5rem; padding:.4rem .75rem; border-bottom:1px solid #e9ecef;">
                <span style="width:50px; flex-shrink:0; font-size:.79rem; color:#9ca3af;">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 style="display:flex; align-items:center; gap:.5rem; padding:.4rem .75rem; border-bottom:1px solid #e9ecef;">
                <span style="width:50px; flex-shrink:0; font-size:.79rem; color:#9ca3af;">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 style="display:flex; align-items:center; gap:.5rem; padding:.4rem .75rem; border-bottom:1px solid #e9ecef;">
                <span style="width:50px; flex-shrink:0; font-size:.79rem; color:#9ca3af;">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>

            <div style="display:flex; align-items:center; gap:.5rem; padding:.4rem .75rem;">
                <span style="width:50px; flex-shrink:0; font-size:.79rem; color:#9ca3af;">Template</span>
                <div style="display:flex; align-items:center; gap:.4rem; flex:1; min-width:0;">
                    @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:.82rem; flex:1; box-shadow:none; min-width:0;"
                                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:.74rem;"
                                wire:click="previewTemplate()"
                                wire:loading.attr="disabled"
                                wire:target="previewTemplate"
                                @if(!$templateId) disabled @endif>
                            <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:.74rem;"
                                wire:click="applyTemplate()"
                                wire:loading.attr="disabled"
                                wire:target="applyTemplate"
                                @if(!$templateId) disabled @endif>
                            <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-opacity duration-150"
             x-transition:enter-start="opacity-0"
             x-transition:enter-end="opacity-100"
             class="flex-shrink-0"
             style="border-bottom:1px solid #e5e7eb; display:flex; flex-direction:column; max-height:220px; background:#fff;">
            <div style="background:#f9fafb; border-bottom:1px solid #e5e7eb; padding:.4rem .75rem;
                        display:flex; align-items:center; gap:.5rem; flex-shrink:0;">
                <i class="mdi mdi-eye-outline text-muted" style="font-size:.85rem;"></i>
                <span style="font-size:.8rem; font-weight:600; color:#374151;">Template Preview</span>
                <span class="text-muted fst-italic text-truncate" style="font-size:.78rem; flex:1;"
                      x-text="preview?.subject ?? ''"></span>
                <template x-if="preview?.unknownPlaceholders?.length > 0">
                    <span class="badge bg-warning-subtle text-warning border border-warning-subtle flex-shrink-0"
                          style="font-size:.65rem;"
                          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 flex-shrink-0"
                        style="font-size:.74rem;"
                        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 flex-shrink-0"
                        style="font-size:.74rem;"
                        x-on:click="showPreview = false">
                    <i class="mdi mdi-close"></i>
                </button>
            </div>
            <div style="flex:1; overflow:auto;">
                <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:160px; border:0; display:block;"
                ></iframe>
            </div>
        </div>

        {{-- WYSIWYG toolbar --}}
        <div style="display:flex; align-items:center; gap:.2rem; padding:.3rem .5rem;
                    border-bottom:1px solid #e5e7eb; background:#f9fafb; flex-shrink:0;">
            <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>

            @if($templateId)
                @php $activeTpl = $templates->firstWhere('id', $templateId); @endphp
                @if($activeTpl)
                    <div class="ms-auto d-flex align-items-center gap-1" 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)">
                            <i class="mdi mdi-close"></i>
                        </button>
                    </div>
                @endif
            @endif
        </div>

        {{-- Editable body --}}
        <div style="flex:1; overflow-y:auto; min-height:0; overscroll-behavior:contain;">
            <div
                contenteditable="true"
                x-ref="editor"
                style="outline:none; font-size:.88rem; line-height:1.65; min-height:100px; padding:.75rem .75rem .5rem;"
                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 style="font-size:.82rem; color:#9ca3af; border-top:1px solid #e5e7eb;
                            margin:.25rem .75rem 0; padding:.5rem 0 .75rem;">
                    {!! $signature !!}
                </div>
            @endif
        </div>

        {{-- Footer --}}
        <div style="display:flex; align-items:center; gap:.5rem; padding:.5rem .75rem;
                    border-top:1px solid #e5e7eb; background:#f9fafb; flex-shrink:0;">
            <button
                type="button"
                class="btn btn-primary btn-sm d-flex align-items-center gap-1"
                x-on:click="doSend()"
                :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="close()">
                Discard
            </button>
            <span class="ms-auto text-muted" style="font-size:.72rem; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
                via {{ $senders->firstWhere('id', $senderId)?->email_address ?? '—' }}
            </span>
        </div>

    </div>{{-- /compose body --}}

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

</div>