document.addEventListener('DOMContentLoaded', () => {
    const exportBtn = document.getElementById('btn-export');
    const canvasArea = document.getElementById('area-4');

    if (exportBtn && canvasArea) {
        exportBtn.addEventListener('click', () => {
            const originalText = exportBtn.innerHTML;
            exportBtn.innerHTML = '⏳ Exportiere...';
            exportBtn.disabled = true;

            const originalZoom = window.currentZoom || 1.0;
            const hadGrid = canvasArea.classList.contains('show-grid') || !canvasArea.classList.contains('hide-grid');

            if (typeof applyZoom !== 'undefined') {
                window.currentZoom = 1.0;
                applyZoom();
            } else {
                canvasArea.style.transform = 'scale(1)';
            }

            canvasArea.classList.remove('show-grid');
            canvasArea.classList.add('hide-grid');

            setTimeout(() => {
                html2canvas(canvasArea, {
                    backgroundColor: '#ffffff',
                    scale: 2
                }).then(canvas => {
                    const link = document.createElement('a');
                    link.download = 'Schaltplan_Export.png';
                    link.href = canvas.toDataURL('image/png');
                    link.click();

                    restoreExportState(originalZoom, hadGrid, originalText);
                    
                    if (typeof addHistory === 'function') {
                        addHistory('Schaltplan als PNG exportiert');
                    }
                }).catch(err => {
                    alert('Beim Exportieren ist leider ein Fehler aufgetreten.');
                    restoreExportState(originalZoom, hadGrid, originalText);
                });
            }, 250); 
        });
    }

    function restoreExportState(zoomLevel, showGrid, btnText) {
        if (typeof applyZoom !== 'undefined') {
            window.currentZoom = zoomLevel;
            applyZoom();
        } else {
            canvasArea.style.transform = `scale(${zoomLevel})`;
        }

        if (showGrid) {
            canvasArea.classList.add('show-grid');
            canvasArea.classList.remove('hide-grid');
        }

        exportBtn.innerHTML = btnText;
        exportBtn.disabled = false;
    }
});