// Enhanced Modern Interactions for Orange Pi Homelab Dashboard 2025

document.addEventListener('DOMContentLoaded', function() {
    console.log('🚀 Orange Pi Homelab Dashboard - Enhanced Glassmorphism v2.0');
    
    // Add smooth scrolling
    document.documentElement.style.scrollBehavior = 'smooth';
    
    // Enhanced loading animations for widgets and cards
    const animatedElements = document.querySelectorAll('.widget, .card, .service-card, [class*="card"], [class*="widget"]');
    
    animatedElements.forEach((element, index) => {
        element.style.opacity = '0';
        element.style.transform = 'translateY(30px)';
        element.style.transition = 'opacity 0.8s ease, transform 0.8s ease';
        
        // Staggered animation with intersection observer for better performance
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    setTimeout(() => {
                        entry.target.style.opacity = '1';
                        entry.target.style.transform = 'translateY(0)';
                    }, index * 50);
                    observer.unobserve(entry.target);
                }
            });
        }, { threshold: 0.1 });
        
        observer.observe(element);
    });
    
    // Enhanced ripple effect for interactive elements
    function createAdvancedRipple(e) {
        const element = e.currentTarget;
        const rect = element.getBoundingClientRect();
        const size = Math.max(rect.width, rect.height);
        const x = e.clientX - rect.left - size / 2;
        const y = e.clientY - rect.top - size / 2;
        
        const ripple = document.createElement('span');
        ripple.className = 'ripple';
        ripple.style.width = ripple.style.height = size + 'px';
        ripple.style.left = x + 'px';
        ripple.style.top = y + 'px';
        
        // Ensure proper positioning
        if (getComputedStyle(element).position === 'static') {
            element.style.position = 'relative';
        }
        element.style.overflow = 'hidden';
        element.appendChild(ripple);
        
        // Clean up
        setTimeout(() => {
            if (ripple.parentNode) {
                ripple.parentNode.removeChild(ripple);
            }
        }, 600);
    }
    
    // Add ripple to all interactive elements
    const interactiveSelectors = [
        '.service-card', '.card', '.widget', 'button', '.btn',
        '[class*="card"]', '[class*="widget"]', '[role="button"]',
        'a[href]', '[onclick]', '[class*="clickable"]'
    ];
    
    interactiveSelectors.forEach(selector => {
        document.querySelectorAll(selector).forEach(element => {
            element.addEventListener('click', createAdvancedRipple);
            
            // Add cursor pointer if not already set
            if (getComputedStyle(element).cursor === 'auto') {
                element.style.cursor = 'pointer';
            }
        });
    });
    
    // Dynamic blur adjustment based on scroll (performance optimized)
    let lastScrollY = window.scrollY;
    let ticking = false;
    
    function updateBlur() {
        const scrollDelta = Math.abs(window.scrollY - lastScrollY);
        const dynamicBlur = Math.min(30, 20 + scrollDelta * 0.1);
        
        document.documentElement.style.setProperty('--blur-strength', `${dynamicBlur}px`);
        
        lastScrollY = window.scrollY;
        ticking = false;
    }
    
    window.addEventListener('scroll', () => {
        if (!ticking) {
            requestAnimationFrame(updateBlur);
            ticking = true;
        }
    });
    
    // Enhanced hover effects for service status indicators
    const statusElements = document.querySelectorAll('[class*="status"], .text-green-500, .text-red-500, .text-yellow-500');
    statusElements.forEach(element => {
        element.addEventListener('mouseenter', function() {
            this.style.transform = 'scale(1.05)';
            this.style.transition = 'transform 0.2s ease';
        });
        
        element.addEventListener('mouseleave', function() {
            this.style.transform = 'scale(1)';
        });
    });
    
    // Add loading shimmer effect remover
    setTimeout(() => {
        document.querySelectorAll('.loading-shimmer').forEach(el => {
            el.classList.remove('loading-shimmer');
        });
    }, 2000);
    
    // Dynamic time updates for widgets
    function updateDateTime() {
        const timeElements = document.querySelectorAll('.datetime, [class*="time"], [class*="date"]');
        timeElements.forEach(element => {
            const now = new Date();
            const options = {
                weekday: 'short',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            };
            
            if (element.textContent.includes('time') || element.textContent.includes('date')) {
                element.textContent = now.toLocaleDateString('en-GB', options);
            }
        });
    }
    
    // Update time every minute
    setInterval(updateDateTime, 60000);
    updateDateTime();
    
    // Enhanced search functionality
    const searchInputs = document.querySelectorAll('input[type="search"], input[type="text"], .search-container input');
    searchInputs.forEach(input => {
        input.addEventListener('focus', function() {
            this.parentElement.style.transform = 'scale(1.02)';
            this.parentElement.style.transition = 'transform 0.3s ease';
        });
        
        input.addEventListener('blur', function() {
            this.parentElement.style.transform = 'scale(1)';
        });
        
        // Add search suggestions or filtering if needed
        input.addEventListener('input', function() {
            const query = this.value.toLowerCase();
            if (query.length > 0) {
                // Could add service filtering here
                console.log('Searching for:', query);
            }
        });
    });
    
    // Service card health check simulation
    function updateServiceHealth() {
        const services = document.querySelectorAll('.service-card, .card, [class*="service"]');
        services.forEach(service => {
            const statusElements = service.querySelectorAll('[class*="status"]');
            statusElements.forEach(status => {
                // Simulate health check (in real implementation, this would be API calls)
                if (Math.random() > 0.9) { // 10% chance of status change
                    const currentClass = status.className;
                    if (currentClass.includes('up')) {
                        status.className = currentClass.replace('up', 'unknown');
                        status.textContent = '● Checking...';
                    } else if (currentClass.includes('unknown')) {
                        status.className = currentClass.replace('unknown', 'up');
                        status.textContent = '● Online';
                    }
                }
            });
        });
    }
    
    // Run health checks every 30 seconds
    setInterval(updateServiceHealth, 30000);
    
    // Add keyboard navigation support
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Tab') {
            // Enhance tab navigation for accessibility
            const focusableElements = document.querySelectorAll(
                'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
            );
            
            focusableElements.forEach(element => {
                element.addEventListener('focus', function() {
                    this.style.outline = '2px solid rgba(255, 255, 255, 0.5)';
                    this.style.outlineOffset = '2px';
                });
                
                element.addEventListener('blur', function() {
                    this.style.outline = 'none';
                });
            });
        }
        
        // Add escape key to clear search
        if (e.key === 'Escape') {
            searchInputs.forEach(input => {
                input.value = '';
                input.blur();
            });
        }
    });
    
    // Performance monitoring for blur effects
    function checkPerformance() {
        const start = performance.now();
        requestAnimationFrame(() => {
            const end = performance.now();
            const frameDuration = end - start;
            
            // If frame time is too long, reduce blur for performance
            if (frameDuration > 16.67) { // 60fps = 16.67ms per frame
                document.documentElement.style.setProperty('--blur-strength', '10px');
                console.warn('Reduced blur effects for performance');
            }
        });
    }
    
    // Check performance every 5 seconds
    setInterval(checkPerformance, 5000);
    
    // Add theme detection and adjustment
    const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)');
    function handleThemeChange(e) {
        if (e.matches) {
            document.documentElement.style.setProperty('--glass-bg', 'rgba(255, 255, 255, 0.05)');
        } else {
            document.documentElement.style.setProperty('--glass-bg', 'rgba(0, 0, 0, 0.05)');
        }
    }
    
    prefersDarkScheme.addEventListener('change', handleThemeChange);
    handleThemeChange(prefersDarkScheme);
    
    // Add service card click handling for navigation
    document.querySelectorAll('.service-card, [class*="service"]').forEach(card => {
        card.addEventListener('click', function(e) {
            // Look for href in the card or its children
            const link = this.querySelector('a[href]') || this.closest('a[href]');
            if (link && !e.defaultPrevented) {
                // Add slight delay for animation
                setTimeout(() => {
                    window.open(link.href, '_blank');
                }, 100);
            }
        });
    });
    
    console.log('✨ Enhanced Glassmorphism Dashboard initialized successfully!');
});

// Add CSS for better accessibility and interactions
const additionalStyles = document.createElement('style');
additionalStyles.textContent = `
    /* Enhanced focus states */
    *:focus {
        outline: 2px solid rgba(255, 255, 255, 0.5) !important;
        outline-offset: 2px !important;
    }
    
    /* Reduce motion for users who prefer it */
    @media (prefers-reduced-motion: reduce) {
        *, *::before, *::after {
            animation-duration: 0.01ms !important;
            animation-iteration-count: 1 !important;
            transition-duration: 0.01ms !important;
        }
    }
    
    /* Enhanced touch targets for mobile */
    @media (max-width: 768px) {
        button, .btn, .service-card, [role="button"] {
            min-height: 44px !important;
            min-width: 44px !important;
        }
    }
    
    /* Print styles */
    @media print {
        *, *::before, *::after {
            background: white !important;
            color: black !important;
            backdrop-filter: none !important;
            box-shadow: none !important;
        }
    }
`;

document.head.appendChild(additionalStyles);
