// --- 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('boxCanvas');
    const ctx = canvas.getContext('2d');

    // Inputs UI
    const boxModelSelect = document.getElementById('boxModel');
    const sideWidthInput = document.getElementById('sideWidth');
    const boxHeightInput = document.getElementById('boxHeight');
    const bgColor = document.getElementById('bgColor');
    const patternColor = document.getElementById('patternColor'); // Nuevo
    const bgImageInput = document.getElementById('bgImageInput');
    const repeatBg = document.getElementById('repeatBg');
    const strokeColor = document.getElementById('strokeColor');
    const mainImageInput = document.getElementById('mainImageInput');
    const imgScale = document.getElementById('imgScale');
    const imgYOffset = document.getElementById('imgYOffset');
    const boxText = document.getElementById('boxText');
    const fontSelector = document.getElementById('fontSelector');
    const textColor = document.getElementById('textColor');
    const downloadBtn = document.getElementById('downloadBtn');
    const instructionText = document.getElementById('instructionText');
    const patternBtns = document.querySelectorAll('.pattern-btn'); // Nuevo

    let bgImgObj = null;
    let mainImgObj = null;
    let activePattern = 'none'; // none, cow, dots, etc.

    // Píxeles por cm (Alta resolución para impresión)
    const CM_TO_PX = 45; 
    const MARGIN = 60; 

    // --- GENERADOR DE PATRONES (Procedural) ---
    function generatePatternImage(type, color) {
        const patCanvas = document.createElement('canvas');
        const pCtx = patCanvas.getContext('2d');
        const size = 100; // Tamaño del cuadro del patrón
        patCanvas.width = size;
        patCanvas.height = size;

        // Fondo transparente (se verá el bgColor del input)
        pCtx.clearRect(0,0,size,size);
        pCtx.fillStyle = color;

        if (type === 'dots') {
            pCtx.beginPath();
            pCtx.arc(25, 25, 10, 0, Math.PI*2);
            pCtx.arc(75, 75, 10, 0, Math.PI*2);
            pCtx.fill();
        } 
        else if (type === 'stripes') {
            pCtx.fillRect(0, 0, 20, 100);
            pCtx.fillRect(50, 0, 20, 100);
        }
        else if (type === 'checkers') {
            pCtx.fillRect(0, 0, 50, 50);
            pCtx.fillRect(50, 50, 50, 50);
        }
        else if (type === 'cow') {
            // Manchas aleatorias simuladas
            drawBlob(pCtx, 20, 20, 15);
            drawBlob(pCtx, 80, 30, 20);
            drawBlob(pCtx, 40, 80, 18);
            drawBlob(pCtx, 90, 90, 12);
            // Manchas en los bordes para continuidad
            drawBlob(pCtx, 0, 50, 15);
            drawBlob(pCtx, 100, 50, 15);
        }
        else if (type === 'hearts') {
            drawHeart(pCtx, 25, 25, 20, color);
            drawHeart(pCtx, 75, 75, 20, color);
        }
        else if (type === 'stars') {
            drawStar(pCtx, 25, 25, 5, 15, 7, color);
            drawStar(pCtx, 75, 75, 5, 15, 7, color);
        }
        else if (type === 'flowers') {
            drawFlower(pCtx, 25, 25, 15, color);
            drawFlower(pCtx, 75, 75, 15, color);
        }

        const img = new Image();
        img.src = patCanvas.toDataURL();
        img.onload = () => {
            bgImgObj = img;
            repeatBg.checked = true; // Forzar mosaico para patrones
            draw();
        };
    }

    // --- FUNCIONES DE DIBUJO DE FORMAS PARA PATRONES ---
    function drawBlob(ctx, x, y, r) {
        ctx.beginPath();
        ctx.arc(x, y, r, 0, Math.PI * 2);
        // Deformar un poco para parecer mancha
        ctx.ellipse(x, y, r, r*0.8, Math.random(), 0, Math.PI*2);
        ctx.fill();
    }
    
    function drawHeart(ctx, x, y, size) {
        ctx.save();
        ctx.translate(x, y);
        ctx.scale(size/100, size/100);
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.bezierCurveTo(-50, -50, -100, 0, 0, 100);
        ctx.bezierCurveTo(100, 0, 50, -50, 0, 0);
        ctx.fill();
        ctx.restore();
    }

    function drawStar(ctx, cx, cy, spikes, outerRadius, innerRadius) {
        let rot = Math.PI / 2 * 3;
        let x = cx;
        let y = cy;
        let step = Math.PI / spikes;

        ctx.beginPath();
        ctx.moveTo(cx, cy - outerRadius);
        for (let i = 0; i < spikes; i++) {
            x = cx + Math.cos(rot) * outerRadius;
            y = cy + Math.sin(rot) * outerRadius;
            ctx.lineTo(x, y);
            rot += step;

            x = cx + Math.cos(rot) * innerRadius;
            y = cy + Math.sin(rot) * innerRadius;
            ctx.lineTo(x, y);
            rot += step;
        }
        ctx.lineTo(cx, cy - outerRadius);
        ctx.closePath();
        ctx.fill();
    }

    function drawFlower(ctx, x, y, radius) {
        ctx.save();
        ctx.translate(x, y);
        for (let i = 0; i < 5; i++) {
            ctx.rotate(Math.PI * 2 / 5);
            ctx.beginPath();
            ctx.arc(0, radius/2, radius/2, 0, Math.PI*2);
            ctx.fill();
        }
        ctx.beginPath();
        ctx.arc(0, 0, radius/3, 0, Math.PI*2); // Centro
        ctx.globalCompositeOperation = "destination-out"; // Borrar centro
        ctx.fill();
        ctx.globalCompositeOperation = "source-over";
        ctx.restore();
    }


    // --- MOTOR DE DIBUJO PRINCIPAL (Igual que antes, optimizado) ---
    function draw() {
        const model = boxModelSelect.value;
        
        if (model === 'hexagonal') instructionText.innerText = "ℹ️ Mitad del Hexágono (3 lados). Imprime 2 hojas.";
        else if (model === 'pyramid') instructionText.innerText = "ℹ️ Molde Pirámide. Base cuadrada incluida.";
        else instructionText.innerText = "ℹ️ Molde completo en 1 hoja.";

        const dim = calculateDimensions(model);
        canvas.width = dim.w + (MARGIN * 2);
        canvas.height = dim.h + (MARGIN * 2);

        ctx.clearRect(0, 0, canvas.width, canvas.height);

        const startX = MARGIN + dim.offsetX; 
        const startY = MARGIN + dim.topPadding;

        // MÁSCARA DE RECORTE (FONDO)
        ctx.save();
        ctx.beginPath();
        definePath(model, startX, startY);
        ctx.closePath();
        ctx.clip();

        // Dibujar Color de Fondo Base PRIMERO
        ctx.fillStyle = bgColor.value;
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // Dibujar Imagen/Patrón ENCIMA
        if (bgImgObj) {
            if (repeatBg.checked) {
                const tempC = document.createElement('canvas');
                const tCtx = tempC.getContext('2d');
                // Escalar si es patrón procedural (ya es pequeño) o imagen subida (puede ser grande)
                let scalePat = 1.0;
                if (activePattern === 'none') scalePat = 0.4; // Imagen subida, hacerla pequeña para mosaico
                
                tempC.width = bgImgObj.width * scalePat; 
                tempC.height = bgImgObj.height * scalePat;
                tCtx.drawImage(bgImgObj, 0, 0, tempC.width, tempC.height);
                const pattern = ctx.createPattern(tempC, 'repeat');
                ctx.fillStyle = pattern;
                ctx.fillRect(0, 0, canvas.width, canvas.height);
            } else {
                ctx.drawImage(bgImgObj, 0, 0, canvas.width, canvas.height);
            }
        }
        ctx.restore();

        // LÍNEAS
        ctx.lineWidth = 3;
        ctx.strokeStyle = strokeColor.value;
        ctx.beginPath(); definePath(model, startX, startY); ctx.stroke();

        ctx.beginPath(); ctx.setLineDash([10, 10]); 
        ctx.lineWidth = 2; ctx.strokeStyle = "#555"; 
        drawInternalLines(model, startX, startY); ctx.stroke(); ctx.setLineDash([]); 

        drawDecorations(model, startX, startY);
    }

    // ... [AQUÍ VAN LAS MISMAS FUNCIONES DE CÁLCULO DEL CÓDIGO ANTERIOR] ...
    // ... (calculateDimensions, definePath, drawInternalLines, drawDecorations, drawPetalPath) ...
    // Copia las funciones del código previo de 'centros.js' aquí abajo para no hacer el mensaje eterno,
    // ya que la geometría no cambió, solo la lógica de patrones.
    
    // TE LAS PEGO AQUÍ PARA ASEGURAR QUE FUNCIONE AL COPIAR:

    function calculateDimensions(model) {
        const W = parseFloat(sideWidthInput.value) * CM_TO_PX;
        const H = parseFloat(boxHeightInput.value) * CM_TO_PX;
        let totalW = 0, totalH = 0, topPadding = 0, offsetX = 0;

        if (model === 'hexagonal') {
            totalW = (W * 3) + (CM_TO_PX * 1.2);
            totalH = H + (W * 1.4);
            topPadding = W * 0.8;
        } else if (model === 'milkbox') {
            totalW = (W * 4) + (CM_TO_PX * 1.2);
            totalH = H + (W * 1.3);
            topPadding = W * 0.7;
        } else if (model === 'pyramid') {
            totalW = (W * 4) + (CM_TO_PX * 1.2);
            totalH = H + W; 
            topPadding = 0; 
        } else if (model === 'popcorn') {
            const topW = W * 1.4; const diff = (topW - W) / 2; 
            totalW = (topW * 4) + (CM_TO_PX * 1.2);
            totalH = H;
            offsetX = diff; 
        } else if (model === 'cube') {
            totalW = (W * 4) + (CM_TO_PX * 1.2);
            totalH = (W * 3); 
            topPadding = W; 
        }
        return { w: totalW, h: totalH, topPadding: topPadding, offsetX: offsetX };
    }

    function definePath(model, x, y) {
        const W = parseFloat(sideWidthInput.value) * CM_TO_PX;
        const H = parseFloat(boxHeightInput.value) * CM_TO_PX;
        const flap = 1.2 * CM_TO_PX; 

        if (model === 'hexagonal') {
            const pH = W * 0.8; const bH = W * 0.6;
            ctx.moveTo(x, y);
            drawPetalPath(ctx, x, y, W, pH); drawPetalPath(ctx, x + W, y, W, pH); drawPetalPath(ctx, x + W*2, y, W, pH);
            ctx.lineTo(x + W*3 + flap, y + 20); ctx.lineTo(x + W*3 + flap, y + H - 20); ctx.lineTo(x + W*3, y + H);
            ctx.lineTo(x + W*3 - (W*0.15), y + H + bH); ctx.lineTo(x + W*2 + (W*0.15), y + H + bH); ctx.lineTo(x + W*2, y + H);
            ctx.lineTo(x + W*2 - (W*0.15), y + H + bH); ctx.lineTo(x + W + (W*0.15), y + H + bH); ctx.lineTo(x + W, y + H);
            ctx.lineTo(x + W - (W*0.15), y + H + bH); ctx.lineTo(x + (W*0.15), y + H + bH); ctx.lineTo(x, y + H);
            ctx.lineTo(x, y);
        } else if (model === 'pyramid') {
            const baseY = y + H;
            ctx.moveTo(x, baseY);
            ctx.lineTo(x + W*0.5, y); ctx.lineTo(x + W, baseY); ctx.lineTo(x + W*1.5, y); ctx.lineTo(x + W*2, baseY);
            ctx.lineTo(x + W*2.5, y); ctx.lineTo(x + W*3, baseY); ctx.lineTo(x + W*3.5, y); ctx.lineTo(x + W*4, baseY);
            ctx.lineTo(x + W*4 + flap, baseY - 30); ctx.lineTo(x + W*4 + (flap*0.5), baseY + 20); ctx.lineTo(x + W*4, baseY);
            ctx.lineTo(x + W*3, baseY); ctx.lineTo(x + W*2, baseY); 
            ctx.lineTo(x + W*2, baseY + W); ctx.lineTo(x + W, baseY + W); ctx.lineTo(x + W, baseY);
            ctx.lineTo(x, baseY); ctx.closePath();
        } else if (model === 'popcorn') {
            const topW = W * 1.4; const diff = (topW - W) / 2;
            ctx.moveTo(x, y + H); ctx.lineTo(x - diff, y);
            const panelTopW = topW;
            for(let i=0; i<4; i++) { let currX = (x - diff) + (panelTopW * i); ctx.lineTo(currX + panelTopW, y); }
            const topRightX = (x - diff) + (topW * 4); const bottomRightX = x + (W * 4);
            ctx.lineTo(topRightX + flap, y + 20); ctx.lineTo(bottomRightX + flap, y + H - 20); ctx.lineTo(bottomRightX, y + H);
            ctx.lineTo(x, y + H); ctx.closePath();
        } else if (model === 'milkbox') {
            const roofH = W * 0.7; const baseH = W * 0.6;
            ctx.moveTo(x, y);
            ctx.lineTo(x, y - roofH); ctx.lineTo(x + W*4, y - roofH); ctx.lineTo(x + W*4, y);
            ctx.lineTo(x + W*4 + flap, y + 10); ctx.lineTo(x + W*4 + flap, y + H - 10); ctx.lineTo(x + W*4, y + H);
            ctx.lineTo(x + W*4, y + H + baseH); ctx.lineTo(x + W*3, y + H + baseH); ctx.lineTo(x + W*3, y + H);
            ctx.lineTo(x + W*3, y + H + baseH); ctx.lineTo(x + W*2, y + H + baseH); ctx.lineTo(x + W*2, y + H);
            ctx.lineTo(x + W*2, y + H + baseH); ctx.lineTo(x + W, y + H + baseH); ctx.lineTo(x + W, y + H);
            ctx.lineTo(x + W, y + H + baseH); ctx.lineTo(x, y + H + baseH); ctx.lineTo(x, y + H);
            ctx.lineTo(x, y); ctx.closePath();
        } else if (model === 'cube') {
            ctx.moveTo(x, y); ctx.lineTo(x + W*2, y);
            ctx.lineTo(x + W*2, y - W + 15); ctx.lineTo(x + W*3, y - W + 15); ctx.lineTo(x + W*3, y);
            ctx.lineTo(x + W*4, y);
            ctx.lineTo(x + W*4 + flap, y + 10); ctx.lineTo(x + W*4 + flap, y + W - 10); ctx.lineTo(x + W*4, y + W);
            ctx.lineTo(x + W*3, y + W);
            ctx.lineTo(x + W*3, y + W*2 + 15); ctx.lineTo(x + W*2, y + W*2 + 15); ctx.lineTo(x + W*2, y + W);
            ctx.lineTo(x, y + W); ctx.closePath();
        }
    }

    function drawInternalLines(model, x, y) {
        const W = parseFloat(sideWidthInput.value) * CM_TO_PX;
        const H = parseFloat(boxHeightInput.value) * CM_TO_PX;
        if (model === 'hexagonal') {
            for (let i = 1; i <= 3; i++) { ctx.moveTo(x + W*i, y); ctx.lineTo(x + W*i, y + H); }
            ctx.moveTo(x, y); ctx.lineTo(x + W*3, y); ctx.moveTo(x, y+H); ctx.lineTo(x + W*3, y+H);
        } else if (model === 'pyramid') {
            const baseY = y + H;
            for (let i = 1; i <= 4; i++) { ctx.moveTo(x + W*i, baseY); ctx.lineTo(x + W*(i-0.5), y); }
            ctx.moveTo(x + W, baseY); ctx.lineTo(x + W*2, baseY); ctx.moveTo(x + W, baseY + W); ctx.lineTo(x + W*2, baseY + W);
        } else if (model === 'popcorn') {
            const topW = W * 1.4; const diff = (topW - W) / 2;
            for(let i=1; i<=3; i++) {
                const tx = (x - diff) + (topW * i); const bx = x + (W * i);
                ctx.moveTo(tx, y); ctx.lineTo(bx, y + H);
            }
            ctx.moveTo(x, y+H); ctx.lineTo(x+W*4, y+H);
        } else if (model === 'cube') {
            for(let i=1; i<=3; i++) ctx.moveTo(x + W*i, y), ctx.lineTo(x + W*i, y + W);
            ctx.moveTo(x, y); ctx.lineTo(x + W*4, y); ctx.moveTo(x, y+W); ctx.lineTo(x + W*4, y+W);
            ctx.moveTo(x + W*2, y - W); ctx.lineTo(x + W*3, y - W); ctx.moveTo(x + W*2, y + 2*W); ctx.lineTo(x + W*3, y + 2*W);
        } else if (model === 'milkbox') {
            const roofH = W * 0.7;
            for(let i=1; i<=3; i++) { ctx.moveTo(x + W*i, y - roofH); ctx.lineTo(x + W*i, y + H); }
            ctx.moveTo(x, y); ctx.lineTo(x + W*4, y); ctx.moveTo(x, y+H); ctx.lineTo(x + W*4, y+H);
            ctx.moveTo(x, y - roofH/2); ctx.lineTo(x + W*4, y - roofH/2);
        }
    }

    function drawDecorations(model, x, y) {
        const W = parseFloat(sideWidthInput.value) * CM_TO_PX;
        const H = parseFloat(boxHeightInput.value) * CM_TO_PX;
        let cx = 0, cy = 0;

        if (model === 'hexagonal') { cx = x + W*1.5; cy = y + H/2; }
        else if (model === 'milkbox') { cx = x + W*1.5; cy = y + H/2; } 
        else if (model === 'pyramid') { cx = x + W*1.5; cy = y + H - (H*0.4); } 
        else if (model === 'popcorn') { 
            const topW = W * 1.4; const diff = (topW - W) / 2;
            cx = x + W*1.5 + (diff*1.5); cy = y + H/2; 
        } else if (model === 'cube') { cx = x + W*1.5; cy = y + W/2; } 

        if (mainImgObj) {
            const scale = parseInt(imgScale.value) / 100;
            const offset = parseInt(imgYOffset.value);
            const maxW = W * 0.9;
            let iW = mainImgObj.width; let iH = mainImgObj.height;
            if (iW > iH) { iW = maxW * scale; iH = (mainImgObj.height / mainImgObj.width) * iW; } 
            else { iH = (model==='pyramid' ? H*0.5 : H*0.7) * scale; iW = (mainImgObj.width / mainImgObj.height) * iH; }
            ctx.drawImage(mainImgObj, cx - iW/2, cy - iH/2 + offset, iW, iH);
        }

        if (boxText.value) {
            ctx.textAlign = "center";
            ctx.fillStyle = textColor.value;
            ctx.strokeStyle = "white";
            ctx.lineWidth = 3;
            const fontSize = W * 0.18;
            ctx.font = `bold ${fontSize}px "${fontSelector.value}"`;
            const ty = cy + (H*0.35); 
            ctx.strokeText(boxText.value, cx, ty);
            ctx.fillText(boxText.value, cx, ty);
        }
    }

    function drawPetalPath(ctx, cx, cy, w, h) {
        ctx.bezierCurveTo(cx, cy - h*0.5, cx + w*0.5, cy - h, cx + w*0.5, cy - h);
        ctx.bezierCurveTo(cx + w*0.5, cy - h, cx + w, cy - h*0.5, cx + w, cy);
    }

    // --- LISTENERS ---
    const inputs = [boxModelSelect, sideWidthInput, boxHeightInput, bgColor, patternColor, repeatBg, strokeColor, imgScale, imgYOffset, boxText, fontSelector, textColor];
    inputs.forEach(el => {
        el.addEventListener('input', draw);
        el.addEventListener('change', draw);
    });

    patternBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
            patternBtns.forEach(b => b.classList.remove('active'));
            e.currentTarget.classList.add('active');
            const type = e.currentTarget.dataset.pattern;
            const color = patternColor.value;
            activePattern = type;
            
            if (type === 'none') {
                bgImgObj = null;
                draw();
            } else {
                generatePatternImage(type, color);
            }
        });
    });

    patternColor.addEventListener('input', () => {
        if (activePattern !== 'none') generatePatternImage(activePattern, patternColor.value);
    });

    bgImageInput.addEventListener('change', (e) => {
        const f = e.target.files[0]; if(!f) return;
        const r = new FileReader();
        r.onload = (ev) => { 
            const img = new Image();
            img.onload = () => {
                bgImgObj = img; 
                activePattern = 'none';
                patternBtns.forEach(b => b.classList.remove('active'));
                draw();
            };
            img.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) => { mainImgObj = new Image(); mainImgObj.onload = draw; mainImgObj.src = ev.target.result; };
        r.readAsDataURL(f);
    });

    downloadBtn.addEventListener('click', () => {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF({ orientation: 'l', unit: 'mm', format: 'a4' });
        const imgData = canvas.toDataURL('image/png');
        const props = doc.getImageProperties(imgData);
        const pdfW = 297; const pdfH = 210; 
        const ratio = Math.min((pdfW-10)/props.width, (pdfH-10)/props.height);
        const w = props.width * ratio;
        const h = props.height * ratio;
        
        doc.addImage(imgData, 'PNG', (pdfW-w)/2, (pdfH-h)/2, w, h);
        doc.setFontSize(10);
        doc.text(`Molde: ${boxModelSelect.options[boxModelSelect.selectedIndex].text} - espacioapp.site`, 10, 200);
        doc.save('Molde_Caja.pdf');
    });

    draw(); 
});