// --- Lógica de Sesión ---
const userSessionElement = document.getElementById('user-session');
function checkLoginStatus() {
    fetch('check_session.php', { cache: 'no-store' })
        .then(r => r.json()).then(d => {
            if (d.loggedIn) userSessionElement.innerHTML = `Hola, <strong>${d.nombre}</strong> | <a href="index.html">Volver</a>`;
        }).catch(e => console.error(e));
}
checkLoginStatus();

document.addEventListener('DOMContentLoaded', () => {
    const canvas = document.getElementById('chipCanvas');
    const ctx = canvas.getContext('2d');

    // Elementos UI
    const paperSizeSelect = document.getElementById('paperSize');
    const bgColor = document.getElementById('bgColor');
    const bgImageInput = document.getElementById('bgImageInput');
    const repeatBg = document.getElementById('repeatBg');
    const stripColor = document.getElementById('stripColor');
    const mainImageInput = document.getElementById('mainImageInput');
    const imgScale = document.getElementById('imgScale');
    const chipText = document.getElementById('chipText');
    const chipSubText = document.getElementById('chipSubText');
    const fontSelector = document.getElementById('fontSelector');
    const textColor = document.getElementById('textColor');
    const showBarcode = document.getElementById('showBarcode');
    const showCrimp = document.getElementById('showCrimp');
    const downloadBtn = document.getElementById('downloadBtn');

    // --- ESTADO GLOBAL ---
    let state = {
        img: { obj: null, x: 0, y: 0, w: 0, h: 0, isLoaded: false },
        text1: { x: 0, y: 0, text: "", w: 0, h: 0 },
        text2: { x: 0, y: 0, text: "", w: 0, h: 0 },
        bgImg: null
    };

    let isDragging = null; 
    let hoveredItem = null;
    let dragStart = { x: 0, y: 0 };

    // Dimensiones en mm (Landscape para el diseño en pantalla)
    const PAPER_DIMENSIONS = {
        a4: { w: 297, h: 210 },
        letter: { w: 279.4, h: 215.9 }
    };

    // --- CONFIGURACIÓN INICIAL ---
    function setCanvasSize() {
        const type = paperSizeSelect.value;
        const baseHeight = 1000; 
        const paperW = PAPER_DIMENSIONS[type].w;
        const paperH = PAPER_DIMENSIONS[type].h;
        const aspectRatio = paperW / paperH;

        canvas.height = baseHeight;
        canvas.width = baseHeight * aspectRatio;
        
        // Centrar elementos por defecto (solo si es la primera vez)
        const W = canvas.width;
        const H = canvas.height;
        
        if (state.img.x === 0) {
            state.img.x = W * 0.5;
            state.img.y = H * 0.5;
            state.text1.x = W * 0.5;
            state.text1.y = H - (H * 0.18);
            state.text2.x = W * 0.5;
            state.text2.y = H - (H * 0.12);
        }
        
        draw();
    }

    // --- UPDATE DIMENSIONS ---
    function updateDimensions() {
        const H = canvas.height;

        if (state.img.isLoaded && state.img.obj) {
            const scaleVal = parseInt(imgScale.value) / 100;
            const baseSize = H * 0.5; 
            const ratio = state.img.obj.width / state.img.obj.height;
            state.img.w = ratio * baseSize * scaleVal;
            state.img.h = baseSize * scaleVal;
        }

        if (chipText.value.trim() !== "") {
            const size1 = H * 0.12;
            ctx.font = `bold ${size1}px "${fontSelector.value}"`;
            state.text1.text = chipText.value;
            state.text1.w = ctx.measureText(state.text1.text).width;
            state.text1.h = size1;
        } else { state.text1.w = 0; }

        if (chipSubText.value.trim() !== "") {
            const size2 = H * 0.08;
            ctx.font = `bold ${size2}px "${fontSelector.value}"`;
            state.text2.text = chipSubText.value;
            state.text2.w = ctx.measureText(state.text2.text).width;
            state.text2.h = size2;
        } else { state.text2.w = 0; }
    }

    // --- DIBUJAR ---
    function draw() {
        updateDimensions();
        const W = canvas.width;
        const H = canvas.height;
        ctx.clearRect(0, 0, W, H);

        // 1. Fondo
        if (state.bgImg && state.bgImg.complete) {
            if (repeatBg.checked) {
                const tempCanvas = document.createElement('canvas');
                const tempCtx = tempCanvas.getContext('2d');
                const scalePattern = 0.3; 
                tempCanvas.width = state.bgImg.width * scalePattern;
                tempCanvas.height = state.bgImg.height * scalePattern;
                tempCtx.drawImage(state.bgImg, 0, 0, tempCanvas.width, tempCanvas.height);
                const pattern = ctx.createPattern(tempCanvas, 'repeat');
                ctx.fillStyle = pattern;
                ctx.fillRect(0, 0, W, H);
            } else {
                ctx.drawImage(state.bgImg, 0, 0, W, H);
            }
        } else {
            ctx.fillStyle = bgColor.value;
            ctx.fillRect(0, 0, W, H);
        }

        // 2. Guías
        const sideW = W * 0.25;
        const centerW = W * 0.50;
        ctx.setLineDash([15, 15]);
        ctx.strokeStyle = "rgba(0,0,0,0.2)";
        ctx.lineWidth = 3;
        ctx.beginPath();
        ctx.moveTo(sideW, 0); ctx.lineTo(sideW, H);
        ctx.moveTo(sideW + centerW, 0); ctx.lineTo(sideW + centerW, H);
        ctx.stroke();
        ctx.setLineDash([]);

        // 3. Franjas
        const stripH = H * 0.08; 
        ctx.fillStyle = stripColor.value;
        ctx.fillRect(0, 0, W, stripH); 
        ctx.fillRect(0, H - stripH, W, stripH); 

        if (showCrimp.checked) {
            drawCrimp(0, W, stripH); 
            drawCrimp(H - stripH, W, stripH); 
        }

        // 4. Imagen
        if (state.img.isLoaded && state.img.obj) {
            ctx.drawImage(state.img.obj, state.img.x - state.img.w/2, state.img.y - state.img.h/2, state.img.w, state.img.h);
            if (isDragging === 'img' || hoveredItem === 'img') {
                ctx.strokeStyle = "#007bff"; ctx.lineWidth = 4;
                ctx.strokeRect(state.img.x - state.img.w/2, state.img.y - state.img.h/2, state.img.w, state.img.h);
            }
        }

        // 5. Textos
        ctx.textAlign = "center"; ctx.textBaseline = "middle";
        ctx.fillStyle = textColor.value; ctx.strokeStyle = "white";

        if (state.text1.w > 0) {
            ctx.font = `bold ${state.text1.h}px "${fontSelector.value}"`;
            ctx.lineWidth = state.text1.h * 0.1;
            ctx.strokeText(state.text1.text, state.text1.x, state.text1.y);
            ctx.fillText(state.text1.text, state.text1.x, state.text1.y);
            if (isDragging === 'text1' || hoveredItem === 'text1') {
                ctx.strokeStyle = "#007bff"; ctx.lineWidth = 2;
                ctx.strokeRect(state.text1.x - state.text1.w/2 - 10, state.text1.y - state.text1.h/2, state.text1.w + 20, state.text1.h);
            }
        }

        if (state.text2.w > 0) {
            ctx.font = `bold ${state.text2.h}px "${fontSelector.value}"`;
            ctx.lineWidth = state.text2.h * 0.1;
            ctx.strokeText(state.text2.text, state.text2.x, state.text2.y);
            ctx.fillText(state.text2.text, state.text2.x, state.text2.y);
            if (isDragging === 'text2' || hoveredItem === 'text2') {
                ctx.strokeStyle = "#007bff"; ctx.lineWidth = 2;
                ctx.strokeRect(state.text2.x - state.text2.w/2 - 10, state.text2.y - state.text2.h/2, state.text2.w + 20, state.text2.h);
            }
        }

        // 6. Extras
        if (showBarcode.checked) {
            const barW = sideW * 0.6; const barH = H * 0.12;
            const barX = (sideW - barW) / 2; const barY = H - stripH - barH - (H * 0.05);
            ctx.fillStyle = "white"; ctx.fillRect(barX, barY, barW, barH);
            ctx.fillStyle = "black";
            for(let i=0; i<barW; i+= (barW/35)) { if(Math.random() > 0.3) ctx.fillRect(barX + i, barY + 5, (barW/70), barH - 25); }
            ctx.font = `bold ${barH * 0.15}px Arial`; ctx.textAlign = "center";
            ctx.fillText("www.espacioapp.site", barX + barW/2, barY + barH - 5);
        }
        
        // Marco de Corte
        ctx.strokeStyle = "black"; ctx.lineWidth = 1; ctx.strokeRect(0, 0, W, H);
    }

    function drawCrimp(y, width, height) {
        ctx.fillStyle = "rgba(255,255,255,0.3)";
        const step = width / 100;
        for (let i = 0; i < width; i += step) ctx.fillRect(i, y, step/2, height);
    }

    // --- INTERACCIÓN ---
    function getMousePos(evt) {
        const rect = canvas.getBoundingClientRect();
        const scaleX = canvas.width / rect.width;
        const scaleY = canvas.height / rect.height;
        const clientX = evt.touches ? evt.touches[0].clientX : evt.clientX;
        const clientY = evt.touches ? evt.touches[0].clientY : evt.clientY;
        return { x: (clientX - rect.left) * scaleX, y: (clientY - rect.top) * scaleY };
    }

    function isHit(pos, objType) {
        if (objType === 'img' && state.img.isLoaded && state.img.w > 0) {
            const l = state.img.x - state.img.w / 2;
            const r = state.img.x + state.img.w / 2;
            const t = state.img.y - state.img.h / 2;
            const b = state.img.y + state.img.h / 2;
            return pos.x >= l && pos.x <= r && pos.y >= t && pos.y <= b;
        }
        if (objType === 'text1' && state.text1.w > 0) {
            return pos.x >= state.text1.x - state.text1.w/2 - 10 && pos.x <= state.text1.x + state.text1.w/2 + 10 &&
                   pos.y >= state.text1.y - state.text1.h/2 && pos.y <= state.text1.y + state.text1.h/2;
        }
        if (objType === 'text2' && state.text2.w > 0) {
            return pos.x >= state.text2.x - state.text2.w/2 - 10 && pos.x <= state.text2.x + state.text2.w/2 + 10 &&
                   pos.y >= state.text2.y - state.text2.h/2 && pos.y <= state.text2.y + state.text2.h/2;
        }
        return false;
    }

    const handleStart = (e) => {
        if(e.type === 'touchstart') e.preventDefault();
        const pos = getMousePos(e);
        if (isHit(pos, 'text2')) isDragging = 'text2';
        else if (isHit(pos, 'text1')) isDragging = 'text1';
        else if (isHit(pos, 'img')) isDragging = 'img';
        else return;
        dragStart = pos;
        draw(); 
        canvas.classList.add('dragging');
    };

    const handleMove = (e) => {
        if(e.type === 'touchmove') e.preventDefault();
        const pos = getMousePos(e);
        if (isDragging) {
            const dx = pos.x - dragStart.x;
            const dy = pos.y - dragStart.y;
            if (isDragging === 'img') { state.img.x += dx; state.img.y += dy; }
            else if (isDragging === 'text1') { state.text1.x += dx; state.text1.y += dy; }
            else if (isDragging === 'text2') { state.text2.x += dx; state.text2.y += dy; }
            dragStart = pos;
            draw();
        } else {
            if (isHit(pos, 'text2') || isHit(pos, 'text1') || isHit(pos, 'img')) hoveredItem = true;
            else hoveredItem = null;
            canvas.style.cursor = hoveredItem ? 'grab' : 'default';
            draw();
        }
    };

    const endDrag = () => { isDragging = null; canvas.classList.remove('dragging'); draw(); };
    
    canvas.addEventListener('mousedown', handleStart);
    canvas.addEventListener('touchstart', handleStart, {passive: false});
    canvas.addEventListener('mousemove', handleMove);
    canvas.addEventListener('touchmove', handleMove, {passive: false});
    canvas.addEventListener('mouseup', endDrag);
    canvas.addEventListener('touchend', endDrag);
    canvas.addEventListener('mouseout', endDrag);

    // --- LISTENERS INPUTS ---
    const inputs = [bgColor, repeatBg, stripColor, imgScale, chipText, chipSubText, fontSelector, textColor, showBarcode, showCrimp];
    inputs.forEach(el => { el.addEventListener('input', draw); el.addEventListener('change', draw); });
    paperSizeSelect.addEventListener('change', setCanvasSize);

    bgImageInput.addEventListener('change', (e) => {
        const f = e.target.files[0]; if(!f) return;
        const r = new FileReader();
        r.onload = (ev) => { state.bgImg = new Image(); state.bgImg.onload = draw; state.bgImg.src = ev.target.result; };
        r.readAsDataURL(f);
    });

    mainImageInput.addEventListener('change', (e) => {
        const f = e.target.files[0]; if(!f) return;
        const r = new FileReader();
        r.onload = (ev) => {
            state.img.obj = new Image();
            state.img.obj.onload = () => {
                state.img.isLoaded = true;
                state.img.x = canvas.width / 2; state.img.y = canvas.height / 2;
                updateDimensions(); draw();
            };
            state.img.obj.src = ev.target.result;
        };
        r.readAsDataURL(f);
    });

    // --- DESCARGA PDF MEJORADA (AJUSTE SEGURO) ---
    downloadBtn.addEventListener('click', () => {
        downloadBtn.disabled = true;
        downloadBtn.textContent = "Generando PDF...";
        
        const { jsPDF } = window.jspdf;
        const paperType = paperSizeSelect.value;
        
        // Crear PDF en PORTRAIT (Vertical) para evitar confusión en la impresora
        const doc = new jsPDF({ orientation: 'portrait', unit: 'mm', format: paperType });
        
        const pageW = (paperType === 'a4') ? 210 : 215.9;
        const pageH = (paperType === 'a4') ? 297 : 279.4;

        // 1. Rotar el diseño (Canvas Horizontal -> Vertical)
        const rotCanvas = document.createElement('canvas');
        rotCanvas.width = canvas.height;
        rotCanvas.height = canvas.width;
        const rotCtx = rotCanvas.getContext('2d');

        // Trasladar y Rotar 90 grados
        rotCtx.translate(rotCanvas.width / 2, rotCanvas.height / 2);
        rotCtx.rotate(90 * Math.PI / 180);
        
        // Limpiar visuales antes de dibujar
        hoveredItem = null; isDragging = null; draw();

        // Dibujar la imagen original en el contexto rotado
        rotCtx.drawImage(canvas, -canvas.width / 2, -canvas.height / 2);

        // 2. Calcular Ajuste Seguro (Fit to Page)
        const imgData = rotCanvas.toDataURL('image/jpeg', 1.0);
        
        // --- MARGEN DE SEGURIDAD DE 15MM (1.5CM) ---
        // Esto es lo que arregla el problema de recorte de la impresora
        const marginSafety = 15; 
        const maxW = pageW - (marginSafety * 2);
        const maxH = pageH - (marginSafety * 2);

        // Calcular ratio para "Contain" (Ajustar sin deformar)
        const imgRatio = rotCanvas.width / rotCanvas.height;
        const pageRatio = maxW / maxH;
        
        let finalW, finalH;

        if (imgRatio > pageRatio) {
            finalW = maxW;
            finalH = finalW / imgRatio;
        } else {
            finalH = maxH;
            finalW = finalH * imgRatio;
        }

        // Centrar en la página
        const x = (pageW - finalW) / 2;
        const y = (pageH - finalH) / 2;

        doc.addImage(imgData, 'JPEG', x, y, finalW, finalH);
        
        // 3. Instrucciones
        doc.addPage();
        doc.setFontSize(16); doc.text("Instrucciones Chip Bag", 20, 20);
        doc.setFontSize(12); 
        doc.text("1. Imprime en papel fotográfico (Glossy).", 20, 40);
        doc.text("2. El diseño tiene un margen blanco de seguridad grande.", 20, 50);
        doc.text("   IMPORTANTE: Recorta TODO el borde blanco con tijera.", 20, 60);
        doc.text("   (El diseño se redujo ligeramente para garantizar que tu impresora no lo corte).", 20, 70);
        doc.text("3. Arma tu bolsita pegando al centro.", 20, 85);

        doc.save(`ChipBag_${chipText.value || 'Diseño'}.pdf`);
        
        downloadBtn.disabled = false;
        downloadBtn.textContent = "📥 Descargar PDF";
    });

    setCanvasSize();
});