/**
 * Turbo Dashboard JavaScript
 */

(function($) {
    'use strict';

    // Dashboard functionality
    const TurboDashboard = {
        
        init: function() {
            this.bindEvents();
            this.initTooltips();
        },
        
        bindEvents: function() {
            // Tab switching
            $(document).on('click', '.trstemp-tab-link', this.switchTab);
            
            // Tool actions
            $(document).on('click', '.activate-plugins-btn', this.activatePlugins);
            
            // Smooth scrolling for anchor links
            $(document).on('click', 'a[href^="#"]', this.smoothScroll);
        },
        
        switchTab: function(e) {
            e.preventDefault();
            
            const tabName = $(this).attr('href').replace('#', '');
            
            // Remove active class from all tabs and links
            $('.tab-content').removeClass('active');
            $('.trstemp-tab-link').removeClass('active');
            
            // Add active class to selected tab and link
            $('#' + tabName).addClass('active');
            $(this).addClass('active');
            
            // Update URL without page reload
            if (history.pushState) {
                history.pushState(null, null, '#' + tabName);
            }
        },
        
        testImport: function(e) {
            e.preventDefault();
            
            const $button = $(this);
            const originalText = $button.text();
            
            $button.text('Testing...').prop('disabled', true);
            
            $.ajax({
                url: trstemp_dashboard.ajax_url,
                type: 'POST',
                data: {
                    action: 'debug_import',
                    nonce: trstemp_dashboard.nonce
                },
                success: function(response) {
                    TurboDashboard.showNotice('Test import completed. Check debug log.', 'success');
                },
                error: function() {
                    TurboDashboard.showNotice('Test import failed.', 'error');
                },
                complete: function() {
                    $button.text(originalText).prop('disabled', false);
                }
            });
        },
        
        activatePlugins: function(e) {
            e.preventDefault();
            
            const $button = $(this);
            const originalText = $button.text();
            
            $button.text('Activating...').prop('disabled', true);
            
            $.ajax({
                url: trstemp_dashboard.ajax_url,
                type: 'POST',
                data: {
                    action: 'activate_required_plugins',
                    nonce: trstemp_dashboard.nonce
                },
                success: function(response) {
                    TurboDashboard.showNotice('Plugins activated successfully!', 'success');
                    setTimeout(() => location.reload(), 1500);
                },
                error: function() {
                    TurboDashboard.showNotice('Plugin activation failed.', 'error');
                },
                complete: function() {
                    $button.text(originalText).prop('disabled', false);
                }
            });
        },
        
        smoothScroll: function(e) {
            const target = $(this.getAttribute('href'));
            
            if (target.length) {
                e.preventDefault();
                $('html, body').animate({
                    scrollTop: target.offset().top - 100
                }, 500);
            }
        },
        
        initTooltips: function() {
            // Initialize tooltips for elements with title attributes
            $('[title]').each(function() {
                const $this = $(this);
                const title = $this.attr('title');
                
                $this.removeAttr('title').on('mouseenter', function() {
                    TurboDashboard.showTooltip($this, title);
                }).on('mouseleave', function() {
                    $('.turbo-tooltip').remove();
                });
            });
        },
        
        showTooltip: function($element, text) {
            const $tooltip = $('<div class="turbo-tooltip">' + text + '</div>');
            const offset = $element.offset();
            
            $tooltip.css({
                position: 'absolute',
                top: offset.top - 35,
                left: offset.left + ($element.outerWidth() / 2) - 50,
                background: '#333',
                color: 'white',
                padding: '8px 12px',
                borderRadius: '4px',
                fontSize: '12px',
                zIndex: 9999,
                whiteSpace: 'nowrap'
            });
            
            $('body').append($tooltip);
        },
        
        showNotice: function(message, type = 'info') {
            const $notice = $(`
                <div class="turbo-notice turbo-notice-${type}">
                    <span class="notice-icon">${this.getNoticeIcon(type)}</span>
                    <span class="notice-message">${message}</span>
                    <button class="trstemp-notice-dismiss" onclick="$(this).parent().fadeOut()">&times;</button>
                </div>
            `);
            
            // Remove existing notices
            $('.turbo-notice').remove();
            
            // Add new notice
            $('body').prepend($notice);
            
            // Auto-hide after 5 seconds
            setTimeout(() => {
                $notice.fadeOut();
            }, 5000);
        },
        
        getNoticeIcon: function(type) {
            const icons = {
                success: '✅',
                error: '❌',
                warning: '⚠️',
                info: 'ℹ️'
            };
            return icons[type] || icons.info;
        }
    };
    
    // Initialize dashboard when document is ready
    $(document).ready(function () {

        $('.trstemp-tab-link').on('click', function (e) {
            e.preventDefault(); // stops browser scroll

            const tabName = this.getAttribute('href').substring(1);

            // Remove active states
            $('.trstemp-tab-link').removeClass('active');
            $('.tab-content').removeClass('active');

            // Activate current
            $(this).addClass('active');
            $('#' + tabName).addClass('active');

            // Update URL hash WITHOUT scrolling
            history.pushState(null, null, '#' + tabName);
        });

        // Load tab from URL hash (no scroll)
        const hash = window.location.hash.replace('#', '');
        if (hash && $('#' + hash).length) {
            $('.trstemp-tab-link').removeClass('active');
            $('.tab-content').removeClass('active');

            $(`.trstemp-tab-link[href="#${hash}"]`).addClass('active');
            $('#' + hash).addClass('active');
        }

        // Initialize the dashboard
        TurboDashboard.init();
    });
    
    // Add notice styles
    $('<style>').text(`
        .turbo-notice {
            position: fixed;
            top: 32px;
            right: 20px;
            background: white;
            border-left: 4px solid #667eea;
            padding: 15px 20px;
            border-radius: 4px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            z-index: 999999;
            display: flex;
            align-items: center;
            gap: 10px;
            max-width: 400px;
        }
        .turbo-notice-success { border-left-color: #28a745; }
        .turbo-notice-error { border-left-color: #dc3545; }
        .turbo-notice-warning { border-left-color: #ffc107; }
        .trstemp-notice-dismiss {
            background: none;
            border: none;
            font-size: 18px;
            cursor: pointer;
            color: #333;
            margin-left: auto;
            opacity: 0.7;
        }
        .trstemp-notice-dismiss:hover { opacity: 1; }
    `).appendTo('head');

})(jQuery);
