// ════════════════════════════════════════════════════════════════════════════
//  EDITOR CORE (editor_core.js) – Setup, Zoom, Raster & Globale Variablen
// ════════════════════════════════════════════════════════════════════════════

const editorStyle = document.createElement('style');
editorStyle.innerHTML = `
    #editor-scale-wrapper { user-select: none; }
    #editor-canvas { cursor: crosshair; }
    #editor-canvas * { pointer-events: all !important; }
`;
document.head.appendChild(editorStyle);

// ── DOM-Referenzen ──
window.fullscreenEditor = document.getElementById('fullscreen-editor');
window.editorCanvas     = document.getElementById('editor-canvas');
window.toolBtns         = document.querySelectorAll('#editor-toolbar .editor-btn[data-tool]');
window.scaleWrapper     = document.getElementById('editor-scale-wrapper');
window.zoomLevelText    = document.getElementById('editor-zoom-level');
window.codePanel        = document.getElementById('editor-code-panel');
window.codeOutput       = document.getElementById('editor-code-output');

// ── Zustand (Global für alle Editor-Dateien) ──
window.currentTool            = 'select';
window.isDrawing              = false;
window.startX                 = 0;
window.startY                 = 0;
window.currentElement         = null;
window.editingComponent       = null;
window.editingInstance        = null;
window.selectedEditorElement  = null;
window.editorHandles          = [];
window.activeDragHandle       = null;

window.OUTPUT_VIEWBOX = '0 0 120 160';
window.OUTPUT_WIDTH   = 120;
window.OUTPUT_HEIGHT  = 160;

window.editorZoom       = 2.5;  
window._previewTimer    = null; 
window.gridSize         = 5;    
window.currentFontSize  = 10;   

// ── Zoom ──
window.updateEditorZoom = function() {
    if (window.scaleWrapper) window.scaleWrapper.style.transform = `scale(${window.editorZoom})`;
    if (window.zoomLevelText) window.zoomLevelText.innerText = `${Math.round(window.editorZoom * 100)}%`;
};

window.autoFitZoom = function() {
    window.editorZoom = 2.0; // Standard-Zoom
    window.updateEditorZoom();
};

const editorBtnZoomIn = document.getElementById('editor-zoom-in');
if (editorBtnZoomIn) editorBtnZoomIn.addEventListener('click', () => {
    window.editorZoom = Math.min(4.0, window.editorZoom + 0.25);
    window.updateEditorZoom();
});

const editorBtnZoomOut = document.getElementById('editor-zoom-out');
if (editorBtnZoomOut) editorBtnZoomOut.addEventListener('click', () => {
    window.editorZoom = Math.max(0.5, window.editorZoom - 0.25);
    window.updateEditorZoom();
});

// ── Raster & UI Injections ──
(function injectToolbarControls() {
    function inject() {
        const toolbar = document.getElementById('editor-toolbar');
        if (!toolbar) return; 

        const s = document.createElement('style');
        s.innerHTML = `
            .ed-ctrl-group { display: inline-flex; align-items: center; gap: 4px; margin-left: 8px; padding-left: 8px; border-left: 1px solid rgba(255,255,255,0.25); }
            .ed-ctrl-label { color: #bdc3c7; font-size: 11px; white-space: nowrap; font-family: Arial, sans-serif; }
            .ed-ctrl-select, .ed-ctrl-number { background: #2c3e50; color: white; border: 1px solid #7f8c8d; border-radius: 4px; padding: 3px 5px; font-size: 12px; height: 26px; }
            .ed-ctrl-number { width: 52px; text-align: center; }
            .ed-ctrl-select:focus, .ed-ctrl-number:focus { outline: none; border-color: #3498db; }
        `;
        document.head.appendChild(s);

        const gridGroup = document.createElement('span');
        gridGroup.className = 'ed-ctrl-group';
        gridGroup.innerHTML = `
            <span class="ed-ctrl-label">⊞ Raster</span>
            <select class="ed-ctrl-select" id="ed-grid-size">
                <option value="2">2 px</option>
                <option value="5" selected>5 px (Standard)</option>
                <option value="10">10 px</option>
                <option value="20">20 px</option>
            </select>
        `;
        toolbar.insertBefore(gridGroup, document.getElementById('btn-editor-grid'));

        const fontGroup = document.createElement('span');
        fontGroup.className = 'ed-ctrl-group';
        fontGroup.innerHTML = `
            <span class="ed-ctrl-label">Ａ Textgr.</span>
            <input type="number" class="ed-ctrl-number" id="ed-font-size" min="4" max="48" step="1" value="10">
        `;
        toolbar.insertBefore(fontGroup, document.getElementById('btn-editor-grid'));

        document.getElementById('ed-grid-size').addEventListener('change', function () {
            window.gridSize = parseInt(this.value, 10);
            window.applyGridPattern(window.gridSize);
        });

        document.getElementById('ed-font-size').addEventListener('change', function () {
            window.currentFontSize = Math.max(4, Math.min(48, parseInt(this.value, 10) || 10));
            this.value = window.currentFontSize;
            if (window.selectedEditorElement && window.selectedEditorElement.tagName.toLowerCase() === 'text') {
                window.selectedEditorElement.setAttribute('font-size', window.currentFontSize);
                if (typeof schedulePreviewUpdate === 'function') schedulePreviewUpdate();
            }
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', inject);
    } else {
        inject();
    }
})();

window.applyGridPattern = function(size) {
    let defs = window.editorCanvas.querySelector('defs');
    if (!defs) {
        defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
        window.editorCanvas.insertBefore(defs, window.editorCanvas.firstChild);
    }
    let pattern = defs.querySelector('pattern');
    if (!pattern) {
        pattern = document.createElementNS('http://www.w3.org/2000/svg', 'pattern');
        pattern.setAttribute('id', 'editor-grid-pattern-dyn');
        pattern.setAttribute('patternUnits', 'userSpaceOnUse');
        defs.appendChild(pattern);
        const gridBg = document.getElementById('editor-grid-bg');
        if (gridBg) gridBg.style.backgroundImage = 'none'; 
    }
    pattern.setAttribute('width',  size);
    pattern.setAttribute('height', size);
    let path = pattern.querySelector('path, line');
    if (!path) {
        path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        pattern.appendChild(path);
    }
    path.setAttribute('d', `M ${size} 0 L 0 0 0 ${size}`);
    path.setAttribute('fill', 'none');
    path.setAttribute('stroke', '#c8c8c8');
    path.setAttribute('stroke-width', '0.4');
    
    const gridBg = document.getElementById('editor-grid-bg');
    if (gridBg) {
        gridBg.style.backgroundSize = `${size}px ${size}px`;
    }
};

const btnEditorGrid = document.getElementById('btn-editor-grid');
if (btnEditorGrid) btnEditorGrid.addEventListener('click', (e) => {
    const gridBg = document.getElementById('editor-grid-bg');
    if (gridBg.style.display === 'none') {
        gridBg.style.display = 'block';
        e.currentTarget.style.backgroundColor = '#f39c12';
        e.currentTarget.style.color = 'black';
    } else {
        gridBg.style.display = 'none';
        e.currentTarget.style.backgroundColor = '#7f8c8d';
        e.currentTarget.style.color = 'white';
    }
});