// --- Lógica de Sesión (Se ejecuta de inmediato) ---
const creditCounter = document.getElementById('creditCounterDisplay');
const userSessionElement = document.getElementById('user-session');

function updateCreditCounter(amount) {
    if (creditCounter) {
        creditCounter.textContent = `Créditos: ${amount}`;
        creditCounter.style.display = 'block';
    }
}

function checkLoginStatus() {
    fetch('check_session.php', { cache: 'no-store' })
        .then(response => { if (!response.ok) throw new Error('Network response was not ok'); return response.json(); })
        .then(data => {
            if (data.loggedIn) {
                userSessionElement.innerHTML = `
                    <div class="user-info">
                        Bienvenido, <strong>${data.nombre}</strong> | <a href="index.html">Inicio</a> | <a href="galeria.html">Mi Galería</a> | <a href="comunidad.html">Galería Pública</a> | <a href="logout.php">Cerrar Sesión</a>
                    </div>`;
                updateCreditCounter(data.creditos);
            } else {
                alert('Necesitas iniciar sesión para usar esta herramienta.');
                window.location.href = 'index.html';
            }
        })
        .catch(error => {
            console.error('Error al chequear la sesión:', error);
            alert('Error de conexión o de sesión. Redirigiendo al inicio.');
            window.location.href = 'index.html';
        });
}

// Iniciar la comprobación de sesión
checkLoginStatus();

