/**
 * 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) {
        var t = window.iwT || {};
        container.innerHTML =
            '<div class="media-picker-toolbar">' +
                '<input type="text" class="media-picker-search" id="pickerSearch" placeholder="' + (t.search_images || 'Search images…') + '" autocomplete="off">' +
                '<span class="media-picker-toolbar-label">' + (t.folder_label || 'Folder:') + '</span>' +
                '<select class="media-picker-folder" id="pickerFolder">' +
                    '<option value="">' + (t.all_media || 'All media') + '</option>' +
                    '<option value="0">' + (t.unassigned || 'Unassigned') + '</option>' +
                '</select>' +
            '</div>' +
            '<div class="media-picker-body" id="pickerGrid">' +
                '<p style="text-align:center;color:var(--gray-400);padding-top:3rem;">' + (t.loading || '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;">' + ((window.iwT||{}).loading || '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;">' + ((window.iwT||{}).no_images || '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;">' + ((window.iwT||{}).load_failed || '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;');
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Generic Section Media Field – reusable image picker for any form field
// ═══════════════════════════════════════════════════════════════════════════════
//
// Usage: Call initSectionMediaFields() or attach to elements with
// class "section-media-field-wrap". Each wrap contains:
//   <input type="text" name="..." class="section-media-input">
//   <button type="button" class="section-media-browse">Browse Media</button>
//   <button type="button" class="section-media-remove">×</button>
//   <div class="section-media-preview"><img></div>
//
// The browse button opens a shared modal. On image select, the input gets
// the image URL and the preview updates. Works for multiple fields on the
// same page (each opens the same modal but writes to its own input).
//
(function () {
    'use strict';

    var _smfModal       = null;   // Shared modal element
    var _smfLoaded      = false;  // Whether images have been fetched
    var _smfActiveField = null;   // Which input should receive the selected image

    // ── Public initialiser – call after DOM ready or after dynamic content ──
    window.initSectionMediaFields = function (root) {
        root = root || document;
        root.querySelectorAll('.section-media-field-wrap').forEach(function (wrap) {
            if (wrap._smfInitialised) return;
            wrap._smfInitialised = true;

            var input   = wrap.querySelector('.section-media-input');
            var browse  = wrap.querySelector('.section-media-browse');
            var remove  = wrap.querySelector('.section-media-remove');
            var preview = wrap.querySelector('.section-media-preview');
            var prevImg = preview ? preview.querySelector('img') : null;

            // Update preview visibility
            function refreshPreview() {
                if (!preview || !prevImg) return;
                var val = (input ? input.value : '').trim();
                if (val) {
                    prevImg.src = val.indexOf('/') === 0 ? val : '/uploads/' + val;
                    prevImg.alt = '';
                    preview.style.display = '';
                } else {
                    preview.style.display = 'none';
                    prevImg.src = '';
                }
            }

            // Initial state
            refreshPreview();

            // Browse button → open modal
            if (browse && input) {
                browse.addEventListener('click', function (e) {
                    e.preventDefault();
                    _smfActiveField = { input: input, refreshPreview: refreshPreview };
                    openSMFModal();
                });
            }

            // Remove button → clear field
            if (remove && input) {
                remove.addEventListener('click', function (e) {
                    e.preventDefault();
                    input.value = '';
                    refreshPreview();
                });
            }

            // Manual edit → refresh preview
            if (input) {
                input.addEventListener('change', refreshPreview);
            }
        });
    };

    // ── Upload helper inside modal ──────────────────────────────────────────
    function handleSMFUpload(file) {
        if (!file) { console.warn('[IW Upload] No file provided'); return; }

        var grid = _smfModal ? _smfModal.querySelector('.smf-grid') : null;

        // Pre-flight: client-side file size check (5 MB limit matches server)
        var t = window.iwT || {};
        if (file.size > 5 * 1024 * 1024) {
            var sizeMsg = (t.file_too_large || 'File too large (max. 5 MB). Current size: :size MB').replace(':size', (file.size / 1024 / 1024).toFixed(1));
            if (grid) grid.innerHTML = '<p style="text-align:center;color:#dc2626;padding:2rem;">' + sizeMsg + '</p>';
            return;
        }

        // Pre-flight: check CSRF token exists
        var csrfInput = document.querySelector('input[name="_csrf_token"]');
        if (!csrfInput || !csrfInput.value) {
            console.error('[IW Upload] No CSRF token found on page!');
            if (grid) grid.innerHTML = '<p style="text-align:center;color:#dc2626;padding:2rem;">' + (t.csrf_missing || 'CSRF token missing.') + '</p>';
            return;
        }

        var formData = new FormData();
        formData.append('media_file', file);
        formData.append('_csrf_token', csrfInput.value);

        console.log('[IW Upload] Uploading:', file.name, '(' + (file.size / 1024).toFixed(0) + ' KB)', 'CSRF:', csrfInput.value.substring(0, 8) + '…');

        var uploadingMsg = (t.uploading || 'Uploading… (:size KB)').replace(':size', (file.size / 1024).toFixed(0));
        if (grid) grid.innerHTML = '<p style="text-align:center;padding:2rem;color:#6b7280;">' + uploadingMsg + '</p>';

        // Use XMLHttpRequest for better compatibility and progress tracking
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/admin/media/upload', true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

        xhr.onload = function () {
            console.log('[IW Upload] Response:', xhr.status, xhr.responseText.substring(0, 200));

            var data;
            try {
                data = JSON.parse(xhr.responseText);
            } catch (e) {
                // Server returned non-JSON (e.g. plain text error, HTML error page)
                var msg = xhr.responseText || ('HTTP ' + xhr.status);
                var httpErrMsg = (t.upload_http_err || 'Upload failed (HTTP :status): :body').replace(':status', xhr.status).replace(':body', msg.replace(/</g, '&lt;').substring(0, 200));
                if (grid) grid.innerHTML = '<p style="text-align:center;color:#dc2626;padding:2rem;">' + httpErrMsg + '</p>';
                return;
            }

            if (data.success && data.url) {
                console.log('[IW Upload] Success:', data.url);
                if (_smfActiveField) {
                    _smfActiveField.input.value = data.url;
                    _smfActiveField.refreshPreview();
                }
                closeSMFModal();
            } else if (data.error) {
                var failMsg = (t.upload_failed || 'Upload failed: :error').replace(':error', (data.error || '').replace(/</g, '&lt;'));
                if (grid) grid.innerHTML = '<p style="text-align:center;color:#dc2626;padding:2rem;">' + failMsg + '</p>';
            } else {
                // Upload succeeded but no URL returned – refresh grid
                _smfLoaded = false;
                loadSMFImages();
            }
        };

        xhr.onerror = function () {
            console.error('[IW Upload] Network error – request did not reach server');
            if (grid) grid.innerHTML = '<p style="text-align:center;color:#dc2626;padding:2rem;">' + (t.network_error || 'Network error.') + '</p>';
        };

        xhr.ontimeout = function () {
            console.error('[IW Upload] Timeout');
            if (grid) grid.innerHTML = '<p style="text-align:center;color:#dc2626;padding:2rem;">' + (t.upload_timeout || 'Upload timeout.') + '</p>';
        };

        xhr.timeout = 60000; // 60 seconds
        xhr.send(formData);
    }

    // ── Build & open the shared modal ───────────────────────────────────────
    function openSMFModal() {
        if (!_smfModal) {
            _smfModal = document.createElement('div');
            _smfModal.id = 'sectionMediaPickerOverlay';
            _smfModal.className = 'media-picker-overlay';
            _smfModal.setAttribute('role', 'dialog');
            _smfModal.setAttribute('aria-modal', 'true');
            var t = window.iwT || {};
            _smfModal.setAttribute('aria-label', t.select_image || 'Select image');
            _smfModal.innerHTML =
                '<div class="media-picker-modal" style="max-width:860px;">' +
                    '<div class="media-picker-header">' +
                        '<h3>' + (t.select_image || 'Select image') + '</h3>' +
                        '<button type="button" class="media-picker-close smf-close" aria-label="Close">&times;</button>' +
                    '</div>' +
                    '<div class="smf-toolbar" style="display:flex;gap:0.75rem;padding:0.75rem 1.25rem;border-bottom:1px solid #e5e7eb;align-items:center;">' +
                        '<input type="text" class="form-control smf-search" placeholder="' + (t.search || 'Search…') + '" style="flex:1;">' +
                        '<label class="btn btn-secondary btn-sm" style="cursor:pointer;margin:0;">' +
                            (t.upload_btn || '⬆ Upload') + ' <input type="file" class="smf-upload-input" accept="image/*" style="display:none;">' +
                        '</label>' +
                    '</div>' +
                    '<div class="smf-grid" style="padding:1rem;max-height:420px;overflow-y:auto;">' +
                        '<p style="text-align:center;color:#6b7280;padding:2rem;">' + (t.loading || 'Loading…') + '</p>' +
                    '</div>' +
                '</div>';
            document.body.appendChild(_smfModal);

            // Close button
            _smfModal.querySelector('.smf-close').addEventListener('click', closeSMFModal);

            // Backdrop click
            _smfModal.addEventListener('click', function (e) {
                if (e.target === _smfModal) closeSMFModal();
            });

            // Escape key
            document.addEventListener('keydown', function (e) {
                if (e.key === 'Escape' && _smfModal.style.display !== 'none') closeSMFModal();
            });

            // Search
            var searchInput = _smfModal.querySelector('.smf-search');
            if (searchInput) {
                searchInput.addEventListener('input', function () {
                    var q = this.value.toLowerCase();
                    _smfModal.querySelectorAll('.smf-item').forEach(function (item) {
                        var name = (item.dataset.name || '').toLowerCase();
                        item.style.display = (!q || name.indexOf(q) !== -1) ? '' : 'none';
                    });
                });
            }

            // Upload input
            var uploadInput = _smfModal.querySelector('.smf-upload-input');
            if (uploadInput) {
                uploadInput.addEventListener('change', function () {
                    if (this.files && this.files[0]) handleSMFUpload(this.files[0]);
                    this.value = '';
                });
            }
        }

        _smfModal.style.display = '';
        document.body.classList.add('iw-modal-open');

        if (!_smfLoaded) loadSMFImages();
    }

    function closeSMFModal() {
        if (_smfModal) _smfModal.style.display = 'none';
        document.body.classList.remove('iw-modal-open');
        _smfActiveField = null;
    }

    // ── Fetch images from /admin/media/picker-images ────────────────────────
    function loadSMFImages() {
        var grid = _smfModal ? _smfModal.querySelector('.smf-grid') : null;
        if (!grid) return;

        var t = window.iwT || {};
        grid.innerHTML = '<p style="text-align:center;color:#6b7280;padding:2rem;">' + (t.loading || 'Loading…') + '</p>';

        fetch('/admin/media/picker-images')
            .then(function (r) { return r.json(); })
            .then(function (data) {
                _smfLoaded = true;
                var images = data.images || data || [];
                if (!images.length) {
                    grid.innerHTML = '<p style="text-align:center;color:#6b7280;padding:2rem;">' + (t.no_images || 'No images found.') + '</p>';
                    return;
                }

                var html = '<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(100px,1fr));gap:0.5rem;">';
                images.forEach(function (img) {
                    var url  = _escH(img.url || '');
                    var thumb = _escH(img.thumb_url || img.url || '');
                    var name = _escH(img.name || img.title || '');
                    html += '<div class="smf-item" data-url="' + url + '" data-name="' + name + '" ' +
                            'style="cursor:pointer;border:2px solid transparent;border-radius:6px;overflow:hidden;aspect-ratio:1;background:#f3f4f6;" ' +
                            'title="' + name + '">' +
                            '<img src="' + thumb + '" alt="' + name + '" loading="lazy" ' +
                            'style="width:100%;height:100%;object-fit:cover;">' +
                            '</div>';
                });
                html += '</div>';
                grid.innerHTML = html;

                // Click handler → select image
                grid.querySelectorAll('.smf-item').forEach(function (item) {
                    item.addEventListener('click', function () {
                        if (_smfActiveField) {
                            _smfActiveField.input.value = item.dataset.url;
                            _smfActiveField.refreshPreview();
                        }
                        closeSMFModal();
                    });
                });
            })
            .catch(function () {
                grid.innerHTML = '<p style="text-align:center;color:#dc2626;padding:2rem;">' + ((window.iwT||{}).load_failed || 'Failed to load images.') + '</p>';
            });
    }

    function _escH(str) {
        return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }

    // Auto-init on DOMContentLoaded
    document.addEventListener('DOMContentLoaded', function () {
        initSectionMediaFields();
    });
})();
