<?php
/**
 * Player settings page
 *
 * @link       https://mementor.no
 * @since      1.0.0
 *
 * @package    TTSWP
 * @subpackage Mementor_TTS/admin/partials/pages
 */

// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

// 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'),
        esc_html__('Access Denied', 'text-to-speech-tts'),
        array('response' => 403)
    );
}

// Get current settings with proper error handling
$show_time = get_option('mementor_tts_show_time', true);
$show_volume = get_option('mementor_tts_show_volume', true);
$speed_control = get_option('mementor_tts_speed_control', false);
$show_download = get_option('mementor_tts_show_download', false);
$show_info = get_option('mementor_tts_show_info', false);

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

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

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

?>

<?php
$tts_page_title = __('Audio Player Customization', 'text-to-speech-tts');
$tts_topbar_actions = '<button type="button" id="reset-player-settings" class="tts-btn" onclick="if(confirm(\'' . esc_js(__('Are you sure you want to reset all player settings to default values?', 'text-to-speech-tts')) . '\')){ document.getElementById(\'reset-player-form\').submit(); }">' . esc_html__('Reset', 'text-to-speech-tts') . '</button>'
    . '<button type="submit" form="player-settings-form" class="tts-btn tts-btn-primary">' . esc_html__('Save settings', 'text-to-speech-tts') . '</button>';
$tts_requires_connection = true; // gate page behind SaaS connection