// --- Lógica de la Herramienta 3D ---
document.addEventListener('DOMContentLoaded', () => {

    // --- Variables Globales de la Herramienta ---
    const charInput = document.getElementById('charInput');
    const font3dSelector = document.getElementById('font3dSelector');
    const letterHeightInput = document.getElementById('letterHeight');
    const letterDepthInput = document.getElementById('letterDepth');
    const paperSizeSelector = document.getElementById('paperSizeSelector');
    const generate3dPdfBtn = document.getElementById('generate3dPdfBtn');
    const statusDiv = document.getElementById('status');

    const fontCache = new Map();

    const FONT_URLS = {
        'Anton': '/fonts/Anton-Regular.ttf',
        'Bebas Neue': '/fonts/BebasNeue-Regular.ttf',
        'Oswald': '/fonts/Oswald-Bold.ttf',
        'Alfa Slab One': '/fonts/AlfaSlabOne-Regular.ttf',
    };

    async function loadFont(fontName) {
        if (fontCache.has(fontName)) {
            return fontCache.get(fontName);
        }
        statusDiv.textContent = `Cargando fuente ${fontName}...`;
        const fontURL = FONT_URLS[fontName];
        
        try {
            const response = await fetch(fontURL);
            if (!response.ok) throw new Error(`No se pudo cargar la fuente: ${response.statusText}. URL: ${fontURL}`);
            const fontBuffer = await response.arrayBuffer();
            const font = opentype.parse(fontBuffer);
            fontCache.set(fontName, font);
            statusDiv.textContent = 'Fuente cargada. Listo para generar.';
            return font;
        } catch (error) {
            console.error('Error al cargar la fuente:', error);
            statusDiv.textContent = `Error: No se pudo cargar la fuente ${fontName}. (Revisa la consola)`;
            return null;
        }
    }

    // --- Funciones Auxiliares ---
    function distance(x1, y1, x2, y2) {
        return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
    }

    function drawTabs(doc, x, y, length, width, tabSize = 10) {
        doc.setLineDashPattern([2, 2], 0); 
        doc.setDrawColor(150, 150, 150); 
        
        let currentX = x;
        while (currentX + tabSize * 1.5 < x + length) {
            doc.lines([[0, 0], [tabSize, -tabSize], [tabSize * 1.5, 0]], currentX, y, [1, 1], 'S');
            currentX += tabSize * 1.5;
        }
        currentX = x;
        while (currentX + tabSize * 1.5 < x + length) {
            doc.lines([[0, 0], [tabSize, tabSize], [tabSize * 1.5, 0]], currentX, y + width, [1, 1], 'S');
            currentX += tabSize * 1.5;
        }
        
        doc.setLineDashPattern([], 0); 
        doc.setDrawColor(0, 0, 0); 
    }

    function drawOpentypePath(doc, path, x, y, scale, isFlipped = false) {
        const commands = path.commands;
        const scaleX = isFlipped ? -scale : scale;
        doc.setLineWidth(0.2);
        doc.setDrawColor(0, 0, 0);
        doc.setFillColor(240, 240, 240);

        let currentX = 0;
        let currentY = 0;

        for (let cmd of commands) {
            let x1 = cmd.x1 * scaleX + x; let y1 = cmd.y1 * scale + y;
            let x2 = cmd.x2 * scaleX + x; let y2 = cmd.y2 * scale + y;
            let cmdX = cmd.x * scaleX + x; let cmdY = cmd.y * scale + y;
            
            if (cmd.type === 'M') { 
                doc.moveTo(cmdX, cmdY); 
                currentX = cmdX;
                currentY = cmdY;
            } 
            else if (cmd.type === 'L') { 
                doc.lineTo(cmdX, cmdY); 
                currentX = cmdX;
                currentY = cmdY;
            } 
            else if (cmd.type === 'C') { 
                doc.curveTo(x1, y1, x2, y2, cmdX, cmdY); 
                currentX = cmdX;
                currentY = cmdY;
            } 
            else if (cmd.type === 'Q') { 
                let c1x = currentX + (2/3) * (x1 - currentX);
                let c1y = currentY + (2/3) * (y1 - currentY);
                let c2x = cmdX + (2/3) * (x1 - cmdX);
                let c2y = cmdY + (2/3) * (y1 - cmdY);
                doc.curveTo(c1x, c1y, c2x, c2y, cmdX, cmdY); 
                currentX = cmdX;
                currentY = cmdY;
            } 
            else if (cmd.type === 'Z') { 
                doc.close(); 
            }
        }
        doc.fill("evenodd"); 
    }

    function addSideStrips(doc, path, scale, depthMM, paperWidth, paperHeight, margin) {
        let pieceNumber = 1;
        let currentX = margin;
        let currentY = margin + 15; 
        const tabSize = 10; 
        const stripWidth = depthMM; 
        const gap = 5; 

        doc.addPage();
        doc.setFontSize(10);
        doc.text('Tiras Laterales (Piezas C)', margin, margin);

        let pathX = 0, pathY = 0, startX = 0, startY = 0;
        
        for (let cmd of path.commands) {
            let segmentLength = 0;
            let isCurve = false;
            if (cmd.type === 'M') {
                pathX = cmd.x; pathY = cmd.y;
                startX = cmd.x; startY = cmd.y;
                continue; 
            } else if (cmd.type === 'L') {
                segmentLength = distance(pathX, pathY, cmd.x, cmd.y);
                isCurve = false;
            } else if (cmd.type === 'C') {
                let l1 = distance(pathX, pathY, cmd.x1, cmd.y1);
                let l2 = distance(cmd.x1, cmd.y1, cmd.x2, cmd.y2);
                let l3 = distance(cmd.x2, cmd.y2, cmd.x, cmd.y);
                segmentLength = l1 + l2 + l3;
                isCurve = true;
            } else if (cmd.type === 'Q') {
                let l1 = distance(pathX, pathY, cmd.x1, cmd.y1);
                let l2 = distance(cmd.x1, cmd.y1, cmd.x, cmd.y);
                segmentLength = l1 + l2;
                isCurve = true;
            } else if (cmd.type === 'Z') {
                segmentLength = distance(pathX, pathY, startX, startY);
                isCurve = false;
            }

            if (cmd.x !== undefined) pathX = cmd.x;
            if (cmd.y !== undefined) pathY = cmd.y;
            if (segmentLength === 0) continue;
            let stripLength = segmentLength * scale;
            
            while (stripLength > 0) {
                let drawableLength = Math.min(stripLength, paperWidth - margin * 2);
                if (currentX + drawableLength > paperWidth - margin) {
                    currentY += stripWidth + tabSize * 2 + gap; 
                    currentX = margin;
                }
                if (currentY + stripWidth + tabSize * 2 > paperHeight - margin) {
                    doc.addPage();
                    doc.setFontSize(10);
                    doc.text('Tiras Laterales (Continuación)', margin, margin);
                    currentY = margin + 15;
                    currentX = margin;
                }
                doc.setDrawColor(0, 0, 0);
                doc.setLineWidth(0.2);
                doc.rect(currentX, currentY, drawableLength, stripWidth);
                drawTabs(doc, currentX, currentY, drawableLength, stripWidth, tabSize);
                doc.setFontSize(8);
                let label = `C${pieceNumber}`;
                if (stripLength > drawableLength) label += ` (Parte 1)`;
                if (drawableLength < stripLength) label = `C${pieceNumber} (Parte 2)`;
                doc.text(label, currentX + 2, currentY + stripWidth / 2, { baseline: 'middle' });
                if (isCurve) {
                    doc.text('(CURVA - doblar con cuidado)', currentX + 20, currentY + stripWidth / 2, { baseline: 'middle' });
                }
                currentX += drawableLength + gap;
                stripLength -= drawableLength;
                if (stripLength > 0) pieceNumber++; 
            }
            pieceNumber++;
        }
    }


    // --- FUNCIÓN PRINCIPAL DE GENERACIÓN DE PDF ---
    async function generatePDF() {
        generate3dPdfBtn.disabled = true;
        statusDiv.textContent = 'Generando PDF... por favor espera.';

        try {
            const { jsPDF } = window.jspdf;
            const char = charInput.value.toUpperCase();
            const fontName = font3dSelector.value;
            const targetHeightCM = parseFloat(letterHeightInput.value);
            const targetDepthCM = parseFloat(letterDepthInput.value);
            const paper = paperSizeSelector.value;
            
            const font = await loadFont(fontName);
            if (!font) {
                throw new Error("La carga de la fuente falló. Ver el error de estado.");
            }

            const doc = new jsPDF({ orientation: 'portrait', unit: 'mm', format: paper });
            const paperWidth = doc.internal.pageSize.getWidth();
            const paperHeight = doc.internal.pageSize.getHeight();
            const margin = 10;
            const targetHeightMM = targetHeightCM * 10;
            const targetDepthMM = targetDepthCM * 10;

            const path = font.getPath(char, 0, 0, 1000); 
            const box = path.getBoundingBox();
            const fontHeight = box.y2 - box.y1;
            const fontWidth = box.x2 - box.x1;
            const scale = targetHeightMM / fontHeight;
            const targetWidthMM = fontWidth * scale;

            // Página 1: Instrucciones
            doc.setFontSize(24);
            doc.text('Plano de Armado - Letra 3D', paperWidth / 2, 20, { align: 'center' });
            doc.setFontSize(12);
            doc.text(`Carácter: "${char}" (${fontName})`, margin, 40);
            doc.text(`Alto: ${targetHeightCM} cm`, margin, 50);
            doc.text(`Profundidad: ${targetDepthCM} cm`, margin, 60);
            doc.text('Instrucciones:', margin, 80);
            doc.text('1. Imprime todas las hojas en tamaño 100% (Real).', margin, 90);
            doc.text('2. Recorta las piezas por la línea continua.', margin, 100);
            doc.text('3. Dobla con cuidado por las líneas punteadas (pestañas).', margin, 110);
            doc.text('4. Pega las pestañas a las caras Frontal y Trasera.', margin, 120);
            doc.text('Piezas Incluidas:', margin, 140);
            doc.text('- 1 x Cara Frontal (Pieza A)', margin, 150);
            doc.text('- 1 x Cara Trasera (Pieza B, en espejo)', margin, 160);
            doc.text('- Tiras Laterales (Piezas C, numeradas)', margin, 170);

            // Página 2: Cara Frontal
            doc.addPage();
            doc.setFontSize(10);
            doc.text(`Cara Frontal - "${char}" - Pieza A`, margin, margin);
            const x_offset = (paperWidth - targetWidthMM) / 2;
            const y_offset = (paperHeight - targetHeightMM) / 2;
            drawOpentypePath(doc, path, x_offset, y_offset, scale);
            
            // Página 3: Cara Trasera
            doc.addPage();
            doc.text(`Cara Trasera (Espejo) - "${char}" - Pieza B`, margin, margin);
            doc.saveGraphicsState();
            
            // --- ¡LÍNEA CORREGIDA! ---
            // doc.matrix(-1, 0, 0, 1, paperWidth, 0); // <-- Esta era la línea del error, ahora eliminada.
            
            const x_offset_mirror = (paperWidth + targetWidthMM) / 2;
            drawOpentypePath(doc, path, x_offset_mirror, y_offset, scale, true); // La función ya sabe voltearlo
            doc.restoreGraphicsState();
            
            // Páginas Siguientes: Tiras Laterales
            addSideStrips(doc, path, scale, targetDepthMM, paperWidth, paperHeight, margin);
            
            // Guardar PDF
            doc.save(`Molde_3D_${char}_${fontName}.pdf`);
            statusDiv.textContent = '¡PDF con moldes 3D generado! Revisa tus descargas.';

        } catch (err) {
            console.error(err);
            statusDiv.textContent = 'Error: No se pudo generar el PDF.';
        } finally {
            generate3dPdfBtn.disabled = false;
        }
    }

    // --- INICIALIZACIÓN ---
    generate3dPdfBtn.addEventListener('click', generatePDF);

});