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

document.addEventListener('DOMContentLoaded', () => {

    /**
     * -----------------------------------------------------------------------
     * 0. Counter Animation
     * -----------------------------------------------------------------------
     */
    function animateCounter(element, target) {
        if (!element || isNaN(target)) return;

        let current = 0;
        const duration = 1000;
        const startTime = Date.now();

        function updateCounter() {
            const elapsed = Date.now() - startTime;
            const progress = Math.min(elapsed / duration, 1);

            // Easing function for smooth animation
            current = Math.floor(target * easeOutQuad(progress));
            element.textContent = current;

            if (progress < 1) {
                requestAnimationFrame(updateCounter);
            } else {
                element.textContent = target;
            }
        }

        function easeOutQuad(t) {
            return 1 - (1 - t) * (1 - t);
        }

        updateCounter();
    }

    // Animate all summary cards with data-count attribute
    const summaryCards = document.querySelectorAll('.sifency-summary-card');
    summaryCards.forEach(card => {
        const valueElement = card.querySelector('.sifency-summary-value');
        if (valueElement) {
            const targetValue = parseInt(valueElement.textContent, 10);
            if (!isNaN(targetValue) && targetValue > 0) {
                // Start animation when card comes into view
                const observer = new IntersectionObserver((entries) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            animateCounter(valueElement, targetValue);
                            observer.unobserve(entry.target);
                        }
                    });
                }, { threshold: 0.5 });

                observer.observe(card);
            }
        }
    });

    /**
     * -----------------------------------------------------------------------
     * 1. Copy System Info
     * -----------------------------------------------------------------------
     */
    const copyBtn = document.querySelector('#sifency-copy-system-info');
    const infoTextarea = document.querySelector('#sifency-system-info-textarea');

    if (copyBtn && infoTextarea) {
        copyBtn.addEventListener('click', function (e) {
            e.preventDefault();

            const text = infoTextarea.value;

            // Clipboard API with fallback
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text).then(function () {
                    const original = copyBtn.textContent;
                    copyBtn.textContent = 'Copied!';
                    setTimeout(() => copyBtn.textContent = original, 2000);
                }).catch(function (err) {
                    console.error('Clipboard error:', err);
                    fallbackCopy(text);
                });
            } else {
                fallbackCopy(text);
            }

            function fallbackCopy(text) {
                infoTextarea.select();
                infoTextarea.setSelectionRange(0, 99999);
                document.execCommand('copy');

                const original = copyBtn.textContent;
                copyBtn.textContent = 'Copied!';
                setTimeout(() => copyBtn.textContent = original, 2000);
            }
        });
    }

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

        e.preventDefault();

        const action = btn.dataset.action;
        const enable = action === 'enable';

        document.querySelectorAll('.sifency-widget-toggle-checkbox').forEach(input => {
            if (!input.disabled) {
                input.checked = enable;
            }
        });
    });


    /**
     * -----------------------------------------------------------------------
     * 3. Fullwidth Toggle
     * -----------------------------------------------------------------------
     */
    const fullWidthBtn = document.querySelector('#sifency-toggle-fullwidth');

    if (fullWidthBtn) {
        fullWidthBtn.addEventListener('click', () => {
            document.body.classList.toggle('fullwidth-enabled');
        });
    }


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

    if (filterButtons.length > 0 && themeCards.length > 0) {

        filterButtons.forEach(button => {
            button.addEventListener('click', () => {

                // Activate clicked button
                filterButtons.forEach(b => b.classList.remove('active'));
                button.classList.add('active');

                const filter = button.dataset.filter;

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

            });
        });
    }

});


jQuery(document).ready(function ($) {

    var currentCategory = 'all';
    var currentFilter = 'all'; // all, free, pro

    function applySifencyFilters() {

        $('.sifency-widget-category-block').each(function () {
            var $section = $(this);
            var sectionId = $section.attr('id');

            var isCategoryMatch = (currentCategory === 'all' || currentCategory === sectionId);

            if (!isCategoryMatch) {
                $section.hide();
                return; // Skip processing cards if section is hidden
            }

            var visibleCards = 0;

            $section.find('.sifency-widget-card').each(function () {
                var $card = $(this);
                var cardType = $card.data('widget-type'); // free or pro

                var isTypeMatch = (currentFilter === 'all' || currentFilter === cardType);

                if (isTypeMatch) {
                    $card.show();
                    visibleCards++;
                } else {
                    $card.hide();
                }
            });
            if (visibleCards > 0) {
                $section.fadeIn(200);
            } else {
                $section.hide();
            }
        });
    }

    $('.sifency-tab-trigger').on('click', function (e) {
        e.preventDefault();
        $('.sifency-tab-trigger').removeClass('active');
        $(this).addClass('active');

        currentCategory = $(this).data('target');
        applySifencyFilters();
    });

    $('.sifency-filter-btn').on('click', function (e) {
        e.preventDefault();
        $('.sifency-filter-btn').removeClass('active');
        $(this).addClass('active');

        currentFilter = $(this).data('filter');
        applySifencyFilters();
    });
});