window.setupDragDrop = (el, dotNetHelper) => {
    if (!el || !el.addEventListener) return;

    const preventDefault = (e) => {
        e.preventDefault();
        e.stopPropagation();
    };

    const handleDragEnter = (e) => {
        preventDefault(e);
        el.classList.add('upload-zone--dragover');
    };

    const handleDragOver = (e) => {
        preventDefault(e);
        e.dataTransfer.dropEffect = 'copy';
    };

    const handleDragLeave = (e) => {
        preventDefault(e);
        // Nur entfernen wenn wir wirklich die Zone verlassen (nicht Kind-Elemente)
        if (!el.contains(e.relatedTarget)) {
            el.classList.remove('upload-zone--dragover');
        }
    };

    const handleDrop = (e) => {
        preventDefault(e);
        el.classList.remove('upload-zone--dragover');

        if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            const files = Array.from(e.dataTransfer.files);

            files.forEach(file => {
                const reader = new FileReader();
                reader.onload = (event) => {
                    const dataUrl = event.target.result;
                    const base64 = dataUrl.split(',')[1];

                    if (dotNetHelper) {
                        dotNetHelper.invokeMethodAsync('OnFilesDropped', {
                            name: file.name,
                            size: file.size,
                            content: base64
                        });
                    }
                };
                reader.readAsDataURL(file);
            });
        }
    };

    el.addEventListener('dragenter', handleDragEnter);
    el.addEventListener('dragover', handleDragOver);
    el.addEventListener('dragleave', handleDragLeave);
    el.addEventListener('drop', handleDrop);

    // Klick auf Zone öffnet Dateidialog
    const hiddenInput = document.createElement('input');
    hiddenInput.type = 'file';
    hiddenInput.multiple = true;
    hiddenInput.accept = '.xml,.pdf,.zfx';
    hiddenInput.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer;';
    el.style.position = 'relative';
    el.appendChild(hiddenInput);

    hiddenInput.addEventListener('change', (e) => {
        const files = Array.from(e.target.files);

        files.forEach(file => {
            const reader = new FileReader();
            reader.onload = (event) => {
                const dataUrl = event.target.result;
                const base64 = dataUrl.split(',')[1];

                if (dotNetHelper) {
                    dotNetHelper.invokeMethodAsync('OnFilesDropped', {
                        name: file.name,
                        size: file.size,
                        content: base64
                    });
                }
            };
            reader.readAsDataURL(file);
        });

        hiddenInput.value = '';
    });
};

window.fitColumns = (tableSelector) => {
    const table = document.querySelector(tableSelector);
    if (!table) return;

    const colgroup = table.querySelector('colgroup');
    const cols = colgroup ? colgroup.querySelectorAll('col') : null;
    const colCount = cols ? cols.length : 0;
    if (colCount === 0) return;

    const maxWidths = new Array(colCount).fill(0);

    // Hilfsfunktion: Inhalt einer Zelle messen (unabhängig von overflow/table-layout)
    const measureContent = (cell) => {
        const computed = window.getComputedStyle(cell);
        const tmp = document.createElement('span');
        tmp.style.position = 'absolute';
        tmp.style.visibility = 'hidden';
        tmp.style.whiteSpace = 'nowrap';
        tmp.style.fontFamily = computed.fontFamily;
        tmp.style.fontSize = computed.fontSize;
        tmp.style.fontWeight = computed.fontWeight;
        tmp.style.letterSpacing = computed.letterSpacing;
        tmp.innerHTML = cell.innerHTML;
        document.body.appendChild(tmp);
        const contentW = tmp.scrollWidth;
        document.body.removeChild(tmp);
        // Padding links + rechts zur Inhaltsbreite addieren
        const paddingLeft = parseFloat(computed.paddingLeft) || 0;
        const paddingRight = parseFloat(computed.paddingRight) || 0;
        return contentW + paddingLeft + paddingRight;
    };

    // Header messen (nur Spalte 2)
    const thead = table.querySelector('thead');
    if (thead) {
        const headerRow = thead.querySelector('tr');
        if (headerRow) {
            const th = headerRow.cells[1];
            if (th) {
                const w = measureContent(th);
                maxWidths[1] = w;
            }
        }
    }

    // Body-Zellen messen (nur Spalte 2)
    const tbody = table.querySelector('tbody');
    if (tbody) {
        const rows = tbody.querySelectorAll('tr');
        for (const row of rows) {
            const cell = row.cells[1];
            if (cell) {
                const w = measureContent(cell);
                if (w > maxWidths[1]) maxWidths[1] = w;
            }
        }
    }

    // Keine col-Breiten setzen — CSS übernimmt das
};
