/**
 * AI Voice Agent Selector - Settings Page
 *
 * Handles dynamic voice display updates when user changes voice selection.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/assets/js
 * @since      0.12.11
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        var isSavingVoice = false;
        var queuedVoice = null;

        function saveVoiceSelection(selectedVoice) {
            if (!window.sitestaffrSettingsVoice || !sitestaffrSettingsVoice.ajaxUrl || !sitestaffrSettingsVoice.nonce) {
                return;
            }

            if (isSavingVoice) {
                queuedVoice = selectedVoice;
                return;
            }

            // Instant-save: status feedback only, no dirty tracking.
            var status = SiteStaffrSaveUX.status('#sitestaffr-voice-save-status');
            isSavingVoice = true;
            status.saving();

            $.ajax({
                url: sitestaffrSettingsVoice.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'sitestaffr_update_ai_voice',
                    nonce: sitestaffrSettingsVoice.nonce,
                    ai_voice: selectedVoice
                },
                success: function(response) {
                    if (response && response.success) {
                        status.saved();
                    } else {
                        // Falls back to the component's localized "Save failed."
                        status.error(response && response.data && response.data.message);
                    }
                },
                error: function() {
                    status.error();
                },
                complete: function() {
                    isSavingVoice = false;

                    if (queuedVoice && queuedVoice !== selectedVoice) {
                        var nextVoice = queuedVoice;
                        queuedVoice = null;
                        saveVoiceSelection(nextVoice);
                        return;
                    }

                    queuedVoice = null;
                }
            });
        }

        /**
         * Update voice display with selected voice data
         * Centralized function used by both dropdown and arrow navigation
         * @since 0.12.27
         */
        function updateVoiceDisplay(selectedVoice, shouldPersist) {
            var $select = $('#sitestaffr-voice-select');
            var voiceInfo = window.sitestaffrVoiceData ? sitestaffrVoiceData[selectedVoice] : null;
            if (!voiceInfo) {
                return;
            }

            var category = voiceInfo.category || 'standard';
            var tagline = voiceInfo.tagline || '';
            var description = voiceInfo.description || '';
            var avatar = voiceInfo.avatar || '';
            var name = voiceInfo.name || selectedVoice;

            // Update voice display
            $('#sitestaffr-voice-name').text(name);
            $('#sitestaffr-voice-tagline').text(tagline);
            $('#sitestaffr-voice-description').text(description);
            if (voiceInfo.best_for) {
                var bestForHtml = voiceInfo.best_for
                    .split('|')
                    .map(function(item) {
                        return item.trim();
                    })
                    .filter(function(item) {
                        return item.length > 0;
                    })
                    .join(' <span class="sitestaffr-voice-best-for-separator">|</span> ');
                $('#sitestaffr-voice-best-for .sitestaffr-voice-best-for-values').html(bestForHtml);
            }

            // Update avatar image
            var $avatarImg = $('#sitestaffr-voice-avatar');
            if ($avatarImg.length && avatar) {
                // Build image URL using plugin URL from localized script
                var imageUrl = sitestaffrPluginUrl + 'assets/images/' + avatar;
                $avatarImg.attr('src', imageUrl);
                $avatarImg.attr('alt', name + ' avatar');
            }

            // Update badge based on category
            var badgeText = 'Standard';
            if (category === 'recommended') {
                badgeText = '⭐ Recommended';
            } else if (category === 'expressive') {
                badgeText = 'Expressive';
            }
            $('#sitestaffr-voice-badge')
                .text(badgeText)
                .removeClass('sitestaffr-voice-badge-recommended sitestaffr-voice-badge-standard sitestaffr-voice-badge-expressive')
                .addClass('sitestaffr-voice-badge-' + category);

            // Update preview button data attribute
            $('#sitestaffr-voice-preview-btn').attr('data-voice', selectedVoice);

            // Update dropdown selection
            $select.val(selectedVoice);

            // Update avatar strip selection state
            $('.sitestaffr-voice-avatar-option')
                .removeClass('is-active')
                .attr('aria-checked', 'false');
            $('.sitestaffr-voice-avatar-option[data-voice="' + selectedVoice + '"]')
                .addClass('is-active')
                .attr('aria-checked', 'true');

            if (shouldPersist) {
                saveVoiceSelection(selectedVoice);
            }
        }

        // Voice dropdown change handler
        $('#sitestaffr-voice-select').on('change', function() {
            var selectedVoice = $(this).val();
            updateVoiceDisplay(selectedVoice, true);
        });

        // Avatar strip click handler
        $(document).on('click', '.sitestaffr-voice-avatar-option', function(e) {
            e.preventDefault();
            var selectedVoice = $(this).attr('data-voice');
            if (selectedVoice) {
                updateVoiceDisplay(selectedVoice, true);
            }
        });

        /**
         * Arrow navigation click handlers
         * Navigate through voices with wraparound support
         * @since 0.12.27
         */
        $('.sitestaffr-voice-prev, .sitestaffr-voice-next').on('click', function(e) {
            e.preventDefault();

            var $select = $('#sitestaffr-voice-select');
            var currentValue = $select.val();
            var voices = window.sitestaffrVoiceData ? Object.keys(sitestaffrVoiceData) : [];
            var currentIndex = voices.indexOf(currentValue);

            if (currentIndex === -1 || !voices.length) {
                return; // Safety check
            }

            var newIndex;
            if ($(this).hasClass('sitestaffr-voice-prev')) {
                // Previous: wrap to last if at first
                newIndex = (currentIndex === 0) ? (voices.length - 1) : (currentIndex - 1);
            } else {
                // Next: wrap to first if at last
                newIndex = (currentIndex === voices.length - 1) ? 0 : (currentIndex + 1);
            }

            var newVoice = voices[newIndex];
            updateVoiceDisplay(newVoice, true);
        });

        // Voice preview button click handler
        $(document).on('click', '.sitestaffr-voice-preview-btn', function(e) {
            e.preventDefault();

            var $button = $(this);
            var voice = $button.attr('data-voice');
            var $icon = $button.find('.dashicons');
            var isIconOnly = $button.hasClass('sitestaffr-voice-preview-btn--icon');

            var version = (window.sitestaffrSettingsVoice && sitestaffrSettingsVoice.version) ? sitestaffrSettingsVoice.version : '';
            var cacheSuffix = version ? ('?v=' + encodeURIComponent(version)) : '';
            var audioUrl = sitestaffrPluginUrl + 'assets/audio/voice-samples/' + voice + '.mp3' + cacheSuffix;

            // Create or reuse audio element
            if (!window.sitestaffrVoicePreviewAudio) {
                window.sitestaffrVoicePreviewAudio = new Audio();
            }

            var audio = window.sitestaffrVoicePreviewAudio;
            var resetButtonState = function() {
                $icon.removeClass('dashicons-controls-pause').addClass('dashicons-controls-play');
                $button.removeClass('is-playing');
                if (isIconOnly) {
                    $button.attr('aria-label', 'Preview Voice');
                    $button.attr('title', 'Preview Voice');
                }
            };
            var setPlayingState = function() {
                $icon.removeClass('dashicons-controls-play').addClass('dashicons-controls-pause');
                $button.addClass('is-playing');
                if (isIconOnly) {
                    $button.attr('aria-label', 'Stop Voice Preview');
                    $button.attr('title', 'Stop Voice Preview');
                }
            };

            // If already playing this voice, stop it
            if (!audio.paused && audio.src.includes(voice + '.mp3')) {
                audio.pause();
                audio.currentTime = 0;
                resetButtonState();
                return;
            }

            // Stop any currently playing audio
            if (!audio.paused) {
                audio.pause();
                audio.currentTime = 0;
            }

            // Update UI to playing state
            setPlayingState();

            // Play new audio
            audio.src = audioUrl;
            audio.play().then(function() {
                // Audio playing successfully
            }).catch(function(error) {
                console.error('SiteStaffr: Error playing voice sample:', error);
                alert('Voice sample not available yet. Sample audio files will be added soon.');
                resetButtonState();
            });

            // Reset button when audio ends
            audio.onended = function() {
                resetButtonState();
            };
        });
    });

})(jQuery);
