<?php
/**
 * Text to Speech Generator Admin Page
 *
 * @package    TTSWP
 * @subpackage Mementor_TTS/admin/partials
 */

// Check if this file is called directly
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Verify user capabilities
if (!current_user_can('manage_options')) {
    wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'text-to-speech-tts'));
}

// Make sure plugin functions are available
if (!function_exists('is_plugin_active')) {
    include_once(ABSPATH . 'wp-admin/includes/plugin.php');
}

// Check if API key is set
$has_api_key = !empty(get_option('mementor_tts_api_key'));

// Check if user has a paid plan via SaaS
$is_pro_active = ttswp_has_paid_plan();

// Get current voice and language settings
$selected_voice_id = get_option('mementor_tts_voice', '');
$selected_voice = get_option('mementor_tts_voice_name', 'Adam');
$selected_language = get_option('mementor_tts_language', 'English');

// Check for custom voice ID (for paid plan users)
$custom_voice_id = '';
if ($is_pro_active) {
    $custom_voice_id = get_option('mementor_tts_custom_voice_id', '');
}

// Get selected model
$selected_model = get_option('mementor_tts_model', 'eleven_flash_v2_5');

// Character limits based on model and plan
if ($is_pro_active) {
    // Paid plan users get higher limits based on model
    if ($selected_model === 'eleven_flash_v2_5') {
        $char_limit = 40000;
    } else if ($selected_model === 'eleven_turbo_v2_5') {
        $char_limit = 40000;
    } else if ($selected_model === 'eleven_multilingual_v2') {
        $char_limit = 10000;
    } else if ($selected_model === 'eleven_v3') {
        $char_limit = 3000;
    } else {
        $char_limit = 10000;
    }
} else {
    // Free users only have access to eleven_flash_v2_5 with 2000 characters
    $char_limit = 2000;
}

// Get white label settings
require_once MEMENTOR_TTS_PLUGIN_DIR . 'admin/class-mementor-tts-admin.php';
$admin = new Mementor_TTS_Admin('mementor-tts', MEMENTOR_TTS_VERSION);
$white_label_logo = $admin->get_white_label_logo();
$white_label_name = $admin->get_white_label_name();

// Credits are managed by the SaaS — read from cached transient
$credits_left = (int) get_transient('tts_credits_balance');

// Default text for textarea
$default_text = 'Hello, future listener! Haha! This is just a quick, grin-inducing preview of the text-to-speech awesomeness coming your way. With one click, our generator hands you a tiny shortcode — ready to drop anywhere in your content. Easy, right?! Soon your words will spring to life in a warm, human-like voice that even your goldfish will admire. Stay tuned, and enjoy the magic…';
?>

<?php
$tts_page_title = __('Shortcode Generator', 'text-to-speech-tts');
$tts_topbar_actions = '';
$tts_requires_connection = true; // gate page behind SaaS connection

