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

    <x-title>Email Triage</x-title>

    {{-- ── TAB BAR ─────────────────────────────────────────────────────────── --}}
    <div class="d-flex align-items-center gap-0 mb-3 border-bottom pb-0">
        @php
            $tabs = [
                'dsar_evidence'       => ['label' => 'DSAR Evidence',    'icon' => 'mdi-file-check-outline',      'color' => 'success'],
                'dsar_updates'        => ['label' => 'Updates',          'icon' => 'mdi-email-sync-outline',      'color' => 'info'],
                'dsar_needs_research' => ['label' => 'Needs Research',   'icon' => 'mdi-magnify-scan',            'color' => 'warning'],
                'unknown'             => ['label' => 'Unknown',          'icon' => 'mdi-help-circle-outline',     'color' => 'secondary'],
            ];
        @endphp
        @foreach($tabs as $key => $cfg)
            @php $cnt = $counts[$key] ?? 0; @endphp
            <button
                type="button"
                wire:click="setTab('{{ $key }}')"
                class="btn btn-sm border-0 rounded-0 px-4 py-2 fw-medium position-relative {{ $tab === $key ? 'text-primary border-bottom border-2 border-primary' : 'text-muted' }}"
                style="border-bottom: {{ $tab === $key ? '2px solid #0d6efd' : '2px solid transparent' }} !important; margin-bottom: -1px;"
            >
                <i class="mdi {{ $cfg['icon'] }} me-1"></i>{{ $cfg['label'] }}
                @if($cnt > 0)
                    <span class="badge bg-{{ $cfg['color'] }} ms-1" style="font-size:.65rem;">{{ $cnt }}</span>
                @endif
            </button>
        @endforeach

        <div class="ms-auto d-flex align-items-center gap-2 pe-1">
            <div class="form-check form-switch mb-0 d-flex align-items-center gap-2" style="font-size:.82rem;">
                <input class="form-check-input" type="checkbox" id="showActioned"
                       wire:model.live="showActioned">
                <label class="form-check-label text-muted" for="showActioned">Show actioned</label>
            </div>
        </div>
    </div>

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

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

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

                @if($messages->isEmpty())
                    <div class="p-4 text-center text-muted small">
                        <i class="mdi mdi-check-all d-block mb-2" style="font-size:2rem; opacity:.3;"></i>
                        All clear — nothing to triage here.
                    </div>
                @else
                    <div class="list-group list-group-flush flex-grow-1">
                        @foreach($messages as $msg)
                            @php
                                $isPending    = $msg->triage_status === 'pending';
                                $isInProgress = $msg->triage_status === 'in_progress';
                                $isActioned   = $msg->triage_status === 'actioned';
                                $isDismissed  = $msg->triage_status === 'dismissed';
                                $isActive     = $messageId === $msg->id;
                            @endphp
                            <button
                                type="button"
                                wire:click="openMessage({{ $msg->id }})"
                                class="list-group-item list-group-item-action text-start border-0 {{ $isActive ? 'active' : '' }}"
                                style="padding: .6rem .75rem .6rem 0; position: relative;
                                       {{ $isPending && !$isActive ? 'background-color: rgba(13,110,253,.04);' : '' }}
                                       {{ $isActioned || $isDismissed ? 'opacity:.55;' : '' }}"
                            >
                                {{-- Status accent bar --}}
                                <div style="position:absolute; left:0; top:0; bottom:0; width:3px; border-radius:0 2px 2px 0;
                                            background: {{ $isPending && !$isActive ? '#0d6efd' : ($isInProgress && !$isActive ? '#fd7e14' : 'transparent') }};"></div>

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

                                    <div class="flex-grow-1 overflow-hidden">
                                        <div class="d-flex justify-content-between align-items-start mb-1">
                                            <span class="{{ $isPending ? 'fw-bold' : 'text-muted' }} text-truncate"
                                                  style="font-size:.83rem; max-width:175px;">
                                                {{ $msg->from_email ?: '(unknown sender)' }}
                                            </span>
                                            <span class="text-muted ms-1 flex-shrink-0" style="font-size:.73rem;">
                                                {{ $msg->created_at->format('d M') }}
                                            </span>
                                        </div>
                                        <div class="{{ $isPending ? 'fw-semibold text-body' : 'text-muted' }} text-truncate"
                                             style="font-size:.82rem;">
                                            {{ $msg->subject ?: '(no subject)' }}
                                        </div>
                                        <div class="d-flex align-items-center gap-1 mt-1 flex-wrap">
                                            @if($isInProgress)
                                                <span class="badge" style="font-size:.67rem; background:#fff3cd; color:#856404;">In progress</span>
                                            @elseif($isActioned)
                                                <span class="badge bg-success-subtle text-success" style="font-size:.67rem;">Actioned</span>
                                            @elseif($isDismissed)
                                                <span class="badge bg-secondary-subtle text-secondary" style="font-size:.67rem;">Dismissed</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)

                    {{-- Header --}}
                    <div class="border-bottom flex-shrink-0">

                        {{-- ── Message meta ── --}}
                        <div class="px-3 pt-3 pb-2">
                            <h5 class="mb-1 text-truncate" style="max-width:100%;">{{ $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 class="text-muted">&bull; {{ $openMessage->created_at->format('d M Y, H:i') }}</span>

                                {{-- Synapse classification inline --}}
                                <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_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-primary text-decoration-none"
                                       style="font-size:.68rem;">
                                        <i class="mdi mdi-link-variant me-1"></i>DSAR{{ $dsar->reference ? ': ' . $dsar->reference : ' #' . $dsar->id }}
                                    </a>
                                @endif
                                @if($openMessage->classification_notes)
                                    <span class="text-muted fst-italic" style="font-size:.75rem;">{{ $openMessage->classification_notes }}</span>
                                @endif
                            </div>
                        </div>

                        {{-- ── Action toolbar ── --}}
                        <div class="px-3 pb-2 d-flex align-items-center gap-2 flex-wrap">

                            {{-- Navigate --}}
                            @if(($tab === 'dsar_evidence' || $tab === 'dsar_needs_research')
                                && $openMessage->messageable_type
                                && str_contains($openMessage->messageable_type, 'Dsar')
                                && $openMessage->messageable)
                                <a wire:navigate href="{{ route('dsars.view', $openMessage->messageable) }}"
                                   class="btn btn-sm btn-outline-secondary">
                                    <i class="mdi mdi-open-in-new me-1"></i>Open DSAR
                                </a>
                            @endif

                            {{-- Reply --}}
                            <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>

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

                            {{-- Workflow --}}
                            @if(in_array($openMessage->triage_status, ['pending', 'in_progress']))
                                <button type="button"
                                        class="btn btn-sm btn-success"
                                        wire:click="markActioned({{ $openMessage->id }})">
                                    <i class="mdi mdi-check me-1"></i>Mark actioned
                                </button>
                                <button type="button"
                                        class="btn btn-sm btn-outline-danger"
                                        wire:click="dismiss({{ $openMessage->id }})"
                                        wire:confirm="Dismiss this email from the triage queue?">
                                    <i class="mdi mdi-close me-1"></i>Dismiss
                                </button>
                            @else
                                <span class="badge bg-{{ $openMessage->triage_status === 'actioned' ? 'success' : 'secondary' }}-subtle
                                             text-{{ $openMessage->triage_status === 'actioned' ? 'success' : 'secondary' }}
                                             border" style="font-size:.75rem;">
                                    {{ ucfirst($openMessage->triage_status) }}
                                </span>
                            @endif

                            @if($tab === 'dsar_needs_research')
                                <button type="button"
                                        class="btn btn-sm btn-outline-warning"
                                        wire:click="unlinkFromDsar({{ $openMessage->id }})"
                                        wire:confirm="Move this email to Unknown and remove the DSAR link?">
                                    <i class="mdi mdi-link-off me-1"></i>Unlink DSAR
                                </button>
                            @endif

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

                            {{-- Synapse --}}
                            <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>

                    {{-- Link-to-DSAR panel (unknown tab only) --}}
                    @if($tab === 'unknown')
                        <div class="border-bottom px-3 py-2 bg-light" style="font-size:.85rem;">
                            <div class="fw-semibold mb-1 text-muted small text-uppercase">
                                <i class="mdi mdi-link-variant me-1"></i>Link to a DSAR
                            </div>
                            <div class="d-flex gap-2">
                                <input type="text"
                                       class="form-control form-control-sm"
                                       placeholder="Search by DSAR reference or client name…"
                                       wire:model.live.debounce.250ms="dsarSearch"
                                       style="max-width:340px;">
                            </div>
                            @if(count($dsarResults) > 0)
                                <div class="mt-2 d-flex flex-column gap-1">
                                    @foreach($dsarResults as $dsar)
                                        @php
                                            $client = $dsar->claim?->client;
                                            $label  = trim(($client?->name_first ?? '') . ' ' . ($client?->name_last ?? ''));
                                        @endphp
                                        <div class="d-flex align-items-center gap-2 p-2 border rounded bg-white" style="font-size:.82rem;">
                                            <div class="flex-grow-1">
                                                <span class="fw-medium">{{ $dsar->reference ?: 'DSAR #' . $dsar->id }}</span>
                                                @if($label)
                                                    <span class="text-muted ms-2">{{ $label }}</span>
                                                @endif
                                                @if($dsar->institution)
                                                    <span class="text-muted ms-2">— {{ $dsar->institution->name }}</span>
                                                @endif
                                                <span class="badge bg-secondary ms-1" style="font-size:.65rem;">{{ $dsar->status }}</span>
                                            </div>
                                            <button type="button"
                                                    class="btn btn-sm btn-outline-primary py-0 px-2"
                                                    wire:click="linkToDsar({{ $openMessage->id }}, {{ $dsar->id }})">
                                                Link
                                            </button>
                                        </div>
                                    @endforeach
                                </div>
                            @elseif(strlen($dsarSearch) >= 2)
                                <p class="text-muted small mt-2 mb-0">No open DSARs found matching "{{ $dsarSearch }}".</p>
                            @endif
                        </div>
                    @endif

                    {{-- Scrollable body + attachments --}}
                    <div class="flex-grow-1 overflow-auto" style="min-height:0;">
                        <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;
                                            $mime      = $attachment->mime ?? '';
                                            $fname     = strtolower($attachment->filename ?? '');
                                            $isImage   = str_starts_with($mime, 'image/')
                                                      || (bool) preg_match('/\.(jpg|jpeg|png|gif|webp|bmp|svg)$/', $fname);
                                            $isPdf     = str_contains($mime, 'pdf') || str_ends_with($fname, '.pdf');
                                            $isText    = str_starts_with($mime, 'text/');
                                            $previewable = $isImage || $isPdf || $isText;
                                            // Only offer a manual note for non-previewable attachments that have no text
                                            $needsNote = !$previewable && in_array($exStatus, ['skipped', 'failed', null]);
                                        @endphp
                                        <div class="border rounded p-2" style="font-size:.82rem;"
                                             x-data="{ textOpen: false }">

                                            <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>
                                                <div class="d-flex align-items-center gap-1 flex-shrink-0">
                                                    @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($mime ?: ($isImage ? 'image/jpeg' : ''))
                                                                })">
                                                            <i class="mdi mdi-eye-outline"></i>
                                                        </button>
                                                    @endif
                                                    <a 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>

                                                @if($exStatus === 'completed')
                                                    <button type="button" x-on:click="textOpen = !textOpen"
                                                            class="badge bg-transparent p-0 text-success border-0"
                                                            style="font-size:.68rem;">
                                                        <i class="mdi mdi-text-box-check-outline me-1"></i>Text extracted
                                                        <i x-bind:class="textOpen ? 'mdi mdi-chevron-up' : 'mdi mdi-chevron-down'" class="mdi"></i>
                                                    </button>
                                                @elseif($exStatus === 'manual')
                                                    <button type="button" x-on:click="textOpen = !textOpen"
                                                            class="badge bg-transparent p-0 text-info border-0"
                                                            style="font-size:.68rem;">
                                                        <i class="mdi mdi-pencil-outline me-1"></i>Manual note
                                                        <i x-bind:class="textOpen ? 'mdi mdi-chevron-up' : 'mdi mdi-chevron-down'" class="mdi"></i>
                                                    </button>
                                                @elseif(!$previewable && ($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 --}}
                                            @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

                                            {{-- Manual note --}}
                                            @if($needsNote || $exStatus === 'manual')
                                                @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' : '{{ !empty($attachment->extracted_text) ? 'Edit note' : 'Add context note' }}'"></span>
                                                        </button>
                                                    </div>
                                                @endif
                                                <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>{{-- /scrollable body --}}

                    <livewire:contact.inbox-reply-panel
                        :message-id="$openMessage->id"
                        :key="'reply-triage-' . $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 d-block mb-2" style="font-size:3rem; opacity:.3;"></i>
                            <p class="mb-0">Select an email to review 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;"
    >
        <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>

        <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>
            <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 :href="download" target="_blank" class="btn btn-sm btn-outline-secondary py-0 px-2" style="font-size:.78rem;">
                    <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">
                    <i class="mdi mdi-close"></i>
                </button>
            </div>
            <div class="flex-grow-1 overflow-hidden d-flex align-items-center justify-content-center bg-light" style="padding:0;">
                <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>
                <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>