include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-open.php';
?>
<?php
    $player_reset_success = isset($_GET['reset']) && $_GET['reset'] === 'success';

    // Settings saved notices are handled by the toast notification in layout-close.php
    include(MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/navigation.php');
?>

    <!-- Player Preview (inline) -->
    <div class="tts-card tts-player-preview-card mementor-tts-sticky-preview" id="tts-inline-preview">
        <div class="tts-card-header tts-preview-header">
            <h3 class="tts-card-title"><?php esc_html_e('Preview', 'text-to-speech-tts'); ?></h3>
            <p class="tts-card-desc tts-live-label"><span class="tts-live-dot"></span><?php esc_html_e('See changes in real time', 'text-to-speech-tts'); ?></p>
        </div>
        <div class="mementor-tts-preview-player-wrapper">
            <div class="mementor-tts-preview-player">
                <?php if (get_option('mementor_tts_show_player_label', false)): ?>
                <div id="preview-player-label" class="mementor-tts-player-label text-<?php echo esc_attr(get_option('mementor_tts_player_label_position', 'left')); ?>">
                    <?php echo esc_html(get_option('mementor_tts_player_label', 'Write Your Own Label Text Here:')); ?>
                </div>
                <?php endif; ?>
                <div class="mementor-tts-player">
                    <audio preload="auto">
                        <source src="<?php echo esc_url(MEMENTOR_TTS_PLUGIN_URL . 'admin/audio/player-settings.mp3'); ?>" type="audio/mpeg">
                        <?php esc_html_e('Your browser does not support the audio element.', 'text-to-speech-tts'); ?>
                    </audio>
                    <div class="mementor-tts-custom-controls" data-player-initialized="false" data-show-play-bg="<?php echo esc_attr(get_option('mementor_tts_show_play_bg', true) ? 'true' : 'false'); ?>">
                        <button class="mementor-tts-play-button">
                            <span class="dashicons dashicons-controls-play mementor-dashicons mementor-dashicons-controls-play"></span>
                        </button>
                        <span class="mementor-tts-time-display" <?php echo !$show_time ? 'style="display:none;"' : ''; ?>>0:00</span>
                        <?php if ( get_option('mementor_tts_progress_type', 'linear') === 'waveform_progress' && $is_pro_active ) : ?>
                        <div class="mementor-tts-progress-container mementor-tts-waveform" data-progress-type="waveform_progress" data-post-id="0"></div>
                        <?php else : ?>
                        <div class="mementor-tts-progress-container">
                            <div class="mementor-tts-progress-bar"></div>
                        </div>
                        <?php endif; ?>
                        <span class="mementor-tts-duration-display" <?php echo !$show_time ? 'style="display:none;"' : ''; ?>>0:00</span>
                        <button class="mementor-tts-volume-button" <?php echo !$show_volume ? 'style="display:none;"' : ''; ?>>
                            <span class="dashicons dashicons-controls-volumeon mementor-dashicons mementor-dashicons-controls-volumeon"></span>
                        </button>
                        <button class="mementor-tts-speed-button" <?php echo !$speed_control ? 'style="display:none;"' : ''; ?>>1.0x</button>
                        <a href="#" class="mementor-tts-download-button" <?php echo !$show_download ? 'style="display:none;"' : ''; ?>>
                            <span class="dashicons dashicons-download mementor-dashicons mementor-dashicons-download"></span>
                        </a>
                        <button type="button" class="mementor-tts-info-button" <?php echo !$show_info ? 'style="display:none;"' : ''; ?>>
                            <span class="dashicons dashicons-info mementor-dashicons mementor-dashicons-info"></span>
                        </button>
                    </div>
                </div>
            <?php if ($show_info): ?>
                <div class="mementor-tts-info-popup">
                    <p><?php
                    $tts_link_url = __('https://mementor.no/en/wordpress-plugins/text-to-speech/', 'text-to-speech-tts');
                    $tts_link_text = __('Text to Speech for WordPress plugin', 'text-to-speech-tts');
                    $elevenlabs_link_text = __('ElevenLabs', 'text-to-speech-tts');
                    $info_text = sprintf(
                        /* translators: %1$s: Text to Speech plugin link (bold), %2$s: ElevenLabs link (bold) */
                        __('Generated with Mementor\'s %1$s, using %2$s technology.', 'text-to-speech-tts'),
                        '<a href="' . esc_url($tts_link_url) . '" target="_blank" rel="noopener"><strong>' . esc_html($tts_link_text) . '</strong></a>',
                        '<a href="https://try.elevenlabs.io/mementor" target="_blank" rel="noopener"><strong>' . esc_html($elevenlabs_link_text) . '</strong></a>'
                    );
                    echo wp_kses($info_text, array('a' => array('href' => array(), 'target' => array(), 'rel' => array()), 'strong' => array()));
                    ?></p>
                </div>
            <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Player Preview (sticky footer) -->
    <div id="tts-sticky-preview" class="mementor-tts-sticky-footer mementor-tts-sticky-preview-bar" style="display:none !important;">
        <div class="mementor-tts-sticky-inner">
            <button class="mementor-tts-sticky-play" aria-label="<?php esc_attr_e('Play', 'text-to-speech-tts'); ?>">
                <svg class="mementor-tts-sticky-icon-play" width="20" height="20" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                    <path d="M8 5v14l11-7z"/>
                </svg>
                <svg class="mementor-tts-sticky-icon-pause" width="20" height="20" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg" style="display:none !important;">
                    <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
                </svg>
            </button>
            <div class="mementor-tts-sticky-info">
                <span class="mementor-tts-sticky-title"><?php esc_html_e('Sample Post Title', 'text-to-speech-tts'); ?></span>
            </div>
            <div class="mementor-tts-sticky-progress-wrap">
                <span class="mementor-tts-sticky-time"<?php echo $show_time ? '' : ' style="display:none !important;"'; ?>>0:00</span>
                <?php if ( get_option('mementor_tts_progress_type', 'linear') === 'waveform_progress' && $is_pro_active ) : ?>
                <div class="mementor-tts-sticky-progress-container mementor-tts-waveform" data-progress-type="waveform_progress" data-post-id="0"></div>
                <?php else : ?>
                <div class="mementor-tts-sticky-progress-container">
                    <div class="mementor-tts-sticky-progress-bar" style="width: 35%;"></div>
                </div>
                <?php endif; ?>
                <span class="mementor-tts-sticky-duration"<?php echo $show_time ? '' : ' style="display:none !important;"'; ?>>0:27</span>
            </div>
            <button class="mementor-tts-sticky-volume" aria-label="<?php esc_attr_e('Mute', 'text-to-speech-tts'); ?>"<?php echo $show_volume ? '' : ' style="display:none !important;"'; ?>>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                    <path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/>
                </svg>
            </button>
            <button class="mementor-tts-sticky-speed" aria-label="<?php esc_attr_e('Playback speed', 'text-to-speech-tts'); ?>"<?php echo $speed_control ? '' : ' style="display:none !important;"'; ?>>1x</button>
            <a class="mementor-tts-sticky-download" href="#" aria-label="<?php esc_attr_e('Download', 'text-to-speech-tts'); ?>"<?php echo $show_download ? '' : ' style="display:none !important;"'; ?>>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                    <path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/>
                </svg>
            </a>
            <button class="mementor-tts-sticky-close" aria-label="<?php esc_attr_e('Close', 'text-to-speech-tts'); ?>">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                    <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
                </svg>
            </button>
        </div>
        <audio preload="auto">
            <source src="<?php echo esc_url(MEMENTOR_TTS_PLUGIN_URL . 'admin/audio/player-settings.mp3'); ?>" type="audio/mpeg">
        </audio>
        <div class="tts-sticky-preview-label">
            <span class="tts-live-dot"></span><?php esc_html_e('Sticky Footer Preview', 'text-to-speech-tts'); ?>
        </div>
    </div>

    <?php if (current_user_can('manage_options')) : ?>
        <form method="post" action="options.php" id="player-settings-form" spellcheck="false">
            <?php
            settings_fields('mementor_tts_player_settings');
            do_settings_sections('mementor_tts_player_settings');

            // Update the form redirect URL to use the new page URL
            $referer = admin_url('admin.php?page=text-to-speech-tts-player');
            ?>
            <input type="hidden" name="_wp_http_referer" value="<?php echo esc_attr($referer); ?>">
            <?php wp_nonce_field('mementor_tts_nonce', 'mementor_tts_nonce'); ?>

            <!-- Player Settings + Label — side by side -->
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 16px; margin-bottom: 16px;">
                <!-- Placement & Size -->
                <div class="tts-card tts-card-inset" style="margin-bottom: 0;">
                    <div class="tts-card-header tts-card-header-inline">
                        <h3 class="tts-card-title"><?php esc_html_e('Player Settings', 'text-to-speech-tts'); ?></h3>
                        <p class="tts-card-desc"><?php esc_html_e('Placement, width, and alignment', 'text-to-speech-tts'); ?></p>
                    </div>
                    <?php
                    $current_position = get_option('mementor_tts_player_position', 'after_content');
                    $current_alignment = get_option('mementor_tts_player_alignment', 'left');
                    ?>
                    <div class="tts-audio-grid" style="grid-template-columns: repeat(2, 1fr);">
                        <div class="tts-audio-field">
                            <label class="tts-audio-label"><?php esc_html_e('Placement', 'text-to-speech-tts'); ?></label>
                            <select name="mementor_tts_player_position" id="mementor_tts_player_position">
                                <option value="after_title_before_excerpt" <?php selected($current_position, 'after_title_before_excerpt'); ?>><?php esc_html_e('Beginning of Content', 'text-to-speech-tts'); ?></option>
                                <option value="before_excerpt" <?php selected($current_position, 'before_excerpt'); ?>><?php esc_html_e('Before Excerpt', 'text-to-speech-tts'); ?></option>
                                <option value="after_excerpt" <?php selected($current_position, 'after_excerpt'); ?>><?php esc_html_e('After Excerpt', 'text-to-speech-tts'); ?></option>
                                <option value="after_title_after_excerpt" <?php selected($current_position, 'after_title_after_excerpt'); ?>><?php esc_html_e('After First Paragraph', 'text-to-speech-tts'); ?></option>
                                <option value="after_content" <?php selected($current_position, 'after_content'); ?>><?php esc_html_e('End of Content', 'text-to-speech-tts'); ?></option>
                                <option value="sticky_footer" <?php selected($current_position, 'sticky_footer'); ?> <?php echo $is_pro_active ? '' : 'disabled'; ?>>
                                    <?php esc_html_e('Sticky Footer', 'text-to-speech-tts'); ?>
                                </option>
                            </select>
                            <?php if ( ! $is_pro_active && $current_position !== 'sticky_footer' ) : ?>
                                <span class="tts-pro-badge"><?php esc_html_e('PRO', 'text-to-speech-tts'); ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="tts-audio-field">
                            <label class="tts-audio-label"><?php esc_html_e('Progress Bar', 'text-to-speech-tts'); ?></label>
                            <?php $current_progress_type = get_option('mementor_tts_progress_type', 'linear'); ?>
                            <select name="mementor_tts_progress_type" id="mementor_tts_progress_type">
                                <option value="linear" <?php selected($current_progress_type, 'linear'); ?>><?php esc_html_e('Linear', 'text-to-speech-tts'); ?></option>
                                <option value="waveform_progress" <?php selected($current_progress_type, 'waveform_progress'); ?> <?php echo $is_pro_active ? '' : 'disabled'; ?>>
                                    <?php esc_html_e('Waveform', 'text-to-speech-tts'); ?>
                                </option>
                            </select>
                            <?php if ( ! $is_pro_active && $current_progress_type !== 'waveform_progress' ) : ?>
                                <span class="tts-pro-badge"><?php esc_html_e('PRO', 'text-to-speech-tts'); ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="tts-audio-grid" style="grid-template-columns: repeat(3, 1fr); margin-top: 8px;">
                        <div class="tts-audio-field">
                            <label class="tts-audio-label"><?php esc_html_e('Width', 'text-to-speech-tts'); ?></label>
                            <select name="mementor_tts_player_width" id="mementor_tts_player_width">
                                <option value="content_width" <?php selected(get_option('mementor_tts_player_width', 'content_width'), 'content_width'); ?>><?php esc_html_e('Content Width', 'text-to-speech-tts'); ?></option>
                                <option value="full_width" <?php selected(get_option('mementor_tts_player_width', 'content_width'), 'full_width'); ?>><?php esc_html_e('Full Width', 'text-to-speech-tts'); ?></option>
                            </select>
                        </div>
                        <div class="tts-audio-field">
                            <label class="tts-audio-label"><?php esc_html_e('Max Width', 'text-to-speech-tts'); ?></label>
                            <div class="mementor-tts-input-group">
                                <input type="number" name="mementor_tts_player_max_width" id="mementor_tts_player_max_width" value="<?php echo esc_attr(get_option('mementor_tts_player_max_width', '100')); ?>" min="10" max="2000" step="1">
                                <select name="mementor_tts_player_max_width_unit" id="mementor_tts_player_max_width_unit">
                                    <option value="%" <?php selected(get_option('mementor_tts_player_max_width_unit', '%'), '%'); ?>>%</option>
                                    <option value="px" <?php selected(get_option('mementor_tts_player_max_width_unit', '%'), 'px'); ?>>px</option>
                                </select>
                            </div>
                        </div>
                        <div class="tts-audio-field">
                            <label class="tts-audio-label"><?php esc_html_e('Alignment', 'text-to-speech-tts'); ?></label>
                            <select name="mementor_tts_player_alignment" id="mementor_tts_player_alignment">
                                <option value="left" <?php selected($current_alignment, 'left'); ?>><?php esc_html_e('Left', 'text-to-speech-tts'); ?></option>
                                <option value="center" <?php selected($current_alignment, 'center'); ?>><?php esc_html_e('Center', 'text-to-speech-tts'); ?></option>
                                <option value="right" <?php selected($current_alignment, 'right'); ?>><?php esc_html_e('Right', 'text-to-speech-tts'); ?></option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Label -->
                <div class="tts-card tts-card-inset" id="tts-label-settings" style="margin-bottom: 0;">
                    <div class="tts-card-header tts-card-header-inline">
                        <h3 class="tts-card-title"><?php esc_html_e('Label', 'text-to-speech-tts'); ?></h3>
                        <p class="tts-card-desc"><?php esc_html_e('Text label above the player', 'text-to-speech-tts'); ?></p>
                    </div>
                    <div class="tts-audio-grid" style="grid-template-columns: repeat(3, 1fr);">
                        <div class="tts-audio-field">
                            <label class="tts-audio-label"><?php esc_html_e('Show Label', 'text-to-speech-tts'); ?></label>
                            <div class="mementor-tts-toggle">
                                <input type="checkbox" id="mementor_tts_show_player_label" name="mementor_tts_show_player_label" value="1" <?php checked(get_option('mementor_tts_show_player_label'), true); ?>>
                                <label for="mementor_tts_show_player_label">
                                    <span class="slider"></span>
                                </label>
                            </div>
                        </div>
                        <div class="tts-audio-field" style="grid-column: span 2;">
                            <label class="tts-audio-label"><?php esc_html_e('Label Text', 'text-to-speech-tts'); ?></label>
                            <input type="text" name="mementor_tts_player_label" id="mementor_tts_player_label" value="<?php echo esc_attr(get_option('mementor_tts_player_label', __('Listen to this article:', 'text-to-speech-tts'))); ?>">
                        </div>
                    </div>
                    <div class="tts-audio-grid" style="grid-template-columns: repeat(4, 1fr); margin-top: 8px;">
                        <div class="tts-audio-field">
                            <label class="tts-audio-label"><?php esc_html_e('Position', 'text-to-speech-tts'); ?></label>
                            <select name="mementor_tts_player_label_position" id="mementor_tts_player_label_position">
                                <option value="left" <?php selected(get_option('mementor_tts_player_label_position'), 'left'); ?>><?php esc_html_e('Left', 'text-to-speech-tts'); ?></option>
                                <option value="center" <?php selected(get_option('mementor_tts_player_label_position'), 'center'); ?>><?php esc_html_e('Center', 'text-to-speech-tts'); ?></option>
                                <option value="right" <?php selected(get_option('mementor_tts_player_label_position'), 'right'); ?>><?php esc_html_e('Right', 'text-to-speech-tts'); ?></option>
                            </select>
                        </div>
                        <div class="tts-audio-field">
                            <label class="tts-audio-label"><?php esc_html_e('Size', 'text-to-speech-tts'); ?></label>
                            <input type="number" name="mementor_tts_player_label_size" id="mementor_tts_player_label_size" value="<?php echo esc_attr(get_option('mementor_tts_player_label_size', '14')); ?>" min="10" max="32">
                        </div>
                        <div class="tts-audio-field">
                            <label class="tts-audio-label"><?php esc_html_e('Weight', 'text-to-speech-tts'); ?></label>
                            <?php $current_weight = get_option('mementor_tts_player_label_weight', '400'); ?>
                            <select name="mementor_tts_player_label_weight" id="mementor_tts_player_label_weight">
                                <option value="400" <?php selected($current_weight, '400'); ?>><?php esc_html_e('Normal', 'text-to-speech-tts'); ?></option>
                                <option value="500" <?php selected($current_weight, '500'); ?>><?php esc_html_e('Medium', 'text-to-speech-tts'); ?></option>
                                <option value="700" <?php selected($current_weight, '700'); ?>><?php esc_html_e('Bold', 'text-to-speech-tts'); ?></option>
                            </select>
                        </div>
                        <div class="tts-audio-field">
                            <label class="tts-audio-label"><?php esc_html_e('Color', 'text-to-speech-tts'); ?></label>
                            <div class="tts-color-input-row">
                                <input type="color" name="mementor_tts_player_label_color" id="mementor_tts_player_label_color" value="<?php echo esc_attr(get_option('mementor_tts_player_label_color', '#1d2327')); ?>">
                                <input type="text" class="mementor-tts-color-text" data-color-input="mementor_tts_player_label_color" value="<?php echo esc_attr(get_option('mementor_tts_player_label_color', '#1d2327')); ?>">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tip: Shortcode placement -->
            <div class="tts-card tts-card-inset tts-tip-card">
                <div class="tts-card-header tts-card-header-inline">
                    <h3 class="tts-card-title"><?php esc_html_e('Want to control audio player placement?', 'text-to-speech-tts'); ?></h3>
                    <p class="tts-card-desc"><?php esc_html_e('This overrides the Player placement setting.', 'text-to-speech-tts'); ?></p>
                </div>
                <p class="tts-tip-body"><?php
                    printf(
                        /* translators: 1: Shortcode tag (e.g. [tts_player]) wrapped in <code>. 2: PHP do_shortcode() snippet wrapped in <code>. */
                        esc_html__('Add %1$s anywhere in your post or page content to place the audio player exactly where you want it. For direct use in theme template files, use the PHP equivalent: %2$s', 'text-to-speech-tts'),
                        '<code>[tts_player]</code>',
                        '<code>&lt;?php echo do_shortcode(\'[tts_player]\'); ?&gt;</code>'
                    );
                ?></p>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 16px; margin-bottom: 16px;">
            <!-- Controls -->
            <div class="tts-card tts-card-inset" style="margin-bottom: 0;">
                <div class="tts-card-header tts-card-header-inline">
                    <h3 class="tts-card-title"><?php esc_html_e('Controls', 'text-to-speech-tts'); ?></h3>
                    <p class="tts-card-desc"><?php esc_html_e('Enable or disable player features', 'text-to-speech-tts'); ?></p>
                </div>
                <div class="tts-controls-grid">
                    <div class="tts-control-item">
                        <span class="tts-control-label"><?php esc_html_e('Time display', 'text-to-speech-tts'); ?></span>
                        <div class="mementor-tts-toggle"><input type="checkbox" id="mementor_tts_show_time" name="mementor_tts_show_time" value="1" <?php checked($show_time); ?>><label for="mementor_tts_show_time"><span class="slider"></span></label></div>
                    </div>
                    <div class="tts-control-item">
                        <span class="tts-control-label"><?php esc_html_e('Speed control', 'text-to-speech-tts'); ?></span>
                        <div class="mementor-tts-toggle"><input type="checkbox" id="mementor_tts_speed_control" name="mementor_tts_speed_control" value="1" <?php checked($speed_control); ?>><label for="mementor_tts_speed_control"><span class="slider"></span></label></div>
                    </div>
                    <div class="tts-control-item">
                        <span class="tts-control-label"><?php esc_html_e('Volume control', 'text-to-speech-tts'); ?></span>
                        <div class="mementor-tts-toggle"><input type="checkbox" id="mementor_tts_show_volume" name="mementor_tts_show_volume" value="1" <?php checked($show_volume); ?>><label for="mementor_tts_show_volume"><span class="slider"></span></label></div>
                    </div>
                    <div class="tts-control-item">
                        <span class="tts-control-label"><?php esc_html_e('Download icon', 'text-to-speech-tts'); ?></span>
                        <div class="mementor-tts-toggle"><input type="checkbox" id="mementor_tts_show_download" name="mementor_tts_show_download" value="1" <?php checked($show_download); ?>><label for="mementor_tts_show_download"><span class="slider"></span></label></div>
                    </div>
                    <div class="tts-control-item">
                        <span class="tts-control-label"><?php esc_html_e('Autoplay', 'text-to-speech-tts'); ?></span>
                        <div class="mementor-tts-toggle"><input type="checkbox" id="mementor_tts_autoplay" name="mementor_tts_autoplay" value="1" <?php checked(get_option('mementor_tts_autoplay', false)); ?>><label for="mementor_tts_autoplay"><span class="slider"></span></label></div>
                    </div>
                    <div class="tts-control-item">
                        <span class="tts-control-label"><?php esc_html_e('Loop', 'text-to-speech-tts'); ?></span>
                        <div class="mementor-tts-toggle"><input type="checkbox" id="mementor_tts_loop" name="mementor_tts_loop" value="1" <?php checked(get_option('mementor_tts_loop', false)); ?>><label for="mementor_tts_loop"><span class="slider"></span></label></div>
                    </div>
                    <?php $info_2 = function_exists('ttswp_info_2') && ttswp_info_2(); ?>
                    <?php if ($info_2) : ?>
                        <input type="hidden" name="mementor_tts_show_info" value="1">
                    <?php else : ?>
                        <div class="tts-control-item">
                            <span class="tts-control-label"><?php esc_html_e('Information', 'text-to-speech-tts'); ?></span>
                            <div class="mementor-tts-toggle">
                                <input type="checkbox" id="mementor_tts_show_info" name="mementor_tts_show_info" value="1" <?php checked($show_info); ?>>
                                <label for="mementor_tts_show_info"><span class="slider"></span></label>
                            </div>
                        </div>
                    <?php endif; ?>
                    <div class="tts-control-item">
                        <span class="tts-control-label"><?php esc_html_e('Button background', 'text-to-speech-tts'); ?></span>
                        <div class="mementor-tts-toggle"><input type="checkbox" id="mementor_tts_show_play_bg" name="mementor_tts_show_play_bg" value="1" <?php checked(get_option('mementor_tts_show_play_bg', true)); ?>><label for="mementor_tts_show_play_bg"><span class="slider"></span></label></div>
                    </div>
                </div>
            </div>

            <!-- Colors -->
            <div class="tts-card tts-card-inset" style="margin-bottom: 0;">
                <div class="tts-card-header tts-card-header-inline">
                    <h3 class="tts-card-title"><?php esc_html_e('Colors', 'text-to-speech-tts'); ?></h3>
                    <p class="tts-card-desc"><?php esc_html_e('Customize the player color scheme', 'text-to-speech-tts'); ?></p>
                </div>


                <div class="tts-color-grid tts-color-grid-4">
                    <div class="tts-color-field">
                        <label class="tts-color-label"><?php esc_html_e('Background', 'text-to-speech-tts'); ?></label>
                        <div class="tts-color-input-row">
                            <input type="color" name="mementor_tts_player_bg_color" id="mementor_tts_player_bg_color" value="<?php echo esc_attr(get_option('mementor_tts_player_bg_color', '#f6f7fb')); ?>">
                            <input type="text" class="mementor-tts-color-text" data-color-input="mementor_tts_player_bg_color" value="<?php echo esc_attr(get_option('mementor_tts_player_bg_color', '#f6f7fb')); ?>">
                        </div>
                    </div>
                    <div class="tts-color-field">
                        <label class="tts-color-label"><?php esc_html_e('Border', 'text-to-speech-tts'); ?></label>
                        <div class="tts-color-input-row">
                            <input type="color" name="mementor_tts_player_border_color" id="mementor_tts_player_border_color" value="<?php echo esc_attr(get_option('mementor_tts_player_border_color', '#dcdcde')); ?>">
                            <input type="text" class="mementor-tts-color-text" data-color-input="mementor_tts_player_border_color" value="<?php echo esc_attr(get_option('mementor_tts_player_border_color', '#dcdcde')); ?>">
                        </div>
                    </div>
                    <div class="tts-color-field">
                        <label class="tts-color-label"><?php esc_html_e('Button BG', 'text-to-speech-tts'); ?></label>
                        <div class="tts-color-input-row">
                            <input type="color" name="mementor_tts_play_button_bg" id="mementor_tts_play_button_bg" value="<?php echo esc_attr(get_option('mementor_tts_play_button_bg', '#ffffff')); ?>">
                            <input type="text" class="mementor-tts-color-text" data-color-input="mementor_tts_play_button_bg" value="<?php echo esc_attr(get_option('mementor_tts_play_button_bg', '#ffffff')); ?>">
                        </div>
                    </div>
                    <div class="tts-color-field">
                        <label class="tts-color-label"><?php esc_html_e('Accent', 'text-to-speech-tts'); ?></label>
                        <div class="tts-color-input-row">
                            <input type="color" name="mementor_tts_player_accent_color" id="mementor_tts_player_accent_color" value="<?php echo esc_attr(get_option('mementor_tts_player_accent_color', '#2271b1')); ?>">
                            <input type="text" class="mementor-tts-color-text" data-color-input="mementor_tts_player_accent_color" value="<?php echo esc_attr(get_option('mementor_tts_player_accent_color', '#2271b1')); ?>">
                        </div>
                    </div>
                    <div class="tts-color-field">
                        <label class="tts-color-label"><?php esc_html_e('Timer', 'text-to-speech-tts'); ?></label>
                        <div class="tts-color-input-row">
                            <input type="color" name="mementor_tts_timer_color" id="mementor_tts_timer_color" value="<?php echo esc_attr(get_option('mementor_tts_timer_color', '#1d2327')); ?>">
                            <input type="text" class="mementor-tts-color-text" data-color-input="mementor_tts_timer_color" value="<?php echo esc_attr(get_option('mementor_tts_timer_color', '#1d2327')); ?>">
                        </div>
                    </div>
                    <div class="tts-color-field">
                        <label class="tts-color-label"><?php esc_html_e('Progress bar', 'text-to-speech-tts'); ?></label>
                        <div class="tts-color-input-row">
                            <input type="color" name="mementor_tts_progress_bar_default" id="mementor_tts_progress_bar_default" value="<?php echo esc_attr(get_option('mementor_tts_progress_bar_default', '#e0e0e0')); ?>">
                            <input type="text" class="mementor-tts-color-text" data-color-input="mementor_tts_progress_bar_default" value="<?php echo esc_attr(get_option('mementor_tts_progress_bar_default', '#e0e0e0')); ?>">
                        </div>
                    </div>
                    <div class="tts-color-field">
                        <label class="tts-color-label"><?php esc_html_e('Active Bar', 'text-to-speech-tts'); ?></label>
                        <div class="tts-color-input-row">
                            <input type="color" name="mementor_tts_progress_bar_playing" id="mementor_tts_progress_bar_playing" value="<?php echo esc_attr(get_option('mementor_tts_progress_bar_playing', '#2271b1')); ?>">
                            <input type="text" class="mementor-tts-color-text" data-color-input="mementor_tts_progress_bar_playing" value="<?php echo esc_attr(get_option('mementor_tts_progress_bar_playing', '#2271b1')); ?>">
                        </div>
                    </div>
                    <div class="tts-color-field" id="tts-opacity-field">
                        <label class="tts-color-label"><?php esc_html_e('Opacity', 'text-to-speech-tts'); ?> <span class="tts-tooltip">?<span class="tts-tooltip-text"><?php esc_html_e('Background opacity for the Sticky Footer player.', 'text-to-speech-tts'); ?></span></span></label>
                        <div class="tts-opacity-input-row">
                            <input type="range" name="mementor_tts_player_opacity" id="mementor_tts_player_opacity" min="0.1" max="1" step="0.05" value="<?php echo esc_attr(get_option('mementor_tts_player_opacity', '1')); ?>">
                            <span class="tts-opacity-value" id="tts-opacity-display"><?php echo esc_html(get_option('mementor_tts_player_opacity', '1')); ?></span>
                        </div>
                    </div>
                </div>
            </div>
            </div>

            <!-- Sizing & Spacing -->
            <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('Sizing & Spacing', 'text-to-speech-tts'); ?></h3>
                    <p class="tts-card-desc"><?php esc_html_e('Adjust typography, padding, and outer margins.', 'text-to-speech-tts'); ?></p>
                </div>

                <div class="tts-audio-grid" style="grid-template-columns: repeat(5, 1fr);">
                    <div class="tts-audio-field">
                        <label class="tts-audio-label"><?php esc_html_e('Play Icon Size', 'text-to-speech-tts'); ?></label>
                        <input type="number" name="mementor_tts_play_icon_size" id="mementor_tts_play_icon_size" min="12" max="48" value="<?php echo esc_attr(get_option('mementor_tts_play_icon_size', '24')); ?>">
                    </div>
                    <div class="tts-audio-field">
                        <label class="tts-audio-label"><?php esc_html_e('Font Size', 'text-to-speech-tts'); ?></label>
                        <input type="number" name="mementor_tts_font_size" id="mementor_tts_font_size" min="12" max="24" value="<?php echo esc_attr(get_option('mementor_tts_font_size', '14')); ?>">
                    </div>
                    <div class="tts-audio-field">
                        <label class="tts-audio-label"><?php esc_html_e('Player Padding', 'text-to-speech-tts'); ?></label>
                        <input type="number" name="mementor_tts_player_padding" id="mementor_tts_player_padding" min="0" max="40" value="<?php echo esc_attr(get_option('mementor_tts_player_padding', '12')); ?>">
                    </div>
                    <div class="tts-audio-field">
                        <label class="tts-audio-label"><?php esc_html_e('Margin Top', 'text-to-speech-tts'); ?></label>
                        <input type="number"
                            name="mementor_tts_player_margin_top"
                            id="mementor_tts_player_margin_top"
                            value="<?php echo esc_attr(get_option('mementor_tts_player_margin_top', '0')); ?>"
                            min="-100"
                            max="100"
                            step="1">
                    </div>
                    <div class="tts-audio-field">
                        <label class="tts-audio-label"><?php esc_html_e('Margin Bottom', 'text-to-speech-tts'); ?></label>
                        <input type="number"
                            name="mementor_tts_player_margin_bottom"
                            id="mementor_tts_player_margin_bottom"
                            value="<?php echo esc_attr(get_option('mementor_tts_player_margin_bottom', '0')); ?>"
                            min="-100"
                            max="100"
                            step="1">
                    </div>
                </div>
            </div>
        </form>
    <?php else : ?>
        <div class="notice notice-error">
            <p><?php esc_html_e('You do not have sufficient permissions to access these settings.', 'text-to-speech-tts'); ?></p>
        </div>
    <?php endif; ?>
<script>
(function() {
    var positionSelect = document.getElementById('mementor_tts_player_position');
    var labelCard = document.getElementById('tts-label-settings');
    var inlinePreview = document.getElementById('tts-inline-preview');
    var stickyPreview = document.getElementById('tts-sticky-preview');
    var opacityField = document.getElementById('tts-opacity-field');

    var layoutFieldIds = ['mementor_tts_player_width', 'mementor_tts_player_max_width', 'mementor_tts_player_alignment'];
    var layoutFields = [];
    layoutFieldIds.forEach(function(id) {
        var el = document.getElementById(id);
        if (el) {
            var field = el.closest('.tts-audio-field');
            if (field && layoutFields.indexOf(field) === -1) layoutFields.push(field);
        }
    });

    function toggleStickyFields() {
        var isSticky = positionSelect.value === 'sticky_footer';
        layoutFields.forEach(function(f) { f.classList.toggle('tts-fields-disabled', isSticky); });
        if (labelCard) labelCard.classList.toggle('tts-fields-disabled', isSticky);
        if (opacityField) opacityField.classList.toggle('tts-fields-disabled', !isSticky);
        if (inlinePreview) inlinePreview.style.display = isSticky ? 'none' : '';
        if (stickyPreview) stickyPreview.style.display = isSticky ? '' : 'none';
    }

    // Sync sticky preview controls with toggle settings
    if (stickyPreview) {
        var timeToggle = document.getElementById('mementor_tts_show_time');
        var volumeToggle = document.getElementById('mementor_tts_show_volume');
        var speedToggle = document.getElementById('mementor_tts_speed_control');
        var downloadToggle = document.getElementById('mementor_tts_show_download');

        var stickyTime = stickyPreview.querySelectorAll('.mementor-tts-sticky-time, .mementor-tts-sticky-duration');
        var stickyVolume = stickyPreview.querySelector('.mementor-tts-sticky-volume');
        var stickySpeed = stickyPreview.querySelector('.mementor-tts-sticky-speed');
        var stickyDownload = stickyPreview.querySelector('.mementor-tts-sticky-download');

        function setDisplay(el, visible) {
            if (!el) return;
            if (visible) {
                el.style.removeProperty('display');
            } else {
                // Shared frontend CSS sets `display: flex !important` on these
                // controls, so hiding them requires !important priority too.
                el.style.setProperty('display', 'none', 'important');
            }
        }

        function syncStickyControls() {
            stickyTime.forEach(function(el) { setDisplay(el, !!(timeToggle && timeToggle.checked)); });
            setDisplay(stickyVolume,   !!(volumeToggle   && volumeToggle.checked));
            setDisplay(stickySpeed,    !!(speedToggle    && speedToggle.checked));
            setDisplay(stickyDownload, !!(downloadToggle && downloadToggle.checked));
        }

        // Button background toggle — sticky play button loses its bg/border when off.
        var playBgToggle = document.getElementById('mementor_tts_show_play_bg');
        var stickyPlay   = stickyPreview.querySelector('.mementor-tts-sticky-play');
        function syncStickyPlayBg() {
            if (!stickyPlay) return;
            if (playBgToggle && !playBgToggle.checked) {
                stickyPlay.style.setProperty('background-color', 'transparent', 'important');
            } else {
                stickyPlay.style.removeProperty('background-color');
            }
        }
        syncStickyPlayBg();
        if (playBgToggle) playBgToggle.addEventListener('change', syncStickyPlayBg);

        syncStickyControls();
        [timeToggle, volumeToggle, speedToggle, downloadToggle].forEach(function(toggle) {
            if (toggle) toggle.addEventListener('change', syncStickyControls);
        });

        // Opacity slider live preview — background-only
        var opacitySlider = document.getElementById('mementor_tts_player_opacity');
        var opacityDisplay = document.getElementById('tts-opacity-display');
        var bgColorInput = document.getElementById('mementor_tts_player_bg_color');

        function hexToRgba(hex, alpha) {
            var r = parseInt(hex.slice(1, 3), 16);
            var g = parseInt(hex.slice(3, 5), 16);
            var b = parseInt(hex.slice(5, 7), 16);
            return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + alpha + ')';
        }

        function updateStickyBg() {
            if (!opacitySlider || !bgColorInput) return;
            var val = parseFloat(opacitySlider.value);
            if (opacityDisplay) opacityDisplay.textContent = val;
            var bg = bgColorInput.value || '#f6f7fb';
            stickyPreview.style.setProperty('--mementor-tts-sticky-bg', val < 1 ? hexToRgba(bg, val) : bg);
        }

        if (opacitySlider) opacitySlider.addEventListener('input', updateStickyBg);
        if (bgColorInput) bgColorInput.addEventListener('input', updateStickyBg);

        // Wire up sticky preview play button
        var stickyAudio = stickyPreview.querySelector('audio');
        var stickyPlayBtn = stickyPreview.querySelector('.mementor-tts-sticky-play');
        var stickyIconPlay = stickyPreview.querySelector('.mementor-tts-sticky-icon-play');
        var stickyIconPause = stickyPreview.querySelector('.mementor-tts-sticky-icon-pause');
        var stickyTimeEl = stickyPreview.querySelector('.mementor-tts-sticky-time');
        var stickyDurationEl = stickyPreview.querySelector('.mementor-tts-sticky-duration');
        var stickyProgressBar = stickyPreview.querySelector('.mementor-tts-sticky-progress-bar');

        if (stickyAudio && stickyPlayBtn) {
            stickyPlayBtn.addEventListener('click', function() {
                if (stickyAudio.paused) { stickyAudio.play(); } else { stickyAudio.pause(); }
            });

            stickyAudio.addEventListener('play', function() {
                if (stickyIconPlay) stickyIconPlay.style.display = 'none';
                if (stickyIconPause) stickyIconPause.style.display = '';
            });
            stickyAudio.addEventListener('pause', function() {
                if (stickyIconPlay) stickyIconPlay.style.display = '';
                if (stickyIconPause) stickyIconPause.style.display = 'none';
            });
            stickyAudio.addEventListener('timeupdate', function() {
                if (!stickyAudio.duration) return;
                var pct = (stickyAudio.currentTime / stickyAudio.duration) * 100;
                if (stickyProgressBar) stickyProgressBar.style.width = pct + '%';
                if (stickyTimeEl) stickyTimeEl.textContent = formatTime(stickyAudio.currentTime);
            });
            stickyAudio.addEventListener('loadedmetadata', function() {
                if (stickyDurationEl) stickyDurationEl.textContent = formatTime(stickyAudio.duration);
            });
            stickyAudio.addEventListener('ended', function() {
                if (stickyIconPlay) stickyIconPlay.style.display = '';
                if (stickyIconPause) stickyIconPause.style.display = 'none';
                if (stickyProgressBar) stickyProgressBar.style.width = '0%';
                if (stickyTimeEl) stickyTimeEl.textContent = '0:00';
            });
        }

        function formatTime(seconds) {
            if (isNaN(seconds) || !isFinite(seconds)) return '0:00';
            var m = Math.floor(seconds / 60);
            var s = Math.floor(seconds % 60);
            return m + ':' + (s < 10 ? '0' : '') + s;
        }
    }

    // --- Sizing & Spacing — live preview on both inline and sticky ---------
    // The inline preview honours the CSS custom properties already. The sticky
    // preview's CSS hardcodes several sizes with !important, so we override
    // those elements inline for it.

    var stickyPlayEl    = stickyPreview ? stickyPreview.querySelector('.mementor-tts-sticky-play') : null;
    var stickyPlaySvgs  = stickyPlayEl ? stickyPlayEl.querySelectorAll('svg') : [];
    var stickyTextEls   = stickyPreview ? stickyPreview.querySelectorAll('.mementor-tts-sticky-title, .mementor-tts-sticky-time, .mementor-tts-sticky-duration, .mementor-tts-sticky-speed') : [];

    var playIconInput = document.getElementById('mementor_tts_play_icon_size');
    function applyPlayIconSize() {
        if (!playIconInput) return;
        var size = parseInt(playIconInput.value, 10) || 24;
        if (inlinePreview) inlinePreview.style.setProperty('--mementor-tts-play-icon-size', size + 'px');
        if (stickyPreview) stickyPreview.style.setProperty('--mementor-tts-play-icon-size', size + 'px');
        // Sticky CSS hardcodes 36x36 for the button and 20x20 for the SVG — override.
        if (stickyPlayEl) {
            stickyPlayEl.style.setProperty('width',  (size * 1.5) + 'px', 'important');
            stickyPlayEl.style.setProperty('height', (size * 1.5) + 'px', 'important');
        }
        stickyPlaySvgs.forEach(function(svg) {
            svg.setAttribute('width',  size);
            svg.setAttribute('height', size);
        });
    }

    var fontSizeInput = document.getElementById('mementor_tts_font_size');
    function applyFontSize() {
        if (!fontSizeInput) return;
        var size = parseInt(fontSizeInput.value, 10) || 14;
        if (inlinePreview) inlinePreview.style.setProperty('--mementor-tts-font-size', size + 'px');
        if (stickyPreview) stickyPreview.style.setProperty('--mementor-tts-font-size', size + 'px');
        // Sticky title / time / speed pill hardcode their own font-size — override.
        stickyTextEls.forEach(function(el) {
            el.style.setProperty('font-size', size + 'px', 'important');
        });
    }

    var paddingInput = document.getElementById('mementor_tts_player_padding');
    function applyPadding() {
        if (!paddingInput) return;
        var v = paddingInput.value === '' ? '' : paddingInput.value + 'px';
        if (inlinePreview) inlinePreview.style.setProperty('--mementor-tts-player-padding', v);
        if (stickyPreview) stickyPreview.style.setProperty('--mementor-tts-player-padding', v);
    }

    // Margins: inline preview uses real margin; sticky is pinned to bottom by
    // position:fixed, so we preview margin-bottom via a translate so the user
    // still gets a visual sense of the gap.
    var marginTopInput    = document.getElementById('mementor_tts_player_margin_top');
    var marginBottomInput = document.getElementById('mementor_tts_player_margin_bottom');
    function applyMargins() {
        var top    = parseInt(marginTopInput    && marginTopInput.value,    10) || 0;
        var bottom = parseInt(marginBottomInput && marginBottomInput.value, 10) || 0;
        if (inlinePreview) {
            inlinePreview.style.marginTop    = top    + 'px';
            inlinePreview.style.marginBottom = bottom + 'px';
        }
        if (stickyPreview) {
            stickyPreview.style.setProperty('transform', 'translateY(-' + bottom + 'px)', 'important');
        }
    }

    [
        [playIconInput, applyPlayIconSize],
        [fontSizeInput, applyFontSize],
        [paddingInput,  applyPadding],
        [marginTopInput,    applyMargins],
        [marginBottomInput, applyMargins]
    ].forEach(function(pair) {
        var input = pair[0];
        var fn    = pair[1];
        if (!input) return;
        fn();
        input.addEventListener('input', fn);
    });

    toggleStickyFields();
    positionSelect.addEventListener('change', toggleStickyFields);
})();
</script>
<?php include MEMENTOR_TTS_PLUGIN_DIR . 'admin/partials/layout-close.php'; ?>

<?php if (!empty($player_reset_success)) : ?>
<script>
if (typeof mementorTTSShowNotification === 'function') {
    mementorTTSShowNotification('<?php echo esc_js(__('Player settings have been reset to defaults.', 'text-to-speech-tts')); ?>', 'success');
}
</script>
<?php endif; ?>

<!-- Hidden form for reset action -->
<form id="reset-player-form" method="post" action="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-player')); ?>">
    <input type="hidden" name="mementor_tts_reset_player" value="1" />
    <?php wp_nonce_field('mementor_tts_reset_nonce', 'mementor_tts_reset_nonce'); ?>
</form>
<!-- End of player.php content -->
