/**
 * ITSWEBER CMS – Admin JavaScript
 */

document.addEventListener('DOMContentLoaded', function () {
    // ── Sidebar toggle for mobile ─────────────────────────────────────────
    var toggle   = document.getElementById('sidebarToggle');
    var sidebar  = document.getElementById('adminSidebar');
    var backdrop = document.getElementById('sidebarBackdrop');

    function openSidebar() {
        sidebar.classList.add('open');
        if (backdrop) backdrop.classList.add('open');
        if (toggle)   toggle.setAttribute('aria-expanded', 'true');
    }

    function closeSidebar() {
        sidebar.classList.remove('open');
        if (backdrop) backdrop.classList.remove('open');
        if (toggle)   toggle.setAttribute('aria-expanded', 'false');
    }

    if (toggle && sidebar) {
        toggle.addEventListener('click', function () {
            sidebar.classList.contains('open') ? closeSidebar() : openSidebar();
        });
    }

    if (backdrop) {
        backdrop.addEventListener('click', closeSidebar);
    }

    // Close sidebar on Escape key
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && sidebar && sidebar.classList.contains('open')) {
            closeSidebar();
        }
    });

    // ── Collapsible nav-groups ─────────────────────────────────────────────
    document.querySelectorAll('.nav-group-toggle').forEach(function (toggle) {
        toggle.addEventListener('click', function () {
            var group = this.closest('.nav-group');
            if (group) {
                group.classList.toggle('open');
            }
        });
    });

    // ── Auto-dismiss alerts after 5 seconds ───────────────────────────────
    document.querySelectorAll('.alert').forEach(function (alert) {
        setTimeout(function () {
            alert.style.transition = 'opacity 0.3s';
            alert.style.opacity    = '0';
            setTimeout(function () { alert.remove(); }, 300);
        }, 5000);
    });

    // ── Auto-generate slug from title ─────────────────────────────────────
    var titleInput = document.getElementById('title');
    var slugInput  = document.getElementById('slug');

    if (titleInput && slugInput && !slugInput.value) {
        titleInput.addEventListener('input', function () {
            slugInput.value = this.value
                .toLowerCase()
                .replace(/[^a-z0-9äöüß]+/g, '-')
                .replace(/^-|-$/g, '');
        });
    }

    // ── Media Picker wiring ───────────────────────────────────────────────
    // Looks for [data-media-picker] buttons anywhere in the page and wires
    // them to the #mediaPickerOverlay modal (present on pages/form and
    // blog/form). Images are loaded from /admin/media/picker-images (JSON).
    initMediaPicker();
});

/**
 * Initialise the media picker modal.
 *
 * The picker button carries:
 *   data-media-picker          – marks the button
 *   data-editor-target="id"    – id of the <textarea> whose Jodit instance
 *                                should receive the inserted HTML
 */
