/**
 * ITSWEBER CMS – Lucide Icon Picker
 * Global admin component for selecting Lucide icons.
 * Reads icon data from window.__lucideIcons (set by PHP in admin layout).
 */
(function () {
    'use strict';

    var overlay, modal, searchInput, body, footerInfo, targetInput, catalogue;

    function init() {
        catalogue = window.__lucideIcons || [];
        if (!catalogue.length) return;

        // Build modal DOM
        overlay = document.createElement('div');
        overlay.className = 'icon-picker-overlay';
        overlay.innerHTML =
            '<div class="icon-picker-modal">' +
                '<div class="icon-picker-header">' +
                    '<h3>Icon w\u00e4hlen</h3>' +
                    '<input type="text" class="icon-picker-search" placeholder="Suchen\u2026" autocomplete="off">' +
                    '<button type="button" class="icon-picker-close" title="Schlie\u00dfen">&times;</button>' +
                '</div>' +
                '<div class="icon-picker-body"></div>' +
                '<div class="icon-picker-footer">' +
                    '<span class="selected-info"></span>' +
                    '<div>' +
                        '<button type="button" class="btn btn-sm btn-secondary icon-picker-clear">Leeren</button> ' +
                        '<button type="button" class="btn btn-sm btn-primary icon-picker-confirm">Übernehmen</button>' +
                    '</div>' +
                '</div>' +
            '</div>';

        document.body.appendChild(overlay);

        modal = overlay.querySelector('.icon-picker-modal');
        searchInput = overlay.querySelector('.icon-picker-search');
        body = overlay.querySelector('.icon-picker-body');
        footerInfo = overlay.querySelector('.selected-info');

        // Events
        overlay.addEventListener('click', function (e) {
            if (e.target === overlay) close();
        });
        overlay.querySelector('.icon-picker-close').addEventListener('click', close);
        overlay.querySelector('.icon-picker-clear').addEventListener('click', function () {
            selectIcon('');
            close();
        });
        overlay.querySelector('.icon-picker-confirm').addEventListener('click', function () {
            close();
        });
        searchInput.addEventListener('input', function () {
            renderGrid(this.value.trim().toLowerCase());
        });
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape' && overlay.classList.contains('active')) close();
        });

        renderGrid('');

        // Attach to existing icon inputs
        attachToInputs();

        // Watch for dynamically added sections (PageBuilder adds items via JS)
        observeNewInputs();
    }

    var selectedName = '';

    function renderGrid(filter) {
        var html = '';
        var count = 0;

        for (var c = 0; c < catalogue.length; c++) {
            var cat = catalogue[c];
            var items = '';
            for (var i = 0; i < cat.icons.length; i++) {
                var icon = cat.icons[i];
                if (filter && icon.name.indexOf(filter) === -1) continue;
                var sel = icon.name === selectedName ? ' selected' : '';
                items += '<div class="icon-picker-item' + sel + '" data-name="' + icon.name + '" title="' + icon.name + '">' +
                    icon.svg +
                    '<span class="icon-picker-item-name">' + icon.name + '</span>' +
                '</div>';
                count++;
            }
            if (items) {
                html += '<div class="icon-picker-category">' +
                    '<div class="icon-picker-category-label">' + cat.category + '</div>' +
                    '<div class="icon-picker-grid">' + items + '</div>' +
                '</div>';
            }
        }

        if (!count) {
            html = '<div class="icon-picker-empty">Keine Icons gefunden f\u00fcr &bdquo;' + escHtml(filter) + '&ldquo;</div>';
        }

        body.innerHTML = html;

        // Click handlers on items
        var items = body.querySelectorAll('.icon-picker-item');
        for (var j = 0; j < items.length; j++) {
            items[j].addEventListener('click', function () {
                selectIcon(this.getAttribute('data-name'));
            });
        }
    }

    function selectIcon(name) {
        selectedName = name;

        // Update visual selection
        var all = body.querySelectorAll('.icon-picker-item');
        for (var i = 0; i < all.length; i++) {
            all[i].classList.toggle('selected', all[i].getAttribute('data-name') === name);
        }

        // Update footer info
        if (name) {
            var svg = getIconSvg(name);
            footerInfo.innerHTML = (svg || '') + ' <strong>' + escHtml(name) + '</strong>';
        } else {
            footerInfo.innerHTML = '<em>Kein Icon gew\u00e4hlt</em>';
        }

        // Update target input
        if (targetInput) {
            // For text inputs: set name; for textareas: set full SVG
            if (targetInput.tagName === 'TEXTAREA') {
                targetInput.value = name ? getIconSvg(name) : '';
            } else {
                targetInput.value = name;
            }
            // Trigger change event so frameworks detect the update
            targetInput.dispatchEvent(new Event('input', { bubbles: true }));
            targetInput.dispatchEvent(new Event('change', { bubbles: true }));
            // Update preview if exists
            updatePreview(targetInput);
        }
    }

    function getIconSvg(name) {
        for (var c = 0; c < catalogue.length; c++) {
            for (var i = 0; i < catalogue[c].icons.length; i++) {
                if (catalogue[c].icons[i].name === name) return catalogue[c].icons[i].svg;
            }
        }
        return '';
    }

    function findIconName(value) {
        // Try to find by exact name
        value = (value || '').trim();
        for (var c = 0; c < catalogue.length; c++) {
            for (var i = 0; i < catalogue[c].icons.length; i++) {
                if (catalogue[c].icons[i].name === value) return value;
            }
        }
        return '';
    }

    function open(input) {
        targetInput = input;
        var currentVal = (input.value || '').trim();

        // Determine current selection
        selectedName = findIconName(currentVal);

        searchInput.value = '';
        renderGrid('');
        overlay.classList.add('active');
        searchInput.focus();

        // Scroll selected into view
        setTimeout(function () {
            var sel = body.querySelector('.icon-picker-item.selected');
            if (sel) sel.scrollIntoView({ block: 'center', behavior: 'smooth' });
        }, 100);
    }

    function close() {
        overlay.classList.remove('active');
        targetInput = null;
    }

    function attachToInputs() {
        // Find all icon inputs by name pattern
        var selectors = [
            'input[name="item_icon[]"]',
            'input[name="hg_icon[]"]',
            'input[name="tc_icon[]"]',
            'input[name="contact_icon[]"]',
            'input[name="info_icon[]"]',
            'textarea[name="fsc_icon[]"]',
            'textarea[name="tsc_icon[]"]',
            'textarea[name="card_icon[]"]'
        ];
        var inputs = document.querySelectorAll(selectors.join(','));
        for (var i = 0; i < inputs.length; i++) {
            wrapWithPicker(inputs[i]);
        }
    }

    function wrapWithPicker(input) {
        if (input.dataset.iconPickerAttached) return;
        input.dataset.iconPickerAttached = '1';

        // Detect if parent uses CSS grid and widen the icon column
        var parent = input.parentNode;
        var parentDisplay = window.getComputedStyle(parent).display;
        if (parentDisplay === 'grid') {
            var cols = parent.style.gridTemplateColumns || '';
            if (cols.indexOf('80px') === 0) {
                parent.style.gridTemplateColumns = cols.replace('80px', 'minmax(140px,auto)');
            }
        }

        // Create wrapper
        var wrapper = document.createElement('span');
        wrapper.className = 'icon-input-wrapper';

        // Preview element
        var preview = document.createElement('span');
        preview.className = 'icon-input-preview';
        updatePreviewEl(preview, input.value);

        // Pick button
        var btn = document.createElement('button');
        btn.type = 'button';
        btn.className = 'icon-pick-btn';
        btn.title = 'Icon w\u00e4hlen';
        btn.innerHTML = '<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>';

        btn.addEventListener('click', function (e) {
            e.preventDefault();
            open(input);
        });

        // Insert wrapper around input
        input.parentNode.insertBefore(wrapper, input);
        wrapper.appendChild(preview);
        wrapper.appendChild(input);
        wrapper.appendChild(btn);

        // Update preview on manual input change
        input.addEventListener('input', function () {
            updatePreview(this);
        });
    }

    function updatePreview(input) {
        var wrapper = input.closest('.icon-input-wrapper');
        if (!wrapper) return;
        var preview = wrapper.querySelector('.icon-input-preview');
        if (preview) updatePreviewEl(preview, input.value);
    }

    function updatePreviewEl(el, value) {
        value = (value || '').trim();
        if (!value) {
            el.innerHTML = '';
            return;
        }
        var name = findIconName(value);
        if (name) {
            el.innerHTML = getIconSvg(name);
        } else if (value.indexOf('<svg') !== -1) {
            // Raw SVG in textarea
            el.innerHTML = value;
        } else {
            el.innerHTML = '<span style="font-size:1.2em">' + escHtml(value) + '</span>';
        }
    }

    function observeNewInputs() {
        if (!window.MutationObserver) return;
        var observer = new MutationObserver(function (mutations) {
            for (var m = 0; m < mutations.length; m++) {
                var added = mutations[m].addedNodes;
                for (var n = 0; n < added.length; n++) {
                    if (added[n].nodeType !== 1) continue;
                    var el = added[n];
                    var inputs = el.querySelectorAll ? el.querySelectorAll(
                        'input[name$="_icon[]"], textarea[name$="_icon[]"]'
                    ) : [];
                    for (var i = 0; i < inputs.length; i++) {
                        wrapWithPicker(inputs[i]);
                    }
                    // Also check if the element itself is an icon input
                    if (el.matches && el.matches('input[name$="_icon[]"], textarea[name$="_icon[]"]')) {
                        wrapWithPicker(el);
                    }
                }
            }
        });
        var container = document.querySelector('.admin-main') || document.body;
        observer.observe(container, { childList: true, subtree: true });
    }

    function escHtml(s) {
        var d = document.createElement('div');
        d.textContent = s;
        return d.innerHTML;
    }

    // Public API
    window.IconPicker = { open: open, close: close };

    // Init when DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
