/**
 * Sifency Admin Script
 *
 * - Clipboard copy using navigator.clipboard
 * - Widget enable/disable toggle
 * - Dashboard filter system
 * - Fullwidth switcher
 * - Tooltips & Accordions
 *
 * @package Sifency
 * @since 1.0.4
 */

(function ($) {
    'use strict';

    const SifencyAdmin = {

        /**
         * Central Initialization
         */
        init: function () {
            this.initCounter();
            this.initClipboard();
            this.initWidgetToggles();
            this.initFullwidthToggle();
            this.initDashboardFilters();
            this.initWidgetFilters();
            this.initGridFilters();
            this.initAccordions();
            this.initTooltips();
        },

        /**
         * Global Utilities
         */
        Utils: {
            debounce: function (func, delay) {
                let timeoutId;
                return function (...args) {
                    clearTimeout(timeoutId);
                    timeoutId = setTimeout(() => func.apply(this, args), delay);
                };
            },
            easeOutQuad: function (t) {
                return t * (2 - t);
            }
        },

        /**
         * 0. Counter Animation
         */
        initCounter: function () {
            const cards = document.querySelectorAll('.sifency-summary-card');
            if (!cards.length) return;

            const observer = new IntersectionObserver((entries, obs) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const valEl = entry.target.querySelector('.sifency-summary-value');
                        if (valEl) {
                            const target = parseInt(valEl.textContent, 10);
                            if (!isNaN(target) && target > 0) {
                                this.animateCounter(valEl, target);
                            }
                        }
                        obs.unobserve(entry.target);
                    }
                });
            }, { threshold: 0.5 });

            cards.forEach(c => observer.observe(c));
        },

        animateCounter: function (el, target) {
            let start = null;
            const duration = 1000;

            const step = (timestamp) => {
                if (!start) start = timestamp;
                const progress = Math.min((timestamp - start) / duration, 1);

                el.textContent = Math.floor(target * this.Utils.easeOutQuad(progress));

                if (progress < 1) {
                    window.requestAnimationFrame(step);
                } else {
                    el.textContent = target;
                }
            };
            window.requestAnimationFrame(step);
        },

        /**
         * 1. Copy System Info
         */
        initClipboard: function () {
            const btn = document.querySelector('#sifency-copy-system-info');
            const textarea = document.querySelector('#sifency-system-info-textarea');

            if (!btn || !textarea) return;

            const fallbackCopy = (text) => {
                textarea.select();
                textarea.setSelectionRange(0, 99999);
                try {
                    document.execCommand('copy');
                } catch (err) {
                    console.error('Clipboard fallback failed', err);
                }
                this.showCopiedState(btn);
            };

            btn.addEventListener('click', (e) => {
                e.preventDefault();
                const text = textarea.value;

                if (navigator.clipboard && window.isSecureContext) {
                    navigator.clipboard.writeText(text)
                        .then(() => this.showCopiedState(btn))
                        .catch(() => fallbackCopy(text));
                } else {
                    fallbackCopy(text);
                }
            });
        },

        showCopiedState: function (btn) {
            const original = btn.dataset.originalText || btn.textContent;
            btn.dataset.originalText = original; // Store original state
            btn.textContent = 'Copied!';
            setTimeout(() => btn.textContent = original, 2000);
        },

        /**
         * 2. Toggle All Widgets (Enable / Disable)
         */
        initWidgetToggles: function () {
            document.body.addEventListener('click', (e) => {
                const btn = e.target.closest('.sifency-toggle-all-btn');
                if (!btn) return;

                e.preventDefault();
                const enable = btn.dataset.action === 'enable';

                document.querySelectorAll('.sifency-widget-toggle-checkbox:not(:disabled)')
                    .forEach(input => input.checked = enable);
            });
        },

        /**
         * 3. Fullwidth Toggle
         */
        initFullwidthToggle: function () {
            const btn = document.querySelector('#sifency-toggle-fullwidth');
            if (btn) {
                btn.addEventListener('click', () => document.body.classList.toggle('fullwidth-enabled'));
            }
        },

        /**
         * 4. Dashboard Filter System (Vanilla JS)
         */
        initDashboardFilters: function () {
            const filterButtons = document.querySelectorAll('.sifency-dashboard-nav .sifency-nav-item');
            const themeCards = document.querySelectorAll('.sifency-theme-grid .sifency-theme-card');

            if (!filterButtons.length || !themeCards.length) return;

            filterButtons.forEach(button => {
                button.addEventListener('click', () => {
                    filterButtons.forEach(b => b.classList.remove('active'));
                    button.classList.add('active');

                    const filter = button.dataset.filter;
                    themeCards.forEach(card => {
                        const isHidden = filter !== 'all' && card.dataset.category !== filter;
                        card.classList.toggle('sifency-card-hidden', isHidden);
                    });
                });
            });
        },

        /**
         * 5. Widget Settings Filters (jQuery)
         */
        initWidgetFilters: function () {
            let currentCategory = 'all';
            let currentFilter = 'all';

            const applyFilters = () => {
                $('.sifency-widget-category-block').each(function () {
                    const $section = $(this);
                    if (currentCategory !== 'all' && currentCategory !== $section.attr('id')) {
                        $section.hide();
                        return;
                    }

                    let visibleCards = 0;
                    $section.find('.sifency-widget-card').each(function () {
                        const $card = $(this);
                        if (currentFilter === 'all' || currentFilter === $card.data('widget-type')) {
                            $card.show();
                            visibleCards++;
                        } else {
                            $card.hide();
                        }
                    });

                    visibleCards > 0 ? $section.fadeIn(200) : $section.hide();
                });
            };

            $('.sifency-tab-trigger').on('click', function (e) {
                e.preventDefault();
                $(this).addClass('active').siblings('.sifency-tab-trigger').removeClass('active');
                currentCategory = $(this).data('target');
                applyFilters();
            });

            $('.sifency-filter-btn').on('click', function (e) {
                e.preventDefault();
                $(this).addClass('active').siblings('.sifency-filter-btn').removeClass('active');
                currentFilter = $(this).data('filter');
                applyFilters();
            });
        },

        /**
         * 6. Admin Grid & Search Filters (jQuery)
         */
        initGridFilters: function () {
            const filterGrid = () => {
                const type = $('.sifency-type-btn.active').data('type') || 'all';
                const cat = $('.sifency-nav-item.active').data('cat') || 'all';
                const search = ($('#sifency-admin-search').val() || '').toLowerCase();

                $('.sifency-theme-card').each(function () {
                    const $el = $(this);
                    const elType = $el.data('type');
                    const elCat = $el.data('cat');
                    const elTitle = String($el.data('title')).toLowerCase();

                    const show = (type === 'all' || elType === type) &&
                        (cat === 'all' || elCat === cat) &&
                        (!search || elTitle.includes(search));

                    show ? $el.fadeIn(200) : $el.hide();
                });
            };

            $('.sifency-type-btn, .sifency-nav-item').not('.sifency-dashboard-nav .sifency-nav-item').on('click', function () {
                $(this).addClass('active').siblings().removeClass('active');
                filterGrid();
            });

            // Added debounce to search so typing doesn't choke browser memory
            $('#sifency-admin-search').on('input keyup', this.Utils.debounce(filterGrid, 250));
        },

        /**
         * 8. Nav Accordions (Vanilla JS)
         */
        initAccordions: function () {
            const accordions = document.querySelectorAll('.sifency-nav-accordion');

            accordions.forEach(acc => {
                const summary = acc.querySelector('summary');
                const content = acc.querySelector('.sifency-accordion-content');

                if (!summary || !content) return;

                if (acc.hasAttribute('open')) {
                    content.style.maxHeight = content.scrollHeight + 'px';
                }

                summary.addEventListener('click', (e) => {
                    e.preventDefault();
                    const isOpen = acc.hasAttribute('open');

                    // Close all other accordions safely
                    accordions.forEach(other => {
                        if (other !== acc) {
                            other.removeAttribute('open');
                            const otherContent = other.querySelector('.sifency-accordion-content');
                            if (otherContent) otherContent.style.maxHeight = null;
                        }
                    });

                    // Toggle current
                    if (!isOpen) {
                        acc.setAttribute('open', '');
                        content.style.maxHeight = content.scrollHeight + 'px';
                    } else {
                        acc.removeAttribute('open');
                        content.style.maxHeight = null;
                    }
                });
            });
        },

        /**
         * 9. Tooltip Generator (Vanilla JS)
         */
        initTooltips: function () {
            const triggers = document.querySelectorAll('[data-tooltip]');
            if (!triggers.length) return;

            let tooltipEl = document.createElement('div');
            tooltipEl.className = 'sifency-tooltip-element';
            document.body.appendChild(tooltipEl);

            const showTooltip = (e) => {
                const trigger = e.currentTarget;
                const text = trigger.getAttribute('data-tooltip');

                if (!text) return;

                tooltipEl.textContent = text;
                const rect = trigger.getBoundingClientRect();

                const scrollY = window.scrollY || window.pageYOffset;
                const scrollX = window.scrollX || window.pageXOffset;

                const top = rect.top + scrollY + (rect.height / 2) - (tooltipEl.offsetHeight / 2);
                const left = rect.right + scrollX + 10;

                tooltipEl.style.top = `${top}px`;
                tooltipEl.style.left = `${left}px`;

                requestAnimationFrame(() => tooltipEl.classList.add('is-visible'));
            };

            const hideTooltip = () => tooltipEl.classList.remove('is-visible');

            triggers.forEach(trigger => {
                trigger.addEventListener('mouseenter', showTooltip);
                trigger.addEventListener('mouseleave', hideTooltip);
                trigger.addEventListener('mousedown', hideTooltip);
            });
        }
    };

    // Initialize all functionality safely once DOM is fully parsed
    $(document).ready(function () {
        SifencyAdmin.init();
    });

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

        const notice = document.getElementById("sifency-template-notice");
        const closeBtn = document.querySelector(".sifency-notice-close");

        if (!notice) return;

        if (localStorage.getItem("sifency_notice_closed")) {
            notice.style.display = "none";
        }

        if (closeBtn) {
            closeBtn.addEventListener("click", function () {
                notice.style.display = "none";
                localStorage.setItem("sifency_notice_closed", "true");
            });
        }

    });
    document.addEventListener("DOMContentLoaded", function () {
        const el = document.querySelector(".fade-in");
        if (!el) {
            return;
        }
        setTimeout(() => {
            el.classList.add("show");
        }, 2000);
    });
    // ------------------------------------------------------------------
    // Utility: get all toggleable checkboxes in a scope.
    // scope = document | HTMLElement
    // When is_pro_environment is false, pro-widget checkboxes are skipped
    // (they are disabled, so the browser won't submit them, but we also
    // stop JS from interacting with them).
    // ------------------------------------------------------------------
    function getToggleableCheckboxes(scope) {
        return Array.from(
            scope.querySelectorAll('.sifency-widget-toggle-checkbox:not([disabled])')
        );
    }

    // ------------------------------------------------------------------
    // Global Enable All / Disable All
    // ------------------------------------------------------------------
    document.querySelectorAll('.sifency-toggle-all-btn[data-scope="global"]').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const action = this.dataset.action;
            const checkboxes = getToggleableCheckboxes(document);
            checkboxes.forEach(function (cb) {
                cb.checked = ('enable' === action);
            });
        });
    });

    // ------------------------------------------------------------------
    // Per-category Enable All / Disable All
    // ------------------------------------------------------------------
    document.querySelectorAll('.sifency-category-toggle-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const action = this.dataset.action;
            const categoryId = this.dataset.category;
            const block = document.getElementById(categoryId);

            if (!block) {
                return;
            }

            // Only touch non-disabled checkboxes so locked pro widgets are safe.
            const checkboxes = getToggleableCheckboxes(block);
            checkboxes.forEach(function (cb) {
                cb.checked = ('enable' === action);
            });
        });
    });

    // ------------------------------------------------------------------
    // Category nav tab switching (filter visible categories)
    // ------------------------------------------------------------------
    const tabTriggers = document.querySelectorAll('.sifency-tab-trigger');
    const catBlocks = document.querySelectorAll('.sifency-widget-category-block');

    tabTriggers.forEach(function (trigger) {
        trigger.addEventListener('click', function () {
            tabTriggers.forEach(function (t) { t.classList.remove('active'); });
            this.classList.add('active');

            const target = this.dataset.target;

            catBlocks.forEach(function (block) {
                if ('all' === target || block.id === target) {
                    block.style.display = '';
                } else {
                    block.style.display = 'none';
                }
            });
        });
    });

})(jQuery);