<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-0 border-bottom pb-0 flex-shrink-0">
        @php
            $tabs = [
                'dsar_evidence'       => ['label' => 'DSAR Evidence',                'icon' => 'mdi-file-check-outline',      'color' => 'success'],
                'dsar_updates'        => ['label' => 'Acknowledgements/Auto-Replies', 'icon' => 'mdi-email-sync-outline',      'color' => 'info'],
                'dsar_needs_research' => ['label' => 'Pushback/Wrong Information',   'icon' => 'mdi-magnify-scan',            'color' => 'warning'],
                'portal_response'     => ['label' => 'Portal Responses',             'icon' => 'mdi-link-box-outline',        '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' : '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

        {{-- ── Toolbar (right side of tab row) ── --}}
        <div class="ms-auto d-flex align-items-center gap-2 pe-2 flex-shrink-0">

            {{-- 3-state view mode toggle --}}
            <div class="btn-group btn-group-sm" role="group" style="font-size:.78rem;">
                <button
                    type="button"
                    wire:click="setViewMode('mine')"
                    class="btn {{ $viewMode === 'mine' ? 'btn-primary' : 'btn-outline-secondary' }}"
                    title="Show only emails matched to my clients"
                >My Emails</button>
                <button
                    type="button"
                    wire:click="setViewMode('mine_and_unmatched')"
                    class="btn {{ $viewMode === 'mine_and_unmatched' ? 'btn-primary' : 'btn-outline-secondary' }}"
                    title="Show my matched emails + unmatched emails"
                >My + Unmatched</button>
                <button
                    type="button"
                    wire:click="setViewMode('unmatched_only')"
                    class="btn {{ $viewMode === 'unmatched_only' ? 'btn-primary' : 'btn-outline-secondary' }}"
                    title="Show only unmatched emails"
                >Unmatched Only</button>
            </div>

            {{-- Handler override dropdown --}}
            @can('inbox.override_handler')
                <div class="d-flex align-items-center gap-1" style="font-size:.8rem;">
                    <i class="mdi mdi-account-switch-outline text-muted"></i>
                    <select
                        class="form-select form-select-sm"
                        style="font-size:.78rem; max-width:180px;"
                        wire:change="setOverrideHandler($event.target.value)"
                    >
                        <option value="">My queue ({{ auth()->user()->name_first }} {{ auth()->user()->name_last }})</option>
                        @foreach($availableHandlers as $handler)
                            @if($handler->id !== auth()->id())
                                <option value="{{ $handler->id }}" {{ $overrideHandlerId === $handler->id ? 'selected' : '' }}>
                                    {{ $handler->name_first }} {{ $handler->name_last }}
                                </option>
                            @endif
                        @endforeach
                    </select>
                </div>
            @endcan

        </div>
    </div>

    {{-- ── OVERRIDE BANNER ─────────────────────────────────────────────────── --}}
    @if($overrideHandlerId)
        @php $overrideUser = $availableHandlers->firstWhere('id', $overrideHandlerId); @endphp
        @if($overrideUser)
            <div class="d-flex align-items-center gap-2 px-3 py-1 flex-shrink-0"
                 style="background:#fff3cd; font-size:.8rem; border-bottom: 1px solid #ffc107;">
                <i class="mdi mdi-account-switch-outline text-warning"></i>
                <span>Viewing <strong>{{ $overrideUser->name_first }} {{ $overrideUser->name_last }}</strong>'s queue</span>
                <button type="button"
                        class="btn btn-link btn-sm p-0 text-muted ms-1"
                        style="font-size:.75rem;"
                        wire:click="setOverrideHandler(null)">
                    Return to my queue
                </button>
            </div>
        @endif
    @endif

    {{-- ── MAIN CONTENT ────────────────────────────────────────────────────── --}}
    <div class="flex-grow-1 d-flex flex-column overflow-hidden">

        @if($currentMessage)

            {{-- ── EMAIL HEADER + ACTIONS ─────────────────────────────────── --}}
            @php
                $isMatched  = $currentMessage->messageable_type && str_contains($currentMessage->messageable_type, 'Dsar');
                $dsarLinked = $isMatched && $currentMessage->messageable instanceof \App\Models\Dsar\Dsar
                            ? $currentMessage->messageable : null;
            @endphp
            <div class="flex-shrink-0" style="border-bottom:1px solid #e5e7eb;">

                {{-- ── Match status strip ── --}}
                @if($dsarLinked)
                    <div style="background:#f0fdf4; border-bottom:1px solid #bbf7d0; padding:.45rem 1rem; display:flex; align-items:center; gap:.6rem; flex-wrap:wrap;">
                        <span style="display:inline-flex; align-items:center; gap:.3rem; color:#15803d; font-weight:700; font-size:.72rem; text-transform:uppercase; letter-spacing:.05em;">
                            <i class="mdi mdi-link-variant"></i> Matched
                        </span>
                        <a wire:navigate href="{{ route('dsars.view', $dsarLinked) }}"
                           style="color:#15803d; font-weight:600; font-size:.82rem; text-decoration:none; padding:.1rem .45rem; background:rgba(22,163,74,.12); border-radius:.3rem;">
                            {{ $dsarLinked->reference ?? 'DSAR #' . $dsarLinked->id }}
                        </a>
                        @if($dsarLinked->claim?->client)
                            @php $linkedClient = $dsarLinked->claim->client; @endphp
                            <span style="color:#166534; font-size:.8rem;">
                                · {{ $linkedClient->name_first }} {{ $linkedClient->name_last }}
                            </span>
                        @endif
                        @if($dsarLinked->institution)
                            <span style="color:#166534; font-size:.78rem; opacity:.8;">
                                — {{ $dsarLinked->institution->display_name }}
                            </span>
                        @endif
                        <div class="ms-auto d-flex align-items-center gap-2">
                            @can('dsars.batch.send')
                                @php
                                    $currentStatus = $dsarLinked->status;
                                    $settableStatuses = \App\Enum\Dsar\DsarStatus::triageSelectable();
                                @endphp
                                <select class="form-select form-select-sm py-0 w-auto"
                                        style="font-size:.72rem; max-width:190px; border-color:#bbf7d0;"
                                        wire:change="updateDsarStatus($event.target.value)"
                                        title="Set DSAR status">
                                    @unless(in_array($currentStatus, $settableStatuses, true))
                                        <option value="{{ $currentStatus }}" selected disabled>
                                            {{ \App\Enum\Dsar\DsarStatus::label($currentStatus) }} (current)
                                        </option>
                                    @endunless
                                    @foreach($settableStatuses as $s)
                                        <option value="{{ $s }}" @selected($currentStatus === $s)>
                                            {{ \App\Enum\Dsar\DsarStatus::label($s) }}
                                        </option>
                                    @endforeach
                                </select>
                            @endcan
                            <button type="button"
                                    wire:click="toggleRelink"
                                    class="btn btn-sm py-0 px-2"
                                    style="font-size:.72rem; color:{{ $relinking ? '#dc2626' : '#15803d' }}; border:1px solid {{ $relinking ? '#fca5a5' : '#bbf7d0' }}; background:{{ $relinking ? '#fef2f2' : 'rgba(22,163,74,.08)' }};">
                                @if($relinking)
                                    <i class="mdi mdi-close me-1"></i>Cancel
                                @else
                                    <i class="mdi mdi-swap-horizontal me-1"></i>Change DSAR
                                @endif
                            </button>
                        </div>
                    </div>
                @else
                    <div style="background:#fffbeb; border-bottom:1px solid #fde68a; padding:.45rem 1rem; display:flex; align-items:center; gap:.6rem;">
                        <span style="display:inline-flex; align-items:center; gap:.3rem; color:#92400e; font-weight:700; font-size:.72rem; text-transform:uppercase; letter-spacing:.05em;">
                            <i class="mdi mdi-link-off"></i> Unmatched
                        </span>
                        <span style="color:#92400e; font-size:.8rem;">Search in the left panel to link this email to a DSAR</span>
                    </div>
                @endif

                {{-- ── Subject + meta + actions ── --}}
                <div class="d-flex align-items-start gap-3 px-3 pt-2 pb-2">
                    <div class="overflow-hidden flex-grow-1">
                        <h5 class="mb-1 fw-semibold text-truncate" style="font-size:1rem; line-height:1.35; max-width:100%;">
                            {{ $currentMessage->subject ?: '(no subject)' }}
                        </h5>
                        <div class="d-flex align-items-center flex-wrap gap-2" style="font-size:.81rem; color:#6b7280;">
                            <span class="fw-medium" style="color:#374151;">{{ $currentMessage->from_email }}</span>
                            <span style="opacity:.5;">&bull;</span>
                            <span>{{ $currentMessage->created_at->format('d M Y, H:i') }}</span>
                        </div>
                    </div>

                    {{-- Action buttons --}}
                    <div class="d-flex align-items-center gap-2 flex-shrink-0 pt-1">
                        @if($dsarLinked)
                            <a wire:navigate href="{{ route('dsars.view', $dsarLinked) }}"
                               class="btn btn-sm btn-outline-secondary">
                                <i class="mdi mdi-open-in-new me-1"></i>Open DSAR
                            </a>
                            <button type="button"
                                    class="btn btn-sm btn-success"
                                    wire:click="dismiss"
                                    wire:confirm="Mark this email as actioned and load the next one?"
                                    wire:loading.attr="disabled"
                                    wire:target="dismiss">
                                <span wire:loading.remove wire:target="dismiss"><i class="mdi mdi-check me-1"></i>Action</span>
                                <span wire:loading wire:target="dismiss"><span class="spinner-border spinner-border-sm" role="status"></span></span>
                            </button>
                        @endif
                        <div class="vr" style="height:20px;"></div>
                        <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>
                        {{-- Manual reclassify dropdown --}}
                        @php
                            $queueLabels = [
                                'dsar_evidence'       => 'DSAR Evidence',
                                'dsar_updates'        => 'Acknowledgements / Auto-Replies',
                                'dsar_needs_research' => 'Pushback / Wrong Information',
                                'portal_response'     => 'Portal Responses',
                                'unknown'             => 'Unknown',
                            ];
                        @endphp
                        <div x-data="{ open: false }" class="position-relative">
                            <button type="button"
                                    class="btn btn-sm btn-outline-secondary"
                                    x-on:click="open = !open"
                                    x-on:click.outside="open = false">
                                <i class="mdi mdi-swap-horizontal me-1"></i>Move to…
                            </button>
                            <div x-show="open" x-cloak
                                 style="position:absolute; right:0; top:calc(100% + 4px); background:#fff;
                                        border:1px solid #e5e7eb; border-radius:.4rem; box-shadow:0 4px 16px rgba(0,0,0,.12);
                                        z-index:200; min-width:220px; padding:.25rem 0;">
                                @foreach($queueLabels as $queueKey => $queueName)
                                    @if($queueKey !== $tab)
                                        <button type="button"
                                                class="w-100 text-start border-0 px-3 py-2"
                                                style="background:none; font-size:.82rem; color:#374151; display:flex; align-items:center; gap:.5rem;"
                                                onmouseover="this.style.background='#f3f4f6'"
                                                onmouseout="this.style.background='none'"
                                                wire:click="moveToQueue('{{ $queueKey }}')"
                                                x-on:click="open = false">
                                            {{ $queueName }}
                                        </button>
                                    @endif
                                @endforeach
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {{-- ── SPLIT PANELS ────────────────────────────────────────────── --}}
            <div class="d-flex flex-grow-1 overflow-hidden">

                {{-- LEFT: Thread / Email body panel --}}
                <div class="d-flex flex-column border-end" style="width:50%; min-width:0;">
                    {{-- Panel header --}}
                    <div class="px-3 py-2 flex-shrink-0" style="border-bottom:1px solid #e5e7eb;">
                        <span class="text-muted" style="font-size:.75rem; font-weight:600; text-transform:uppercase; letter-spacing:.04em;">
                            @if($isMatched)Thread @else Email @endif
                        </span>
                    </div>

                    {{-- Panel content --}}
                    <div class="flex-grow-1 overflow-auto" style="min-height:0; background:#fff;">

                        @if($isMatched && !$relinking)
                            {{-- DSAR Thread timeline --}}
                            <div class="p-2 d-flex flex-column gap-2">
                                @foreach($thread as $msg)
                                    @php
                                        $isInbound  = $msg->direction->value === 'inbound';
                                        $isCurrent  = $msg->id === $currentMessage->id;
                                        $dirBg      = $isInbound  ? '#eff6ff' : '#f9fafb';
                                        $dirBorder  = $isInbound  ? '#bfdbfe' : '#e5e7eb';
                                        $dirColor   = $isInbound  ? '#2563eb' : '#6b7280';
                                        $dirLabel   = $isInbound  ? 'Inbound'  : 'Outbound';
                                        $dirIcon    = $isInbound  ? 'mdi-email-arrow-left-outline' : 'mdi-email-arrow-right-outline';
                                    @endphp
                                    <div
                                        x-data="{ open: @js($isCurrent) }"
                                        class="rounded overflow-hidden"
                                        style="border:1px solid {{ $isCurrent ? '#93c5fd' : $dirBorder }};
                                               {{ $isCurrent ? 'box-shadow:0 0 0 2px rgba(59,130,246,.2);' : '' }}"
                                    >
                                        {{-- Message row (always visible) --}}
                                        <button
                                            type="button"
                                            class="w-100 text-start border-0 p-0"
                                            style="background:{{ $isCurrent ? '#dbeafe' : $dirBg }}; display:block;"
                                            x-on:click="open = !open"
                                        >
                                            <div class="d-flex align-items-center gap-2 px-3 py-2">
                                                <span class="flex-shrink-0 d-flex align-items-center gap-1"
                                                      style="font-size:.68rem; font-weight:700; text-transform:uppercase; letter-spacing:.04em; color:{{ $dirColor }};">
                                                    <i class="mdi {{ $dirIcon }}"></i>{{ $dirLabel }}
                                                </span>
                                                <span class="text-truncate flex-grow-1"
                                                      style="font-size:.81rem; font-weight:{{ $isCurrent ? '600' : '400' }}; color:{{ $isCurrent ? '#1d4ed8' : '#374151' }};">
                                                    {{ $isInbound ? $msg->from_email : ($msg->recipient_email ?? 'Sent') }}
                                                </span>
                                                <span class="flex-shrink-0" style="font-size:.71rem; color:#9ca3af;">
                                                    {{ $msg->created_at->format('d M, H:i') }}
                                                </span>
                                                @if($isCurrent)
                                                    <span class="flex-shrink-0"
                                                          style="font-size:.65rem; font-weight:700; color:#1d4ed8; background:#bfdbfe; border-radius:.25rem; padding:.1rem .35rem;">
                                                        Current
                                                    </span>
                                                @endif
                                                <i class="mdi flex-shrink-0"
                                                   :class="open ? 'mdi-chevron-up' : 'mdi-chevron-down'"
                                                   style="font-size:.9rem; color:#9ca3af;"></i>
                                            </div>
                                            @if($msg->subject && !$isCurrent)
                                                <div class="px-3 pb-2 text-truncate" style="font-size:.74rem; color:#6b7280;">{{ $msg->subject }}</div>
                                            @endif
                                        </button>

                                        {{-- Message body (expandable) --}}
                                        <div x-show="open" x-cloak
                                             x-transition:enter="transition-opacity duration-150"
                                             x-transition:enter-start="opacity-0"
                                             x-transition:enter-end="opacity-100"
                                             style="border-top:1px solid {{ $isCurrent ? '#93c5fd' : $dirBorder }};">
                                            @if($msg->body_html)
                                                <iframe
                                                    srcdoc="{!! htmlspecialchars($msg->body_html) !!}"
                                                    sandbox="allow-same-origin"
                                                    style="width:100%; height:300px; border:0; display:block;"
                                                    loading="lazy"
                                                ></iframe>
                                            @elseif($msg->body_text)
                                                <pre class="p-3 mb-0" style="white-space:pre-wrap; font-family:inherit; font-size:.83rem; max-height:300px; overflow-y:auto; background:#fff;">{{ $msg->body_text }}</pre>
                                            @else
                                                <p class="p-3 mb-0" style="font-size:.82rem; color:#9ca3af;">No body content.</p>
                                            @endif
                                        </div>
                                    </div>
                                @endforeach
                            </div>

                        @else
                            {{-- Unmatched or re-linking: DSAR search at top --}}
                            <div class="d-flex flex-column h-100" style="overflow:hidden;">

                                {{-- DSAR link/relink search — pinned at top --}}
                                <div class="px-3 py-3 flex-shrink-0"
                                     style="border-bottom:1px solid #e5e7eb; background:#eff6ff;">
                                    <div class="fw-semibold mb-2" style="font-size:.74rem; text-transform:uppercase; letter-spacing:.05em; color:#1d4ed8; display:flex; align-items:center; gap:.35rem;">
                                        @if($relinking)
                                            <i class="mdi mdi-swap-horizontal"></i> Change DSAR
                                        @else
                                            <i class="mdi mdi-link-variant"></i> Link to a DSAR
                                        @endif
                                    </div>
                                    <input
                                        type="text"
                                        class="form-control form-control-sm mb-2"
                                        placeholder="Search by reference (ours or theirs) or client name…"
                                        wire:model.live.debounce.250ms="dsarSearch"
                                        style="border-color:#bfdbfe;"
                                    >
                                    @if($dsarResults->isNotEmpty())
                                        <div class="d-flex flex-column gap-1" style="max-height:320px; overflow-y:auto; overscroll-behavior:contain;">
                                            @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; border-color:#bfdbfe !important;">
                                                    <div class="flex-grow-1 overflow-hidden">
                                                        <span class="fw-semibold text-primary">{{ $dsar->reference ?: 'DSAR #' . $dsar->id }}</span>
                                                        @if($dsar->receiver_reference)
                                                            <span class="text-muted ms-1 font-monospace" style="font-size:.7rem;">· their ref {{ $dsar->receiver_reference }}</span>
                                                        @endif
                                                        @if($label)
                                                            <span class="text-muted ms-2">{{ $label }}</span>
                                                        @endif
                                                        @if($dsar->institution)
                                                            <span class="text-muted ms-1">— {{ $dsar->institution->display_name }}</span>
                                                        @endif
                                                        <span class="badge {{ \App\Enum\Dsar\DsarStatus::badgeFor($dsar->status) }} ms-1" style="font-size:.62rem;">{{ \App\Enum\Dsar\DsarStatus::label($dsar->status) }}</span>
                                                    </div>
                                                    @if($relinking)
                                                        <button
                                                            type="button"
                                                            class="btn btn-sm btn-warning py-0 px-3 flex-shrink-0"
                                                            wire:click="relinkToDsar({{ $dsar->id }})"
                                                            wire:loading.attr="disabled"
                                                            wire:target="relinkToDsar({{ $dsar->id }})"
                                                        >
                                                            <span wire:loading.remove wire:target="relinkToDsar({{ $dsar->id }})"><i class="mdi mdi-swap-horizontal me-1"></i>Re-link</span>
                                                            <span wire:loading wire:target="relinkToDsar({{ $dsar->id }})"><span class="spinner-border spinner-border-sm" role="status"></span></span>
                                                        </button>
                                                    @else
                                                        <button
                                                            type="button"
                                                            class="btn btn-sm btn-primary py-0 px-3 flex-shrink-0"
                                                            wire:click="linkToDsar({{ $dsar->id }})"
                                                            wire:loading.attr="disabled"
                                                            wire:target="linkToDsar({{ $dsar->id }})"
                                                        >
                                                            <span wire:loading.remove wire:target="linkToDsar({{ $dsar->id }})"><i class="mdi mdi-link-variant me-1"></i>Link</span>
                                                            <span wire:loading wire:target="linkToDsar({{ $dsar->id }})"><span class="spinner-border spinner-border-sm" role="status"></span></span>
                                                        </button>
                                                    @endif
                                                </div>
                                            @endforeach
                                        </div>
                                    @elseif(strlen($dsarSearch) >= 2)
                                        <p style="color:#3b82f6; font-size:.8rem; margin:0;">No open DSARs found matching "{{ $dsarSearch }}".</p>
                                    @endif
                                </div>

                                {{-- Re-linking: thread context / Unmatched: email body --}}
                                <div class="flex-grow-1 overflow-auto" style="min-height:0;">
                                    @if($relinking && $thread->isNotEmpty())
                                        <div class="p-2 d-flex flex-column gap-2">
                                            @foreach($thread as $msg)
                                                @php
                                                    $isInbound = $msg->direction->value === 'inbound';
                                                    $isCurrent = $msg->id === $currentMessage->id;
                                                    $dirBg     = $isInbound ? '#eff6ff' : '#f9fafb';
                                                    $dirBorder = $isInbound ? '#bfdbfe' : '#e5e7eb';
                                                    $dirColor  = $isInbound ? '#2563eb' : '#6b7280';
                                                    $dirLabel  = $isInbound ? 'Inbound' : 'Outbound';
                                                    $dirIcon   = $isInbound ? 'mdi-email-arrow-left-outline' : 'mdi-email-arrow-right-outline';
                                                @endphp
                                                <div x-data="{ open: @js($isCurrent) }"
                                                     class="rounded overflow-hidden"
                                                     style="border:1px solid {{ $isCurrent ? '#93c5fd' : $dirBorder }}; {{ $isCurrent ? 'box-shadow:0 0 0 2px rgba(59,130,246,.2);' : '' }}">
                                                    <button type="button" class="w-100 text-start border-0 p-0"
                                                            style="background:{{ $isCurrent ? '#dbeafe' : $dirBg }}; display:block;"
                                                            x-on:click="open = !open">
                                                        <div class="d-flex align-items-center gap-2 px-3 py-2">
                                                            <span class="flex-shrink-0 d-flex align-items-center gap-1"
                                                                  style="font-size:.68rem; font-weight:700; text-transform:uppercase; letter-spacing:.04em; color:{{ $dirColor }};">
                                                                <i class="mdi {{ $dirIcon }}"></i>{{ $dirLabel }}
                                                            </span>
                                                            <span class="text-truncate flex-grow-1"
                                                                  style="font-size:.81rem; font-weight:{{ $isCurrent ? '600' : '400' }}; color:{{ $isCurrent ? '#1d4ed8' : '#374151' }};">
                                                                {{ $isInbound ? $msg->from_email : ($msg->recipient_email ?? 'Sent') }}
                                                            </span>
                                                            <span class="flex-shrink-0" style="font-size:.71rem; color:#9ca3af;">{{ $msg->created_at->format('d M, H:i') }}</span>
                                                            <i class="mdi flex-shrink-0" :class="open ? 'mdi-chevron-up' : 'mdi-chevron-down'" style="font-size:.9rem; color:#9ca3af;"></i>
                                                        </div>
                                                    </button>
                                                    <div x-show="open" x-cloak style="border-top:1px solid {{ $isCurrent ? '#93c5fd' : $dirBorder }};">
                                                        @if($msg->body_html)
                                                            <iframe srcdoc="{!! htmlspecialchars($msg->body_html) !!}" sandbox="allow-same-origin"
                                                                    style="width:100%; height:220px; border:0; display:block;" loading="lazy"></iframe>
                                                        @elseif($msg->body_text)
                                                            <pre class="p-3 mb-0" style="white-space:pre-wrap; font-family:inherit; font-size:.83rem; max-height:220px; overflow-y:auto;">{{ $msg->body_text }}</pre>
                                                        @else
                                                            <p class="p-3 mb-0 text-muted" style="font-size:.82rem;">No body content.</p>
                                                        @endif
                                                    </div>
                                                </div>
                                            @endforeach
                                        </div>
                                    @else
                                        <div class="p-3 h-100">
                                            @if($currentMessage->body_html)
                                                <iframe srcdoc="{!! htmlspecialchars($currentMessage->body_html) !!}"
                                                        sandbox="allow-same-origin"
                                                        style="width:100%; height:100%; min-height:280px; border:0; display:block;"></iframe>
                                            @elseif($currentMessage->body_text)
                                                <pre style="white-space:pre-wrap; font-family:inherit; font-size:.9rem;">{{ $currentMessage->body_text }}</pre>
                                            @else
                                                <p class="text-muted">This email has no body content.</p>
                                            @endif
                                        </div>
                                    @endif
                                </div>

                            </div>
                        @endif

                    </div>
                </div>

                {{-- RIGHT: Attachments panel --}}
                <div class="d-flex flex-column" style="flex:1; min-width:0;">
                    {{-- Panel header --}}
                    <div class="px-3 py-2 flex-shrink-0" style="border-bottom:1px solid #e5e7eb;">
                        <span class="text-muted" style="font-size:.75rem; font-weight:600; text-transform:uppercase; letter-spacing:.04em;">
                            Attachments
                            @if($currentMessage->attachments->isNotEmpty())
                                ({{ $currentMessage->attachments->count() }})
                            @endif
                        </span>
                    </div>

                    {{-- Panel content --}}
                    <div class="flex-grow-1 overflow-auto p-2" style="min-height:0; background:#fff;">

                        @if($currentMessage->attachments->isEmpty())
                            <div class="text-center text-muted py-5" style="font-size:.85rem;">
                                <i class="mdi mdi-paperclip-off d-block mb-2" style="font-size:2rem; opacity:.3;"></i>
                                No attachments
                            </div>
                        @else
                            <div class="d-flex flex-column gap-2">
                                @foreach($currentMessage->attachments as $attachment)
                                    @php
                                        $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');
                                    @endphp
                                    <div
                                        x-data="{ open: false }"
                                        class="rounded overflow-hidden"
                                        style="border:1px solid #e5e7eb;"
                                    >
                                        {{-- Attachment header --}}
                                        <div class="d-flex align-items-center gap-2 px-3 py-2"
                                             style="background:#fff; border-bottom:1px solid transparent;"
                                             :style="open ? 'border-bottom-color:#e5e7eb;' : ''">
                                            <i class="mdi mdi-paperclip flex-shrink-0" style="color:#6b7280;"></i>
                                            <button
                                                type="button"
                                                class="btn btn-link btn-sm p-0 text-start text-truncate flex-grow-1"
                                                style="font-size:.82rem; font-weight:500; color:#374151;"
                                                x-on:click="open = !open"
                                                :title="open ? 'Collapse' : 'Preview inline'"
                                            >
                                                {{ $attachment->filename }}
                                            </button>
                                            @if($attachment->size)
                                                <span class="flex-shrink-0" style="font-size:.71rem; color:#9ca3af;">
                                                    {{ number_format($attachment->size / 1024, 1) }} KB
                                                </span>
                                            @endif
                                            <button
                                                type="button"
                                                class="btn btn-sm btn-outline-secondary py-0 px-1 flex-shrink-0"
                                                style="font-size:.72rem;"
                                                x-on:click="open = !open"
                                                :title="open ? 'Collapse' : 'Expand preview'"
                                            >
                                                <i class="mdi" :class="open ? 'mdi-chevron-up' : 'mdi-eye-outline'"></i>
                                            </button>
                                            <a
                                                href="{{ route('inbox.attachment.download', $attachment) }}"
                                                target="_blank"
                                                class="btn btn-sm btn-outline-secondary py-0 px-1 flex-shrink-0"
                                                style="font-size:.72rem;"
                                                title="Download"
                                            >
                                                <i class="mdi mdi-download"></i>
                                            </a>
                                        </div>

                                        {{-- Inline preview --}}
                                        <div x-show="open" x-cloak class="border-top"
                                             x-transition:enter="transition-opacity duration-150"
                                             x-transition:enter-start="opacity-0"
                                             x-transition:enter-end="opacity-100">
                                            @if($isImage)
                                                <div class="p-2 d-flex align-items-center justify-content-center" style="background:#fff;">
                                                    <img
                                                        src="{{ route('inbox.attachment.preview', $attachment) }}"
                                                        alt="{{ $attachment->filename }}"
                                                        style="max-width:100%; max-height:480px; object-fit:contain; display:block; border-radius:.25rem;"
                                                    >
                                                </div>
                                            @elseif($isPdf)
                                                {{-- PDFs must NOT be sandboxed: Chrome blocks its built-in PDF
                                                     viewer inside a sandboxed iframe ("page blocked"). The viewer
                                                     isolates the PDF from this origin, so a plain iframe is safe. --}}
                                                <iframe
                                                    src="{{ route('inbox.attachment.preview', $attachment) }}"
                                                    title="{{ $attachment->filename }}"
                                                    style="width:100%; height:480px; border:0; display:block;"
                                                ></iframe>
                                            @else
                                                <iframe
                                                    src="{{ route('inbox.attachment.preview', $attachment) }}"
                                                    style="width:100%; height:480px; border:0; display:block;"
                                                    sandbox="allow-same-origin allow-scripts"
                                                ></iframe>
                                            @endif
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        @endif

                        {{-- Per-email activity trail — every human action on this email --}}
                        <div class="mt-3 pt-3 border-top">
                            <livewire:history :owner="$currentMessage" :key="'msg-hist-' . $currentMessage->id" />
                        </div>

                    </div>
                </div>

            </div>{{-- /split panels --}}

        @else

            {{-- ── EMPTY STATE ─────────────────────────────────────────────── --}}
            <div class="flex-grow-1 d-flex align-items-center justify-content-center text-muted">
                <div class="text-center">
                    <i class="mdi mdi-check-all d-block mb-3" style="font-size:3.5rem; opacity:.25;"></i>
                    <p class="mb-1 fw-semibold" style="font-size:1rem;">All clear</p>
                    <p class="mb-0 small">
                        @if($viewMode === 'mine')
                            No pending emails matched to your clients in this section.
                        @elseif($viewMode === 'mine_and_unmatched')
                            No pending emails (matched or unmatched) in this section.
                        @else
                            No unmatched emails in this section.
                        @endif
                    </p>
                    @if($viewMode === 'mine')
                        <p class="mt-2 mb-0 small text-muted">
                            Try <button type="button" class="btn btn-link btn-sm p-0" wire:click="setViewMode('mine_and_unmatched')" style="font-size:inherit;">My + Unmatched</button>
                            to also see unmatched emails.
                        </p>
                    @endif
                </div>
            </div>

        @endif

    </div>

    {{-- Reply panel (position:fixed — must live outside the @if block) --}}
    @if($currentMessage)
        <livewire:contact.inbox-reply-panel
            :message-id="$currentMessage->id"
            :key="'reply-triage-' . $currentMessage->id"
        />
    @endif

</div>