include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-open.php';
?>
<?php include(MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/navigation.php'); ?>

            <!-- Voice Settings Card -->
            <div class="tts-card tts-card-inset">
                <div class="tts-card-header tts-card-header-inline">
                    <h3 class="tts-card-title"><?php esc_html_e('Voice', 'text-to-speech-tts'); ?></h3>
                    <p class="tts-card-desc"><?php esc_html_e('Current voice and credits.', 'text-to-speech-tts'); ?></p>
                </div>
                <div class="mementor-tts-voice-settings-row">
                    <!-- Left: Voice Avatar -->
                    <div class="mementor-tts-voice-avatar">
                        <?php
                        $avatar_image = !empty($custom_voice_id)
                            ? 'admin/images/avatar/custom_voice.svg'
                            : 'admin/images/avatar/Female2_2.svg';
                        ?>
                        <img src="<?php echo esc_url(MEMENTOR_TTS_PLUGIN_URL . $avatar_image); ?>"
                             alt="<?php esc_attr_e('Voice Avatar', 'text-to-speech-tts'); ?>"
                             id="mementor-tts-voice-avatar-img">
                    </div>

                    <!-- Middle: Voice Information -->
                    <div class="mementor-tts-current-voice-info">
                        <?php if (!empty($custom_voice_id)): ?>
                            <h4 id="mementor-tts-voice-name"><?php esc_html_e('Custom Voice', 'text-to-speech-tts'); ?></h4>
                            <p id="mementor-tts-voice-details">
                                <?php esc_html_e('Voice ID:', 'text-to-speech-tts'); ?>
                                <?php echo esc_html($custom_voice_id); ?>
                            </p>
                            <p style="color: #2196F3; font-size: 12px; margin-top: 5px;">
                                <span class="dashicons dashicons-info"></span>
                                <?php esc_html_e('Using your custom ElevenLabs voice', 'text-to-speech-tts'); ?>
                            </p>
                        <?php else: ?>
                            <h4 id="mementor-tts-voice-name"><?php echo esc_html($selected_voice); ?></h4>
                            <?php
                            $tts_language_names = array(
                                'en' => 'English', 'no' => 'Norwegian', 'bg' => 'Bulgarian', 'de' => 'German',
                                'fr' => 'French', 'es' => 'Spanish', 'it' => 'Italian', 'pt' => 'Portuguese',
                                'nl' => 'Dutch', 'pl' => 'Polish', 'sv' => 'Swedish', 'da' => 'Danish',
                                'fi' => 'Finnish', 'ro' => 'Romanian', 'el' => 'Greek', 'cs' => 'Czech',
                                'hu' => 'Hungarian', 'hr' => 'Croatian', 'sk' => 'Slovak', 'uk' => 'Ukrainian',
                                'ru' => 'Russian', 'tr' => 'Turkish', 'ar' => 'Arabic', 'hi' => 'Hindi',
                                'ja' => 'Japanese', 'ko' => 'Korean', 'zh' => 'Chinese', 'id' => 'Indonesian',
                                'ms' => 'Malay', 'th' => 'Thai', 'vi' => 'Vietnamese', 'tl' => 'Filipino',
                            );
                            $tts_lang_display = isset($tts_language_names[$selected_language]) ? $tts_language_names[$selected_language] : strtoupper($selected_language);
                            ?>
                            <p id="mementor-tts-voice-language"><?php echo esc_html($tts_lang_display); ?></p>
                            <p id="mementor-tts-voice-details">
                                <?php esc_html_e('Voice ID:', 'text-to-speech-tts'); ?>
                                <?php echo esc_html($selected_voice_id ?: $selected_voice); ?>
                            </p>
                        <?php endif; ?>
                    </div>

                    <!-- Right: Voice Change Button and Credits Badge -->
                    <div class="mementor-tts-header-actions">
                        <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-voices')); ?>"
                           class="button mementor-tts-change-voice-btn">
                            <span class="dashicons dashicons-admin-users" aria-hidden="true"></span>
                            <span><?php esc_html_e('Change Voice/Language', 'text-to-speech-tts'); ?></span>
                        </a>
                        <div class="mementor-tts-credits-badge"
                             <?php /* translators: %s: Remaining credit balance formatted with thousands separators. */ ?>
                             title="<?php echo esc_attr(sprintf(__('Credits remaining: %s', 'text-to-speech-tts'), number_format($credits_left))); ?>">
                            <span class="dashicons dashicons-universal-access-alt"></span>
                            <span><?php esc_html_e('Remaining Credits:', 'text-to-speech-tts'); ?> <?php echo esc_html(number_format($credits_left)); ?></span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Model Selector Card -->
            <div class="tts-card tts-card-inset">
                <div class="mementor-tts-model-selector-wrapper">
                    <button type="button" class="mementor-tts-model-section-toggle" aria-expanded="false">
                        <span class="dashicons dashicons-arrow-down-alt2"></span>
                        <span class="toggle-text"><?php esc_html_e('Model Selection', 'text-to-speech-tts'); ?></span>
                    </button>
                    <div class="mementor-tts-model-selector-section collapsed">
                        <!-- Left Card: Model Information -->
                        <div class="mementor-tts-model-info-card">
                        <h3><?php esc_html_e('Available Models', 'text-to-speech-tts'); ?></h3>
                        <div class="mementor-tts-model-info-list">
                            <div class="mementor-tts-model-info-item">
                                <div class="mementor-tts-model-info-header">
                                    <strong><?php esc_html_e('Eleven Flash v2.5', 'text-to-speech-tts'); ?></strong>
                                    <span class="mementor-tts-model-badge free"><?php esc_html_e('Free', 'text-to-speech-tts'); ?></span>
                                </div>
                                <p><?php esc_html_e('Fast speech synthesis with support for up to 40,000 characters. Ideal for quick audio generation.', 'text-to-speech-tts'); ?></p>
                            </div>

                            <div class="mementor-tts-model-info-item">
                                <div class="mementor-tts-model-info-header">
                                    <strong><?php esc_html_e('Eleven Turbo v2.5', 'text-to-speech-tts'); ?></strong>
                                    <span class="mementor-tts-model-badge pro"><?php esc_html_e('PRO', 'text-to-speech-tts'); ?></span>
                                </div>
                                <p><?php esc_html_e('Our fastest model with support for 40,000 characters. Optimized for speed without compromising quality.', 'text-to-speech-tts'); ?></p>
                            </div>

                            <div class="mementor-tts-model-info-item">
                                <div class="mementor-tts-model-info-header">
                                    <strong><?php esc_html_e('Eleven Multilingual v2', 'text-to-speech-tts'); ?></strong>
                                    <span class="mementor-tts-model-badge pro"><?php esc_html_e('PRO', 'text-to-speech-tts'); ?></span>
                                </div>
                                <p><?php esc_html_e('Supports 28 languages with up to 10,000 characters. Perfect for multilingual content.', 'text-to-speech-tts'); ?></p>
                            </div>

                            <div class="mementor-tts-model-info-item">
                                <div class="mementor-tts-model-info-header">
                                    <strong><?php esc_html_e('Eleven v3', 'text-to-speech-tts'); ?></strong>
                                    <span class="mementor-tts-model-badge pro"><?php esc_html_e('PRO', 'text-to-speech-tts'); ?></span>
                                </div>
                                <p><?php esc_html_e('Advanced model with 70+ languages and SSML support for emotional expressions and sound effects. Limited to 3,000 characters.', 'text-to-speech-tts'); ?></p>
                            </div>
                        </div>
                    </div>

                    <!-- Right Card: Model Selector -->
                    <div class="mementor-tts-model-selector-card">
                        <h3><?php esc_html_e('Select Model', 'text-to-speech-tts'); ?></h3>
                        <div class="mementor-tts-model-toggles">
                            <button type="button" class="mementor-tts-model-toggle <?php echo $selected_model === 'eleven_flash_v2_5' ? 'active' : ''; ?>"
                                    data-model="eleven_flash_v2_5" data-chars="40000">
                                <span class="mementor-tts-model-name"><?php esc_html_e('Eleven Flash v2.5', 'text-to-speech-tts'); ?></span>
                                <span class="mementor-tts-model-meta"><?php esc_html_e('40,000 characters', 'text-to-speech-tts'); ?></span>
                            </button>

                            <?php if ($is_pro_active): ?>
                            <button type="button" class="mementor-tts-model-toggle <?php echo $selected_model === 'eleven_turbo_v2_5' ? 'active' : ''; ?>"
                                    data-model="eleven_turbo_v2_5" data-chars="40000">
                                <span class="mementor-tts-model-name"><?php esc_html_e('Eleven Turbo v2.5', 'text-to-speech-tts'); ?></span>
                                <span class="mementor-tts-model-meta"><?php esc_html_e('40,000 characters', 'text-to-speech-tts'); ?></span>
                            </button>

                            <button type="button" class="mementor-tts-model-toggle <?php echo $selected_model === 'eleven_multilingual_v2' ? 'active' : ''; ?>"
                                    data-model="eleven_multilingual_v2" data-chars="10000">
                                <span class="mementor-tts-model-name"><?php esc_html_e('Eleven Multilingual v2', 'text-to-speech-tts'); ?></span>
                                <span class="mementor-tts-model-meta"><?php esc_html_e('10,000 characters', 'text-to-speech-tts'); ?></span>
                            </button>

                            <button type="button" class="mementor-tts-model-toggle <?php echo $selected_model === 'eleven_v3' ? 'active' : ''; ?>"
                                    data-model="eleven_v3" data-chars="3000">
                                <span class="mementor-tts-model-name"><?php esc_html_e('Eleven v3', 'text-to-speech-tts'); ?></span>
                                <span class="mementor-tts-model-meta"><?php esc_html_e('3,000 characters', 'text-to-speech-tts'); ?></span>
                            </button>
                            <?php else: ?>
                            <button type="button" class="mementor-tts-model-toggle mementor-tts-model-disabled"
                                    disabled title="<?php esc_attr_e('PRO Feature', 'text-to-speech-tts'); ?>">
                                <span class="mementor-tts-model-name"><?php esc_html_e('Eleven Turbo v2.5', 'text-to-speech-tts'); ?></span>
                                <span class="mementor-tts-model-meta"><?php esc_html_e('40,000 characters', 'text-to-speech-tts'); ?></span>
                                <span class="tts-pro-badge"><?php esc_html_e('PRO', 'text-to-speech-tts'); ?></span>
                            </button>

                            <button type="button" class="mementor-tts-model-toggle mementor-tts-model-disabled"
                                    disabled title="<?php esc_attr_e('PRO Feature', 'text-to-speech-tts'); ?>">
                                <span class="mementor-tts-model-name"><?php esc_html_e('Eleven Multilingual v2', 'text-to-speech-tts'); ?></span>
                                <span class="mementor-tts-model-meta"><?php esc_html_e('10,000 characters', 'text-to-speech-tts'); ?></span>
                                <span class="tts-pro-badge"><?php esc_html_e('PRO', 'text-to-speech-tts'); ?></span>
                            </button>

                            <button type="button" class="mementor-tts-model-toggle mementor-tts-model-disabled"
                                    disabled title="<?php esc_attr_e('PRO Feature', 'text-to-speech-tts'); ?>">
                                <span class="mementor-tts-model-name"><?php esc_html_e('Eleven v3', 'text-to-speech-tts'); ?></span>
                                <span class="mementor-tts-model-meta"><?php esc_html_e('3,000 characters', 'text-to-speech-tts'); ?></span>
                                <span class="tts-pro-badge"><?php esc_html_e('PRO', 'text-to-speech-tts'); ?></span>
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                    </div>
                </div>
            </div>

            <!-- Text Input Card -->
            <div class="tts-card tts-card-inset">
                <div class="tts-card-header tts-card-header-inline">
                    <h3 class="tts-card-title"><?php esc_html_e('Text Input', 'text-to-speech-tts'); ?></h3>
                    <p class="tts-card-desc"><?php esc_html_e('Enter text to convert to speech.', 'text-to-speech-tts'); ?></p>
                </div>

                <!-- Main Content Area with textarea and side panel -->
                <div class="mementor-tts-flex-container<?php echo $is_pro_active ? ' mementor-tts-pro-active' : ''; ?>">
                    <!-- Left Column: Text Input Area -->
                    <div class="mementor-tts-input-column">
                        <div class="mementor-tts-text-input-container">
                            <!-- SSML Toolbar -->
                            <div class="mementor-tts-ssml-toolbar" role="toolbar" aria-label="<?php esc_attr_e('SSML Formatting Options', 'text-to-speech-tts'); ?>">
                                <div class="mementor-tts-ssml-toolbar-left">
                                    <button type="button" class="mementor-tts-ssml-btn" data-ssml="break" title="<?php esc_attr_e('Pause/Break', 'text-to-speech-tts'); ?>">
                                        <span class="dashicons dashicons-clock" aria-hidden="true"></span>
                                        <?php esc_html_e('Pause/Break', 'text-to-speech-tts'); ?>
                                    </button>

                                    <span class="tts-ssml-btn-wrap" data-tooltip="<?php echo $is_pro_active ? esc_attr__('Add emotional expressions (click for examples)', 'text-to-speech-tts') : esc_attr__('Emotional expressions — requires Eleven v3 model', 'text-to-speech-tts'); ?>">
                                    <button type="button" class="mementor-tts-ssml-btn<?php echo $is_pro_active ? '' : ' mementor-tts-pro-feature'; ?>" data-ssml="emotional" <?php echo $is_pro_active ? '' : 'disabled'; ?>>
                                        <span class="dashicons dashicons-smiley" aria-hidden="true"></span>
                                        <?php esc_html_e('Expressions', 'text-to-speech-tts'); ?>
                                        <?php if (!$is_pro_active): ?>
                                        <span class="tts-pro-badge"><?php esc_html_e('PRO', 'text-to-speech-tts'); ?></span>
                                        <?php endif; ?>
                                    </button>
                                    </span>

                                    <span class="tts-ssml-btn-wrap" data-tooltip="<?php echo $is_pro_active ? esc_attr__('Add sound effects (click for examples)', 'text-to-speech-tts') : esc_attr__('Sound effects — requires Eleven v3 model', 'text-to-speech-tts'); ?>">
                                    <button type="button" class="mementor-tts-ssml-btn<?php echo $is_pro_active ? '' : ' mementor-tts-pro-feature'; ?>" data-ssml="sound-effects" <?php echo $is_pro_active ? '' : 'disabled'; ?>>
                                        <span class="dashicons dashicons-controls-volumeon" aria-hidden="true"></span>
                                        <?php esc_html_e('Effects', 'text-to-speech-tts'); ?>
                                        <?php if (!$is_pro_active): ?>
                                        <span class="tts-pro-badge"><?php esc_html_e('PRO', 'text-to-speech-tts'); ?></span>
                                        <?php endif; ?>
                                    </button>
                                    </span>

                                    <span class="tts-ssml-btn-wrap" data-tooltip="<?php echo $is_pro_active ? esc_attr__('Add special effects (click for examples)', 'text-to-speech-tts') : esc_attr__('Special audio effects — requires Eleven v3 model', 'text-to-speech-tts'); ?>">
                                    <button type="button" class="mementor-tts-ssml-btn<?php echo $is_pro_active ? '' : ' mementor-tts-pro-feature'; ?>" data-ssml="unique-special" <?php echo $is_pro_active ? '' : 'disabled'; ?>>
                                        <span class="dashicons dashicons-image-filter" aria-hidden="true"></span>
                                        <?php esc_html_e('Special', 'text-to-speech-tts'); ?>
                                        <?php if (!$is_pro_active): ?>
                                        <span class="tts-pro-badge"><?php esc_html_e('PRO', 'text-to-speech-tts'); ?></span>
                                        <?php endif; ?>
                                    </button>
                                    </span>
                                </div>

                            </div>

                            <!-- Text Area -->
                            <div class="mementor-tts-text-header">
                                <label for="mementor-tts-text" class="textarea-label">
                                    <?php esc_html_e('Enter your text', 'text-to-speech-tts'); ?>
                                </label>
                                <button type="button" id="mementor-tts-reset-btn" class="button button-secondary">
                                    <span class="dashicons dashicons-update" aria-hidden="true"></span>
                                    <span><?php esc_html_e('Reset to Default', 'text-to-speech-tts'); ?></span>
                                </button>
                            </div>
                            <div class="mementor-tts-text-container">
                                <textarea id="mementor-tts-text"
                                          name="mementor_tts_text"
                                          maxlength="<?php echo esc_attr($char_limit); ?>"
                                          data-default-text="<?php echo esc_attr($default_text); ?>"
                                          aria-describedby="mementor-tts-char-counter"><?php echo esc_textarea($default_text); ?></textarea>
                                <div class="mementor-tts-char-counter" id="mementor-tts-char-counter">
                                    <span id="mementor-tts-current-chars">0</span> /
                                    <span id="mementor-tts-max-chars"><?php echo esc_html($char_limit); ?></span>
                                    <?php esc_html_e('characters', 'text-to-speech-tts'); ?>
                                </div>
                            </div>

                            <?php
                            // Get custom intro/outro text to check if they exist
                            $custom_intro = get_option('mementor_tts_text_before', '');
                            $custom_outro = get_option('mementor_tts_text_after', '');
                            $has_custom_content = !empty($custom_intro) || !empty($custom_outro);
                            ?>
                            <?php if ($has_custom_content): ?>
                            <div class="mementor-tts-ssml-toolbar-right">
                                <?php if (!empty($custom_intro)): ?>
                                <?php /* translators: %s: First few words of the custom intro text that will be prepended to the generated audio. */ ?>
                                <label class="mementor-tts-toolbar-checkbox" title="<?php echo esc_attr(sprintf(__('Include custom introduction: "%s"', 'text-to-speech-tts'), wp_trim_words($custom_intro, 10))); ?>">
                                    <input type="checkbox" id="mementor-tts-include-intro">
                                    <span><?php esc_html_e('Include Custom Intro', 'text-to-speech-tts'); ?></span>
                                </label>
                                <?php endif; ?>
                                <?php if (!empty($custom_outro)): ?>
                                <?php /* translators: %s: First few words of the custom outro text that will be appended to the generated audio. */ ?>
                                <label class="mementor-tts-toolbar-checkbox" title="<?php echo esc_attr(sprintf(__('Include custom outro: "%s"', 'text-to-speech-tts'), wp_trim_words($custom_outro, 10))); ?>">
                                    <input type="checkbox" id="mementor-tts-include-outro">
                                    <span><?php esc_html_e('Include Custom Outro', 'text-to-speech-tts'); ?></span>
                                </label>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Right Column: Side Panel -->
                    <div class="mementor-tts-controls-column">
                        <!-- PRO Upsell Box -->
                        <?php if (!$is_pro_active) : ?>
                        <div class="mementor-tts-pro-upsell">
                            <h3>
                                <span class="dashicons dashicons-star-filled" aria-hidden="true"></span>
                                <?php esc_html_e('Did You Know?', 'text-to-speech-tts'); ?>
                            </h3>
                            <ul>
                                <li><?php esc_html_e('With the PRO version, you can use this TTS-generator to generate ultra-high quality audio—up to 40,000 characters with Flash v2.5 or Turbo v2.5, or 10,000 with Multilingual v2!', 'text-to-speech-tts'); ?></li>
                                <li><?php esc_html_e('You can also add natural-sounding pauses to your voiceovers with ease. Just place your cursor where you want a break, click the "Pause/Break" button, and voilà—your audio flows like a pro.', 'text-to-speech-tts'); ?></li>
                            </ul>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Bottom Action Buttons -->
                <div class="mementor-tts-action-row">
                    <div class="mementor-tts-action-buttons">
                        <button type="button" id="mementor-tts-play-btn" class="button button-primary">
                            <span class="dashicons dashicons-controls-play" aria-hidden="true"></span>
                            <span class="button-text"><?php esc_html_e('Play Demo', 'text-to-speech-tts'); ?></span>
                        </button>
                        <button type="button" id="mementor-tts-download-btn" class="button" disabled>
                            <span class="dashicons dashicons-download" aria-hidden="true"></span>
                            <span class="button-text"><?php esc_html_e('Download Audio', 'text-to-speech-tts'); ?></span>
                        </button>
                        <button type="button" id="mementor-tts-copy-shortcode-btn" class="button">
                            <span class="dashicons dashicons-shortcode" aria-hidden="true"></span>
                            <span class="button-text"><?php esc_html_e('Copy Shortcode', 'text-to-speech-tts'); ?></span>
                        </button>
                    </div>
                    <!-- Inline error display (shown directly in generator area) -->
                    <div id="mementor-tts-inline-error" style="display:none; margin-top: 10px; padding: 10px 15px; background: rgb(237, 0, 22); border: 1px solid rgb(245, 198, 203); color: rgb(255, 255, 255); border-radius: 4px; font-size: 13px;"></div>
                </div>
            </div>

            <!-- Shortcode Card -->
            <div class="tts-card tts-card-inset">
                <div class="tts-card-header tts-card-header-inline">
                    <h3 class="tts-card-title"><?php esc_html_e('Shortcode', 'text-to-speech-tts'); ?></h3>
                    <p class="tts-card-desc"><?php esc_html_e('Customize and copy the shortcode for your content.', 'text-to-speech-tts'); ?></p>
                </div>

                <!-- Shortcode Customizer -->
                <div class="mementor-tts-shortcode-customizer">
                    <h3><?php esc_html_e('Shortcode Customizer:', 'text-to-speech-tts'); ?></h3>
                    <div class="mementor-tts-customizer-options">
                        <label class="mementor-tts-customizer-option" title="<?php esc_attr_e('Add a custom label above the player. Edit the shortcode to customize the label text.', 'text-to-speech-tts'); ?>">
                            <input type="checkbox" id="mementor-tts-option-label" data-param="label" data-value="Your Label Text Here">
                            <span><?php esc_html_e('Label', 'text-to-speech-tts'); ?></span>
                        </label>
                        <label class="mementor-tts-customizer-option" title="<?php esc_attr_e('Whether to show the time display in the player.', 'text-to-speech-tts'); ?>">
                            <input type="checkbox" id="mementor-tts-option-time-display" data-param="time_display" data-value="yes">
                            <span><?php esc_html_e('Time Display', 'text-to-speech-tts'); ?></span>
                        </label>
                        <label class="mementor-tts-customizer-option" title="<?php esc_attr_e('Whether to show the speed control in the player.', 'text-to-speech-tts'); ?>">
                            <input type="checkbox" id="mementor-tts-option-speed-control" data-param="speed_control" data-value="yes">
                            <span><?php esc_html_e('Speed', 'text-to-speech-tts'); ?></span>
                        </label>
                        <label class="mementor-tts-customizer-option" title="<?php esc_attr_e('Whether to show the volume control in the player.', 'text-to-speech-tts'); ?>">
                            <input type="checkbox" id="mementor-tts-option-volume-control" data-param="volume_control" data-value="yes">
                            <span><?php esc_html_e('Volume', 'text-to-speech-tts'); ?></span>
                        </label>
                        <label class="mementor-tts-customizer-option" title="<?php esc_attr_e('Whether to show the download icon in the player.', 'text-to-speech-tts'); ?>">
                            <input type="checkbox" id="mementor-tts-option-download" data-param="download" data-value="yes">
                            <span><?php esc_html_e('Download', 'text-to-speech-tts'); ?></span>
                        </label>
                        <label class="mementor-tts-customizer-option" title="<?php esc_attr_e('Whether to automatically play the audio when the page loads.', 'text-to-speech-tts'); ?>">
                            <input type="checkbox" id="mementor-tts-option-autoplay" data-param="autoplay" data-value="yes">
                            <span><?php esc_html_e('Autoplay', 'text-to-speech-tts'); ?></span>
                        </label>
                        <label class="mementor-tts-customizer-option" title="<?php esc_attr_e('Whether to loop the audio.', 'text-to-speech-tts'); ?>">
                            <input type="checkbox" id="mementor-tts-option-loop" data-param="loop" data-value="yes">
                            <span><?php esc_html_e('Loop', 'text-to-speech-tts'); ?></span>
                        </label>
                        <label class="mementor-tts-customizer-option" title="<?php esc_attr_e('Whether to show the information icon in the player.', 'text-to-speech-tts'); ?>">
                            <input type="checkbox" id="mementor-tts-option-information" data-param="information" data-value="yes">
                            <span><?php esc_html_e('Information', 'text-to-speech-tts'); ?></span>
                        </label>
                    </div>
                </div>

                <!-- Permanent Shortcode Display -->
                <div class="mementor-tts-shortcode-display-permanent">
                    <div class="mementor-tts-shortcode-label"><?php esc_html_e('Shortcode:', 'text-to-speech-tts'); ?></div>
                    <pre id="mementor-tts-shortcode-realtime">[mementor-tts]</pre>
                </div>
            </div>

            <!-- History Card -->
            <div class="tts-card tts-card-inset">
                <div class="tts-card-header tts-card-header-inline">
                    <h3 class="tts-card-title"><?php esc_html_e('Recent Generations', 'text-to-speech-tts'); ?></h3>
                    <button type="button" id="mementor-tts-refresh-history" class="tts-btn"><?php esc_html_e('Refresh', 'text-to-speech-tts'); ?></button>
                </div>
                <div class="mementor-tts-history-section">
                    <div class="mementor-tts-history-header" id="mementor-tts-history-toggle">
                        <h3>
                            <span class="mementor-tts-history-count" id="mementor-tts-history-count">(0)</span>
                            <span class="dashicons dashicons-arrow-down-alt2 mementor-tts-history-arrow" aria-hidden="true"></span>
                        </h3>
                    </div>
                    <div class="mementor-tts-history-content" id="mementor-tts-history-content" style="display: none;">
                        <div class="mementor-tts-history-empty" id="mementor-tts-history-empty">
                            <p><?php esc_html_e('No recent generations yet. Generate some audio to see your history here!', 'text-to-speech-tts'); ?></p>
                        </div>
                        <div class="mementor-tts-history-list" id="mementor-tts-history-list">
                            <!-- History items will be populated by JavaScript -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- Hidden shortcode field for clipboard copying -->
            <input type="hidden" id="mementor-tts-shortcode" value="">
            <!-- Hidden voice ID field -->
            <?php
            // Use custom voice ID if available, otherwise use selected voice
            $voice_id_to_use = !empty($custom_voice_id) ? $custom_voice_id : $selected_voice_id;
            ?>
            <input type="hidden" id="mementor-tts-voice-id" value="<?php echo esc_attr($voice_id_to_use); ?>">

<?php include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-close.php'; ?>

<!-- Hidden tooltip contents -->
<!-- Hidden tooltip content for Emotional Expressions -->
<div id="emotional-expressions-tooltip" style="display: none;">
    <?php if (!$is_pro_active && $selected_model !== 'eleven_v3'): ?>
        <div style="background: #fff8e5; border: 1px solid #ffcd00; border-radius: 6px; padding: 20px; text-align: center;">
            <span class="dashicons dashicons-info" style="color: #996800; font-size: 32px; width: 32px; height: 32px; display: block; margin: 0 auto 15px;"></span>
            <p style="font-size: 16px; margin: 0 0 10px 0; color: #1d2327;"><strong><?php esc_html_e('Emotional Expressions require the Eleven v3 model', 'text-to-speech-tts'); ?></strong></p>
            <?php /* translators: %s: Name of the ElevenLabs TTS model currently selected, wrapped in <strong> tags. */ ?>
            <p style="margin: 0 0 15px 0; color: #50575e;"><?php echo sprintf(esc_html__('Your current model is %s.', 'text-to-speech-tts'), '<strong>' . esc_html($selected_model) . '</strong>'); ?></p>
            <p style="margin: 15px 0 0 0; color: #50575e;"><?php esc_html_e('Change Model in "Model Selection" Above', 'text-to-speech-tts'); ?></p>
        </div>
    <?php else: ?>
        <p><strong><?php esc_html_e('Add emotional expressions to your audio with SSML tags like:', 'text-to-speech-tts'); ?></strong></p>
        <p><i>[alarmed], [cracking up], [laughs], [laughs harder], [starts laughing], [stifling laughter], [giggling], [sheepishly], [desperately], [wheezing], [whispers], [sighs], [exhales], [sarcastic], [frustrated], [curious], [excited], [crying], [snorts], [mischievously], [deadpan]</i></p>
        <p><strong><?php esc_html_e('Example:', 'text-to-speech-tts'); ?></strong><br><span class="ssml-code">[excited]</span> I never knew this text to speech plugin from Mementor could be so darn... yes amazing! <span class="ssml-code">[laughing] [clapping]</span></p>
        <div class="mementor-tts-tooltip-footer">
            <button type="button" class="button mementor-tts-tooltip-play-btn" data-example="emotional">
                <span class="dashicons dashicons-controls-play"></span>
                <?php esc_html_e('Play Example', 'text-to-speech-tts'); ?>
            </button>
        </div>
    <?php endif; ?>
</div>

<!-- Hidden tooltip content for Sound Effects -->
<div id="sound-effects-tooltip" style="display: none;">
    <?php if (!$is_pro_active && $selected_model !== 'eleven_v3'): ?>
        <div style="background: #fff8e5; border: 1px solid #ffcd00; border-radius: 6px; padding: 20px; text-align: center;">
            <span class="dashicons dashicons-info" style="color: #996800; font-size: 32px; width: 32px; height: 32px; display: block; margin: 0 auto 15px;"></span>
            <p style="font-size: 16px; margin: 0 0 10px 0; color: #1d2327;"><strong><?php esc_html_e('Sound Effects require the Eleven v3 model', 'text-to-speech-tts'); ?></strong></p>
            <?php /* translators: %s: Name of the ElevenLabs TTS model currently selected, wrapped in <strong> tags. */ ?>
            <p style="margin: 0 0 15px 0; color: #50575e;"><?php echo sprintf(esc_html__('Your current model is %s.', 'text-to-speech-tts'), '<strong>' . esc_html($selected_model) . '</strong>'); ?></p>
            <p style="margin: 15px 0 0 0; color: #50575e;"><?php esc_html_e('Change Model in "Model Selection" Above', 'text-to-speech-tts'); ?></p>
        </div>
    <?php else: ?>
        <p><strong><?php esc_html_e('Add environmental sounds and effects:', 'text-to-speech-tts'); ?></strong></p>
        <p><i>[gunshot], [applause], [clapping], [explosion], [swallows], [gulps]</i></p>
        <p><strong><?php esc_html_e('Example:', 'text-to-speech-tts'); ?></strong><br><span class="ssml-code">[applause]</span> <?php esc_html_e('Thank you all for coming tonight!', 'text-to-speech-tts'); ?> <span class="ssml-code">[gunshot]</span> <?php esc_html_e('What on earth was that, was it you Puff?', 'text-to-speech-tts'); ?></p>
        <div class="mementor-tts-tooltip-footer">
            <button type="button" class="button mementor-tts-tooltip-play-btn" data-example="sound-effects">
                <span class="dashicons dashicons-controls-play"></span>
                <?php esc_html_e('Play Example', 'text-to-speech-tts'); ?>
            </button>
        </div>
    <?php endif; ?>
</div>

<!-- Hidden tooltip content for Unique and Special -->
<div id="unique-special-tooltip" style="display: none;">
    <?php if (!$is_pro_active && $selected_model !== 'eleven_v3'): ?>
        <div style="background: #fff8e5; border: 1px solid #ffcd00; border-radius: 6px; padding: 20px; text-align: center;">
            <span class="dashicons dashicons-info" style="color: #996800; font-size: 32px; width: 32px; height: 32px; display: block; margin: 0 auto 15px;"></span>
            <p style="font-size: 16px; margin: 0 0 10px 0; color: #1d2327;"><strong><?php esc_html_e('Unique and Special effects require the Eleven v3 model', 'text-to-speech-tts'); ?></strong></p>
            <?php /* translators: %s: Name of the ElevenLabs TTS model currently selected, wrapped in <strong> tags. */ ?>
            <p style="margin: 0 0 15px 0; color: #50575e;"><?php echo sprintf(esc_html__('Your current model is %s.', 'text-to-speech-tts'), '<strong>' . esc_html($selected_model) . '</strong>'); ?></p>
            <p style="margin: 15px 0 0 0; color: #50575e;"><?php esc_html_e('Change Model in "Model Selection" Above', 'text-to-speech-tts'); ?></p>
        </div>
    <?php else: ?>
        <p><strong><?php esc_html_e('Experimental tags for creative applications:', 'text-to-speech-tts'); ?></strong></p>
        <p>[strong X accent] (replace X with desired accent), [sings], [woo], [fart]</p>
        <p><strong><?php esc_html_e('Example:', 'text-to-speech-tts'); ?></strong><br>A loving couple in an elevator. <span class="ssml-code">[fart] &lt;break time="0.5s" /&gt; [curious]</span> "Oh my god, was that you?" …If it was, I'd be very proud... <span class="ssml-code">[laughs harder]</span></p>
        <div class="mementor-tts-tooltip-footer">
            <button type="button" class="button mementor-tts-tooltip-play-btn" data-example="unique-special">
                <span class="dashicons dashicons-controls-play"></span>
                <?php esc_html_e('Play Example', 'text-to-speech-tts'); ?>
            </button>
        </div>
    <?php endif; ?>
</div>

<!-- Add inline script to display credits properly and initialize tooltips -->
<script type="text/javascript">
jQuery(document).ready(function($) {
    // Handle model section collapse/expand
    $('.mementor-tts-model-section-toggle').on('click', function() {
        var $toggle = $(this);
        var $section = $('.mementor-tts-model-selector-section');
        var isExpanded = $toggle.attr('aria-expanded') === 'true';

        if (isExpanded) {
            $toggle.attr('aria-expanded', 'false');
            $section.addClass('collapsed');
        } else {
            $toggle.attr('aria-expanded', 'true');
            $section.removeClass('collapsed');
        }
    });

    // Handle model toggle clicks
    $('.mementor-tts-model-toggle:not(.mementor-tts-model-disabled)').on('click', function() {
        var $this = $(this);
        var selectedModel = $this.data('model');
        var charLimit = $this.data('chars');
        var isPro = <?php echo $is_pro_active ? 'true' : 'false'; ?>;

        // Calculate actual char limit based on PRO status
        if (!isPro) {
            charLimit = 2000;
        }

        // Update active state
        $('.mementor-tts-model-toggle').removeClass('active');
        $this.addClass('active');

        // Update textarea maxlength
        $('#mementor-tts-text').attr('maxlength', charLimit);

        // Update character counter display
        $('#mementor-tts-max-chars').text(charLimit.toLocaleString());

        // Save model selection via AJAX
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'mementor_tts_save_model',
                nonce: '<?php echo wp_create_nonce('mementor_tts_nonce'); ?>',
                model: selectedModel
            },
            success: function(response) {
                if (response.success) {
                    // Reload page after 1 second to update tooltips
                    setTimeout(function() {
                        location.reload();
                    }, 1000);
                }
            }
        });
    });

    // Force update the credits display
    var totalCredits = <?php echo intval($credits_left); ?>;

    // Update the credits badge if values are available
    if (totalCredits > 0) {
        $('.mementor-tts-credits-badge span:last').text('<?php esc_html_e('Remaining Credits:', 'text-to-speech-tts'); ?> ' + totalCredits.toLocaleString());
    }

    // Tooltips are auto-initialized by mementor-tts-tooltip.js on document ready

    // Refresh history — remove entries where audio file no longer exists (404)
    $('#mementor-tts-refresh-history').on('click', function(e) {
        e.stopPropagation();
        var $btn = $(this);
        $btn.prop('disabled', true).text('<?php echo esc_js(__('Checking...', 'text-to-speech-tts')); ?>');

        var raw = localStorage.getItem('mementor_tts_generator_history');
        if (!raw) {
            $btn.prop('disabled', false).text('<?php echo esc_js(__('Refresh', 'text-to-speech-tts')); ?>');
            return;
        }

        var history = JSON.parse(raw);
        var checks = [];
        var keep = [];

        history.forEach(function(item) {
            if (item.audioUrl) {
                checks.push(
                    $.ajax({ url: item.audioUrl, type: 'HEAD' })
                        .then(function() { keep.push(item); })
                        .catch(function() { /* 404 — skip */ })
                );
            }
        });

        $.when.apply($, checks).always(function() {
            localStorage.setItem('mementor_tts_generator_history', JSON.stringify(keep));
            var removed = history.length - keep.length;

            // Re-render history list
            $('#mementor-tts-history-list').empty();
            if (keep.length === 0) {
                $('#mementor-tts-history-empty').show();
            } else {
                $('#mementor-tts-history-empty').hide();
            }
            $('#mementor-tts-history-count').text('(' + keep.length + ')');

            $btn.prop('disabled', false).text('<?php echo esc_js(__('Refresh', 'text-to-speech-tts')); ?>');

            if (typeof mementorTTSShowNotification === 'function') {
                if (removed > 0) {
                    mementorTTSShowNotification(removed + ' <?php echo esc_js(__('stale entries removed.', 'text-to-speech-tts')); ?>', 'success');
                } else {
                    mementorTTSShowNotification('<?php echo esc_js(__('All entries are valid.', 'text-to-speech-tts')); ?>', 'success');
                }
            }

            // Reload history display if the generator has a render method
            if (typeof window.ttsGeneratorHistory !== 'undefined' && typeof window.ttsGeneratorHistory.render === 'function') {
                window.ttsGeneratorHistory.render();
            } else {
                location.reload();
            }
        });
    });

    // Handle Play Example button clicks in tooltips
    $(document).on('click', '.mementor-tts-tooltip-play-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();

        var $button = $(this);
        var exampleType = $button.data('example');
        var audioFile = '';

        console.log('Play Example clicked for:', exampleType);

        // Map example type to audio file
        switch(exampleType) {
            case 'emotional':
                audioFile = '<?php echo esc_url(MEMENTOR_TTS_PLUGIN_URL . 'admin/audio/tooltip-emotions.mp3'); ?>';
                break;
            case 'sound-effects':
                audioFile = '<?php echo esc_url(MEMENTOR_TTS_PLUGIN_URL . 'admin/audio/tooltip-effects.mp3'); ?>';
                break;
            case 'unique-special':
                audioFile = '<?php echo esc_url(MEMENTOR_TTS_PLUGIN_URL . 'admin/audio/tooltip-elevator.mp3'); ?>';
                break;
        }

        console.log('Audio file to play:', audioFile);

        if (audioFile) {
            // Check if audio is already playing
            var existingAudio = $button.data('audio');
            if (existingAudio) {
                // Stop and reset if already playing
                existingAudio.pause();
                existingAudio.currentTime = 0;
                $button.data('audio', null);

                // Reset button text and icon
                $button.html('<span class="dashicons dashicons-controls-play"></span> <?php esc_html_e('Play Example', 'text-to-speech-tts'); ?>');
                return;
            }

            // Create new audio element
            var audio = new Audio(audioFile);
            $button.data('audio', audio);

            // Update button to show loading state
            $button.html('<span class="dashicons dashicons-update spinning"></span> <?php esc_html_e('Loading...', 'text-to-speech-tts'); ?>');
            $button.prop('disabled', true);

            // Handle audio events
            audio.addEventListener('canplay', function() {
                $button.prop('disabled', false);
                $button.html('<span class="dashicons dashicons-controls-pause"></span> <?php esc_html_e('Pause', 'text-to-speech-tts'); ?>');
                audio.play();
            });

            audio.addEventListener('ended', function() {
                $button.html('<span class="dashicons dashicons-controls-play"></span> <?php esc_html_e('Play Example', 'text-to-speech-tts'); ?>');
                $button.data('audio', null);
            });

            audio.addEventListener('error', function() {
                console.error('Error loading audio:', audioFile);
                $button.prop('disabled', false);
                $button.html('<span class="dashicons dashicons-controls-play"></span> <?php esc_html_e('Play Example', 'text-to-speech-tts'); ?>');
                alert('<?php esc_html_e('Error loading audio file. Please try again.', 'text-to-speech-tts'); ?>');
            });

            // Load the audio
            audio.load();
        }
    });
});
</script>

