<div>
    <x-title>
        Document Preview
        <x-slot:buttons>
            <button type="button" class="btn btn-light btn-sm"
                    onclick="window.history.length > 1 ? window.history.back() : (window.location.href = '{{ route('dashboard') }}')">
                <i class="mdi mdi-arrow-left me-1"></i>Back
            </button>
            <a href="{{ route('documents.download', $document) }}" class="btn btn-light btn-sm">
                <i class="mdi mdi-download me-1"></i>Download
            </a>
        </x-slot:buttons>
    </x-title>

    {{-- ── Document header ── --}}
    <div class="card shadow-sm mb-3">
        <div class="card-body d-flex flex-wrap align-items-center justify-content-between gap-2 py-3">
            <div class="d-flex align-items-center gap-3">
                <i class="mdi mdi-file-document-outline text-primary" style="font-size: 2rem;"></i>
                <div>
                    <h5 class="mb-0 fw-bold">{{ $document->display_name }}</h5>
                    <small class="text-muted">
                        {{ $document->type->display_name ?? '—' }}
                        · {{ $document->file_size }}
                        ·
                        <span class="text-uppercase">{{ pathinfo($document->file_name, PATHINFO_EXTENSION) ?: $kind }}</span>
                    </small>
                </div>
            </div>

            @unless($finished)
                <button type="button" class="btn btn-success btn-sm" wire:click="finish" wire:loading.attr="disabled">
                    <span wire:loading.remove wire:target="finish"><i class="mdi mdi-check me-1"></i>Finish review &amp; save time</span>
                    <span wire:loading wire:target="finish"><span class="spinner-border spinner-border-sm me-1"></span>Saving…</span>
                </button>
            @endunless
        </div>
    </div>

    <div class="row">
        <div class="col-8">
            {{-- ── Viewer ── --}}
            <div class="card shadow-sm">
                <div class="card-header bg-white d-flex align-items-center justify-content-between py-2">
                    <small class="text-muted text-uppercase fw-semibold" style="letter-spacing:.05em;">
                        @switch($kind)
                            @case('pdf') PDF document @break
                            @case('image') Image @break
                            @case('docx') Word document @break
                            @case('legacy_doc') Legacy Word document @break
                            @case('zip') Archive contents @break
                            @case('audio') Audio @break
                            @case('text') Text @break
                            @default File
                        @endswitch
                    </small>
                    @if($kind === 'pdf' || $kind === 'zip')
                        <div class="btn-group btn-group-sm" role="group" aria-label="Zoom">
                            <button type="button" id="docp-zoom-out" class="btn btn-outline-secondary"><i
                                        class="mdi mdi-magnify-minus-outline"></i></button>
                            <button type="button" id="docp-zoom-in" class="btn btn-outline-secondary"><i
                                        class="mdi mdi-magnify-plus-outline"></i></button>
                        </div>
                    @endif
                </div>

                <div class="card-body p-0">
                    @if($kind === 'zip')
                        <div class="row g-0">
                            {{-- Tree --}}
                            <div class="col-12 col-md-4 col-lg-3 border-end"
                                 style="max-height: calc(100vh - 320px); overflow:auto;">
                                @if(count($zipEntries))
                                    <div class="py-2">
                                        @foreach($zipEntries as $entry)
                                            @if($entry['is_dir'])
                                                <div class="text-muted small fw-semibold py-1 text-truncate"
                                                     style="padding-left: {{ $entry['depth'] * 0.85 + 0.5 }}rem;"
                                                     title="{{ $entry['name'] }}">
                                                    <i class="mdi mdi-folder-outline me-1"></i>{{ $entry['name'] }}
                                                </div>
                                            @else
                                                <button type="button"
                                                        class="docp-zip-entry btn btn-link btn-sm text-decoration-none text-start d-block w-100 text-truncate py-1"
                                                        style="padding-left: {{ $entry['depth'] * 0.85 + 0.5 }}rem;"
                                                        data-url="{{ route('documents.zipEntry', $document) }}?path={{ urlencode($entry['path']) }}"
                                                        data-name="{{ $entry['name'] }}"
                                                        title="{{ $entry['name'] }}">
                                                    <i class="mdi mdi-file-outline me-1"></i>{{ $entry['name'] }}
                                                    <small class="text-muted">({{ \Illuminate\Support\Number::fileSize($entry['size']) }}
                                                        )</small>
                                                </button>
                                            @endif
                                        @endforeach
                                    </div>
                                @else
                                    <p class="text-muted small p-3 mb-0">This archive is empty or could not be read.</p>
                                @endif
                            </div>
                            {{-- Inner-file viewer --}}
                            <div class="col-12 col-md-8 col-lg-9">
                                <div id="docp-viewer" class="p-3 bg-light"
                                     style="min-height: 300px; max-height: calc(100vh - 320px); overflow:auto;">
                                    <div class="text-center text-muted p-5">
                                        <i class="mdi mdi-folder-open-outline" style="font-size: 42px;"></i>
                                        <p class="mt-3 mb-0">Select a file from the archive to preview it.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    @else
                        <div id="docp-viewer" class="p-3 bg-light text-center"
                             style="min-height: 300px; max-height: calc(100vh - 300px); overflow:auto;">
                            <div class="text-muted p-5">
                                <div class="spinner-border spinner-border-sm me-2"></div>
                                Loading preview…
                            </div>
                        </div>
                    @endif
                </div>
            </div>

            @push('scripts')
                {{-- docx-preview (client-side .docx → HTML; document bytes are fetched same-origin and never leave the server) --}}
                <script src="https://unpkg.com/jszip@3.10.1/dist/jszip.min.js"></script>
                <script src="https://unpkg.com/docx-preview@0.3.5/dist/docx-preview.min.js"></script>
                <script>
                    (function () {
                        const RAW_URL = @js(route('documents.raw', $document));
                        const BEACON_URL = @js(route('documents.reviewWip', $document));
                        const REVIEW_TOKEN = @js($reviewToken);
                        const STARTED_AT = @js($wipStartedAt);
                        const KIND = @js($kind);
                        const FILE_NAME = @js($document->file_name);
                        const COMPONENT_ID = @js($this->getId());
                        const PDF_WORKER = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
                        const CSRF = document.querySelector('meta[name="csrf-token"]')?.content || '';

                        let activeHost = null;
                        let pdfScale = 1.25;

                        function kindFromExt(name) {
                            const ext = (name.split('.').pop() || '').toLowerCase();
                            if (ext === 'pdf') return 'pdf';
                            if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'image';
                            if (ext === 'docx') return 'docx';
                            if (['txt', 'csv', 'log', 'md', 'json', 'xml', 'eml'].includes(ext)) return 'text';
                            if (['mp3', 'wav', 'ogg', 'm4a'].includes(ext)) return 'audio';
                            return 'other';
                        }

                        function fallback(host, url, name, msg) {
                            host.innerHTML =
                                '<div class="text-center text-muted p-5">' +
                                '<i class="mdi mdi-file-alert-outline" style="font-size:42px;"></i>' +
                                '<p class="mt-3 mb-3">' + msg + '</p>' +
                                '<a href="' + url + '" class="btn btn-primary btn-sm" download>' +
                                '<i class="mdi mdi-download me-1"></i>Download' + (name ? (' ' + name) : '') + '</a>' +
                                '</div>';
                        }

                        async function paintPdf(host) {
                            const pdf = host._pdf;
                            if (!pdf) return;
                            host.innerHTML = '';
                            const ratio = window.devicePixelRatio || 1;
                            for (let n = 1; n <= pdf.numPages; n++) {
                                const page = await pdf.getPage(n);
                                const vp = page.getViewport({scale: pdfScale});
                                const canvas = document.createElement('canvas');
                                canvas.width = vp.width * ratio;
                                canvas.height = vp.height * ratio;
                                canvas.style.width = vp.width + 'px';
                                canvas.style.height = vp.height + 'px';
                                canvas.className = 'bg-white shadow-sm mb-3 mx-auto d-block';
                                host.appendChild(canvas);
                                const ctx = canvas.getContext('2d');
                                ctx.scale(ratio, ratio);
                                await page.render({canvasContext: ctx, viewport: vp}).promise;
                            }
                        }

                        async function renderPdf(url, host) {
                            if (!window.pdfjsLib) {
                                fallback(host, url, FILE_NAME, 'PDF viewer is unavailable.');
                                return;
                            }
                            window.pdfjsLib.GlobalWorkerOptions.workerSrc = PDF_WORKER;
                            const pdf = await window.pdfjsLib.getDocument(url).promise;
                            host._pdf = pdf;
                            await paintPdf(host);
                        }

                        async function renderInto(host, kind, url, name) {
                            host._pdf = null;
                            host.innerHTML = '<div class="text-muted p-4 text-center"><div class="spinner-border spinner-border-sm me-2"></div>Loading…</div>';
                            try {
                                if (kind === 'pdf') return await renderPdf(url, host);

                                if (kind === 'image') {
                                    host.innerHTML = '';
                                    const img = new Image();
                                    img.src = url;
                                    img.alt = name;
                                    img.className = 'img-fluid d-block mx-auto bg-white shadow-sm';
                                    host.appendChild(img);
                                    return;
                                }

                                if (kind === 'docx') {
                                    if (!window.docx) {
                                        fallback(host, url, name, 'DOCX preview library is unavailable.');
                                        return;
                                    }
                                    const buf = await (await fetch(url, {credentials: 'same-origin'})).arrayBuffer();
                                    host.innerHTML = '';
                                    const target = document.createElement('div');
                                    target.className = 'bg-white p-3 shadow-sm';
                                    host.appendChild(target);
                                    await window.docx.renderAsync(buf, target);
                                    return;
                                }

                                if (kind === 'audio') {
                                    host.innerHTML = '';
                                    const audio = document.createElement('audio');
                                    audio.controls = true;
                                    audio.src = url;
                                    audio.className = 'w-100 mt-4';
                                    host.appendChild(audio);
                                    return;
                                }

                                if (kind === 'text') {
                                    const text = await (await fetch(url, {credentials: 'same-origin'})).text();
                                    const pre = document.createElement('pre');
                                    pre.className = 'p-3 bg-white border rounded small text-start';
                                    pre.style.whiteSpace = 'pre-wrap';
                                    pre.textContent = text;
                                    host.innerHTML = '';
                                    host.appendChild(pre);
                                    return;
                                }

                                fallback(host, url, name, 'Preview is not available for this file type.');
                            } catch (e) {
                                fallback(host, url, name, 'This file could not be rendered. You can download it instead.');
                            }
                        }

                        function bookReviewBeacon() {
                            try {
                                const comp = window.Livewire ? window.Livewire.find(COMPONENT_ID) : null;
                                const fd = new FormData();
                                fd.append('_token', CSRF);
                                fd.append('seconds', String(comp ? (comp.get('wipSeconds') || 0) : 0));
                                const units = comp ? comp.get('wipUnits') : null;
                                if (units) fd.append('units', String(units));
                                const desc = comp ? comp.get('wipDescription') : null;
                                if (desc) fd.append('description', desc);
                                fd.append('reviewToken', REVIEW_TOKEN);
                                fd.append('startedAt', STARTED_AT || '');
                                navigator.sendBeacon(BEACON_URL, fd);
                            } catch (e) { /* best-effort */
                            }
                        }

                        function init() {
                            const viewer = document.getElementById('docp-viewer');
                            if (!viewer) return;

                            document.getElementById('docp-zoom-in')?.addEventListener('click', () => {
                                pdfScale = Math.min(3, pdfScale + 0.25);
                                if (activeHost && activeHost._pdf) paintPdf(activeHost);
                            });
                            document.getElementById('docp-zoom-out')?.addEventListener('click', () => {
                                pdfScale = Math.max(0.5, pdfScale - 0.25);
                                if (activeHost && activeHost._pdf) paintPdf(activeHost);
                            });

                            if (KIND === 'zip') {
                                document.querySelectorAll('.docp-zip-entry').forEach((btn) => {
                                    btn.addEventListener('click', () => {
                                        document.querySelectorAll('.docp-zip-entry.fw-bold').forEach((b) => b.classList.remove('fw-bold'));
                                        btn.classList.add('fw-bold');
                                        activeHost = viewer;
                                        renderInto(viewer, kindFromExt(btn.dataset.name), btn.dataset.url, btn.dataset.name);
                                    });
                                });
                            } else {
                                activeHost = viewer;
                                renderInto(viewer, KIND, RAW_URL, FILE_NAME);
                            }

                            // Safety net: book review WIP if the tab is closed without using "Finish".
                            window.addEventListener('pagehide', bookReviewBeacon);
                        }

                        if (document.readyState === 'loading') {
                            document.addEventListener('DOMContentLoaded', init);
                        } else {
                            init();
                        }
                    })();
                </script>
            @endpush
        </div>
        <div class="col-4">
            {{-- ── WIP capture ── --}}
            @if($finished)
                <div class="alert alert-success d-flex align-items-center" role="alert">
                    <i class="mdi mdi-check-circle-outline me-2 fs-5"></i>
                    <div>
                        Review time saved — <strong>{{ $bookedUnits }}</strong> WIP unit(s) recorded.
                        You can close this tab.
                    </div>
                </div>
            @else
                <div class="mb-3">
                    <x-wip-timer/>
                </div>
            @endif
        </div>
    </div>
</div>
