/**
 * GT BOGO ENGINE — PREMIUM ADMIN JS
 * Commercial-grade UI interactions + Autosave + Import/Export
 */

document.addEventListener("DOMContentLoaded", function () {

    /* ============================================================
       Utility: Quick Selectors
       ============================================================ */
    const $ = (sel, parent = document) => parent.querySelector(sel);
    const $$ = (sel, parent = document) => [...parent.querySelectorAll(sel)];

    /* ============================================================
       Sidebar Active Highlight
       ============================================================ */
    const sidebarLinks = $$(".gt-bogo-sidebar a");
    sidebarLinks.forEach(link => {
        if (link.href === window.location.href) {
            link.classList.add("active");
        }
    });


    /* ============================================================
       Tab Switch Animation
       ============================================================ */
    const tabLinks = $$(".gt-bogo-tab");

    tabLinks.forEach(tab => {
        tab.addEventListener("click", function (e) {
            // Soft animation
            const wrapper = $(".gt-bogo-engine-wrap");
            wrapper.style.opacity = "0.3";

            setTimeout(() => {
                window.location.href = tab.href;
            }, 120);
        });
    });


    /* ============================================================
       PRO Lock Modal
       ============================================================ */
    const proLocks = $$(".gt-bogo-pro-locked");

    proLocks.forEach(lock => {
        lock.addEventListener("click", function (e) {
            e.preventDefault();
            showProModal();
        });
    });

    function showProModal() {
        let modal = $("#gt-bogo-pro-modal");

        if (!modal) {
            // Inject modal HTML
            document.body.insertAdjacentHTML("beforeend", `
                <div id="gt-bogo-pro-modal" class="gt-bogo-pro-overlay">
                    <div class="gt-bogo-pro-window">
                        <h2>Unlock PRO Features</h2>
                        <p>Advanced rule logic, category scopes, unlimited rules, premium support + more.</p>
                        <a href="https://graphictshirts.shop/bogo" target="_blank" class="gt-bogo-pro-btn">
                            Upgrade to GT BOGO PRO
                        </a>
                        <button class="gt-bogo-pro-close">Close</button>
                    </div>
                </div>
            `);
            modal = $("#gt-bogo-pro-modal");
        }

        modal.style.display = "flex";
        $("#gt-bogo-pro-modal .gt-bogo-pro-close").onclick = () => modal.style.display = "none";
        modal.onclick = (e) => {
            if (e.target === modal) modal.style.display = "none";
        };
    }


    /* ============================================================
       Autosave Logic (Settings, Free Rule, PRO Rules)
       ============================================================ */

    // detect forms
    const autosaveForms = $$("form.gt-bogo-autosave");

    autosaveForms.forEach(form => {

        form.addEventListener("change", () => autosaveForm(form));
        form.addEventListener("keyup", () => autosaveForm(form));

        let saveTimeout = null;

        function autosaveForm(form) {
            clearTimeout(saveTimeout);

            saveTimeout = setTimeout(() => {
                const formData = new FormData(form);

                // Add context (settings, free_rule, pro_rules)
                let context = form.dataset.context;
                formData.append("gt_bogo_engine_context", context);

                // Ajax route
                formData.append("action", "gt_bogo_engine_autosave");
                formData.append("gt_bogo_engine_nonce", GT_BOGO_Engine.nonce);

                fetch(ajaxurl, {
                    method: "POST",
                    body: formData
                })
                    .then(r => r.json())
                    .then(res => {
                        showSaveNotice(res.success
                            ? res.data.message
                            : "Save failed");
                    });

            }, 600);
        }
    });


    /* ============================================================
       Save Notice
       ============================================================ */
    function showSaveNotice(msg) {
        let notice = $("#gt-bogo-autosave-notice");

        if (!notice) {
            document.body.insertAdjacentHTML("beforeend", `
                <div id="gt-bogo-autosave-notice" class="gt-bogo-toast"></div>
            `);
            notice = $("#gt-bogo-autosave-notice");
        }

        notice.innerText = msg;
        notice.classList.add("show");

        setTimeout(() => notice.classList.remove("show"), 2600);
    }


    /* ============================================================
       PRO Rule Sorting — Drag & Drop
       ============================================================ */
    const draggables = $$(".gt-bogo-rule-row");
    let dragSrc = null;

    draggables.forEach(row => {
        row.setAttribute("draggable", "true");

        row.addEventListener("dragstart", (e) => {
            dragSrc = row;
            row.style.opacity = "0.4";
        });

        row.addEventListener("dragend", (e) => {
            row.style.opacity = "1";
        });

        row.addEventListener("dragover", (e) => {
            e.preventDefault();
        });

        row.addEventListener("drop", (e) => {
            e.preventDefault();
            if (dragSrc !== row) {
                row.parentNode.insertBefore(dragSrc, row);
            }
        });
    });


    /* ============================================================
       Collapsible Rule Rows
       ============================================================ */
    const collapsers = $$(".gt-bogo-collapse-toggle");

    collapsers.forEach(btn => {
        btn.addEventListener("click", function () {
            let parent = btn.closest(".gt-bogo-rule-row");
            parent.classList.toggle("collapsed");
        });
    });


    /* ============================================================
       Import Rules (JSON)
       ============================================================ */
    const importBtn = $("#gt-bogo-import-btn");
    const importInput = $("#gt-bogo-import-file");

    if (importBtn && importInput) {
        importBtn.addEventListener("click", () => importInput.click());

        importInput.addEventListener("change", function () {
            const file = this.files[0];
            if (!file) return;

            const reader = new FileReader();

            reader.onload = function (e) {
                try {
                    const json = JSON.parse(e.target.result);
                    $("#gt-bogo-import-textarea").value = JSON.stringify(json, null, 2);
                    showSaveNotice("Rules loaded — click Import to apply");
                } catch {
                    alert("Invalid JSON file");
                }
            };

            reader.readAsText(file);
        });
    }


    /* ============================================================
       Export Rules
       ============================================================ */
    const exportBtn = $("#gt-bogo-export-btn");

    if (exportBtn) {
        exportBtn.addEventListener("click", function () {
            fetch(GT_BOGO_Engine.export_url)
                .then(r => r.json())
                .then(data => {
                    const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
                    const url = URL.createObjectURL(blob);

                    const a = document.createElement("a");
                    a.href = url;
                    a.download = "gt-bogo-engine-rules.json";
                    a.click();

                    showSaveNotice("Rules exported successfully");
                });
        });
    }
});

// Initialize Select2 for product/category selection
jQuery(document).ready(function($) {
    if (typeof $.fn.select2 !== 'undefined') {
        // Product selector with AJAX search
        $('.gtbogo-product-selector').select2({
            ajax: {
                url: ajaxurl,
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        action: 'gtbogo_get_products',
                        nonce: gtbogoAjax.nonce,
                        search: params.term
                    };
                },
                processResults: function(response) {
                    if (response.success) {
                        return { results: response.data };
                    }
                    return { results: [] };
                }
            },
            placeholder: 'Type to search products...',
            minimumInputLength: 2,
            multiple: true,
            width: '100%'
        });
        
        // Category selector with AJAX
        $('.gtbogo-category-selector').select2({
            ajax: {
                url: ajaxurl,
                dataType: 'json',
                data: function(params) {
                    return {
                        action: 'gtbogo_get_categories',
                        nonce: gtbogoAjax.nonce
                    };
                },
                processResults: function(response) {
                    if (response.success) {
                        return { results: response.data };
                    }
                    return { results: [] };
                }
            },
            placeholder: 'Select categories...',
            multiple: true,
            width: '100%'
        });
    }
});
