<!-- Modal for PDF and Image viewing -->
<div id="previewModal" class="fixed inset-0 bg-gray-800 bg-opacity-75 flex items-center justify-center hidden w-full z-50">
    <div class="bg-white rounded-lg overflow-hidden shadow-xl transform transition-all min-w-3xl w-[1280px] h-[768px]">
        <div class="p-4 h-full flex flex-col">
            <div class="flex justify-between items-center mb-4">
                <button type="button" id="downloadBtn" class="btn btn-primary btn-sm">
                    <i class="ki-duotone ki-cloud-download me-1"><span class="path1"></span><span class="path2"></span></i>
                    Download File
                </button>
                <button type="button" onclick="closePreviewModal()" class="text-2xl">
                    <i class="ki-filled ki-cross-square text-red-600"></i>
                </button>
            </div>
            <div id="previewContent" class="flex-grow"></div>
        </div>
    </div>
</div>

@push('scripts')
    <script src="{{ asset('vendor/pdfobject.min.js') }}"></script>
    <script>
        let currentFileUrl = '';

        function viewPDF(url) {
            currentFileUrl = url;
            const fileExtension = url.split('.').pop().toLowerCase();
            const previewContent = document.getElementById('previewContent');

            if (['pdf'].includes(fileExtension)) {
                PDFObject.embed(url, "#previewContent");
            } else if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension)) {
                previewContent.innerHTML = `<img src="${url}" alt="Preview" class="max-w-full max-h-full object-contain">`;
            } else {
                previewContent.innerHTML = '<p class="text-center">Unsupported file type</p>';
            }

            document.getElementById('previewModal').classList.remove('hidden');
            document.addEventListener('keydown', handleEscKey);
        }

        function closePreviewModal() {
            document.getElementById('previewModal').classList.add('hidden');
            document.removeEventListener('keydown', handleEscKey);
        }

        function handleEscKey(event) {
            if (event.key === 'Escape') {
                closePreviewModal();
            }
        }

        // Close modal when clicking outside the content
        document.getElementById('previewModal').addEventListener('click', function(event) {
            if (event.target === this) {
                closePreviewModal();
            }
        });

        // Download functionality
        document.getElementById('downloadBtn').addEventListener('click', function() {
            if (currentFileUrl) {
                window.open(currentFileUrl, '_blank');
            }
        });
    </script>
@endpush