<?php
// Enqueue jQuery UI for dialogs
wp_enqueue_script('jquery-ui-dialog');
wp_enqueue_style('wp-jquery-ui-dialog');

// Prepare data for JavaScript
$localized_data = array(
    'ajaxurl' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('mementor_tts_nonce'),
    'is_pro' => $is_pro_active,
    'char_limit' => $char_limit,
    'selected_model' => $selected_model,
    'credits' => $credits_left,
    'voice_id' => $selected_voice_id,
    'plugin_url' => MEMENTOR_TTS_PLUGIN_URL,
    'messages' => array(
        'error_playing' => esc_html__('Error playing audio. Please check the console for details.', 'text-to-speech-tts'),
        'no_audio' => esc_html__('No audio source available', 'text-to-speech-tts'),
        'download_started' => esc_html__('Download started!', 'text-to-speech-tts'),
        'shortcode_copied' => esc_html__('Shortcode copied to clipboard!', 'text-to-speech-tts'),
        'reset_complete' => esc_html__('Reset complete!', 'text-to-speech-tts'),
    ),
    'buttons' => array(
        'generate_audio' => esc_html__('Generate Audio', 'text-to-speech-tts'),
        'play_demo' => esc_html__('Play Demo', 'text-to-speech-tts'),
        'play_generated' => esc_html__('Play Generated Audio', 'text-to-speech-tts'),
        'pause' => esc_html__('Pause', 'text-to-speech-tts'),
        'generating' => esc_html__('Generating...', 'text-to-speech-tts'),
    ),
    'licensePageUrl' => admin_url('admin.php?page=text-to-speech-tts-upgrade'),
);

// Pass the data to JavaScript properly
// Note: This should be done in the enqueue_scripts method of your admin class
// wp_localize_script('mementor-tts-generator', 'mementorTTS', $localized_data);
?>