function initMediaPicker() {
    var btn     = document.querySelector('[data-media-picker]');
    var overlay = document.getElementById('mediaPickerOverlay');

    if (!btn || !overlay) return;

    var body         = document.getElementById('mediaPickerBody');
    var closeBtn     = document.getElementById('mediaPickerClose');
    var editorTarget = btn.dataset.editorTarget || 'content';
    var loaded       = false;

    // ── Open ──────────────────────────────────────────────────────────────
    btn.addEventListener('click', function () {
        overlay.style.display = 'flex';
        if (!loaded) {
            renderPickerShell(body);
            loadPickerImages(body, '', '');
            loaded = true;
        }
    });

    // ── Close ─────────────────────────────────────────────────────────────
    function closePicker() { overlay.style.display = 'none'; }

    closeBtn && closeBtn.addEventListener('click', closePicker);
    overlay.addEventListener('click', function (e) {
        if (e.target === overlay) closePicker();
    });
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && overlay.style.display !== 'none') closePicker();
    });

    // ── Render shell (toolbar + grid container) ───────────────────────────
    function renderPickerShell(container) {
        container.innerHTML =
            '<div class="media-picker-toolbar">' +
                '<input type="text" class="media-picker-search" id="pickerSearch" placeholder="Search images…" autocomplete="off">' +
                '<span class="media-picker-toolbar-label">Folder:</span>' +
                '<select class="media-picker-folder" id="pickerFolder">' +
                    '<option value="">All media</option>' +
                    '<option value="0">Unassigned</option>' +
                '</select>' +
            '</div>' +
            '<div class="media-picker-body" id="pickerGrid">' +
                '<p style="text-align:center;color:var(--gray-400);padding-top:3rem;">Loading…</p>' +
            '</div>';

        var searchInput  = container.querySelector('#pickerSearch');
        var folderSelect = container.querySelector('#pickerFolder');

        // Debounced search
        var searchTimer;
        searchInput.addEventListener('input', function () {
            clearTimeout(searchTimer);
            var q      = searchInput.value;
            var folder = folderSelect.value;
            searchTimer = setTimeout(function () {
                loadPickerImages(container, q, folder);
            }, 350);
        });

        folderSelect.addEventListener('change', function () {
            loadPickerImages(container, searchInput.value, folderSelect.value);
        });
    }

    // ── Fetch images from JSON endpoint ───────────────────────────────────
    function loadPickerImages(container, q, folder) {
        var grid = container.querySelector('#pickerGrid');
        if (!grid) return;

        grid.innerHTML = '<p style="text-align:center;color:var(--gray-400);padding-top:2rem;">Loading…</p>';

        var url = '/admin/media/picker-images?q=' + encodeURIComponent(q) +
                  '&folder=' + encodeURIComponent(folder);

        fetch(url, { credentials: 'same-origin' })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                // Populate named folder options (once, after "All media" + "Unassigned")
                var folderSelect = container.querySelector('#pickerFolder');
                if (folderSelect && folderSelect.options.length <= 2 && data.folders && data.folders.length) {
                    data.folders.forEach(function (f) {
                        var opt = document.createElement('option');
                        opt.value       = f.id;
                        opt.textContent = f.name;
                        folderSelect.appendChild(opt);
                    });
                }

                if (!data.images || data.images.length === 0) {
                    grid.innerHTML = '<p style="text-align:center;color:var(--gray-400);padding-top:3rem;font-size:0.9375rem;">No images found.</p>';
                    return;
                }

                var html = '<div class="media-picker-grid">';
                data.images.forEach(function (img) {
                    html += '<div class="media-picker-item" data-url="' + escHtml(img.url) + '" data-alt="' + escHtml(img.alt || img.name) + '" title="' + escHtml(img.name) + '">' +
                                '<img src="' + escHtml(img.thumb_url || img.url) + '" alt="' + escHtml(img.name) + '" loading="lazy">' +
                                '<div class="media-picker-item-name">' + escHtml(img.name) + '</div>' +
                            '</div>';
                });
                html += '</div>';
                grid.innerHTML = html;

                // Click handler: insert into editor
                grid.querySelectorAll('.media-picker-item').forEach(function (item) {
                    item.addEventListener('click', function () {
                        var url = item.dataset.url;
                        var alt = item.dataset.alt || '';
                        insertImageIntoEditor(editorTarget, url, alt);
                        closePicker();
                    });
                });
            })
            .catch(function () {
                grid.innerHTML = '<p style="text-align:center;color:var(--admin-danger);padding-top:3rem;font-size:0.9375rem;">Failed to load images.</p>';
            });
    }

    // ── Insert <img> tag into the Jodit editor ────────────────────────────
    function insertImageIntoEditor(targetId, url, alt) {
        var textarea = document.getElementById(targetId);
        if (!textarea) return;

        var imgTag = '<img src="' + url + '" alt="' + escAttr(alt) + '">';

        // Try Jodit instance stored on the textarea element
        if (textarea._joditEditor) {
            textarea._joditEditor.selection.insertHTML(imgTag);
            return;
        }

        // Fallback: append to plain textarea value
        textarea.value += '\n' + imgTag;
    }

    // ── HTML helpers ──────────────────────────────────────────────────────
    function escHtml(str) {
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }
    function escAttr(str) {
        return String(str).replace(/"/g, '&quot;');
    }
}
