<div class="inbox-wrapper" style="height: calc(100vh - 120px); display: flex; flex-direction: column;">

    <x-title>Inbox</x-title>

    <div class="card flex-grow-1 overflow-hidden mb-0">
        <div class="card-body p-0 d-flex overflow-hidden" style="height: 100%;">

            {{-- ── LEFT RAIL: sender list ──────────────────────────────────── --}}
            <div class="border-end d-flex flex-column"
                 style="width: 220px; min-width: 220px; overflow-y: auto;">
                <div class="p-3 border-bottom">
                    <span class="text-muted small fw-semibold text-uppercase">Inboxes</span>
                </div>
                <div class="list-group list-group-flush flex-grow-1">
                    @forelse($senders as $sender)
                        <button
                            type="button"
                            wire:click="selectSender({{ $sender->id }})"
                            class="list-group-item list-group-item-action d-flex justify-content-between align-items-center py-2 px-3 border-0 {{ $senderId === $sender->id ? 'active' : '' }}"
                        >
                            <div class="overflow-hidden">
                                <div class="fw-medium text-truncate" style="max-width: 150px; font-size: .85rem;">
                                    {{ $sender->display_name ?: $sender->email_address }}
                                </div>
                                <div class="text-truncate" style="max-width: 150px; font-size: .75rem; opacity: .7;">
                                    {{ $sender->email_address }}
                                </div>
                            </div>
                            @if($sender->unread_count > 0)
                                <span class="badge bg-danger rounded-pill ms-1">{{ $sender->unread_count }}</span>
                            @endif
                        </button>
                    @empty
                        <div class="p-3 text-muted small">No sender addresses configured.</div>
                    @endforelse
                </div>
            </div>

            {{-- ── MIDDLE: message list ─────────────────────────────────────── --}}
            <div class="d-flex flex-column border-end"
                 style="width: 320px; min-width: 280px; overflow-y: auto;">

                {{-- Search bar --}}
                <div class="p-2 border-bottom">
                    <input
                        type="text"
                        class="form-control form-control-sm"
                        placeholder="Search…"
                        wire:model.live.debounce.300ms="search"
                    >
                </div>

                {{-- Classification filter bar --}}
                @if($senderId)
                <div class="px-2 py-2 border-bottom d-flex flex-wrap gap-1" style="font-size:.75rem;">
                    @php
                        $filters = [
                            ''               => 'All',
                            'dsar_response'  => 'DSAR',
                            'dsar_matched'   => 'Matched',
                            'dsar_unmatched' => 'Unmatched',
                            'generic'        => 'Generic',
                            'unclassified'   => 'Unclassified',
                        ];
                    @endphp
                    @foreach($filters as $val => $label)
                        <button
                            type="button"
                            wire:click="setClassificationFilter('{{ $val }}')"
                            class="btn btn-sm py-0 px-2 {{ $classificationFilter === $val ? 'btn-dark' : 'btn-outline-secondary' }}"
                            style="font-size:.72rem; line-height:1.6;"
                        >{{ $label }}</button>
                    @endforeach
                </div>
                @endif

                @if(!$senderId)
                    <div class="p-3 text-muted small">Select an inbox to view messages.</div>
                @elseif($messages->isEmpty())
                    <div class="p-3 text-muted small">No emails found.</div>
                @else
                    <div class="list-group list-group-flush flex-grow-1">
                        @foreach($messages as $msg)
                            @php $isUnread = is_null($msg->read_at); @endphp
                            <button
                                type="button"
                                wire:click="openMessage({{ $msg->id }})"
                                class="list-group-item list-group-item-action text-start border-0 {{ $messageId === $msg->id ? 'active' : '' }}"
                                style="padding: .6rem .75rem .6rem 0; position: relative;
                                       {{ $isUnread && $messageId !== $msg->id ? 'background-color: rgba(13,110,253,.05);' : '' }}"
                            >
                                {{-- Unread accent bar --}}
                                <div style="position:absolute; left:0; top:0; bottom:0; width:3px; border-radius:0 2px 2px 0;
                                            background: {{ $isUnread && $messageId !== $msg->id ? '#0d6efd' : 'transparent' }};"></div>

                                <div class="d-flex align-items-start ps-3">
                                    {{-- Unread dot --}}
                                    <div class="flex-shrink-0 me-2 pt-1" style="width:8px;">
                                        @if($isUnread && $messageId !== $msg->id)
                                            <div style="width:7px; height:7px; border-radius:50%; background:#0d6efd; margin-top:1px;"></div>
                                        @endif
                                    </div>

                                    {{-- Content --}}
                                    <div class="flex-grow-1 overflow-hidden">
                                        <div class="d-flex justify-content-between align-items-start mb-1">
                                            <span class="{{ $isUnread ? 'fw-bold' : 'text-muted' }} text-truncate"
                                                  style="font-size:.85rem; max-width:170px;">
                                                {{ $msg->from_email ?: '(unknown sender)' }}
                                            </span>
                                            <span class="{{ $isUnread ? 'fw-semibold text-body' : 'text-muted' }} ms-1 flex-shrink-0"
                                                  style="font-size:.75rem;">
                                                {{ $msg->created_at->format('d M') }}
                                            </span>
                                        </div>
                                        <div class="{{ $isUnread ? 'fw-semibold text-body' : 'text-muted' }} text-truncate"
                                             style="font-size:.83rem;">
                                            {{ $msg->subject ?: '(no subject)' }}
                                        </div>
                                        <div class="d-flex align-items-center gap-1 mt-1 flex-wrap">
                                            @if($msg->classification_status === 'processing')
                                                <span class="badge text-white" style="font-size:.7rem; background-color:#7c3aed;">
                                                    <i class="mdi mdi-brain me-1"></i>Synapse…
                                                </span>
                                            @elseif($msg->classification === 'dsar_response')
                                                <span class="badge bg-primary" style="font-size:.7rem;">DSAR Response</span>
                                                @if($msg->messageable_type && str_contains($msg->messageable_type, 'Dsar'))
                                                    <span class="badge bg-success" style="font-size:.7rem;">Matched</span>
                                                @endif
                                            @elseif($msg->classification === 'generic')
                                                <span class="badge bg-light text-muted border" style="font-size:.7rem;">Generic</span>
                                            @elseif(!$msg->classification)
                                                <span class="badge bg-light text-muted border" style="font-size:.7rem;">Unclassified</span>
                                            @endif

                                            @if(($msg->attachments_count ?? 0) > 0)
                                                <span class="text-muted d-flex align-items-center gap-1" style="font-size:.72rem;">
                                                    <i class="mdi mdi-paperclip" style="font-size:.8rem;"></i>{{ $msg->attachments_count }}
                                                </span>
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            </button>
                        @endforeach
                    </div>

                    @if($messages->hasPages())
                        <div class="p-2 border-top">
                            {{ $messages->links() }}
                        </div>
                    @endif
                @endif
            </div>

            {{-- ── RIGHT: message detail ────────────────────────────────────── --}}
            <div class="flex-grow-1 d-flex flex-column overflow-hidden">
                @if($openMessage)
                    <div class="border-bottom flex-shrink-0">

                        {{-- ── Message meta ── --}}
                        <div class="px-3 pt-3 pb-2">
                            <h5 class="mb-1 text-truncate">{{ $openMessage->subject ?: '(no subject)' }}</h5>
                            <div class="text-muted small d-flex align-items-center flex-wrap gap-2">
                                <span><span class="fw-medium">From:</span> {{ $openMessage->from_email }}</span>
                                <span>&bull; {{ $openMessage->created_at->format('d M Y, H:i') }}</span>

                                @if($openMessage->classification || $openMessage->classification_status === 'processing')
                                    <span class="fw-semibold text-uppercase ms-1" style="font-size:.62rem; letter-spacing:.05em; color:#7c3aed;">
                                        <i class="mdi mdi-brain"></i> Synapse
                                    </span>
                                    @if($openMessage->classification_status === 'processing')
                                        <span class="badge bg-secondary" style="font-size:.68rem;">
                                            <span class="spinner-border spinner-border-sm me-1" style="width:.55rem;height:.55rem;" role="status"></span>Classifying…
                                        </span>
                                    @elseif($openMessage->classification === 'dsar_response')
                                        <span class="badge bg-primary" style="font-size:.68rem;">DSAR Response</span>
                                    @elseif($openMessage->classification === 'generic')
                                        <span class="badge bg-secondary" style="font-size:.68rem;">Generic</span>
                                    @endif
                                    @if($openMessage->classification_confidence)
                                        <span class="badge bg-light text-muted border" style="font-size:.68rem;">
                                            {{ ucfirst($openMessage->classification_confidence) }} confidence
                                        </span>
                                    @endif
                                    @if($openMessage->messageable_type && str_contains($openMessage->messageable_type, 'Dsar') && $openMessage->messageable)
                                        @php $dsar = $openMessage->messageable; @endphp
                                        <a wire:navigate href="{{ route('dsars.view', $dsar) }}"
                                           class="badge bg-success text-decoration-none" style="font-size:.68rem;">
                                            <i class="mdi mdi-link-variant me-1"></i>DSAR #{{ $dsar->id }}
                                        </a>
                                    @endif
                                    @if($openMessage->classification_notes)
                                        <span class="text-muted fst-italic" style="font-size:.75rem;">{{ $openMessage->classification_notes }}</span>
                                    @endif
                                @endif
                            </div>
                        </div>

                        {{-- ── Action toolbar ── --}}
                        <div class="px-3 pb-2 d-flex align-items-center gap-2 flex-wrap">
                            <button type="button"
                                    class="btn btn-sm btn-outline-secondary"
                                    x-on:click="$dispatch('open-reply-panel')">
                                <i class="mdi mdi-reply me-1"></i>Reply
                            </button>

                            @if($openMessage->read_at)
                                <button type="button"
                                        class="btn btn-sm btn-outline-secondary"
                                        wire:click="markUnread({{ $openMessage->id }})"
                                        title="Mark as unread">
                                    <i class="mdi mdi-email-mark-as-unread me-1"></i>Mark unread
                                </button>
                            @endif

                            <div class="vr" style="height:20px;"></div>

                            <button type="button"
                                    class="btn btn-sm text-white"
                                    style="background-color:#7c3aed;"
                                    wire:click="reclassify({{ $openMessage->id }})"
                                    wire:loading.attr="disabled"
                                    wire:target="reclassify({{ $openMessage->id }})"
                                    title="Re-classify with Synapse">
                                <span wire:loading.remove wire:target="reclassify({{ $openMessage->id }})">
                                    <i class="mdi mdi-brain me-1"></i>Synapse
                                </span>
                                <span wire:loading wire:target="reclassify({{ $openMessage->id }})">
                                    <span class="spinner-border spinner-border-sm" role="status"></span>
                                </span>
                            </button>
                        </div>

                    </div>

                    <div class="flex-grow-1 overflow-auto">
                        <div class="p-3">
                            @if($openMessage->body_html)
                                <iframe
                                    srcdoc="{!! htmlspecialchars($openMessage->body_html) !!}"
                                    sandbox="allow-same-origin"
                                    style="width:100%; height:420px; border:0; display:block;"
                                ></iframe>
                            @elseif($openMessage->body_text)
                                <pre style="white-space: pre-wrap; font-family: inherit; font-size: .9rem;">{{ $openMessage->body_text }}</pre>
                            @else
                                <p class="text-muted">This email has no body content.</p>
                            @endif
                        </div>

                    @if($openMessage->attachments->isNotEmpty())
                        <div class="border-top p-3">
                            <div class="text-muted small fw-semibold mb-2 text-uppercase">
                                Attachments ({{ $openMessage->attachments->count() }})
                            </div>
                            <div class="d-flex flex-column gap-2">
                                @foreach($openMessage->attachments as $attachment)
                                    @php
                                        $exStatus  = $attachment->extraction_status;
                                        $needsNote = in_array($exStatus, ['skipped', 'failed', null]);
                                        $hasNote   = !empty($attachment->extracted_text);
                                    @endphp
                                    <div class="border rounded p-2" style="font-size:.82rem;"
                                         x-data="{ textOpen: false }">

                                        {{-- File row --}}
                                        <div class="d-flex align-items-center gap-2 flex-wrap">
                                            <div class="d-flex align-items-center gap-1 flex-grow-1 overflow-hidden">
                                                <i class="mdi mdi-paperclip text-muted flex-shrink-0"></i>
                                                <span class="fw-medium text-truncate">{{ $attachment->filename }}</span>
                                                @if($attachment->size)
                                                    <span class="text-muted flex-shrink-0">({{ number_format($attachment->size / 1024, 1) }} KB)</span>
                                                @endif
                                            </div>

                                            {{-- Action buttons --}}
                                            <div class="d-flex align-items-center gap-1 flex-shrink-0">
                                                @php
                                                    $previewable = str_starts_with($attachment->mime ?? '', 'image/')
                                                               || str_contains($attachment->mime ?? '', 'pdf')
                                                               || str_starts_with($attachment->mime ?? '', 'text/');
                                                @endphp
                                                @if($previewable)
                                                    <button type="button"
                                                            class="btn btn-sm btn-outline-secondary py-0 px-1"
                                                            style="font-size:.72rem;"
                                                            title="Preview"
                                                            x-on:click="$dispatch('open-attachment-preview', {
                                                                url:      '{{ route('inbox.attachment.preview', $attachment) }}',
                                                                download: '{{ route('inbox.attachment.download', $attachment) }}',
                                                                filename: @js($attachment->filename),
                                                                mime:     @js($attachment->mime ?? '')
                                                            })">
                                                        <i class="mdi mdi-eye-outline"></i>
                                                    </button>
                                                @endif
                                                <a wire:navigate href="{{ route('inbox.attachment.download', $attachment) }}"
                                                   target="_blank"
                                                   class="btn btn-sm btn-outline-secondary py-0 px-1"
                                                   style="font-size:.72rem;"
                                                   title="Download">
                                                    <i class="mdi mdi-download"></i>
                                                </a>
                                            </div>

                                            {{-- Extraction status badge (clickable when text exists) --}}
                                            @if($exStatus === 'completed')
                                                <button type="button" x-on:click="textOpen = !textOpen"
                                                        class="badge bg-success-subtle text-success border border-success-subtle border-0 bg-transparent p-0"
                                                        style="font-size:.68rem;" title="View extracted text">
                                                    <i class="mdi mdi-text-box-check-outline me-1"></i>Text extracted
                                                    <i class="mdi mdi-chevron-down" x-bind:class="textOpen ? 'mdi-chevron-up' : 'mdi-chevron-down'"></i>
                                                </button>
                                            @elseif($exStatus === 'manual')
                                                <button type="button" x-on:click="textOpen = !textOpen"
                                                        class="badge bg-info-subtle text-info border border-info-subtle border-0 bg-transparent p-0"
                                                        style="font-size:.68rem;" title="View / edit note">
                                                    <i class="mdi mdi-pencil-outline me-1"></i>Manual note
                                                    <i class="mdi mdi-chevron-down" x-bind:class="textOpen ? 'mdi-chevron-up' : 'mdi-chevron-down'"></i>
                                                </button>
                                            @elseif($exStatus === 'processing')
                                                <span class="badge bg-secondary-subtle text-secondary border" style="font-size:.68rem;">
                                                    <span class="spinner-border spinner-border-sm" style="width:.55rem;height:.55rem;"></span> Extracting…
                                                </span>
                                            @elseif($exStatus === 'failed')
                                                <span class="badge bg-danger-subtle text-danger border border-danger-subtle" style="font-size:.68rem;">
                                                    <i class="mdi mdi-alert-outline me-1"></i>Extraction failed
                                                </span>
                                            @elseif($exStatus === 'skipped' || is_null($exStatus))
                                                <span class="badge bg-warning-subtle text-warning border border-warning-subtle" style="font-size:.68rem;">
                                                    <i class="mdi mdi-eye-off-outline me-1"></i>Not readable
                                                </span>
                                            @endif
                                        </div>

                                        {{-- Extracted text viewer (completed) --}}
                                        @if($exStatus === 'completed' && !empty($attachment->extracted_text))
                                            <div x-show="textOpen" x-cloak class="mt-2"
                                                 x-transition:enter="transition-opacity duration-150"
                                                 x-transition:enter-start="opacity-0"
                                                 x-transition:enter-end="opacity-100">
                                                <pre class="bg-light border rounded p-2 mb-0"
                                                     style="font-size:.75rem; white-space:pre-wrap; max-height:200px; overflow-y:auto; font-family:inherit;">{{ $attachment->extracted_text }}</pre>
                                            </div>
                                        @endif

                                        {{-- For non-extractable types: show a link to add a manual context note --}}
                                        @if($needsNote)
                                            <div class="mt-1">
                                                <button type="button"
                                                        class="btn btn-link btn-sm p-0 text-muted"
                                                        style="font-size:.75rem;"
                                                        x-on:click="textOpen = !textOpen">
                                                    <i class="mdi mdi-pencil-outline me-1"></i>
                                                    <span x-text="textOpen ? 'Hide' : '{{ $hasNote ? 'Edit note' : 'Add context note' }}'"></span>
                                                </button>
                                            </div>
                                        @endif

                                        {{-- Editable textarea shown when textOpen (manual note or edit of extracted text) --}}
                                        @if($needsNote || $exStatus === 'manual')
                                            <div x-show="textOpen" x-cloak class="mt-1"
                                                 x-transition:enter="transition-opacity duration-150"
                                                 x-transition:enter-start="opacity-0"
                                                 x-transition:enter-end="opacity-100">
                                                @if($needsNote)
                                                    <p class="text-muted mb-1" style="font-size:.72rem;">
                                                        Describe what this attachment contains — Synapse will use this when re-classifying.
                                                    </p>
                                                @endif
                                                <textarea
                                                    class="form-control form-control-sm mb-1"
                                                    rows="3"
                                                    style="font-size:.78rem;"
                                                    placeholder="e.g. Institution states they have no record of this client…"
                                                    x-ref="note_{{ $attachment->id }}"
                                                >{{ $attachment->extracted_text }}</textarea>
                                                <button type="button"
                                                        class="btn btn-sm btn-outline-secondary"
                                                        style="font-size:.75rem;"
                                                        wire:click="saveAttachmentNote({{ $attachment->id }}, $refs.note_{{ $attachment->id }}.value)">
                                                    Save note
                                                </button>
                                            </div>
                                        @endif

                                    </div>
                                @endforeach
                            </div>
                        </div>
                    @endif
                    </div>{{-- /flex-grow-1 overflow-auto --}}

                    <livewire:contact.inbox-reply-panel
                        :message-id="$openMessage->id"
                        :key="'reply-inbox-' . $openMessage->id"
                    />

                @else
                    <div class="flex-grow-1 d-flex align-items-center justify-content-center text-muted">
                        <div class="text-center">
                            <i class="mdi mdi-email-open-outline" style="font-size: 3rem; opacity: .3;"></i>
                            <p class="mt-2 mb-0">Select an email to read it</p>
                        </div>
                    </div>
                @endif
            </div>

        </div>
    </div>

    {{-- ── ATTACHMENT PREVIEW MODAL ──────────────────────────────────── --}}
    <div
        x-data="{
            open: false,
            url: '',
            download: '',
            filename: '',
            mime: '',
            isImage() { return this.mime.startsWith('image/'); },
        }"
        x-on:open-attachment-preview.window="
            url      = $event.detail.url;
            download = $event.detail.download;
            filename = $event.detail.filename;
            mime     = $event.detail.mime;
            open     = true;
        "
        x-on:keydown.escape.window="open = false"
        x-show="open"
        x-cloak
        style="position:fixed; inset:0; z-index:1060; display:flex; align-items:center; justify-content:center;"
    >
        {{-- Backdrop --}}
        <div
            x-on:click="open = false"
            x-transition:enter="transition-opacity duration-200"
            x-transition:enter-start="opacity-0"
            x-transition:enter-end="opacity-100"
            style="position:absolute; inset:0; background:rgba(0,0,0,.65);"
        ></div>

        {{-- Panel --}}
        <div class="bg-white rounded shadow-lg d-flex flex-column"
             style="position:relative; z-index:1; width:90vw; max-width:1100px; height:88vh; overflow:hidden;"
             x-transition:enter="transition-all duration-200"
             x-transition:enter-start="opacity-0 transform scale-95"
             x-transition:enter-end="opacity-100 transform scale-100"
             x-on:click.stop>

            {{-- Modal header --}}
            <div class="d-flex align-items-center gap-2 px-3 py-2 border-bottom flex-shrink-0">
                <i class="mdi mdi-paperclip text-muted"></i>
                <span class="fw-medium text-truncate flex-grow-1" x-text="filename" style="font-size:.9rem;"></span>
                <a wire:navigate :href="download"
                   class="btn btn-sm btn-outline-secondary py-0 px-2"
                   style="font-size:.78rem;"
                   title="Download">
                    <i class="mdi mdi-download me-1"></i>Download
                </a>
                <button type="button"
                        class="btn btn-sm btn-outline-secondary py-0 px-2"
                        x-on:click="open = false"
                        title="Close (Esc)">
                    <i class="mdi mdi-close"></i>
                </button>
            </div>

            {{-- Modal body --}}
            <div class="flex-grow-1 overflow-hidden d-flex align-items-center justify-content-center bg-light" style="padding:0;">
                {{-- Image viewer --}}
                <template x-if="isImage()">
                    <div class="w-100 h-100 d-flex align-items-center justify-content-center p-3">
                        <img :src="url" :alt="filename"
                             style="max-width:100%; max-height:100%; object-fit:contain; display:block; border-radius:.25rem;" />
                    </div>
                </template>
                {{-- PDF / text viewer (iframe) --}}
                <template x-if="!isImage()">
                    <iframe :src="url"
                            style="width:100%; height:100%; border:0;"
                            sandbox="allow-same-origin allow-scripts"></iframe>
                </template>
            </div>

        </div>
    </div>

</div>
