/**
 * Main JavaScript File
 * OBGYN Research & Collaboration Platform
 */

(function($) {
    'use strict';

    // Initialize on document ready
    $(document).ready(function() {
        initializeApp();
    });

    /**
     * Initialize application
     */
    function initializeApp() {
        initTooltips();
        initPopovers();
        initFileUpload();
        initFormValidation();
        initNotifications();
        initSearch();
        initAutoSave();
        
        // Phase 9 Enhancements
        initHeroSlider();
        initAOS();
        initLazyLoad();
        initStickyHeader();
        initScrollToTop();
        initCounterAnimations();
        initMobileMenu();
    }

    /**
     * Initialize Bootstrap tooltips
     */
    function initTooltips() {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function(tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }

    /**
     * Initialize Bootstrap popovers
     */
    function initPopovers() {
        var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
        popoverTriggerList.map(function(popoverTriggerEl) {
            return new bootstrap.Popover(popoverTriggerEl);
        });
    }

    /**
     * Initialize file upload with drag and drop
     */
    function initFileUpload() {
        $('.file-upload-area').on('dragover', function(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).addClass('dragover');
        });

        $('.file-upload-area').on('dragleave', function(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).removeClass('dragover');
        });

        $('.file-upload-area').on('drop', function(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).removeClass('dragover');
            
            var files = e.originalEvent.dataTransfer.files;
            handleFileUpload(files, $(this));
        });

        $('.file-upload-area').on('click', function() {
            $(this).find('input[type="file"]').click();
        });

        $('input[type="file"]').on('change', function() {
            var files = this.files;
            handleFileUpload(files, $(this).closest('.file-upload-area'));
        });
    }

    /**
     * Handle file upload
     */
    function handleFileUpload(files, container) {
        if (files.length === 0) return;

        var fileList = container.find('.file-list');
        if (fileList.length === 0) {
            fileList = $('<div class="file-list mt-3"></div>');
            container.append(fileList);
        }

        Array.from(files).forEach(function(file) {
            var fileItem = $('<div class="alert alert-info alert-dismissible fade show" role="alert"></div>');
            fileItem.html(
                '<i class="fas fa-file"></i> ' + file.name + ' (' + formatFileSize(file.size) + ')' +
                '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>'
            );
            fileList.append(fileItem);
        });
    }

    /**
     * Format file size
     */
    function formatFileSize(bytes) {
        if (bytes >= 1073741824) {
            return (bytes / 1073741824).toFixed(2) + ' GB';
        } else if (bytes >= 1048576) {
            return (bytes / 1048576).toFixed(2) + ' MB';
        } else if (bytes >= 1024) {
            return (bytes / 1024).toFixed(2) + ' KB';
        } else {
            return bytes + ' bytes';
        }
    }

    /**
     * Initialize form validation
     */
    function initFormValidation() {
        // Bootstrap form validation
        var forms = document.querySelectorAll('.needs-validation');
        Array.prototype.slice.call(forms).forEach(function(form) {
            form.addEventListener('submit', function(event) {
                if (!form.checkValidity()) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });

        // Password strength indicator
        $('input[type="password"][name="password"]').on('input', function() {
            var password = $(this).val();
            var strength = checkPasswordStrength(password);
            updatePasswordStrengthIndicator($(this), strength);
        });

        // Confirm password validation
        $('input[name="confirm_password"]').on('input', function() {
            var password = $('input[name="password"]').val();
            var confirmPassword = $(this).val();
            
            if (password !== confirmPassword) {
                this.setCustomValidity('Passwords do not match');
            } else {
                this.setCustomValidity('');
            }
        });
    }

    /**
     * Check password strength
     */
    function checkPasswordStrength(password) {
        var strength = 0;
        
        if (password.length >= 8) strength++;
        if (password.length >= 12) strength++;
        if (/[a-z]/.test(password)) strength++;
        if (/[A-Z]/.test(password)) strength++;
        if (/[0-9]/.test(password)) strength++;
        if (/[^A-Za-z0-9]/.test(password)) strength++;
        
        return strength;
    }

    /**
     * Update password strength indicator
     */
    function updatePasswordStrengthIndicator(input, strength) {
        var indicator = input.siblings('.password-strength');
        
        if (indicator.length === 0) {
            indicator = $('<div class="password-strength mt-2"></div>');
            input.after(indicator);
        }
        
        var strengthText = ['Very Weak', 'Weak', 'Fair', 'Good', 'Strong', 'Very Strong'];
        var strengthClass = ['danger', 'danger', 'warning', 'info', 'success', 'success'];
        
        indicator.html(
            '<div class="progress" style="height: 5px;">' +
            '<div class="progress-bar bg-' + strengthClass[strength] + '" style="width: ' + (strength * 16.67) + '%"></div>' +
            '</div>' +
            '<small class="text-' + strengthClass[strength] + '">' + strengthText[strength] + '</small>'
        );
    }

    /**
     * Initialize notifications
     */
    function initNotifications() {
        // Check for new notifications every 30 seconds
        if ($('#notificationsDropdown').length > 0) {
            setInterval(checkNewNotifications, 30000);
        }

        // Mark notification as read when clicked
        $(document).on('click', '.notification-item', function() {
            var notificationId = $(this).data('id');
            if (notificationId) {
                markNotificationAsRead(notificationId);
            }
        });
    }

    /**
     * Check for new notifications
     */
    function checkNewNotifications() {
        $.ajax({
            url: '/obgyn-research-platform/api/notifications.php',
            method: 'GET',
            data: { action: 'check_new' },
            success: function(response) {
                if (response.success && response.count > 0) {
                    updateNotificationBadge(response.count);
                }
            }
        });
    }

    /**
     * Update notification badge
     */
    function updateNotificationBadge(count) {
        var badge = $('#notificationsDropdown .badge');
        if (count > 0) {
            if (badge.length === 0) {
                badge = $('<span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger"></span>');
                $('#notificationsDropdown').append(badge);
            }
            badge.text(count > 9 ? '9+' : count);
        } else {
            badge.remove();
        }
    }

    /**
     * Mark notification as read
     */
    function markNotificationAsRead(notificationId) {
        $.ajax({
            url: '/obgyn-research-platform/api/notifications.php',
            method: 'POST',
            data: {
                action: 'mark_read',
                notification_id: notificationId
            },
            success: function(response) {
                if (response.success) {
                    $('.notification-item[data-id="' + notificationId + '"]').removeClass('unread');
                }
            }
        });
    }

    /**
     * Initialize search functionality
     */
    function initSearch() {
        var searchTimeout;
        
        $('.search-input').on('input', function() {
            var query = $(this).val();
            var searchType = $(this).data('search-type') || 'all';
            
            clearTimeout(searchTimeout);
            
            if (query.length >= 3) {
                searchTimeout = setTimeout(function() {
                    performSearch(query, searchType);
                }, 500);
            }
        });
    }

    /**
     * Perform search
     */
    function performSearch(query, type) {
        $.ajax({
            url: '/obgyn-research-platform/api/search.php',
            method: 'GET',
            data: {
                q: query,
                type: type
            },
            success: function(response) {
                if (response.success) {
                    displaySearchResults(response.results);
                }
            }
        });
    }

    /**
     * Display search results
     */
    function displaySearchResults(results) {
        var resultsContainer = $('.search-results');
        
        if (resultsContainer.length === 0) {
            resultsContainer = $('<div class="search-results dropdown-menu show" style="width: 100%;"></div>');
            $('.search-box').append(resultsContainer);
        }
        
        resultsContainer.empty();
        
        if (results.length === 0) {
            resultsContainer.append('<div class="dropdown-item">No results found</div>');
        } else {
            results.forEach(function(result) {
                var item = $('<a class="dropdown-item" href="' + result.url + '"></a>');
                item.html(
                    '<div class="d-flex align-items-center">' +
                    '<i class="' + result.icon + ' me-2"></i>' +
                    '<div>' +
                    '<div>' + result.title + '</div>' +
                    '<small class="text-muted">' + result.description + '</small>' +
                    '</div>' +
                    '</div>'
                );
                resultsContainer.append(item);
            });
        }
    }

    /**
     * Initialize auto-save for forms
     */
    function initAutoSave() {
        var autoSaveTimeout;
        
        $('.auto-save-form input, .auto-save-form textarea, .auto-save-form select').on('input change', function() {
            clearTimeout(autoSaveTimeout);
            
            var form = $(this).closest('form');
            
            autoSaveTimeout = setTimeout(function() {
                autoSaveForm(form);
            }, 2000);
        });
    }

    /**
     * Auto-save form data
     */
    function autoSaveForm(form) {
        var formData = form.serialize();
        var saveUrl = form.data('autosave-url');
        
        if (!saveUrl) return;
        
        $.ajax({
            url: saveUrl,
            method: 'POST',
            data: formData + '&action=autosave',
            success: function(response) {
                if (response.success) {
                    showAutoSaveIndicator('Saved');
                }
            },
            error: function() {
                showAutoSaveIndicator('Error saving', 'danger');
            }
        });
    }

    /**
     * Show auto-save indicator
     */
    function showAutoSaveIndicator(message, type) {
        type = type || 'success';
        
        var indicator = $('.autosave-indicator');
        
        if (indicator.length === 0) {
            indicator = $('<div class="autosave-indicator position-fixed bottom-0 end-0 m-3"></div>');
            $('body').append(indicator);
        }
        
        indicator.html(
            '<div class="alert alert-' + type + ' alert-dismissible fade show" role="alert">' +
            '<i class="fas fa-check-circle"></i> ' + message +
            '</div>'
        );
        
        setTimeout(function() {
            indicator.find('.alert').fadeOut(function() {
                $(this).remove();
            });
        }, 3000);
    }

    /**
     * Confirm action
     */
    window.confirmAction = function(message, callback) {
        if (confirm(message)) {
            callback();
        }
    };

    /**
     * Show loading spinner
     */
    window.showLoading = function(element) {
        var spinner = '<span class="loading-spinner"></span>';
        $(element).html(spinner).prop('disabled', true);
    };

    /**
     * Hide loading spinner
     */
    window.hideLoading = function(element, originalText) {
        $(element).html(originalText).prop('disabled', false);
    };

    /**
     * Show toast notification
     */
    window.showToast = function(message, type) {
        type = type || 'info';
        
        var toast = $('<div class="toast-notification"></div>');
        toast.html(
            '<div class="alert alert-' + type + ' alert-dismissible fade show" role="alert">' +
            message +
            '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>' +
            '</div>'
        );
        
        $('body').append(toast);
        
        setTimeout(function() {
            toast.fadeOut(function() {
                $(this).remove();
            });
        }, 5000);
    };

    /**
     * Copy to clipboard
     */
    window.copyToClipboard = function(text) {
        var tempInput = $('<input>');
        $('body').append(tempInput);
        tempInput.val(text).select();
        document.execCommand('copy');
        tempInput.remove();
        
        showToast('Copied to clipboard!', 'success');
    };

    /**
     * Initialize Hero Slider (Swiper) - Phase 9
     */
    function initHeroSlider() {
        if (typeof Swiper !== 'undefined' && document.querySelector('.hero-swiper')) {
            new Swiper('.hero-swiper', {
                loop: true,
                autoplay: {
                    delay: 5000,
                    disableOnInteraction: false,
                },
                pagination: {
                    el: '.swiper-pagination',
                    clickable: true,
                },
                navigation: {
                    nextEl: '.swiper-button-next',
                    prevEl: '.swiper-button-prev',
                },
                effect: 'fade',
                fadeEffect: {
                    crossFade: true
                },
                speed: 1000,
            });
        }
    }

    /**
     * Initialize AOS (Animate On Scroll) - Phase 9
     */
    function initAOS() {
        if (typeof AOS !== 'undefined') {
            AOS.init({
                duration: 1000,
                easing: 'ease-in-out',
                once: true,
                mirror: false,
                offset: 100,
            });
        }
    }

    /**
     * Initialize LazyLoad - Phase 9
     */
    function initLazyLoad() {
        if (typeof LazyLoad !== 'undefined') {
            new LazyLoad({
                elements_selector: '.lazy',
                threshold: 0
            });
        }
    }

    /**
     * Initialize Sticky Header - Phase 9
     */
    function initStickyHeader() {
        var navbar = document.querySelector('.navbar');
        if (!navbar) return;

        window.addEventListener('scroll', function() {
            var currentScroll = window.pageYOffset;
            
            if (currentScroll > 100) {
                navbar.classList.add('navbar-scrolled');
            } else {
                navbar.classList.remove('navbar-scrolled');
            }
        });
    }

    /**
     * Initialize Scroll to Top Button - Phase 9
     */
    function initScrollToTop() {
        // Create scroll to top button if it doesn't exist
        if ($('#scrollToTop').length === 0) {
            var scrollBtn = $('<button id="scrollToTop" class="btn btn-primary" title="Back to top">' +
                '<i class="fas fa-arrow-up"></i></button>');
            $('body').append(scrollBtn);
        }

        var scrollToTopBtn = $('#scrollToTop');

        // Show/hide button based on scroll position
        $(window).scroll(function() {
            if ($(this).scrollTop() > 300) {
                scrollToTopBtn.fadeIn();
            } else {
                scrollToTopBtn.fadeOut();
            }
        });

        // Scroll to top on click
        scrollToTopBtn.click(function() {
            $('html, body').animate({ scrollTop: 0 }, 600);
            return false;
        });
    }

    /**
     * Initialize Counter Animations - Phase 9
     */
    function initCounterAnimations() {
        var counters = document.querySelectorAll('.counter');
        
        if (counters.length === 0) return;

        var observer = new IntersectionObserver(function(entries) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    animateCounter(entry.target);
                    observer.unobserve(entry.target);
                }
            });
        }, { threshold: 0.5 });

        counters.forEach(function(counter) {
            observer.observe(counter);
        });
    }

    /**
     * Animate Counter - Phase 9
     */
    function animateCounter(element) {
        var target = parseInt(element.getAttribute('data-target'));
        var duration = 2000;
        var start = 0;
        var increment = target / (duration / 16);
        
        var timer = setInterval(function() {
            start += increment;
            if (start >= target) {
                element.textContent = target.toLocaleString();
                clearInterval(timer);
            } else {
                element.textContent = Math.floor(start).toLocaleString();
            }
        }, 16);
    }

    /**
     * Initialize Mobile Menu - Phase 9
     */
    function initMobileMenu() {
        // Mobile menu toggle
        $('.navbar-toggler').on('click', function() {
            $('body').toggleClass('mobile-menu-open');
        });

        // Close mobile menu when clicking outside
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.navbar').length && $('body').hasClass('mobile-menu-open')) {
                $('.navbar-toggler').click();
            }
        });

        // Close mobile menu when clicking a link
        $('.navbar-nav a').on('click', function() {
            if (window.innerWidth < 992) {
                $('.navbar-toggler').click();
            }
        });
    }

})(jQuery);
