/**
 * JavaScript for INDEX-SISTEM-JOCURI v2.0
 * Clean, minimal interactions
 */

document.addEventListener('DOMContentLoaded', function() {
    
    // Initialize search functionality
    initializeSearch();
    
    // Initialize filter functionality  
    initializeFilters();
    
    // Initialize UI enhancements
    initializeUIEnhancements();
});

/**
 * Initialize search functionality
 */
function initializeSearch() {
    const searchInput = document.getElementById('search_query');
    
    if (searchInput) {
        // Auto-focus search input on main page
        if (window.location.pathname === '/') {
            searchInput.focus();
        }
        
        // Handle Enter key in search
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                const form = this.closest('form');
                if (form) {
                    form.submit();
                }
            }
        });
        
        // Clear search with Escape key
        searchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                this.value = '';
            }
        });
    }
}

/**
 * Initialize filter functionality
 */
function initializeFilters() {
    const filterSelects = document.querySelectorAll('.filter-select');
    
    filterSelects.forEach(select => {
        // Auto-submit on filter change (for better UX)
        select.addEventListener('change', function() {
            if (this.value && !this.classList.contains('no-auto-submit')) {
                const form = this.closest('form');
                if (form) {
                    // Small delay to prevent rapid submissions
                    setTimeout(() => {
                        form.submit();
                    }, 100);
                }
            }
        });
    });
}

/**
 * Initialize UI enhancements
 */
function initializeUIEnhancements() {
    // Add smooth scrolling for anchor links
    const anchorLinks = document.querySelectorAll('a[href^="#"]');
    anchorLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                e.preventDefault();
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });
    
    // Add loading states to buttons
    const buttons = document.querySelectorAll('.btn');
    buttons.forEach(button => {
        if (button.type === 'submit') {
            button.addEventListener('click', function() {
                const originalText = this.textContent;
                this.textContent = 'Se încarcă...';
                this.disabled = true;
                
                // Re-enable after form submission or timeout
                setTimeout(() => {
                    this.textContent = originalText;
                    this.disabled = false;
                }, 3000);
            });
        }
    });
    
    // Add fade-in animation for activity cards
    const activityCards = document.querySelectorAll('.activity-card');
    if (activityCards.length > 0) {
        // Use Intersection Observer for better performance
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0)';
                }
            });
        }, {
            threshold: 0.1
        });
        
        activityCards.forEach((card, index) => {
            // Initial state
            card.style.opacity = '0';
            card.style.transform = 'translateY(20px)';
            card.style.transition = `opacity 0.6s ease ${index * 0.1}s, transform 0.6s ease ${index * 0.1}s`;
            
            observer.observe(card);
        });
    }
}

/**
 * Clear all filters
 */
function clearFilters() {
    const form = document.querySelector('.search-form');
    if (form) {
        // Clear search input
        const searchInput = form.querySelector('input[name="search_query"]');
        if (searchInput) {
            searchInput.value = '';
        }
        
        // Reset all select elements
        const selects = form.querySelectorAll('select');
        selects.forEach(select => {
            select.selectedIndex = 0;
        });
        
        // Submit form to show all results
        form.submit();
    }
}

/**
 * Remove specific filter
 */
function removeFilter(filterName) {
    const filterElement = document.querySelector(`[name="${filterName}"]`);
    if (filterElement) {
        if (filterElement.tagName === 'SELECT') {
            filterElement.selectedIndex = 0;
        } else {
            filterElement.value = '';
        }
        
        const form = filterElement.closest('form');
        if (form) {
            form.submit();
        }
    }
}

/**
 * Copy current page URL to clipboard
 */
function copyPageURL() {
    if (navigator.clipboard) {
        navigator.clipboard.writeText(window.location.href).then(() => {
            showNotification('Link copiat în clipboard!');
        }).catch(() => {
            fallbackCopyTextToClipboard(window.location.href);
        });
    } else {
        fallbackCopyTextToClipboard(window.location.href);
    }
}

/**
 * Fallback function to copy text to clipboard
 */
function fallbackCopyTextToClipboard(text) {
    const textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.top = "0";
    textArea.style.left = "0";
    textArea.style.position = "fixed";
    
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    
    try {
        document.execCommand('copy');
        showNotification('Link copiat în clipboard!');
    } catch (err) {
        console.error('Could not copy text: ', err);
        showNotification('Nu s-a putut copia link-ul', 'error');
    }
    
    document.body.removeChild(textArea);
}

/**
 * Show notification message
 */
function showNotification(message, type = 'success') {
    // Remove existing notifications
    const existingNotifications = document.querySelectorAll('.notification');
    existingNotifications.forEach(notification => notification.remove());
    
    // Create notification element
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    // Style the notification
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#28a745' : '#dc3545'};
        color: white;
        padding: 1rem 1.5rem;
        border-radius: 6px;
        font-weight: 600;
        z-index: 1000;
        opacity: 0;
        transform: translateX(100%);
        transition: all 0.3s ease;
    `;
    
    document.body.appendChild(notification);
    
    // Animate in
    setTimeout(() => {
        notification.style.opacity = '1';
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // Auto-remove after 3 seconds
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

/**
 * Debounce function for performance optimization
 */
function debounce(func, wait, immediate) {
    let timeout;
    return function executedFunction() {
        const context = this;
        const args = arguments;
        const later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        const callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}

/**
 * Handle form submission with loading state
 */
function handleFormSubmission(form) {
    const submitButton = form.querySelector('button[type="submit"]');
    if (submitButton) {
        const originalText = submitButton.textContent;
        submitButton.textContent = 'Se încarcă...';
        submitButton.disabled = true;
        
        // Set a timeout to re-enable the button in case of slow response
        setTimeout(() => {
            submitButton.textContent = originalText;
            submitButton.disabled = false;
        }, 5000);
    }
}

// Global functions for template usage
window.clearFilters = clearFilters;
window.removeFilter = removeFilter;
window.copyPageURL = copyPageURL;