<x-layouts.app :title="__('Show document')">
    <div class="flex h-screen bg-gray-100" 
        @resize.window.debounce="renderPage(currentPage)">

        <!-- Zona izquierda - Visualizador de documentos -->
        <div class="w-1/2 bg-gray-800 p-4 relative">
            <!-- Loading State -->
            <template x-if="loading">
                <div class="absolute inset-0 bg-white bg-opacity-90 flex items-center justify-center">
                    <div class="text-center">
                        <svg class="animate-spin h-12 w-12 text-blue-500 mx-auto mb-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        <p class="text-gray-600">Cargando documento...</p>
                    </div>
                </div>
            </template>

            <!-- Error State -->
            <template x-if="error">
                <div class="absolute inset-0 bg-red-50 flex items-center justify-center p-4">
                    <div class="text-center text-red-600">
                        <svg class="h-12 w-12 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
                        </svg>
                        <p x-text="error"></p>
                        <p class="mt-2 text-sm">URL del documento: <span class="break-all" x-text="pdfUrl"></span></p>
                    </div>
                </div>
            </template>
            
            <!-- Controles del PDF -->
            <div class="flex items-center justify-between mb-4 bg-gray-700 p-2 rounded">
                <div class="flex items-center space-x-4 text-white">
                    <button @click="previousPage" :disabled="currentPage <= 1" class="disabled:opacity-50">
                        <x-icons icon="chevron-left" class="w-6 h-6" />
                    </button>
                    <span>Página <span x-text="currentPage"></span> de <span x-text="totalPages"></span></span>
                    <button @click="nextPage" :disabled="currentPage >= totalPages" class="disabled:opacity-50">
                        <x-icons icon="chevron-right" class="w-6 h-6" />
                    </button>
                </div>
                <div class="text-white">
                    Zoom: 
                    <select x-model="scale" @change="renderPage(currentPage)" class="bg-gray-600 rounded px-2 py-1">
                        <option value="0.25">25%</option>
                        <option value="0.5">50%</option>
                        <option value="0.75">75%</option>
                        <option value="1">100%</option>
                        <option value="1.5">150%</option>
                        <option value="2">200%</option>
                    </select>
                </div>
            </div>

            <!-- Canvas del PDF con comentarios -->
            <div class="flex-1 bg-white shadow-lg overflow-auto relative" 
                id="pdf-container"
                @scroll.debounce="handleScroll">
                <div class="pdf-page-container" :style="`width: ${pageWidth}px`">
                    <template x-for="(page, index) in renderedPages" :key="index">
                        <div class="pdf-page">
                            <canvas class="pdf-canvas" 
                                :id="`canvas-${page.pageNumber}`"></canvas>
                            <div class="text-layer" 
                                :id="`text-layer-${page.pageNumber}`"></div>
                        </div>
                    </template>
                </div>
                
                <!-- Marcadores de comentarios existentes -->
                <template x-for="comment in comments" :key="comment.id">
                    <div 
                        class="absolute w-4 h-4 bg-yellow-400 rounded-full cursor-pointer border-2 border-yellow-600"
                        :style="`left: ${comment.x * 100}%; top: ${comment.y * 100}%;`"
                        @click="scrollToComment(comment)"
                        x-tooltip="'Ver comentario'"
                    ></div>
                </template>
                
                <!-- Formulario flotante para nuevos comentarios -->
                <div 
                    class="absolute bg-white p-4 rounded-lg shadow-xl w-64" 
                    x-show="showCommentForm"
                    :style="`top: ${clickY}px; left: ${clickX}px`"
                    @click.outside="closeCommentForm"
                >
                    <form @submit.prevent="submitComment">
                        <textarea 
                            x-model="commentText"
                            class="w-full mb-2 p-2 border rounded"
                            placeholder="Escribe tu comentario..."
                            rows="3"
                            required
                        ></textarea>
                        <button 
                            type="submit"
                            class="btn btn-primary w-full flex items-center justify-center"
                        >
                            <x-icons icon="save" class="w-4 h-4 mr-2" /> Guardar
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Zona derecha - Tabs de información -->
        <div x-data="{ activeTab: 'properties' }" class="w-1/2 flex flex-col bg-white">
            <!-- Tabs de navegación -->
            <div class="border-b border-gray-200">
                <nav class="flex space-x-4 px-4 pt-2">
                    <button @click="activeTab = 'properties'" 
                        :class="activeTab === 'properties' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'" 
                        class="py-4 px-1 border-b-2 font-medium">
                        Propiedades
                    </button>
                    <button @click="activeTab = 'security'" 
                        :class="activeTab === 'security' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'" 
                        class="py-4 px-1 border-b-2 font-medium">
                        Seguridad
                    </button>
                    <button @click="activeTab = 'comments'" 
                        :class="activeTab === 'comments'  ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'" 
                        class="py-4 px-1 border-b-2 font-medium">
                        Comentarios
                    </button>
                    <button @click="activeTab = 'history'" 
                        :class="activeTab === 'history' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'" 
                        class="py-4 px-1 border-b-2 font-medium">
                        Historial
                    </button>
                    <button @click="activeTab = 'relations'" 
                        :class="activeTab === 'relations' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'" 
                        class="py-4 px-1 border-b-2 font-medium">
                        Relaciones
                    </button>
                </nav>
            </div>

            <!-- Contenido de los tabs -->
            <div class="flex-1 overflow-y-auto p-4 space-y-6">
                <!-- Propiedades -->
                <div x-show="activeTab === 'properties'">
                    <div class="space-y-4">
                        <x-property-item label="Nombre" :value="$document->name" />
                        <x-property-item label="Tipo" :value="$document->type" />
                        <x-property-item label="Tamaño" :value="$document->size_for_humans" />
                        <x-property-item label="Creado por" :value="Storage::url($document->file_path)" />
                        <x-property-item label="Fecha creación" :value="$document->created_at->format('d/m/Y H:i')" />
                        <x-property-item label="Última modificación" :value="$document->updated_at->format('d/m/Y H:i')" />
                    </div>
                </div>

                <!-- Seguridad -->
                <div x-show="activeTab === 'security'" x-cloak>
                    implementar
                </div>

                <!-- Comentarios -->
                <div x-show="activeTab === 'comments'" x-cloak>
                    <template x-for="comment in comments" :key="comment.id">
                        <div class="p-4 mb-2 border rounded hover:bg-gray-50">
                            <div class="text-sm text-gray-500" 
                                 x-text="`Página ${comment.page} - ${new Date(comment.created_at).toLocaleString()}`"></div>
                            <div x-text="comment.text" class="mt-1"></div>
                        </div>
                    </template>
                </div>

                <!-- Historial -->
                <div x-show="activeTab === 'history'" x-cloak>
                    <div class="space-y-4">
                        @foreach($document->versions as $version)
                            <x-version-item :version="$version" />
                        @endforeach
                    </div>
                </div>

                <!-- Relaciones -->
                <div x-show="activeTab === 'relations'" x-cloak>
                    implementar
                </div>
            </div>
        </div>
    </div>
