/**
 * WPFAQBlock – Drag & Drop + Add Group Modal
 * Steps 8 & 9
 *
 * Requires: admin-builder.js (loaded first via wp_enqueue_script dependency)
 * Uses native HTML5 drag-and-drop — no external library needed.
 *
 * @package WPFAQBlock
 * @since   2.0.0
 */
(function () {
    'use strict';

    var builder = window.wpfaqblockBuilder || {};
    var ajaxFn = builder.ajax || function () { };
    var noticeFn = builder.showNotice || function () { };

    document.addEventListener('DOMContentLoaded', function () {
        initDragDropFaqs();
        initDragDropGroups();
        initGroupModal();
        initGroupEditDelete();
    });

    // ══════════════════════════════════════════════════════════════
    // STEP 8 — Drag & Drop FAQs within a group
    // ══════════════════════════════════════════════════════════════
    function initDragDropFaqs() {
        document.querySelectorAll('.faqb-group__body').forEach(makeListSortable);
    }

    function makeListSortable(list) {
        var dragging = null;

        list.querySelectorAll('.faqb-item').forEach(function (item) {
            makeFaqDraggable(item, list);
        });

        list.addEventListener('dragover', function (e) {
            e.preventDefault();
            var target = e.target.closest('.faqb-item');
            if (target && target !== dragging) {
                var rect = target.getBoundingClientRect();
                var mid = rect.top + rect.height / 2;
                if (e.clientY < mid) {
                    list.insertBefore(dragging, target);
                } else {
                    list.insertBefore(dragging, target.nextSibling);
                }
            }
        });

        list.addEventListener('drop', function (e) {
            e.preventDefault();
            saveItemOrder(list);
        });

        // Store reference so newly added items can use it
        list._wpfaqDragInit = function (item) { makeFaqDraggable(item, list); };

        function makeFaqDraggable(item, container) {
            var handle = item.querySelector('.faqb-item__drag');
            if (!handle) return;

            item.setAttribute('draggable', 'true');

            item.addEventListener('dragstart', function (e) {
                dragging = item;
                item.style.opacity = '.4';
                e.dataTransfer.effectAllowed = 'move';
            });

            item.addEventListener('dragend', function () {
                dragging = null;
                item.style.opacity = '';
            });
        }
    }

    function saveItemOrder(list) {
        var ids = [];
        list.querySelectorAll('.faqb-item').forEach(function (item) {
            if (item.dataset.faqId) ids.push(item.dataset.faqId);
        });
        ajaxFn('wpfaqblock_save_faq_order', { order: ids }, function (res) {
            if (res && res.success) noticeFn('success', res.data.message);
        }, null);
    }

    // ══════════════════════════════════════════════════════════════
    // STEP 8 — Drag & Drop Groups
    // ══════════════════════════════════════════════════════════════
    function initDragDropGroups() {
        var container = document.getElementById('faqb-groups-container');
        if (!container) return;

        var dragging = null;

        container.querySelectorAll('.faqb-group').forEach(function (group) {
            makeGroupDraggable(group, container);
        });

        container.addEventListener('dragover', function (e) {
            e.preventDefault();
            var target = e.target.closest('.faqb-group');
            if (target && target !== dragging) {
                var rect = target.getBoundingClientRect();
                var mid = rect.top + rect.height / 2;
                if (e.clientY < mid) {
                    container.insertBefore(dragging, target);
                } else {
                    container.insertBefore(dragging, target.nextSibling);
                }
            }
        });

        container.addEventListener('drop', function (e) {
            e.preventDefault();
            saveGroupOrder(container);
        });

        function makeGroupDraggable(group) {
            var handle = group.querySelector('.faqb-group__drag-handle');
            if (!handle) return;

            group.setAttribute('draggable', 'true');

            group.addEventListener('dragstart', function (e) {
                dragging = group;
                group.style.opacity = '.4';
                e.dataTransfer.effectAllowed = 'move';
            });

            group.addEventListener('dragend', function () {
                dragging = null;
                group.style.opacity = '';
            });
        }
    }

    function saveGroupOrder(container) {
        var ids = [];
        container.querySelectorAll('.faqb-group').forEach(function (g) {
            if (g.dataset.groupId && g.dataset.groupId !== '0') ids.push(g.dataset.groupId);
        });
        ajaxFn('wpfaqblock_save_group_order', { order: ids }, null, null);
    }

    // ══════════════════════════════════════════════════════════════
    // STEP 9 — Add Group Modal
    // ══════════════════════════════════════════════════════════════
    function initGroupModal() {
        var modal = document.getElementById('faqb-group-modal');
        var overlay = document.getElementById('faqb-modal-overlay');
        var closeBtn = document.getElementById('faqb-modal-close');
        var cancelBtn = document.getElementById('faqb-modal-cancel');
        var createBtn = document.getElementById('faqb-modal-create');
        var nameInput = document.getElementById('faqb-modal-group-name');
        var modalTitle = document.getElementById('faqb-modal-title');
        var modalNotices = document.getElementById('faqb-modal-notices');

        if (!modal) return;

        // Open triggers
        ['faqb-btn-add-group', 'faqb-add-group-bar', 'faqb-empty-add-group'].forEach(function (id) {
            var btn = document.getElementById(id);
            if (btn) btn.addEventListener('click', function () { 
                if ( modalNotices ) modalNotices.style.display = 'none';
                openModal(); 
            });
        });

        function openModal(termId, currentName) {
            nameInput.value = currentName || '';
            nameInput.dataset.editTermId = termId || '';
            modalTitle.textContent = termId ? 'Rename Category' : 'Add New Category';
            createBtn.textContent = termId ? 'Save Changes' : 'Create Category';
            modal.style.display = 'flex';
            overlay.style.display = 'block';
            nameInput.focus();
        }

        function closeModal() { 
            modal.style.display = 'none'; 
            overlay.style.display = 'none';
            nameInput.value = ''; 
        }

        if (closeBtn) closeBtn.addEventListener('click', closeModal);
        if (cancelBtn) cancelBtn.addEventListener('click', closeModal);
        if (overlay) overlay.addEventListener('click', closeModal);

        if (createBtn) {
            createBtn.addEventListener('click', function () {
                var name = nameInput.value.trim();
                var termId = nameInput.dataset.editTermId || '';

                if (!name) { nameInput.focus(); return; }

                var action = termId ? 'wpfaqblock_update_group' : 'wpfaqblock_create_group';
                var payload = termId ? { term_id: termId, name: name } : { name: name };

                createBtn.disabled = true;
                if ( modalNotices ) modalNotices.style.display = 'none';

                ajaxFn(action, payload,
                    function (res) {
                        createBtn.disabled = false;
                        if (!res.success) { 
                            if ( modalNotices ) {
                                modalNotices.innerHTML = '<div class="faqb-notice faqb-notice--error">' + res.data.message + '</div>';
                                modalNotices.style.display = 'block';
                            } else {
                                noticeFn('error', res.data.message);
                            }
                            return; 
                        }
                        closeModal();
                        if (termId) {
                            // Update name in DOM
                            var grp = document.querySelector('.faqb-group[data-group-id="' + termId + '"]');
                            if (grp) {
                                var nameEl = grp.querySelector('.faqb-group__name');
                                if (nameEl) nameEl.textContent = res.data.name;
                                var editBtn = grp.querySelector('.faqb-group-edit-btn');
                                if (editBtn) editBtn.dataset.termName = res.data.name;
                            }
                            // Update name in all relevant selects
                            ['#faqb-edit-group', '#faqb-ai-group'].forEach(function(selector) {
                                var opt = document.querySelector( selector + ' option[value="' + termId + '"]' );
                                if ( opt ) opt.textContent = res.data.name;
                            });
                        } else {
                            // Append new group to container
                            appendNewGroup(res.data.term_id, res.data.name);
                        }
                        noticeFn('success', res.data.message);
                    },
                    function () { createBtn.disabled = false; noticeFn('error', 'Error.'); }
                );
            });
        }

        // Allow Enter key to submit
        if (nameInput) {
            nameInput.addEventListener('keydown', function (e) {
                if (e.key === 'Enter') { e.preventDefault(); createBtn.click(); }
            });
        }

        // Expose openModal for edit buttons
        window._wpfaqOpenGroupModal = openModal;
    }

    function appendNewGroup(termId, name) {
        var container = document.getElementById('faqb-groups-container');
        if (!container) return;

        // Hide empty state
        var empty = document.getElementById('faqb-empty-state');
        if (empty) empty.style.display = 'none';

        var div = document.createElement('div');
        div.className = 'faqb-group';
        div.dataset.groupId = termId;
        div.dataset.groupTerm = termId;
        div.setAttribute('draggable', 'true');
        div.innerHTML =
            '<div class="faqb-group__header" role="button" tabindex="0" aria-expanded="false">' +
            '<span class="faqb-group__drag-handle">⠿</span>' +
            '<span class="faqb-group__name">' + escHtml(name) + '</span>' +
            '<span class="faqb-group__badge">0</span>' +
            '<span class="faqb-group__actions">' +
            '<label class="faqb-toggle" style="margin-right:12px;vertical-align:middle;" title="Enable / disable this Category">' +
            '<input type="checkbox" class="faqb-group-status-toggle" data-group-id="' + termId + '" checked>' +
            '<span class="faqb-toggle__slider"></span>' +
            '</label>' +
            '<button type="button" class="faqb-btn faqb-btn--ghost faqb-btn--icon-only faqb-group-edit-btn" data-term-id="' + termId + '" data-term-name="' + escHtml(name) + '"><span class="dashicons dashicons-edit"></span></button>' +
            '<button type="button" class="faqb-btn faqb-btn--danger faqb-btn--icon-only faqb-group-delete-btn" data-term-id="' + termId + '"><span class="dashicons dashicons-trash"></span></button>' +
            '</span>' +
            '<span class="faqb-group__chevron dashicons dashicons-arrow-down-alt2"></span>' +
            '</div>' +
            '<div class="faqb-group__body">' +
            '<div class="faqb-empty-state"><span class="faqb-empty-state__text">No FAQs yet.</span></div>' +
            '<div class="faqb-group__add-row"><button type="button" class="faqb-btn faqb-btn--outline faqb-btn--sm faqb-add-faq-btn" data-group-id="' + termId + '"><span class="dashicons dashicons-plus-alt2" style="font-size:13px;width:13px;height:13px;"></span> Add FAQ</button></div>' +
            '</div>';

        container.insertBefore(div, document.getElementById('faqb-empty-state'));

        // Wire header toggle
        div.querySelector('.faqb-group__header').addEventListener('click', function (e) {
            if (e.target.closest('.faqb-group__actions')) return;
            div.classList.toggle('is-open');
        });

        // Wire edit/delete/toggle
        attachGroupEditDelete(div.querySelector('.faqb-group-edit-btn'));
        attachGroupDeleteBtn(div.querySelector('.faqb-group-delete-btn'));
        if (window.wpfaqblockBuilder && window.wpfaqblockBuilder.attachGroupToggleListener) {
            window.wpfaqblockBuilder.attachGroupToggleListener(div.querySelector('.faqb-group-status-toggle'));
        }

        // Wire add FAQ btn
        div.querySelector('.faqb-add-faq-btn').addEventListener('click', function () {
            var groupId = termId;
            var fieldPostId = document.getElementById('faqb-edit-post-id');
            var fieldQuestion = document.getElementById('faqb-edit-question');
            var fieldAnswer = document.getElementById('faqb-edit-answer');
            var fieldStatus = document.getElementById('faqb-edit-status');
            var fieldGroup = document.getElementById('faqb-edit-group');
            if (fieldPostId) fieldPostId.value = '';
            if (fieldQuestion) fieldQuestion.value = '';
            if (fieldAnswer) fieldAnswer.value = '';
            if (fieldStatus) fieldStatus.checked = true;
            if (fieldGroup) {
                for (var i = 0; i < fieldGroup.options.length; i++) {
                    if (fieldGroup.options[i].value === String(groupId)) { fieldGroup.selectedIndex = i; break; }
                }
            }
            // Add option if not present
            if (fieldGroup && !fieldGroup.querySelector('option[value="' + groupId + '"]')) {
                var opt = document.createElement('option');
                opt.value = groupId;
                opt.textContent = name;
                fieldGroup.appendChild(opt);
            }
            document.getElementById('faqb-panel-placeholder').style.display = 'none';
            document.getElementById('faqb-panel-form').style.display = 'flex';
            if (fieldQuestion) fieldQuestion.focus();
        });

        // Also add option to edit panel select and AI modal select
        ['faqb-edit-group', 'faqb-ai-group'].forEach(function(id) {
            var sel = document.getElementById(id);
            if (sel && !sel.querySelector('option[value="' + termId + '"]')) {
                var opt = document.createElement('option');
                opt.value = termId;
                opt.textContent = name;
                sel.appendChild(opt);
            }
        });
    }

    // ── Group Edit & Delete buttons ──────────────────────────────
    function initGroupEditDelete() {
        document.querySelectorAll('.faqb-group-edit-btn').forEach(attachGroupEditDelete);
        document.querySelectorAll('.faqb-group-delete-btn').forEach(attachGroupDeleteBtn);
    }

    function attachGroupEditDelete(btn) {
        if (!btn) return;
        btn.addEventListener('click', function (e) {
            e.stopPropagation();
            if (window._wpfaqOpenGroupModal) {
                window._wpfaqOpenGroupModal(btn.dataset.termId, btn.dataset.termName);
            }
        });
    }

    function attachGroupDeleteBtn(btn) {
        if (!btn) return;
        btn.addEventListener('click', function (e) {
            e.stopPropagation();
            if (!window.confirm('Are you sure you want to delete this Category and ALL FAQs inside? This action cannot be undone.')) return;
            var termId = btn.dataset.termId;
            ajaxFn('wpfaqblock_delete_group', { term_id: termId },
                function (res) {
                    if (!res.success) { noticeFn('error', res.data.message); return; }
                    var grp = document.querySelector('.faqb-group[data-group-id="' + termId + '"]');
                    if (grp) grp.remove();
                    // Remove from all relevant selects
                    ['#faqb-edit-group', '#faqb-ai-group'].forEach(function(selector) {
                        var opt = document.querySelector(selector + ' option[value="' + termId + '"]');
                        if (opt) opt.remove();
                    });
                    updateCategoryCountHeader();
                    noticeFn('success', res.data.message);
                },
                function () { noticeFn('error', 'Error.'); }
            );
        });
    }

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

    function updateCategoryCountHeader() {
        var header = document.getElementById('faqb-category-count-header');
        if (!header) return;
        var count = document.querySelectorAll('.faqb-group[data-group-id]:not([data-group-id="0"])').length;
        var text = count === 1 ? '1 Category' : count + ' Categories';
        header.textContent = text;
    }

})();
