/**
 * Mahamitim Theme Updater Admin JavaScript - Modern Version
 */

jQuery(document).ready(function($) {
    'use strict';

    // Global variables
    let isLoading = false;

    // Initialize
    init();

    function init() {
        bindEvents();
        loadVersionsIfReady();
        updateLastUpdateTime();
        updateConnectionStatus();
        updateStats();
    }

    /**
     * Bind all event handlers
     */
    function bindEvents() {
        // Settings form
        $('#mahamitim-settings-form').on('submit', handleSaveSettings);

        // Header actions
        $('#refresh-connection').on('click', handleTestConnection);

        // Quick actions
        $('#quick-update-btn').on('click', handleQuickUpdate);

        // Version management
        $('#refresh-versions').on('click', handleRefreshVersions);
        $('#update-theme').on('click', handleUpdateTheme);

        // Theme version selection
        $('#theme_version').on('change', function() {
            $('#update-theme').prop('disabled', false);
        });

        // Toast close handlers
        $(document).on('click', '.toast-close', function() {
            $(this).closest('.toast').fadeOut(300, function() {
                $(this).remove();
            });
        });

        // Modal handlers
        $('#close-modal, #modal-close-btn').on('click', hideModal);

        // Prevent modal close during update
        $('#update-modal').on('click', function(e) {
            if (e.target === this && !isLoading) {
                hideModal();
            }
        });
    }

    /**
     * Update connection status badge
     */
    function updateConnectionStatus() {
        const badge = $('#connection-badge');
        const text = $('#connection-text');
        const apiStatus = $('#api-status');

        // Set checking state
        badge.removeClass('bg-green-50 text-green-800 bg-red-50 text-red-800')
             .addClass('bg-yellow-50 text-yellow-800');
        badge.find('.mr-2').removeClass('bg-green-500 bg-red-500')
             .addClass('bg-yellow-500 animate-pulse');

        text.text(mahamitimUpdater.strings.connectionTest || 'در حال تست اتصال...');
        if (apiStatus.length) {
            apiStatus.text('در حال بررسی...');
        }

        // Test connection
        handleTestConnection(false);
    }

    /**
     * Handle connection test
     */
    function handleTestConnection(showNotification = true) {
        if (isLoading) return false;

        setLoading(true);

        const data = {
            action: 'mahamitim_test_connection',
            nonce: mahamitimUpdater.nonce
        };

        $.post(mahamitimUpdater.ajaxUrl, data)
            .done(function(response) {
                const badge = $('#connection-badge');
                const text = $('#connection-text');
                const apiStatus = $('#api-status');

                if (response.success) {
                    // Success state
                    badge.removeClass('bg-yellow-50 text-yellow-800 bg-red-50 text-red-800')
                         .addClass('bg-green-50 text-green-800');
                    badge.find('.mr-2').removeClass('bg-yellow-500 bg-red-500 animate-pulse')
                         .addClass('bg-green-500');

                    text.text(mahamitimUpdater.strings.connectionSuccess || 'متصل');
                    if (apiStatus.length) {
                        apiStatus.text('متصل');
                    }

                    if (showNotification) {
                        showToast(mahamitimUpdater.strings.connectionSuccess || 'اتصال برقرار شد', 'success');
                    }
                } else {
                    // Check for support expired
                    if (response.data && (response.data.support_expired || response.data.message === 'support_expired')) {
                        // Support expired state
                        badge.removeClass('bg-yellow-50 text-yellow-800 bg-green-50 text-green-800 bg-red-50 text-red-800')
                             .addClass('bg-amber-50 text-amber-800');
                        badge.find('.mr-2').removeClass('bg-yellow-500 bg-green-500 bg-red-500 animate-pulse')
                             .addClass('bg-amber-500');

                        text.text('پشتیبانی منقضی');
                        if (apiStatus.length) {
                            apiStatus.text('منقضی');
                        }

                        if (showNotification) {
                            handleSupportExpired(response.data);
                        }
                    } else {
                        // Error state
                        badge.removeClass('bg-yellow-50 text-yellow-800 bg-green-50 text-green-800')
                             .addClass('bg-red-50 text-red-800');
                        badge.find('.mr-2').removeClass('bg-yellow-500 bg-green-500 animate-pulse')
                             .addClass('bg-red-500');

                        text.text(mahamitimUpdater.strings.connectionFailed || 'قطع');
                        if (apiStatus.length) {
                            apiStatus.text('قطع');
                        }

                        if (showNotification) {
                            showToast(response.data?.message || mahamitimUpdater.strings.connectionFailed || 'اتصال برقرار نشد', 'error');
                        }
                    }
                }
            })
            .fail(function(jqXHR) {
                const badge = $('#connection-badge');
                const text = $('#connection-text');
                const apiStatus = $('#api-status');

                // Error state
                badge.removeClass('bg-yellow-50 text-yellow-800 bg-green-50 text-green-800')
                     .addClass('bg-red-50 text-red-800');
                badge.find('.mr-2').removeClass('bg-yellow-500 bg-green-500 animate-pulse')
                     .addClass('bg-red-500');

                text.text(mahamitimUpdater.strings.connectionFailed || 'خطا');
                if (apiStatus.length) {
                    apiStatus.text('خطا');
                }

                if (showNotification) {
                    showToast(getErrorMessage(jqXHR), 'error');
                }
            })
            .always(function() {
                setLoading(false);
            });

        return false;
    }

    /**
     * Handle quick update
     */
    function handleQuickUpdate() {
        if (isLoading) return;

        if (!confirm(mahamitimUpdater.strings.confirmUpdate || 'آیا مطمئن هستید؟')) {
            return;
        }

        setLoading(true);
        showModal();

        const data = {
            action: 'mahamitim_update_theme',
            nonce: mahamitimUpdater.nonce,
            version: '' // Latest version
        };

        // Simulate progress steps for quick update
        setTimeout(() => addModalStep('اتصال به سرور API...', 'info', 20), 500);
        setTimeout(() => addModalStep('درخواست دانلود آخرین نسخه...', 'info', 40), 1000);
        setTimeout(() => addModalStep('دانلود فایل ZIP...', 'info', 60), 1500);

        $.post(mahamitimUpdater.ajaxUrl, data)
            .done(function(response) {
                if (response.success) {
                    addModalStep('دانلود با موفقیت تکمیل شد', 'success', 80);
                    setTimeout(() => addModalStep('نصب و پیکربندی قالب...', 'success', 100), 500);

                    showToast(response.data.message || mahamitimUpdater.strings.success, 'success');
                    saveLastUpdateToDatabase(response.data);
                    updateLastUpdateTime();
                    updateStats();
                    completeModal(true);
                } else {
                    // Check for support expired scenario
                    if (response.data && (response.data.support_expired || response.data.message === 'support_expired')) {
                        handleSupportExpired(response.data);
                    } else {
                        addModalStep(response.data.message || 'خطا در بروزرسانی', 'error');
                        showToast(response.data.message || mahamitimUpdater.strings.error, 'error');
                        completeModal(false);
                    }
                }
            })
            .fail(function(jqXHR) {
                addModalStep('خطا در ارتباط با سرور', 'error');
                showToast(getErrorMessage(jqXHR), 'error');
                completeModal(false);
            })
            .always(function() {
                setLoading(false);
            });
    }

    /**
     * Handle theme update
     */
    function handleUpdateTheme() {
        if (isLoading) return;

        const version = $('#theme_version').val();

        if (!confirm(mahamitimUpdater.strings.confirmUpdate || 'آیا مطمئن هستید؟')) {
            return;
        }

        setLoading(true);
        showModal();

        const data = {
            action: 'mahamitim_update_theme',
            nonce: mahamitimUpdater.nonce,
            version: version
        };

        // Simulate progress steps for specific version
        setTimeout(() => addModalStep('اتصال به سرور API...', 'info', 20), 500);
        setTimeout(() => addModalStep(`درخواست دانلود نسخه ${version}...`, 'info', 40), 1000);
        setTimeout(() => addModalStep('دانلود فایل ZIP...', 'info', 60), 1500);

        $.post(mahamitimUpdater.ajaxUrl, data)
            .done(function(response) {
                if (response.success) {
                    addModalStep('دانلود با موفقیت تکمیل شد', 'success', 80);
                    setTimeout(() => addModalStep('نصب و پیکربندی قالب...', 'success', 100), 500);

                    showToast(response.data.message || mahamitimUpdater.strings.success, 'success');
                    saveLastUpdateToDatabase(response.data);
                    updateLastUpdateTime();
                    updateStats();
                    completeModal(true);
                } else {
                    // Check for support expired scenario
                    if (response.data && (response.data.support_expired || response.data.message === 'support_expired')) {
                        handleSupportExpired(response.data);
                    } else {
                        addModalStep(response.data.message || 'خطا در بروزرسانی', 'error');
                        showToast(response.data.message || mahamitimUpdater.strings.error, 'error');
                        completeModal(false);
                    }
                }
            })
            .fail(function(jqXHR) {
                addModalStep('خطا در ارتباط با سرور', 'error');
                showToast(getErrorMessage(jqXHR), 'error');
                completeModal(false);
            })
            .always(function() {
                setLoading(false);
            });
    }

    /**
     * Handle version refresh
     */
    function handleRefreshVersions() {
        if (isLoading) return;

        setLoading(true);
        const $button = $('#refresh-versions');
        const $select = $('#theme_version');

        $button.prop('disabled', true);
        $select.html('<option value="">در حال بارگذاری...</option>');

        const data = {
            action: 'mahamitim_get_versions',
            nonce: mahamitimUpdater.nonce
        };

        $.post(mahamitimUpdater.ajaxUrl, data)
            .done(function(response) {
                if (response.success && response.data) {
                    // Handle direct array response from Django API
                    const versions = Array.isArray(response.data) ? response.data : (response.data.versions || []);

                    $select.empty();
                    $select.append('<option value="">انتخاب نسخه</option>');

                    versions.forEach(function(version) {
                        // Use last_modified date from Django API response
                        const displayDate = version.last_modified ? new Date(version.last_modified).toLocaleDateString('fa-IR') : '';
                        $select.append('<option value="' + version.version + '">' + version.version + (displayDate ? ' (' + displayDate + ')' : '') + '</option>');
                    });

                    showToast('لیست نسخه‌ها بروزرسانی شد', 'success');
                } else {
                    // Check for support expired
                    if (response.data && (response.data.support_expired || response.data.message === 'support_expired')) {
                        handleSupportExpired(response.data);
                        $select.html('<option value="">پشتیبانی منقضی شده</option>');
                    } else {
                        showToast(response.data?.message || 'خطا در دریافت نسخه‌ها', 'error');
                        $select.html('<option value="">خطا در بارگذاری</option>');
                    }
                }
            })
            .fail(function(jqXHR) {
                showToast(getErrorMessage(jqXHR), 'error');
                $select.html('<option value="">خطا در بارگذاری</option>');
            })
            .always(function() {
                setLoading(false);
                $button.prop('disabled', false);
            });
    }

    /**
     * Load versions if ready
     */
    function loadVersionsIfReady() {
        // Auto-load versions on page load after connection test
        setTimeout(function() {
            // Only load if connection test is complete
            if (!isLoading) {
                handleRefreshVersions();
            } else {
                // Retry after another second if still loading
                setTimeout(function() {
                    if (!isLoading) {
                        handleRefreshVersions();
                    }
                }, 1000);
            }
        }, 2000);
    }

    /**
     * Handle support expired scenario
     */
    function handleSupportExpired(data) {
        // Force close any open modals immediately
        $('#update-modal').addClass('hidden');

        // Reset loading state
        setLoading(false);

        // Hide any existing modal
        hideModal();

        // Show support expired modal
        showSupportExpiredModal(data);

        // Update UI to reflect expired state
        updateConnectionStatus();
    }


    /**
     * Show support expired modal
     */
    function showSupportExpiredModal(data) {
        console.log('Showing support expired modal:', data);

        const message = data.message || 'دوره پشتیبانی شما منقضی شده است';
        const renewalUrl = data.renewal_url || '#';
        const expiryDate = data.expiry_date || '';

        // Remove any existing support expired modal
        $('#support-expired-modal').remove();

        // Create support expired modal using classes instead of inline styles for better compatibility
        const $modal = $('<div>')
            .attr('id', 'support-expired-modal')
            .attr('style', 'position: fixed !important; top: 0 !important; left: 0 !important; width: 100vw !important; height: 100vh !important; background-color: rgba(0, 0, 0, 0.9) !important; z-index: 999999 !important; display: flex !important; align-items: center !important; justify-content: center !important; padding: 20px !important; visibility: visible !important; opacity: 1 !important;');

        const $modalContent = $(`
            <div style="background: white; border-radius: 8px; padding: 32px; max-width: 500px; width: 100%; text-align: center; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);">
                <!-- Big Error Icon -->
                <div style="width: 80px; height: 80px; margin: 0 auto 24px; background-color: #fee2e2; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                    <svg style="width: 40px; height: 40px; color: #dc2626;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"/>
                    </svg>
                </div>

                <!-- Content -->
                <h3 style="font-size: 24px; font-weight: bold; color: #dc2626; margin-bottom: 16px;">پشتیبانی منقضی شده</h3>
                <p style="font-size: 16px; color: #374151; margin-bottom: 8px;">${message}</p>
                ${expiryDate ? `<p style="font-size: 14px; color: #6b7280; margin-bottom: 16px;">تاریخ انقضا: ${new Date(expiryDate).toLocaleDateString('fa-IR')}</p>` : ''}

                <!-- Info Box -->
                <div style="background-color: #fef3c7; border: 1px solid #fcd34d; border-radius: 8px; padding: 16px; margin: 16px auto; max-width: 400px;">
                    <p style="font-size: 14px; color: #92400e; text-align: right;">برای ادامه استفاده از بروزرسانی‌ها، لطفاً پشتیبانی خود را تمدید کنید.</p>
                </div>

                <!-- Actions -->
                <div style="display: flex; gap: 16px; margin-top: 32px;">
                    <button type="button" id="close-support-modal" style="flex: 1; padding: 12px 24px; border: 1px solid #d1d5db; background-color: white; border-radius: 6px; font-size: 16px; font-weight: 500; color: #374151; cursor: pointer;">
                        بستن
                    </button>
                    ${renewalUrl !== '#' ? `
                        <button type="button" id="renew-support" style="flex: 1; padding: 12px 24px; background-color: #dc2626; border: none; border-radius: 6px; font-size: 16px; font-weight: 500; color: white; cursor: pointer;">
                            تمدید پشتیبانی
                        </button>
                    ` : ''}
                </div>
            </div>
        `);

        $modal.append($modalContent);

        // Add event handlers
        $modalContent.find('#close-support-modal').on('click', function() {
            $modal.remove();
        });

        if (renewalUrl !== '#') {
            $modalContent.find('#renew-support').on('click', function() {
                window.open(renewalUrl, '_blank');
            });
        }

        // Close modal when clicking backdrop
        $modal.on('click', function(e) {
            if (e.target === this) {
                $modal.remove();
            }
        });

        // Append to body immediately
        $('body').append($modal);

        // Force show the modal with multiple approaches
        const $addedModal = $('#support-expired-modal');

        // Method 1: Ensure it's visible
        $addedModal.show();

        // Method 2: Force display with jQuery
        $addedModal.css('display', 'flex !important');

        // Method 3: Remove any hidden class that might exist
        $addedModal.removeClass('hidden');

        // Add debugging to verify modal is visible
        console.log('Modal added to DOM:', $addedModal.length > 0);
        console.log('Modal z-index:', $addedModal.css('z-index'));
        console.log('Modal display:', $addedModal.css('display'));
        console.log('Modal visibility:', $addedModal.css('visibility'));
        console.log('Modal opacity:', $addedModal.css('opacity'));

        // Additional fallback - use alert if modal still not working
        setTimeout(() => {
            const isVisible = $addedModal.is(':visible') && $addedModal.css('display') !== 'none';
            console.log('Modal is visible after timeout:', isVisible);

            if (!isVisible) {
                console.error('Modal failed to display, using alert fallback');
                alert(message + '\n\nبرای تمدید پشتیبانی، لطفاً با تیم پشتیبانی تماس بگیرید.');
            }
        }, 500);

    }

    /**
     * Save last update data to WordPress database
     */
    function saveLastUpdateToDatabase(updateData) {
        const data = {
            action: 'mahamitim_save_last_update',
            nonce: mahamitimUpdater.nonce,
            update_data: JSON.stringify({
                timestamp: new Date().toISOString(),
                version: updateData.version || 'latest',
                theme_name: updateData.theme_name || 'mahamitim-theme',
                location: updateData.location || '',
                success: true
            })
        };

        $.post(mahamitimUpdater.ajaxUrl, data)
            .done(function(response) {
                if (response.success) {
                    // Update localStorage as well for immediate UI update
                    localStorage.setItem('mahamitim_last_update', new Date().toISOString());
                    console.log('Last update data saved to database');
                }
            })
            .fail(function(jqXHR) {
                console.error('Failed to save last update data:', getErrorMessage(jqXHR));
            });
    }

    /**
     * Update last update time
     */
    function updateLastUpdateTime() {
        // Try to get from localStorage first for immediate display
        let lastUpdate = localStorage.getItem('mahamitim_last_update');
        const $element = $('#stat-last-update');

        if (!lastUpdate) {
            // Fetch from database if not in localStorage
            const data = {
                action: 'mahamitim_get_last_update',
                nonce: mahamitimUpdater.nonce
            };

            $.post(mahamitimUpdater.ajaxUrl, data)
                .done(function(response) {
                    if (response.success && response.data && response.data.timestamp) {
                        lastUpdate = response.data.timestamp;
                        localStorage.setItem('mahamitim_last_update', lastUpdate);

                        if ($element.length) {
                            const date = new Date(lastUpdate);
                            const formattedDate = date.toLocaleDateString('fa-IR');
                            $element.text(formattedDate);
                        }
                    }
                });
        } else if ($element.length) {
            const date = new Date(lastUpdate);
            const formattedDate = date.toLocaleDateString('fa-IR');
            $element.text(formattedDate);
        }
    }

    /**
     * Update stats
     */
    function updateStats() {
        // Update various statistics
        const $status = $('#stat-status');
        if ($status.length) {
            $status.text('آماده');
        }
    }

    /**
     * Show update modal
     */
    function showModal() {
        const $modal = $('#update-modal');
        if ($modal.length) {
            $modal.removeClass('hidden');

            // Reset modal state
            resetModal();

            // Add initial step
            addModalStep('شروع فرآیند بروزرسانی...', 'info', 0);
            updateProgress(10, 'در حال آماده‌سازی...');
        }
    }

    /**
     * Hide update modal
     */
    function hideModal() {
        const $modal = $('#update-modal');
        if ($modal.length && !isLoading) {
            $modal.addClass('hidden');
        }
    }

    /**
     * Reset modal to initial state
     */
    function resetModal() {
        $('#progress-bar').css('width', '0%');
        $('#progress-percentage').text('0%');
        $('#current-step').text('آماده‌سازی...');
        $('#steps-log').empty();
        $('#close-modal').addClass('hidden');
        $('#modal-close-btn').addClass('hidden');
        $('#modal-loading').removeClass('hidden');

        // Reset spinner with shadcn styling
        const $spinner = $('#step-spinner');
        $spinner.removeClass('bg-green-100 bg-red-100').addClass('bg-primary/10');
        $spinner.find('svg').removeClass('text-green-600 text-red-600').addClass('text-primary animate-spin');

        // Reset to spinner icon
        $spinner.find('svg').html(`
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        `);
    }

    /**
     * Update progress bar and current step
     */
    function updateProgress(percentage, stepText) {
        $('#progress-bar').css('width', percentage + '%');
        $('#progress-percentage').text(percentage + '%');
        $('#current-step').text(stepText);
    }

    /**
     * Complete modal (success or error)
     */
    function completeModal(success = true) {
        const $spinner = $('#step-spinner');
        const $loading = $('#modal-loading');
        const $closeBtn = $('#modal-close-btn');
        const $closeX = $('#close-modal');

        // Update spinner based on success/failure with shadcn styling
        if (success) {
            $spinner.removeClass('bg-primary/10').addClass('bg-green-100');
            $spinner.find('svg').removeClass('text-primary animate-spin').addClass('text-green-600');
            $spinner.find('svg').html('<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>');
            updateProgress(100, 'تکمیل شد!');
        } else {
            $spinner.removeClass('bg-primary/10').addClass('bg-red-100');
            $spinner.find('svg').removeClass('text-primary animate-spin').addClass('text-red-600');
            $spinner.find('svg').html('<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>');
        }

        // Show close buttons, hide loading
        $loading.addClass('hidden');
        $closeBtn.removeClass('hidden');
        $closeX.removeClass('hidden');

        // Don't auto-close - let user close manually
    }

    /**
     * Add step to modal log with shadcn-style design
     */
    function addModalStep(message, type = 'info', progress = null) {
        const $log = $('#steps-log');
        if ($log.length) {
            const timestamp = new Date().toLocaleTimeString('fa-IR');


            // Shadcn-style color classes
            const colorClass = {
                success: 'bg-green-50 border-green-200 text-green-900',
                error: 'bg-red-50 border-red-200 text-red-900',
                warning: 'bg-amber-50 border-amber-200 text-amber-900',
                info: 'bg-slate-50 border-slate-200 text-slate-900'
            }[type];

            const stepHtml = `
                <div class="flex items-start gap-2 p-2 rounded border ${colorClass} transition-all duration-150">
                    <div class="flex h-4 w-4 flex-shrink-0 items-center justify-center rounded-full ${
                        type === 'success' ? 'bg-green-100' :
                        type === 'error' ? 'bg-red-100' :
                        type === 'warning' ? 'bg-amber-100' :
                        'bg-slate-100'
                    }">
                        <svg class="h-3 w-3 ${
                            type === 'success' ? 'text-green-600' :
                            type === 'error' ? 'text-red-600' :
                            type === 'warning' ? 'text-amber-600' :
                            'text-slate-600'
                        }" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            ${type === 'success' ? '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>' :
                              type === 'error' ? '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>' :
                              type === 'warning' ? '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01"/>' :
                              '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01"/>'}
                        </svg>
                    </div>
                    <div class="flex-1 min-w-0">
                        <p class="text-xs font-medium leading-tight">${message}</p>
                        <p class="text-xs text-muted-foreground opacity-70">${timestamp}</p>
                    </div>
                </div>
            `;

            $log.append(stepHtml);
            $log.scrollTop($log[0].scrollHeight);

            // Update progress if provided
            if (progress !== null) {
                updateProgress(progress, message);
            }
        }
    }

    /**
     * Show shadcn-style toast notification
     */
    function showToast(message, type = 'info', duration = 5000) {
        const $container = $('#toast-container');
        if (!$container.length) {
            $('body').append('<div id="toast-container" class="fixed bottom-4 left-4 z-50 flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-4 sm:right-4 sm:left-auto sm:top-auto sm:flex-col md:max-w-[420px]"></div>');
        }

        // Shadcn-style color classes with HSL-based color system
        const colorClasses = {
            success: 'border bg-background text-foreground shadow-lg shadow-black/5',
            error: 'destructive border-destructive/50 text-destructive-foreground bg-destructive/10',
            warning: 'border-amber-200 bg-amber-50 text-amber-900 shadow-lg shadow-amber-500/5',
            info: 'border bg-background text-foreground shadow-lg shadow-black/5'
        };

        const iconSvgs = {
            success: '<svg class="h-4 w-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>',
            error: '<svg class="h-4 w-4 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>',
            warning: '<svg class="h-4 w-4 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01"/></svg>',
            info: '<svg class="h-4 w-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01"/></svg>'
        };

        const $toast = $(`
            <div class="toast group pointer-events-auto relative flex w-full items-center justify-between space-x-2 space-x-reverse overflow-hidden rounded-md border p-4 pr-6 transition-all ${colorClasses[type]} data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-bottom-full data-[state=open]:sm:slide-in-from-bottom-full opacity-0 translate-y-full scale-95">
                <div class="flex items-start gap-3">
                    <div class="flex-shrink-0 mt-0.5">
                        ${iconSvgs[type]}
                    </div>
                    <div class="flex-1 space-y-1">
                        <div class="text-sm font-medium leading-none">${message}</div>
                    </div>
                </div>
                <button type="button" class="toast-close absolute left-1 top-1 rounded-md p-1 text-muted-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100">
                    <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                    <span class="sr-only">بستن</span>
                </button>
            </div>
        `);

        $('#toast-container').append($toast);

        // Shadcn-style animation in
        setTimeout(function() {
            $toast.removeClass('opacity-0 translate-y-full scale-95').addClass('opacity-100 translate-y-0 scale-100');
        }, 10);

        // Auto remove with shadcn-style animation
        setTimeout(function() {
            $toast.addClass('opacity-0 translate-y-full scale-95');
            setTimeout(function() {
                $toast.remove();
            }, 200);
        }, duration);
    }

    /**
     * Set loading state
     */
    function setLoading(loading) {
        isLoading = loading;

        if (loading) {
            $('body').addClass('cursor-wait');
        } else {
            $('body').removeClass('cursor-wait');
        }
    }

    /**
     * Get error message from jqXHR
     */
    function getErrorMessage(jqXHR) {
        if (jqXHR.responseJSON && jqXHR.responseJSON.data && jqXHR.responseJSON.data.message) {
            return jqXHR.responseJSON.data.message;
        }

        if (jqXHR.responseText) {
            try {
                const response = JSON.parse(jqXHR.responseText);
                if (response.data && response.data.message) {
                    return response.data.message;
                }
            } catch (e) {
                // Ignore JSON parse errors
            }
        }

        return mahamitimUpdater.strings.error || 'خطای ناشناخته رخ داد';
    }

    /**
     * Handle settings form submission
     */
    function handleSaveSettings(e) {
        e.preventDefault();
        // Settings functionality can be added later
        showToast('تنظیمات ذخیره شد', 'success');
    }

    // Test function for debugging support expired (can be called from browser console)
    window.testSupportExpired = function() {
        console.log('Testing support expired...');

        // First show the modal
        showModal();

        // Then after a short delay, show support expired
        setTimeout(() => {
            const testData = {
                message: 'support_expired',
                expiry_date: '2024-12-31T23:59:59Z',
                renewal_url: 'https://example.com/renew'
            };

            handleSupportExpired(testData);
        }, 1000);
    };
});