/**
 * Text to Speech Plugin Design System JavaScript
 * Version: 1.0.0
 * 
 * JavaScript enhancements for the TTS design system components
 */

(function($) {
    'use strict';
    
    // TTS Design System namespace
    window.TTSDesignSystem = window.TTSDesignSystem || {};
    
    /**
     * Initialize all design system components
     */
    TTSDesignSystem.init = function() {
        this.initTabs();
        this.initToggles();
        this.initAlerts();
        this.initInputGroups();
        this.initVoiceCards();
        this.initFormValidation();
        this.initTooltips();
        this.initModals();
        this.initFileUpload();
        this.initCopyToClipboard();
    };
    
    /**
     * Tab Navigation
     */
    TTSDesignSystem.initTabs = function() {
        $('.tts-nav-tabs').each(function() {
            const $tabNav = $(this);
            const $tabs = $tabNav.find('.tts-nav-tab');
            const tabContainerId = $tabNav.data('tab-container') || 'tts-tab-content';
            
            $tabs.on('click', function(e) {
                e.preventDefault();
                
                const $tab = $(this);
                const tabId = $tab.data('tab');
                
                // Update active tab
                $tabs.removeClass('tts-nav-tab--active');
                $tab.addClass('tts-nav-tab--active');
                
                // Show corresponding content
                $(`#${tabContainerId} .tts-tab-panel`).removeClass('tts-tab-panel--active').hide();
                $(`#${tabContainerId} .tts-tab-panel[data-tab="${tabId}"]`).addClass('tts-tab-panel--active').fadeIn(200);
                
                // Update URL hash without scrolling
                if (history.pushState) {
                    history.pushState(null, null, '#' + tabId);
                }
                
                // Trigger custom event
                $(document).trigger('tts:tab:change', [tabId]);
            });
            
            // Handle initial tab from URL hash
            const hash = window.location.hash.substring(1);
            if (hash && $tabs.filter(`[data-tab="${hash}"]`).length) {
                $tabs.filter(`[data-tab="${hash}"]`).trigger('click');
            } else {
                $tabs.filter('.tts-nav-tab--active').trigger('click');
            }
        });
    };
    
    /**
     * Toggle Switches
     */
    TTSDesignSystem.initToggles = function() {
        $('.tts-toggle__input').on('change', function() {
            const $toggle = $(this);
            const name = $toggle.attr('name');
            const isChecked = $toggle.is(':checked');
            
            // Update any dependent fields
            $(`[data-toggle-dependency="${name}"]`).toggle(isChecked);
            
            // Trigger custom event
            $(document).trigger('tts:toggle:change', [name, isChecked]);
        });
        
        // Initialize dependent fields visibility
        $('.tts-toggle__input').each(function() {
            const $toggle = $(this);
            const name = $toggle.attr('name');
            const isChecked = $toggle.is(':checked');
            $(`[data-toggle-dependency="${name}"]`).toggle(isChecked);
        });
    };
    
    /**
     * Alert Dismissal
     */
    TTSDesignSystem.initAlerts = function() {
        $(document).on('click', '.tts-alert__dismiss', function() {
            const $alert = $(this).closest('.tts-alert');
            $alert.fadeOut(300, function() {
                $alert.remove();
            });
        });
        
        // Auto-dismiss success alerts after 5 seconds
        $('.tts-alert--success').each(function() {
            const $alert = $(this);
            setTimeout(function() {
                $alert.fadeOut(300, function() {
                    $alert.remove();
                });
            }, 5000);
        });
    };
    
    /**
     * Input Groups (password visibility, etc.)
     */
    TTSDesignSystem.initInputGroups = function() {
        $('.tts-input-group__addon--password-toggle').on('click', function() {
            const $addon = $(this);
            const $input = $addon.siblings('input');
            const currentType = $input.attr('type');
            
            if (currentType === 'password') {
                $input.attr('type', 'text');
                $addon.html('<span class="dashicons dashicons-hidden"></span>');
            } else {
                $input.attr('type', 'password');
                $addon.html('<span class="dashicons dashicons-visibility"></span>');
            }
        });
    };
    
    /**
     * Voice Card Selection
     */
    TTSDesignSystem.initVoiceCards = function() {
        // Voice selection
        $(document).on('click', '.tts-voice-select', function(e) {
            e.preventDefault();
            const $button = $(this);
            const $card = $button.closest('.tts-voice-card');
            const voiceId = $card.data('voice-id');
            
            // Remove selected state from all cards
            $('.tts-voice-card').removeClass('tts-voice-card--selected');
            
            // Add selected state to clicked card
            $card.addClass('tts-voice-card--selected');
            
            // Update hidden input if exists
            $('#selected_voice_id').val(voiceId);
            
            // Update button states
            $('.tts-voice-select').text('Select');
            $button.text('Selected');
            
            // Trigger custom event
            $(document).trigger('tts:voice:selected', [voiceId]);
        });
        
        // Voice preview
        $(document).on('click', '.tts-voice-preview', function(e) {
            e.preventDefault();
            const $button = $(this);
            const voiceId = $button.data('voice-id');
            const originalText = $button.text();
            
            // Show loading state
            $button.prop('disabled', true).html('<span class="tts-loading"></span> Loading...');
            
            // Simulate preview (replace with actual preview logic)
            setTimeout(function() {
                $button.prop('disabled', false).text(originalText);
                
                // Trigger custom event
                $(document).trigger('tts:voice:preview', [voiceId]);
            }, 2000);
        });
    };
    
    /**
     * Form Validation
     */
    TTSDesignSystem.initFormValidation = function() {
        $('.tts-form').on('submit', function(e) {
            const $form = $(this);
            let isValid = true;
            
            // Remove previous errors
            $form.find('.tts-form-error').remove();
            $form.find('.tts-form-input--error').removeClass('tts-form-input--error');
            
            // Validate required fields
            $form.find('[required]').each(function() {
                const $field = $(this);
                const value = $field.val();
                
                if (!value || value.trim() === '') {
                    isValid = false;
                    $field.addClass('tts-form-input--error');
                    $field.after('<span class="tts-form-error">This field is required</span>');
                }
            });
            
            // Validate email fields
            $form.find('input[type="email"]').each(function() {
                const $field = $(this);
                const value = $field.val();
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                
                if (value && !emailRegex.test(value)) {
                    isValid = false;
                    $field.addClass('tts-form-input--error');
                    $field.after('<span class="tts-form-error">Please enter a valid email address</span>');
                }
            });
            
            // Validate URL fields
            $form.find('input[type="url"]').each(function() {
                const $field = $(this);
                const value = $field.val();
                const urlRegex = /^https?:\/\/.+/;
                
                if (value && !urlRegex.test(value)) {
                    isValid = false;
                    $field.addClass('tts-form-input--error');
                    $field.after('<span class="tts-form-error">Please enter a valid URL</span>');
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                
                // Scroll to first error
                const $firstError = $form.find('.tts-form-input--error').first();
                if ($firstError.length) {
                    $('html, body').animate({
                        scrollTop: $firstError.offset().top - 100
                    }, 300);
                }
            }
        });
        
        // Clear error on input
        $(document).on('input change', '.tts-form-input--error', function() {
            const $field = $(this);
            $field.removeClass('tts-form-input--error');
            $field.siblings('.tts-form-error').remove();
        });
    };
    
    /**
     * Tooltips
     */
    TTSDesignSystem.initTooltips = function() {
        $('[data-tooltip]').each(function() {
            const $element = $(this);
            const tooltipText = $element.data('tooltip');
            const tooltipPosition = $element.data('tooltip-position') || 'top';
            
            $element.on('mouseenter', function() {
                const $tooltip = $('<div class="tts-tooltip">' + tooltipText + '</div>');
                $('body').append($tooltip);
                
                const elementOffset = $element.offset();
                const elementWidth = $element.outerWidth();
                const elementHeight = $element.outerHeight();
                const tooltipWidth = $tooltip.outerWidth();
                const tooltipHeight = $tooltip.outerHeight();
                
                let top, left;
                
                switch (tooltipPosition) {
                    case 'top':
                        top = elementOffset.top - tooltipHeight - 8;
                        left = elementOffset.left + (elementWidth - tooltipWidth) / 2;
                        break;
                    case 'bottom':
                        top = elementOffset.top + elementHeight + 8;
                        left = elementOffset.left + (elementWidth - tooltipWidth) / 2;
                        break;
                    case 'left':
                        top = elementOffset.top + (elementHeight - tooltipHeight) / 2;
                        left = elementOffset.left - tooltipWidth - 8;
                        break;
                    case 'right':
                        top = elementOffset.top + (elementHeight - tooltipHeight) / 2;
                        left = elementOffset.left + elementWidth + 8;
                        break;
                }
                
                $tooltip.css({
                    top: top + 'px',
                    left: left + 'px'
                }).addClass('tts-tooltip--' + tooltipPosition).fadeIn(200);
            });
            
            $element.on('mouseleave', function() {
                $('.tts-tooltip').fadeOut(200, function() {
                    $(this).remove();
                });
            });
        });
    };
    
    /**
     * Modal System
     */
    TTSDesignSystem.initModals = function() {
        // Open modal
        $(document).on('click', '[data-modal-trigger]', function(e) {
            e.preventDefault();
            const modalId = $(this).data('modal-trigger');
            TTSDesignSystem.openModal(modalId);
        });
        
        // Close modal
        $(document).on('click', '.tts-modal__close, .tts-modal__backdrop', function() {
            TTSDesignSystem.closeModal();
        });
        
        // Close on ESC key
        $(document).on('keydown', function(e) {
            if (e.keyCode === 27) {
                TTSDesignSystem.closeModal();
            }
        });
    };
    
    TTSDesignSystem.openModal = function(modalId) {
        const $modal = $('#' + modalId);
        if (!$modal.length) return;
        
        $('body').addClass('tts-modal-open');
        $modal.fadeIn(300);
        
        // Focus first input if exists
        setTimeout(function() {
            $modal.find('input:first').focus();
        }, 300);
        
        // Trigger custom event
        $(document).trigger('tts:modal:open', [modalId]);
    };
    
    TTSDesignSystem.closeModal = function() {
        const $modal = $('.tts-modal:visible');
        if (!$modal.length) return;
        
        $modal.fadeOut(300, function() {
            $('body').removeClass('tts-modal-open');
        });
        
        // Trigger custom event
        $(document).trigger('tts:modal:close', [$modal.attr('id')]);
    };
    
    /**
     * File Upload Enhancement
     */
    TTSDesignSystem.initFileUpload = function() {
        $('.tts-file-upload').each(function() {
            const $container = $(this);
            const $input = $container.find('input[type="file"]');
            const $label = $container.find('.tts-file-upload__label');
            const $preview = $container.find('.tts-file-upload__preview');
            
            $input.on('change', function() {
                const files = this.files;
                if (files.length > 0) {
                    const file = files[0];
                    $label.text(file.name);
                    
                    // Show preview for images
                    if (file.type.match('image.*') && $preview.length) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            $preview.html('<img src="' + e.target.result + '" alt="Preview">').show();
                        };
                        reader.readAsDataURL(file);
                    }
                } else {
                    $label.text($label.data('default-text') || 'Choose file');
                    $preview.empty().hide();
                }
            });
        });
    };
    
    /**
     * Copy to Clipboard
     */
    TTSDesignSystem.initCopyToClipboard = function() {
        $(document).on('click', '.tts-copy-button', function() {
            const $button = $(this);
            const targetId = $button.data('copy-target');
            const $target = $('#' + targetId);
            const textToCopy = $target.val() || $target.text();
            
            // Create temporary textarea
            const $temp = $('<textarea>');
            $('body').append($temp);
            $temp.val(textToCopy).select();
            
            try {
                document.execCommand('copy');
                const originalText = $button.text();
                $button.text('Copied!');
                
                setTimeout(function() {
                    $button.text(originalText);
                }, 2000);
            } catch (err) {
                console.error('Failed to copy text:', err);
            }
            
            $temp.remove();
        });
    };
    
    /**
     * Utility Functions
     */
    TTSDesignSystem.showNotification = function(message, type = 'info', duration = 5000) {
        const $notification = $('<div class="tts-notification tts-notification--' + type + '">' +
            '<div class="tts-notification__content">' + message + '</div>' +
            '<button class="tts-notification__close">×</button>' +
            '</div>');
        
        $('#tts-notifications').append($notification);
        
        setTimeout(function() {
            $notification.addClass('tts-notification--visible');
        }, 10);
        
        if (duration > 0) {
            setTimeout(function() {
                $notification.removeClass('tts-notification--visible');
                setTimeout(function() {
                    $notification.remove();
                }, 300);
            }, duration);
        }
        
        $notification.find('.tts-notification__close').on('click', function() {
            $notification.removeClass('tts-notification--visible');
            setTimeout(function() {
                $notification.remove();
            }, 300);
        });
    };
    
    TTSDesignSystem.confirm = function(message, onConfirm, onCancel) {
        const modalHtml = `
            <div class="tts-modal" id="tts-confirm-modal">
                <div class="tts-modal__backdrop"></div>
                <div class="tts-modal__content">
                    <div class="tts-modal__header">
                        <h3>Confirm</h3>
                        <button class="tts-modal__close">×</button>
                    </div>
                    <div class="tts-modal__body">
                        <p>${message}</p>
                    </div>
                    <div class="tts-modal__footer">
                        <button class="tts-btn tts-btn--secondary" id="tts-confirm-cancel">Cancel</button>
                        <button class="tts-btn tts-btn--primary" id="tts-confirm-ok">Confirm</button>
                    </div>
                </div>
            </div>
        `;
        
        $('body').append(modalHtml);
        TTSDesignSystem.openModal('tts-confirm-modal');
        
        $('#tts-confirm-ok').on('click', function() {
            TTSDesignSystem.closeModal();
            if (typeof onConfirm === 'function') {
                onConfirm();
            }
            $('#tts-confirm-modal').remove();
        });
        
        $('#tts-confirm-cancel').on('click', function() {
            TTSDesignSystem.closeModal();
            if (typeof onCancel === 'function') {
                onCancel();
            }
            $('#tts-confirm-modal').remove();
        });
    };
    
    // Initialize on document ready
    $(document).ready(function() {
        TTSDesignSystem.init();
        
        // Add notification container if doesn't exist
        if (!$('#tts-notifications').length) {
            $('body').append('<div id="tts-notifications" class="tts-notifications"></div>');
        }
    });
    
})(jQuery);