<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>PDF Cropper Pro - Pedro Bueno</title>
    <link rel="stylesheet" href="/static/style.css">
</head>
<body>
    <div class="container">
        <h1>Recortador Visual de PDF 🚀</h1>

        <label for="pdf-file" class="custom-file-upload">📁 Escolher PDF (Auto-Preview)</label>
        <input type="file" id="pdf-file" accept="application/pdf" onchange="uploadAndPreview()" style="display:none;">

        <div id="loading" style="display:none; color: #4CAF50; margin: 10px;">⏳ Carregando página...</div>

        <div id="preview-container" style="display:none;">
            <div class="nav-controls">
                <button type="button" onclick="changePage(-1)">⬅️ Anterior</button>
                <span id="page-info">Página: 0</span>
                <button type="button" onclick="changePage(1)">Próxima ➡️</button>
            </div>

            <div id="preview-wrapper">
                <img id="pdf-img">
                <div id="selector">
                    <div id="resizer"></div>
                </div>
            </div>
        </div>

        <form action="/processar" method="post" onsubmit="updateCoords()">
            <input type="hidden" name="filename" id="hidden-filename">
            <input type="hidden" name="coords" id="coords-input">
            
            <div class="row">
                <div class="input-group">
                    <label>Início (Pág):</label>
                    <input type="number" name="inicio" id="input-inicio" value="0">
                </div>
                <div class="input-group">
                    <label>Fim (Pág):</label>
                    <input type="number" name="fim" value="1">
                </div>
            </div>
            <button type="submit" class="btn-primary">RECORTAR E BAIXAR ZIP</button>
        </form>
    </div>

    <script>
        const selector = document.getElementById('selector');
        const resizer = document.getElementById('resizer');
        const img = document.getElementById('pdf-img');
        const coordsInput = document.getElementById('coords-input');
        const inputInicio = document.getElementById('input-inicio');
        
        let currentPage = 0;
        let isDragging = false, isResizing = false;
        let startX, startY, startW, startH;

        async function uploadAndPreview() {
            const file = document.getElementById('pdf-file').files[0];
            if(!file) return;
            document.getElementById('loading').style.display = 'block';
            
            const formData = new FormData();
            formData.append('pdf', file);
            const res = await fetch('/upload_preview', { method: 'POST', body: formData });
            const data = await res.json();
            
            document.getElementById('hidden-filename').value = data.filename;
            currentPage = parseInt(inputInicio.value) || 0;
            updatePreview();
        }

        function updatePreview() {
            const filename = document.getElementById('hidden-filename').value;
            img.src = `/preview/${filename}/${currentPage}?t=${new Date().getTime()}`;
            document.getElementById('page-info').innerText = `Visualizando Página: ${currentPage}`;
            inputInicio.value = currentPage;

            img.onload = () => {
                document.getElementById('loading').style.display = 'none';
                document.getElementById('preview-container').style.display = 'block';
                // Reinicia a grade para uma posição visível ao trocar de página
                selector.style.top = "10px";
                selector.style.left = "10px";
                updateCoords();
            };
        }

        function changePage(delta) {
            currentPage += delta;
            if (currentPage < 0) currentPage = 0;
            updatePreview();
        }

        selector.onmousedown = (e) => {
            if(e.target === resizer) return;
            isDragging = true;
            startX = e.clientX - selector.offsetLeft;
            startY = e.clientY - selector.offsetTop;
        };

        resizer.onmousedown = (e) => {
            isResizing = true;
            startX = e.clientX; startY = e.clientY;
            startW = selector.offsetWidth; startH = selector.offsetHeight;
            e.stopPropagation(); e.preventDefault();
        };

        window.onmousemove = (e) => {
            if (isDragging) {
                let x = e.clientX - startX, y = e.clientY - startY;
                x = Math.max(0, Math.min(x, img.offsetWidth - selector.offsetWidth));
                y = Math.max(0, Math.min(y, img.offsetHeight - selector.offsetHeight));
                selector.style.left = x + 'px';
                selector.style.top = y + 'px';
            }
            if (isResizing) {
                let w = startW + (e.clientX - startX), h = startH + (e.clientY - startY);
                w = Math.max(30, Math.min(w, img.offsetWidth - selector.offsetLeft));
                h = Math.max(30, Math.min(h, img.offsetHeight - selector.offsetTop));
                selector.style.width = w + 'px';
                selector.style.height = h + 'px';
            }
            updateCoords();
        };

        window.onmouseup = () => { isDragging = false; isResizing = false; };

        function updateCoords() {
            const data = [
                selector.offsetLeft, selector.offsetTop, 
                selector.offsetWidth, selector.offsetHeight,
                img.clientWidth, img.clientHeight,
                img.naturalWidth, img.naturalHeight
            ];
            coordsInput.value = data.join(',');
        }
    </script>
</body>
</html>