(function($) {
    'use strict';
    
    const IranDargahDashboard = {
        init: function() {
            this.bindEvents();
            this.initTheme();
        },
        
        bindEvents: function() {
            $(document).on('change', '.irandargah-toggle-input', this.handleToggle);
            $(document).on('click', '.irandargah-settings-toggle', this.toggleSettings);
            $(document).on('click', '.irandargah-theme-toggle', this.toggleTheme);
            $(document).on('click', '.irandargah-copy-btn', this.copyToClipboard);
            $(document).on('click', '.irandargah-cancel-btn', this.cancelSettings);
        },
        
        initTheme: function() {
            const savedTheme = localStorage.getItem('irandargah_theme') || 'light';
            this.setTheme(savedTheme);
        },
        
        toggleTheme: function(e) {
            e.preventDefault();
            const currentTheme = $('.irandargah-dashboard-wrap').attr('data-theme');
            const newTheme = currentTheme === 'light' ? 'dark' : 'light';
            IranDargahDashboard.setTheme(newTheme);
        },
        
        setTheme: function(theme) {
            $('.irandargah-dashboard-wrap').attr('data-theme', theme);
            localStorage.setItem('irandargah_theme', theme);
            
            if (typeof irandargahData !== 'undefined') {
                $.ajax({
                    url: irandargahData.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'irandargah_save_theme',
                        theme: theme,
                        nonce: irandargahData.nonce
                    }
                });
            }
        },
        
        handleToggle: function(e) {
            const $toggle = $(this);
            const gatewayId = $toggle.data('gateway-id');
            const enabled = $toggle.is(':checked');
            
            $toggle.prop('disabled', true);
            
            $.ajax({
                url: irandargahData.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'irandargah_toggle_gateway',
                    gateway_id: gatewayId,
                    enabled: enabled ? 'yes' : 'no',
                    nonce: irandargahData.nonce
                },
                success: function(response) {
                    if (response && response.success) {
                        IranDargahDashboard.updateGatewayStatus(gatewayId, enabled);
                        IranDargahDashboard.showNotice('success', response.data && response.data.message ? response.data.message : irandargahData.strings.saved);
                    } else {
                        $toggle.prop('checked', !enabled);
                        IranDargahDashboard.showNotice('error', irandargahData.strings.error);
                    }
                },
                error: function() {
                    $toggle.prop('checked', !enabled);
                    IranDargahDashboard.showNotice('error', irandargahData.strings.error);
                },
                complete: function() {
                    $toggle.prop('disabled', false);
                }
            });
        },
        
        updateGatewayStatus: function(gatewayId, enabled) {
            const $card = $(`.irandargah-gateway-card[data-gateway-id="${gatewayId}"]`);
            const $badge = $card.find('.irandargah-status-badge');
            
            if (enabled) {
                $badge.removeClass('irandargah-status-inactive').addClass('irandargah-status-active');
                $badge.text('فعال');
            } else {
                $badge.removeClass('irandargah-status-active').addClass('irandargah-status-inactive');
                $badge.text('غیرفعال');
            }
        },
        
        toggleSettings: function(e) {
            e.preventDefault();
            const $btn = $(this);
            const gatewayId = $btn.data('gateway-id');
            const $settings = $(`#settings-${gatewayId}`);
            
            if ($settings.is(':visible')) {
                $settings.slideUp(300);
                $btn.find('.btn-icon').text('⚙️');
            } else {
                $('.irandargah-gateway-settings').slideUp(300);
                $settings.slideDown(300);
                $('.irandargah-settings-toggle .btn-icon').text('⚙️');
                $btn.find('.btn-icon').text('▼');
            }
        },
        
        copyToClipboard: function(e) {
            e.preventDefault();
            const $btn = $(this);
            const text = $btn.data('copy');
            
            if (navigator.clipboard) {
                navigator.clipboard.writeText(text).then(function() {
                    const originalText = $btn.text();
                    $btn.text('✓ کپی شد');
                    setTimeout(function() {
                        $btn.text(originalText);
                    }, 2000);
                });
            } else {
                const $temp = $('<textarea>');
                $('body').append($temp);
                $temp.val(text).select();
                document.execCommand('copy');
                $temp.remove();
                
                const originalText = $btn.text();
                $btn.text('✓ کپی شد');
                setTimeout(function() {
                    $btn.text(originalText);
                }, 2000);
            }
        },
        
        cancelSettings: function(e) {
            e.preventDefault();
            const $form = $(this).closest('.irandargah-settings-form');
            const gatewayId = $form.data('gateway-id');
            $(`#settings-${gatewayId}`).slideUp(300);
            $('.irandargah-settings-toggle .btn-icon').text('⚙️');
        },
        
        showNotice: function(type, message) {
            const $notice = $(`
                <div class="irandargah-notice irandargah-notice-${type}">
                    <span class="irandargah-notice-icon">${type === 'success' ? '✓' : '✗'}</span>
                    <span class="irandargah-notice-message">${message}</span>
                </div>
            `);
            
            $('.irandargah-dashboard-wrap').prepend($notice);
            
            setTimeout(function() {
                $notice.fadeOut(300, function() {
                    $(this).remove();
                });
            }, 3000);
        }
    };
    
    $(document).ready(function() {
        IranDargahDashboard.init();
    });
    
})(jQuery);

