// Get DOM elements
const printerSelect = document.getElementById('printerSelect');
const materialSelectButton = document.getElementById('materialSelectButton');
const qualitySelect = document.getElementById('qualitySelect');
const fileInput = document.getElementById('fileInput');
const startPrintBtn = document.getElementById('startPrint');

// Variables to store selected data
let selectedPrinter = '';
let selectedMaterial = '';
let selectedQuality = '';
let selectedFile = null;
let modelInfo = {
    dimensions: '-',
    volume: '-',
    weight: '-',
    cost: '-'
};

// Function to collect current selections
function collectCurrentSelections() {
    selectedPrinter = printerSelect.options[printerSelect.selectedIndex]?.text || printerSelect.value;
    selectedQuality = qualitySelect.options[qualitySelect.selectedIndex]?.text || qualitySelect.value;

    // Get material from dataset (used by the rest of the app)
    const root = document.querySelector('.modulo-impresion3d');
    selectedMaterial = root && root.dataset.selectedMaterial ? root.dataset.selectedMaterial : '-';

    selectedFile = fileInput.files[0];

    // Get calculated results from the UI
    const dimensionsElement = document.getElementById('abmessungen-wert');
    const volumeElement = document.getElementById('volumen-wert');
    const weightElement = document.getElementById('gewicht-wert');
    const costElement = document.getElementById('kosten-wert');

    modelInfo = {
        dimensions: dimensionsElement?.textContent || '-',
        volume: volumeElement?.textContent || '-',
        weight: weightElement?.textContent || '-',
        cost: costElement?.textContent || '-'
    };
}

// Function to generate ticket content
function generateTicketContent() {
    collectCurrentSelections();

    const fileName = selectedFile ? selectedFile.name.replace(/\.[^/.]+$/, "") : '-';
    const currentDate = new Date().toLocaleDateString('de-DE');

    return `3D-DRUCK AUFTRAGSZUSAMMENFASSUNG
=====================================

AUFTRAGSDATEN
-------------
Datum: ${currentDate}
Dateiname: ${fileName}

AUSGEWÄHLTE PARAMETER
---------------------
Drucker: ${selectedPrinter}
Material: ${selectedMaterial}
Qualität: ${selectedQuality}

MODELLDATEN
-----------
Abmessungen (L×B×H): ${modelInfo.dimensions}
Volumen: ${modelInfo.volume}
Materialgewicht: ${modelInfo.weight}

KOSTENBERECHNUNG
----------------
Geschätzte Druckkosten: ${modelInfo.cost} €

UPLOAD-INFORMATION
------------------
Dateiname: ${selectedFile ? selectedFile.name : '-'}
Dateigröße: ${selectedFile ? (selectedFile.size / 1024 / 1024).toFixed(2) + ' MB' : '-'}

HINWEIS
-------
Dies ist eine Kostenschätzung basierend auf den aktuellen Parametern.
Die endgültigen Kosten können je nach Druckergebnis variieren.

=====================================
Generiert von bbw Hochschule - 3D-Druck-Service
`;
}

// Function to download ticket as .txt file
function downloadTicket() {
    collectCurrentSelections();
    // Check if calculations are complete
    const incomplete = [modelInfo.dimensions, modelInfo.volume, modelInfo.weight, modelInfo.cost].some(val => {
        return val === '-' || val === 'Berechne...' || val === 'Calculating...';
    });
    const lang = (document.getElementById('languageSelect')?.value || 'de').toLowerCase();
    if (incomplete) {
        let msg = '';
        if (lang === 'en') {
            msg = 'Please wait until all calculations are complete before generating the order file.';
        } else {
            msg = 'Bitte warten Sie, bis alle Berechnungen abgeschlossen sind, bevor Sie die Bestellungsdatei generieren.';
        }
        showOrderInfoMessage(msg, true);
        return;
    }

    const ticketContent = generateTicketContent();
    const blob = new Blob([ticketContent], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);

    // Create download link
    const a = document.createElement('a');
    a.href = url;
    a.download = `3D-Druck-Auftrag-${new Date().toISOString().split('T')[0]}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    // Show info message to user after download
    showOrderInfoMessage();
}

// Show info message to user after generating the order txt or warning
function showOrderInfoMessage(msg = null, isWarning = false) {
    // Remove previous message if exists
    const prev = document.getElementById('orderInfoMsg');
    if (prev) prev.remove();

    // Get language
    const lang = (document.getElementById('languageSelect')?.value || 'de').toLowerCase();
    let finalMsg = '';
    if (msg) {
        finalMsg = msg;
    } else {
        finalMsg = (lang === 'en')
            ? 'Order file generated!<br><span style="color:#b71c1c;font-size:1.1em;">Please send <b>both</b> the downloaded <b>.txt receipt</b> and your <b>STL file</b> as attachments to <b>info@bbw-hochschule.de</b> to complete your order.</span>'
            : 'Bestellungsdatei generiert!<br><span style="color:#b71c1c;font-size:1.1em;">Bitte senden Sie <b>sowohl</b> die heruntergeladene <b>.txt-Bestellungsdatei</b> als auch Ihre <b>STL-Datei</b> als Anhänge an <b>info@bbw-hochschule.de</b>, um Ihre Bestellung abzuschließen.</span>';
    }
    const infoDiv = document.createElement('div');
    infoDiv.id = 'orderInfoMsg';
    infoDiv.style.background = isWarning ? '#ffebee' : '#e3f2fd';
    infoDiv.style.color = isWarning ? '#b71c1c' : '#0d47a1';
    infoDiv.style.border = isWarning ? '2px solid #b71c1c' : '2px solid #1976d2';
    infoDiv.style.borderRadius = '10px';
    infoDiv.style.padding = '1.3em';
    infoDiv.style.margin = '1.2em 0';
    infoDiv.style.textAlign = 'center';
    infoDiv.style.fontWeight = 'bold';
    infoDiv.style.fontSize = '1.15em';
    infoDiv.innerHTML = finalMsg;

    // Insert after the print button
    const btn = document.getElementById('startPrint');
    if (btn && btn.parentNode) {
        btn.parentNode.insertBefore(infoDiv, btn.nextSibling);
    } else {
        document.body.appendChild(infoDiv);
    }
}

// Inicialización: el botón de imprimir ya está gestionado en main.js

// Asignar el handler directo al botón de imprimir si existe (fallback por robustez)
document.addEventListener('DOMContentLoaded', function () {
    const btn = document.getElementById('startPrint');
    if (btn) {
        btn.onclick = downloadTicket;
    }
});
window.generate3DPrintTicket = downloadTicket;
