/**
 * Mementor TTS Modal Utilities
 * 
 * Shared utility functions for creating and managing modal dialogs
 * across the Text-to-Speech plugin.
 */

(function( $ ) {
    'use strict';

    // Create a namespace for our utility functions
    window.mementorTTSModalUtils = window.mementorTTSModalUtils || {};

    /**
     * Creates a voice limit warning dialog
     * 
     * @param {string} title - The title for the modal
     * @param {string} message - The message to display in the modal
     * @param {string} confirmButtonText - Text for the confirmation button (default: 'Go to My Stats & Voices')
     * @param {string} cancelButtonText - Text for the cancel button (default: 'Close')
     * @param {string} confirmButtonUrl - URL to navigate to when confirm button is clicked
     * @return {HTMLElement} The created modal element
     */
    window.mementorTTSModalUtils.createVoiceLimitDialog = function(title, message, confirmButtonText, cancelButtonText, confirmButtonUrl) {
        // Set default values if not provided
        title = title || 'Voice Limit Reached';
        message = message || 'You have reached your voice limit. Please upgrade to generate more audio.';
        confirmButtonText = confirmButtonText || 'Go to My Stats & Voices';
        cancelButtonText = cancelButtonText || 'Close';
        confirmButtonUrl = confirmButtonUrl || 'admin.php?page=text-to-speech-tts-my-stats-voices';

        // Create modal overlay
        const modal = document.createElement('div');
        modal.className = 'mementor-tts-confirm-modal-overlay active';

        // Create dialog container
        const dialog = document.createElement('div');
        dialog.className = 'mementor-tts-confirm-modal';

        // Create header container with warning icon
        const headerContainer = document.createElement('div');
        headerContainer.className = 'mementor-tts-confirm-modal-header warning';
        const icon = document.createElement('span');
        icon.className = 'dashicons dashicons-warning';
        headerContainer.appendChild(icon);

        // Create title element
        const titleElement = document.createElement('h3');
        titleElement.textContent = title;
        headerContainer.appendChild(titleElement);

        // Create content container
        const content = document.createElement('div');
        content.className = 'mementor-tts-confirm-modal-content';
        content.innerHTML = '<p>' + message + '</p>';

        // Create buttons container
        const buttons = document.createElement('div');
        buttons.className = 'mementor-tts-confirm-modal-buttons';
        buttons.style.display = 'flex';
        buttons.style.width = '100%';
        buttons.style.marginTop = '20px';

        // Create confirm button
        const confirmBtn = document.createElement('button');
        confirmBtn.className = 'mementor-tts-confirm-modal-btn mementor-tts-confirm-modal-btn-danger mementor-tts-confirm-ok';
        confirmBtn.textContent = confirmButtonText;
        confirmBtn.style.flex = '1';
        confirmBtn.style.margin = '0 0 0 5px';
        confirmBtn.style.padding = '10px';
        confirmBtn.style.fontWeight = 'bold';

        // Create cancel button
        const cancelBtn = document.createElement('button');
        cancelBtn.className = 'mementor-tts-confirm-modal-btn mementor-tts-confirm-modal-btn-secondary mementor-tts-confirm-cancel';
        cancelBtn.textContent = cancelButtonText;
        cancelBtn.style.flex = '1';
        cancelBtn.style.margin = '0 5px 0 0';
        cancelBtn.style.padding = '10px';

        // Add event listeners
        confirmBtn.addEventListener('click', function() {
            document.body.removeChild(modal);
            window.location.href = confirmButtonUrl;
        });

        cancelBtn.addEventListener('click', function() {
            document.body.removeChild(modal);
            location.reload(); // Refresh the page to reset UI state
        });

        // Assemble the dialog
        buttons.appendChild(cancelBtn);
        buttons.appendChild(confirmBtn);

        dialog.appendChild(headerContainer);
        dialog.appendChild(content);
        dialog.appendChild(buttons);
        modal.appendChild(dialog);

        // Add to document
        document.body.appendChild(modal);

        return modal;
    };

    /**
     * Shows a voice limit warning dialog
     * 
     * @param {string} message - The message to display in the modal
     */
    window.mementorTTSModalUtils.showVoiceLimitWarning = function(message) {
        return window.mementorTTSModalUtils.createVoiceLimitDialog(
            'Voice Limit Reached',
            message || 'Open My Stats & Voices and delete one or more voices to free up space.',
            'Go to My Stats & Voices',
            'Close',
            'admin.php?page=text-to-speech-tts-my-stats-voices'
        );
    };
    
    /**
     * Creates a PRO-plan required dialog
     * 
     * @param {string} title - The title for the modal
     * @param {string} message - The message to display in the modal
     * @param {string} confirmButtonText - Text for the confirmation button (default: 'Go to Voices')
     * @param {string} cancelButtonText - Text for the cancel button (default: 'Close')
     * @param {string} confirmButtonUrl - URL to navigate to when confirm button is clicked
     * @return {HTMLElement} The created modal element
     */
    window.mementorTTSModalUtils.createProPlanDialog = function(title, message, confirmButtonText, cancelButtonText, confirmButtonUrl) {
        // Set default values if not provided
        title = title || 'Voice Unavailable';
        message = message || '<strong>This voice requires a paid ElevenLabs account.</strong><p><strong>PRO users:</strong> If you see this message, your PRO API key may not be configured correctly. Please contact support.</p><p><strong>Free users:</strong> Select a different voice or upgrade to PRO.</p>';
        confirmButtonText = confirmButtonText || 'Go to Voices';
        cancelButtonText = cancelButtonText || 'Close';
        confirmButtonUrl = confirmButtonUrl || 'admin.php?page=text-to-speech-tts-voices';

        // Create modal overlay
        const modal = document.createElement('div');
        modal.className = 'mementor-tts-confirm-modal-overlay active';

        // Create dialog container
        const dialog = document.createElement('div');
        dialog.className = 'mementor-tts-confirm-modal';

        // Create header container with warning icon
        const headerContainer = document.createElement('div');
        headerContainer.className = 'mementor-tts-confirm-modal-header warning';
        const icon = document.createElement('span');
        icon.className = 'dashicons dashicons-lock';
        headerContainer.appendChild(icon);

        // Create title element
        const titleElement = document.createElement('h3');
        titleElement.textContent = title;
        headerContainer.appendChild(titleElement);

        // Create content container
        const content = document.createElement('div');
        content.className = 'mementor-tts-confirm-modal-content';
        content.innerHTML = message;

        // Create buttons container
        const buttons = document.createElement('div');
        buttons.className = 'mementor-tts-confirm-modal-buttons';
        buttons.style.display = 'flex';
        buttons.style.width = '100%';
        buttons.style.marginTop = '20px';

        // Create confirm button
        const confirmBtn = document.createElement('button');
        confirmBtn.className = 'mementor-tts-confirm-modal-btn mementor-tts-confirm-modal-btn-danger mementor-tts-confirm-ok';
        confirmBtn.textContent = confirmButtonText;
        confirmBtn.style.flex = '1';
        confirmBtn.style.margin = '0 0 0 5px';
        confirmBtn.style.padding = '10px';
        confirmBtn.style.fontWeight = 'bold';

        // Create cancel button
        const cancelBtn = document.createElement('button');
        cancelBtn.className = 'mementor-tts-confirm-modal-btn mementor-tts-confirm-modal-btn-secondary mementor-tts-confirm-cancel';
        cancelBtn.textContent = cancelButtonText;
        cancelBtn.style.flex = '1';
        cancelBtn.style.margin = '0 5px 0 0';
        cancelBtn.style.padding = '10px';

        // Add event listeners
        confirmBtn.addEventListener('click', function() {
            document.body.removeChild(modal);
            window.location.href = confirmButtonUrl;
        });

        cancelBtn.addEventListener('click', function() {
            document.body.removeChild(modal);
            location.reload(); // Refresh the page to reset UI state
        });

        // Assemble the dialog
        buttons.appendChild(cancelBtn);
        buttons.appendChild(confirmBtn);

        dialog.appendChild(headerContainer);
        dialog.appendChild(content);
        dialog.appendChild(buttons);
        modal.appendChild(dialog);

        // Add to document
        document.body.appendChild(modal);

        return modal;
    };

    /**
     * Shows a PRO-plan required dialog
     * 
     * @param {string} message - The message to display in the modal
     */
    window.mementorTTSModalUtils.showProPlanRequired = function(message) {
        return window.mementorTTSModalUtils.createProPlanDialog(
            'Voice Unavailable',
            message || '<strong>This voice requires a paid ElevenLabs account.</strong><p><strong>PRO users:</strong> If you see this message, your PRO API key may not be configured correctly. Please contact support.</p><p><strong>Free users:</strong> Select a different voice or upgrade to PRO.</p>',
            'Go to Voices',
            'Close',
            'admin.php?page=text-to-speech-tts-voices'
        );
    };
    
    /**
     * Creates an API key error dialog
     * 
     * @param {string} title - The title for the modal
     * @param {string} message - The message to display in the modal
     * @param {string} primaryButtonText - Text for the primary button
     * @param {string} secondaryButtonText - Text for the secondary button
     * @param {string} primaryButtonUrl - URL for primary button
     * @param {string} secondaryButtonUrl - URL for secondary button
     * @return {HTMLElement} The created modal element
     */
    window.mementorTTSModalUtils.createApiKeyErrorDialog = function(title, message, primaryButtonText, secondaryButtonText, primaryButtonUrl, secondaryButtonUrl) {
        // Set default values if not provided
        title = title || 'API Key Required';
        message = message || 'You need an API key to generate audio.';
        primaryButtonText = primaryButtonText || 'Get Free API Key';
        secondaryButtonText = secondaryButtonText || 'Upgrade to PRO';
        primaryButtonUrl = primaryButtonUrl || 'admin.php?page=text-to-speech-tts-settings';
        secondaryButtonUrl = secondaryButtonUrl || 'admin.php?page=text-to-speech-tts-upgrade';

        // Create modal overlay
        const modal = document.createElement('div');
        modal.className = 'mementor-tts-confirm-modal-overlay active';

        // Create dialog container
        const dialog = document.createElement('div');
        dialog.className = 'mementor-tts-confirm-modal';

        // Create header container with info icon
        const headerContainer = document.createElement('div');
        headerContainer.className = 'mementor-tts-confirm-modal-header info';
        const icon = document.createElement('span');
        icon.className = 'dashicons dashicons-info';
        headerContainer.appendChild(icon);

        // Create title element
        const titleElement = document.createElement('h3');
        titleElement.textContent = title;
        headerContainer.appendChild(titleElement);

        // Create content container
        const content = document.createElement('div');
        content.className = 'mementor-tts-confirm-modal-content';
        content.innerHTML = message;

        // Create buttons container
        const buttons = document.createElement('div');
        buttons.className = 'mementor-tts-confirm-modal-buttons';
        buttons.style.display = 'flex';
        buttons.style.width = '100%';
        buttons.style.marginTop = '20px';

        // Create primary button
        const primaryBtn = document.createElement('button');
        primaryBtn.className = 'mementor-tts-confirm-modal-btn mementor-tts-confirm-modal-btn-primary mementor-tts-confirm-ok';
        primaryBtn.textContent = primaryButtonText;
        primaryBtn.style.flex = '1';
        primaryBtn.style.margin = '0 5px';
        primaryBtn.style.padding = '10px';
        primaryBtn.style.fontWeight = 'bold';

        // Create secondary button
        const secondaryBtn = document.createElement('button');
        secondaryBtn.className = 'mementor-tts-confirm-modal-btn mementor-tts-confirm-modal-btn-secondary';
        secondaryBtn.textContent = secondaryButtonText;
        secondaryBtn.style.flex = '1';
        secondaryBtn.style.margin = '0 5px';
        secondaryBtn.style.padding = '10px';

        // Create close button
        const closeBtn = document.createElement('button');
        closeBtn.className = 'mementor-tts-confirm-modal-btn mementor-tts-confirm-modal-btn-link mementor-tts-confirm-cancel';
        closeBtn.textContent = 'Close';
        closeBtn.style.width = '100%';
        closeBtn.style.marginTop = '10px';
        closeBtn.style.padding = '10px';

        // Add event listeners
        primaryBtn.addEventListener('click', function() {
            document.body.removeChild(modal);
            // Check if it's an external URL
            if (primaryButtonUrl.startsWith('http://') || primaryButtonUrl.startsWith('https://')) {
                window.open(primaryButtonUrl, '_blank');
            } else {
                window.location.href = primaryButtonUrl;
            }
        });

        secondaryBtn.addEventListener('click', function() {
            document.body.removeChild(modal);
            window.location.href = secondaryButtonUrl;
        });

        closeBtn.addEventListener('click', function() {
            document.body.removeChild(modal);
        });

        // Assemble the dialog
        buttons.appendChild(primaryBtn);
        buttons.appendChild(secondaryBtn);

        dialog.appendChild(headerContainer);
        dialog.appendChild(content);
        dialog.appendChild(buttons);
        dialog.appendChild(closeBtn);
        modal.appendChild(dialog);

        // Add to document
        document.body.appendChild(modal);

        return modal;
    };

    /**
     * Shows a credits exhausted dialog
     * 
     * @param {number} remaining - Remaining credits
     * @param {number} required - Required credits for the operation
     * @param {number} limit - Total credit limit
     */
    window.mementorTTSModalUtils.showCreditsExhausted = function(remaining, required, limit) {
        const title = 'Not enough credits';
        let message = '<p style="font-size: 14px;"><strong>You don\'t have enough credits for this request.</strong></p>';

        if (required > 0) {
            const have = Math.max(0, remaining).toLocaleString();
            message += '<p style="font-size: 14px;">This request needs ' + required.toLocaleString() + ' credits. You have ' + have + '.</p>';
        }

        message += '<p style="font-size: 14px;">Top up now or upgrade your plan to proceed.</p>';

        return window.mementorTTSModalUtils.createApiKeyErrorDialog(
            title,
            message,
            'Top up credits',
            'Upgrade plan',
            'admin.php?page=text-to-speech-tts-account#top-ups',
            'admin.php?page=text-to-speech-tts-account#upgrade'
        );
    };

    /**
     * Shows a demo environment notification dialog for playground.wordpress.net
     */
    window.mementorTTSModalUtils.showDemoNotAvailable = function() {
        const title = 'Audio Generation Not Available in This Demo';
        const message = '<p>You\'re welcome to explore our plugin and try out all its features.</p>' +
                       '<p>However, to generate audio and receive <strong>10,000 free credits</strong>, you\'ll need to install the plugin on your own website — not on playground.wordpress.net.</p>';
        
        // Create modal overlay
        const modal = document.createElement('div');
        modal.className = 'mementor-tts-confirm-modal-overlay active';

        // Create dialog container
        const dialog = document.createElement('div');
        dialog.className = 'mementor-tts-confirm-modal mementor-tts-demo-modal';

        // Create header container with info icon
        const headerContainer = document.createElement('div');
        headerContainer.className = 'mementor-tts-confirm-modal-header info';
        const icon = document.createElement('span');
        icon.className = 'dashicons dashicons-info';
        headerContainer.appendChild(icon);

        // Create title element
        const titleElement = document.createElement('h3');
        titleElement.textContent = title;
        headerContainer.appendChild(titleElement);

        // Create message container
        const messageContainer = document.createElement('div');
        messageContainer.className = 'mementor-tts-confirm-modal-message';
        messageContainer.innerHTML = message;

        // Create button container
        const buttonContainer = document.createElement('div');
        buttonContainer.className = 'mementor-tts-confirm-modal-buttons';

        // Create close button
        const closeButton = document.createElement('button');
        closeButton.className = 'button button-secondary';
        closeButton.textContent = 'Continue exploring';
        closeButton.onclick = function() {
            document.body.removeChild(modal);
        };

        buttonContainer.appendChild(closeButton);

        // Assemble the modal
        dialog.appendChild(headerContainer);
        dialog.appendChild(messageContainer);
        dialog.appendChild(buttonContainer);
        modal.appendChild(dialog);

        // Add to page
        document.body.appendChild(modal);

        // Close on overlay click
        modal.onclick = function(e) {
            if (e.target === modal) {
                document.body.removeChild(modal);
            }
        };

        return modal;
    };

    /**
     * Shows a modern "site not connected" dialog directing users to the Settings page.
     * Self-contained with inline styles matching the TTSWP design language.
     */
    window.mementorTTSModalUtils.showNotConnected = function() {
        // Inject keyframes once
        if (!document.getElementById('tts-nc-keyframes')) {
            var style = document.createElement('style');
            style.id = 'tts-nc-keyframes';
            style.textContent =
                '@keyframes ttsNcFadeIn{from{opacity:0}to{opacity:1}}' +
                '@keyframes ttsNcSlideIn{from{opacity:0;transform:scale(.95) translateY(-10px)}to{opacity:1;transform:scale(1) translateY(0)}}';
            document.head.appendChild(style);
        }

        // Overlay
        var modal = document.createElement('div');
        modal.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(15,23,42,.7);backdrop-filter:blur(4px);z-index:999999;display:flex;align-items:center;justify-content:center;padding:20px;animation:ttsNcFadeIn .3s ease-out';

        // Dialog
        var dialog = document.createElement('div');
        dialog.style.cssText = 'background:linear-gradient(180deg,#fff 0%,#f8fafc 100%);border-radius:20px;box-shadow:0 25px 50px -12px rgba(0,0,0,.25),0 0 0 1px rgba(0,0,0,.05);max-width:420px;width:100%;overflow:hidden;animation:ttsNcSlideIn .3s ease-out';

        // Logo wrap
        var logoWrap = document.createElement('div');
        logoWrap.style.cssText = 'display:flex;justify-content:center;padding:32px 24px 0';
        var logoBox = document.createElement('div');
        logoBox.style.cssText = 'width:64px;height:64px;background:#18181b;border-radius:16px;display:flex;align-items:center;justify-content:center;box-shadow:0 10px 20px -5px rgba(24,24,27,.4)';
        var logoImg = document.createElement('img');
        logoImg.src = (window.mementorTTSAudio && window.mementorTTSAudio.pluginUrl ? window.mementorTTSAudio.pluginUrl : '') + 'admin/images/ttswp-icon.svg';
        logoImg.alt = 'TTSWP';
        logoImg.style.cssText = 'width:48px;height:48px';
        logoBox.appendChild(logoImg);
        logoWrap.appendChild(logoBox);

        // Body
        var body = document.createElement('div');
        body.style.cssText = 'padding:24px 28px 20px;text-align:center';

        var h2 = document.createElement('h2');
        h2.textContent = 'Site Not Connected';
        h2.style.cssText = 'margin:0 0 8px;font-size:22px;font-weight:700;color:#1e293b';
        body.appendChild(h2);

        var subtitle = document.createElement('p');
        subtitle.textContent = 'Connect your site to start generating audio with natural AI voices.';
        subtitle.style.cssText = 'margin:0 0 20px;color:#64748b;font-size:14px;line-height:1.5';
        body.appendChild(subtitle);

        // Feature pills
        var pills = document.createElement('div');
        pills.style.cssText = 'display:flex;justify-content:center;gap:8px;flex-wrap:wrap;margin-bottom:8px';

        var pillData = [
            {icon: '\u{1F3A4}', text: '10,000 Free Credits'},
            {icon: '\u{26A1}', text: 'Instant Setup'},
            {icon: '\u{1F512}', text: 'Secure Connection'}
        ];

        pillData.forEach(function(item) {
            var pill = document.createElement('span');
            pill.style.cssText = 'display:inline-flex;align-items:center;gap:4px;background:#f0ebfd;color:#4a2fa0;font-size:12px;font-weight:600;padding:6px 12px;border-radius:20px;border:1px solid #c9b8f5';
            pill.textContent = item.icon + ' ' + item.text;
            pills.appendChild(pill);
        });
        body.appendChild(pills);

        // Footer with buttons
        var footer = document.createElement('div');
        footer.style.cssText = 'padding:0 28px 24px';

        var connectBtn = document.createElement('button');
        connectBtn.textContent = 'Connect Your Site';
        connectBtn.style.cssText = 'width:100%;padding:14px 20px;border-radius:12px;font-size:15px;font-weight:600;cursor:pointer;border:none;color:#fff;background:linear-gradient(135deg,#6B45D4 0%,#5435B0 100%);box-shadow:0 4px 12px -2px rgba(107,69,212,.4);transition:all .2s ease;display:flex;align-items:center;justify-content:center;gap:8px';
        connectBtn.onmouseenter = function() { this.style.transform = 'translateY(-1px)'; this.style.boxShadow = '0 6px 16px -2px rgba(107,69,212,.5)'; };
        connectBtn.onmouseleave = function() { this.style.transform = 'translateY(0)'; this.style.boxShadow = '0 4px 12px -2px rgba(107,69,212,.4)'; };

        var dismissBtn = document.createElement('button');
        dismissBtn.textContent = 'Not now';
        dismissBtn.style.cssText = 'width:100%;padding:10px;margin-top:8px;border:none;background:transparent;color:#94a3b8;font-size:13px;cursor:pointer;transition:color .2s';
        dismissBtn.onmouseenter = function() { this.style.color = '#64748b'; };
        dismissBtn.onmouseleave = function() { this.style.color = '#94a3b8'; };

        // Events
        connectBtn.addEventListener('click', function() {
            document.body.removeChild(modal);
            window.location.href = 'admin.php?page=text-to-speech-tts-settings';
        });
        dismissBtn.addEventListener('click', function() {
            document.body.removeChild(modal);
        });
        modal.addEventListener('click', function(e) {
            if (e.target === modal) document.body.removeChild(modal);
        });

        footer.appendChild(connectBtn);
        footer.appendChild(dismissBtn);

        // Assemble
        dialog.appendChild(logoWrap);
        dialog.appendChild(body);
        dialog.appendChild(footer);
        modal.appendChild(dialog);
        document.body.appendChild(modal);

        return modal;
    };

    /**
     * Shows an API key error dialog
     *
     * @param {boolean} hasNoApiKey - Whether the user has no API key configured
     * @param {string} errorMessage - The error message from the API
     */
    window.mementorTTSModalUtils.showApiKeyError = function(hasNoApiKey, errorMessage) {
        let title, message;
        
        // Check if this is a "no API key" error
        if (hasNoApiKey || 
            (errorMessage && (errorMessage.includes('needs_authorization') || 
                            errorMessage.includes('Neither authorization header nor xi-api-key received')))) {
            title = 'API Key Required';
            message = '<p style="font-size: 14px;"><strong>You need to connect an API key to generate audio.</strong></p>' +
                     '<p style="font-size: 14px;">Get started with two great options:</p>' +
                     '<ul style="text-align: left; margin: 15px 0; font-size: 14px;">' +
                     '<li><strong>Sign up for a free ElevenLabs account</strong> to unlock 10,000 free credits each month.</li>' +
                     '<li><strong>Upgrade to PRO for just $3.99/month</strong>, which includes 60,000 credits and all PRO features.</li>' +
                     '</ul>';
        } else {
            // User has API key but credits are exhausted
            title = 'Credits Exhausted';
            message = '<p style="font-size: 14px;"><strong>Your ElevenLabs credits have been used up.</strong></p>' +
                     '<p style="font-size: 14px;">To continue generating audio, you have two options:</p>' +
                     '<ul style="text-align: left; margin: 15px 0; font-size: 14px;">' +
                     '<li><strong>Upgrade your <a href="https://try.elevenlabs.io/mementor" target="_blank" style="color: #2271b1;">ElevenLabs account</a></strong> to unlock more monthly credits.</li>' +
                     '<li><strong>Upgrade to PRO for just $3.99/month</strong>, which includes 60,000 credits and all PRO features.</li>' +
                     '</ul>';
        }
        
        return window.mementorTTSModalUtils.createApiKeyErrorDialog(
            title,
            message,
            hasNoApiKey ? 'Get Free API Key' : 'Upgrade ElevenLabs',
            'Upgrade to PRO ($3.99/mo)',
            hasNoApiKey ? 'admin.php?page=text-to-speech-tts-settings' : 'https://try.elevenlabs.io/mementor',
            'admin.php?page=text-to-speech-tts-upgrade'
        );
    };

    /**
     * Creates a success dialog
     * 
     * @param {string} title - The title for the modal
     * @param {string} message - The message to display in the modal
     * @param {string} buttonText - Text for the button (default: 'Close')
     * @param {boolean} autoClose - Whether to auto-close the modal after a delay
     * @param {number} autoCloseDelay - Delay in milliseconds before auto-closing (default: 3000)
     * @return {HTMLElement} The created modal element
     */
    window.mementorTTSModalUtils.createSuccessDialog = function(title, message, buttonText, autoClose, autoCloseDelay) {
        // Set default values if not provided
        title = title || 'Success';
        message = message || 'Operation completed successfully!';
        buttonText = buttonText || 'Close';
        autoClose = autoClose !== false;
        autoCloseDelay = autoCloseDelay || 3000;

        // Create modal overlay
        const modal = document.createElement('div');
        modal.className = 'mementor-tts-confirm-modal-overlay active';

        // Create dialog container
        const dialog = document.createElement('div');
        dialog.className = 'mementor-tts-confirm-modal';

        // Create header container with success icon
        const headerContainer = document.createElement('div');
        headerContainer.className = 'mementor-tts-confirm-modal-header success';
        headerContainer.style.backgroundColor = '#d4edda';
        headerContainer.style.color = '#155724';
        const icon = document.createElement('span');
        icon.className = 'dashicons dashicons-yes-alt';
        icon.style.color = '#28a745';
        headerContainer.appendChild(icon);

        // Create title element
        const titleElement = document.createElement('h3');
        titleElement.textContent = title;
        titleElement.style.color = '#155724';
        headerContainer.appendChild(titleElement);

        // Create content container
        const content = document.createElement('div');
        content.className = 'mementor-tts-confirm-modal-content';
        content.innerHTML = message;

        // Create button
        const button = document.createElement('button');
        button.className = 'mementor-tts-confirm-modal-btn mementor-tts-confirm-modal-btn-primary';
        button.textContent = buttonText;
        button.style.width = '100%';
        button.style.marginTop = '20px';
        button.style.padding = '10px';
        button.style.backgroundColor = '#28a745';
        button.style.borderColor = '#28a745';
        button.style.color = '#fff';

        // Add hover effect
        button.addEventListener('mouseenter', function() {
            button.style.backgroundColor = '#218838';
            button.style.borderColor = '#1e7e34';
        });
        button.addEventListener('mouseleave', function() {
            button.style.backgroundColor = '#28a745';
            button.style.borderColor = '#28a745';
        });

        // Close function
        const closeModal = function() {
            modal.style.animation = 'fadeOut 0.3s ease-out';
            setTimeout(function() {
                if (document.body.contains(modal)) {
                    document.body.removeChild(modal);
                }
            }, 300);
        };

        // Add event listener
        button.addEventListener('click', closeModal);

        // Auto-close if enabled
        if (autoClose) {
            setTimeout(closeModal, autoCloseDelay);
        }

        // Assemble the dialog
        dialog.appendChild(headerContainer);
        dialog.appendChild(content);
        dialog.appendChild(button);
        modal.appendChild(dialog);

        // Add to document
        document.body.appendChild(modal);

        return modal;
    };

    /**
     * Shows a success dialog for audio generation
     * 
     * @param {string} message - Optional custom message
     * @param {number} creditsUsed - Number of credits used (optional)
     * @param {number} remainingCredits - Remaining credits (optional)
     */
    window.mementorTTSModalUtils.showAudioGeneratedSuccess = function(message, creditsUsed, remainingCredits) {
        let content = message || '<p style="font-size: 14px;"><strong>Your audio has been generated successfully!</strong></p>';
        
        if (creditsUsed !== undefined && remainingCredits !== undefined) {
            content += '<p style="font-size: 14px; margin-top: 10px;">Credits used: <strong>' + creditsUsed.toLocaleString() + '</strong><br>' +
                      'Remaining credits: <strong>' + remainingCredits.toLocaleString() + '</strong></p>';
        }
        
        return window.mementorTTSModalUtils.createSuccessDialog(
            'Audio Generated Successfully!',
            content,
            'Great!',
            true,
            4000
        );
    };

})( jQuery );