</x-layouts.app>


<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
<script>
    // Configuración del Visor PDF
    var currentPage = 1;
    var nextPage = 2;

    const url = "{{ Storage::url($document->file_path) }}";
    let pdfDoc = null,
        pageNum = 1,
        pageRendering = false,
        pageNumPending = null,
        scale = 0.8,
        canvas = document.getElementById('pdf-canvas');
        ctx = canvas.getContext('2d');

    function renderPage(num) {
        pageRendering = true;
        pdfDoc.getPage(num).then(function(page) {
            const viewport = page.getViewport({ scale: 1.5 });
            canvas.height = viewport.height;
            canvas.width = viewport.width;

            const renderContext = {
                canvasContext: ctx,
                viewport: viewport
            };
            
            page.render(renderContext).promise.then(() => {
                pageRendering = false;
                loadCommentsForPage(num);
            });

            // Wait for rendering to finish
            renderTask.promise.then(function() {
                pageRendering = false;
                if (pageNumPending !== null) {
                    // New page rendering is pending
                    renderPage(pageNumPending);
                    pageNumPending = null;
                }
            });
        });
    }

    function handleCanvasClick(event) {
            const rect = event.target.getBoundingClientRect();
            this.clickX = event.clientX - rect.left;
            this.clickY = event.clientY - rect.top;
            this.showCommentForm = true;
        }

    // Cargar PDF
    pdfjsLib.getDocument(url).promise.then(function(pdf) {
        pdfDoc = pdf;
        renderPage(pageNum);
    });

    
    /**
     * If another page rendering in progress, waits until the rendering is
     * finised. Otherwise, executes rendering immediately.
     */
    function queueRenderPage(num) {
    if (pageRendering) {
        pageNumPending = num;
    } else {
        renderPage(num);
    }
    }

    /**
     * Displays previous page.
     */
    function onPrevPage() {
    if (pageNum <= 1) {
        return;
    }
    pageNum--;
    queueRenderPage(pageNum);
    }
    document.getElementById('prev').addEventListener('click', onPrevPage);

    /**
     * Displays next page.
     */
    function onNextPage() {
    if (pageNum >= pdfDoc.numPages) {
        return;
    }
    pageNum++;
    queueRenderPage(pageNum);
    }
    document.getElementById('next').addEventListener('click', onNextPage);

    /**
     * Asynchronously downloads PDF.
     */
    pdfjsLib.getDocument(url).promise.then(function(pdfDoc_) {
    pdfDoc = pdfDoc_;
    document.getElementById('page_count').textContent = pdfDoc.numPages;

    // Initial/first page rendering
    renderPage(pageNum);
    });

</script>

<style>
    .pdf-page-container {
        margin: 0 auto;
        padding: 20px 0;
    }
    
    .pdf-page {
        position: relative;
        margin: 0 auto 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    
    .text-layer {
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        overflow: hidden;
        opacity: 0.2;
        line-height: 1;
    }
    
    .text-layer span {
        color: transparent;
        position: absolute;
        white-space: pre;
        cursor: text;
        transform-origin: 0% 0%;
    }
    
    .text-layer ::selection {
        background: rgba(0,0,255,0.2);
    }
    </style>
