// Shared JavaScript for All Pages

// Global variables
let sidebarCollapsed = false;
let darkMode = false;
let currentPage = '';

// Initialize app when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// Initialize all app functionality
function initializeApp() {
    // Get current page from URL
    currentPage = getCurrentPage();
    console.log('Current page detected:', currentPage);
    console.log('Current URL:', window.location.pathname);
    
    // Initialize components
    initSidebarToggle();
    initDarkModeToggle();
    initSidebarDropdowns();
    initPageSpecificFeatures();
    
    // Load saved preferences
    loadPreferences();
    
    // Initialize page-specific features
    switch(currentPage) {
        case 'dashboard':
            console.log('Initializing dashboard...');
            initDashboard();
            break;
        case 'referral':
            console.log('Initializing referral...');
            initReferral();
            break;
        case 'faucet':
            console.log('Initializing faucet...');
            initFaucet();
            break;
        case 'challenge':
            console.log('Initializing challenge...');
            initChallenge();
            break;
        case 'contact':
            console.log('Initializing contact...');
            initContact();
            break;
        case 'faq':
            console.log('Initializing FAQ...');
            initFAQ();
            break;
        case 'shortlinks':
            console.log('Initializing shortlinks...');
            initShortlinks();
            break;
        default:
            console.log('No specific initialization for page:', currentPage);
    }
    
    // Fallback: Check if we're on a faucet page by looking for the timer element
    setTimeout(() => {
        const timeLeftElement = document.getElementById('timeLeft');
        if (timeLeftElement && !window.faucetTimerInitialized) {
            console.log('Fallback: Found timeLeft element, initializing faucet timer...');
            initFaucet();
            window.faucetTimerInitialized = true;
        }
    }, 100);
}

// Get current page name
function getCurrentPage() {
    const path = window.location.pathname;
    const segments = path.split('/').filter(segment => segment !== '');
    
    // Check for member pages
    if (segments.includes('member')) {
        const memberIndex = segments.indexOf('member');
        if (memberIndex + 1 < segments.length) {
            return segments[memberIndex + 1];
        }
    }
    
    // Fallback to last segment
    const page = segments[segments.length - 1] || 'dashboard';
    return page;
}

// Initialize sidebar toggle
function initSidebarToggle() {
    const sidebarToggle = document.getElementById('sidebarToggle');
    const sidebar = document.getElementById('dashboardSidebar');
    const mobileOverlay = document.getElementById('mobileOverlay');
    const body = document.body;
    
    // Set active sidebar item based on current page
    setActiveSidebarItem();
    
    if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('collapsed');
            body.classList.toggle('sidebar-collapsed');
            sidebarCollapsed = !sidebarCollapsed;
            
            // On mobile, also toggle mobile-open class and overlay
            if (window.innerWidth <= 768) {
                sidebar.classList.toggle('mobile-open');
                if (mobileOverlay) {
                    mobileOverlay.classList.toggle('active');
                }
            }
            
            // Save preference
            localStorage.setItem('sidebarCollapsed', sidebarCollapsed);
        });
        
        // Close sidebar when clicking overlay on mobile
        if (mobileOverlay) {
            mobileOverlay.addEventListener('click', function() {
                if (window.innerWidth <= 768 && sidebar.classList.contains('mobile-open')) {
                    sidebar.classList.remove('mobile-open');
                    mobileOverlay.classList.remove('active');
                }
            });
        }
        
        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', function(event) {
            if (window.innerWidth <= 768 && 
                sidebar.classList.contains('mobile-open') && 
                !sidebar.contains(event.target) && 
                !sidebarToggle.contains(event.target)) {
                sidebar.classList.remove('mobile-open');
                if (mobileOverlay) {
                    mobileOverlay.classList.remove('active');
                }
            }
        });
    }
    
    // Handle window resize
    window.addEventListener('resize', function() {
        if (window.innerWidth > 768) {
            const sidebar = document.getElementById('dashboardSidebar');
            const mobileOverlay = document.getElementById('mobileOverlay');
            if (sidebar) sidebar.classList.remove('mobile-open');
            if (mobileOverlay) mobileOverlay.classList.remove('active');
        }
    });
}

// Initialize sidebar dropdowns
function initSidebarDropdowns() {
    // This function is now handled by the inline toggleDropdown function
}

// Custom dropdown toggle function
function toggleDropdown(element) {
    // Find the parent dropdown container
    let dropdown = element.parentElement;
    while (dropdown && !dropdown.classList.contains('sidebar-dropdown')) {
        dropdown = dropdown.parentElement;
    }
    
    if (!dropdown) {
        return;
    }
    
    const isActive = dropdown.classList.contains('active');
    
    // Close all other dropdowns
    document.querySelectorAll('.sidebar-dropdown').forEach(otherDropdown => {
        if (otherDropdown !== dropdown) {
            otherDropdown.classList.remove('active');
        }
    });
    
    // Toggle current dropdown
    if (isActive) {
        dropdown.classList.remove('active');
    } else {
        dropdown.classList.add('active');
    }
}

// Make function globally available
window.toggleDropdown = toggleDropdown;

// Initialize dark mode toggle
function initDarkModeToggle() {
    const darkModeToggle = document.getElementById('darkModeToggle');
    const body = document.body;
    
    // Check for saved theme preference or default to light mode
    const currentTheme = localStorage.getItem('theme') || 'light';
    if (currentTheme === 'dark') {
        body.classList.add('dark-mode');
        darkModeToggle.classList.add('active');
        darkMode = true;
    }
    
    if (darkModeToggle) {
        darkModeToggle.addEventListener('click', function() {
            body.classList.toggle('dark-mode');
            darkModeToggle.classList.toggle('active');
            darkMode = !darkMode;
            
            // Save theme preference
            localStorage.setItem('theme', darkMode ? 'dark' : 'light');
        });
    }
}

// Load saved preferences
function loadPreferences() {
    // Load sidebar state
    const savedSidebarState = localStorage.getItem('sidebarCollapsed');
    if (savedSidebarState === 'true') {
        const sidebar = document.getElementById('dashboardSidebar');
        const body = document.body;
        if (sidebar) {
            sidebar.classList.add('collapsed');
            body.classList.add('sidebar-collapsed');
            sidebarCollapsed = true;
        }
    }
}

// Initialize page-specific features
function initPageSpecificFeatures() {
    // Common features for all pages
    initTooltips();
    initAnimations();
}

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

// Initialize animations
function initAnimations() {
    // Animate elements on scroll
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('fade-in');
            }
        });
    }, observerOptions);
    
    // Observe all cards and sections
    document.querySelectorAll('.stat-card, .action-card, .benefit-card, .challenge-card, .contact-card, .faq-item').forEach(el => {
        observer.observe(el);
    });
}

// Dashboard specific functions
function initDashboard() {
    loadRecentActivity();
}

function loadRecentActivity() {
    // Activity is already in HTML, just add animations
    const activityItems = document.querySelectorAll('.activity-item');
    activityItems.forEach((item, index) => {
        setTimeout(() => {
            item.classList.add('fade-in');
        }, index * 200);
    });
}

// Referral specific functions
function initReferral() {
    loadReferralsTable();
}

function loadReferralsTable() {
    // The table is already populated by PHP, just add animations
    const tableBody = document.getElementById('referralsTableBody');
    if (tableBody) {
        const rows = tableBody.querySelectorAll('tr');
        rows.forEach((row, index) => {
            row.style.opacity = '0';
            row.style.transform = 'translateY(20px)';
            row.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
            
            setTimeout(() => {
                row.style.opacity = '1';
                row.style.transform = 'translateY(0)';
            }, index * 100);
        });
    }
}

function copyReferralLink() {
    const referralLink = document.getElementById('referralLink');
    if (referralLink) {
        referralLink.select();
        referralLink.setSelectionRange(0, 99999);
        document.execCommand('copy');
        showToast('Referral link copied to clipboard!', 'success');
    }
}

// Faucet specific functions
function initFaucet() {
    if (window.faucetTimerInitialized) {
        console.log('Faucet timer already initialized, skipping...');
        return;
    }
    
    console.log('Initializing faucet timer...');
    startFaucetTimer();
    updateFaucetInfo();
    window.faucetTimerInitialized = true;
}

function startFaucetTimer() {
    const timeLeftElement = document.getElementById('timeLeft');

    const claimButton = document.getElementById('claimButton'); 
    console.log('Looking for timeLeft element:', timeLeftElement);
    
    if (!timeLeftElement) {
        console.log('timeLeft element not found!');
        return;
    }
    
    // Get timer value from the data attribute
    let timeLeft = 0;
    
    if (timeLeftElement.dataset.timer) {
        timeLeft = parseInt(timeLeftElement.dataset.timer) || 0;
        console.log('Timer value from data attribute:', timeLeft);
    } else {
        console.log('No timer data attribute found');
    }
    
    // If no time left, show ready state
    if (timeLeft <= 0) {
        console.log('No time left, showing ready state');
        timeLeftElement.textContent = 'Ready!';
        return;
    }
    
    console.log('Starting countdown timer with', timeLeft, 'seconds');
    
    const timer = setInterval(() => {
        const minutes = Math.floor(timeLeft / 60);
        const seconds = timeLeft % 60;
        
        timeLeftElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        
        if (timeLeft <= 0) {
            clearInterval(timer);
            timeLeftElement.textContent = 'Ready!';
            claimButton.textContent = "Reload to claim";
        }
        
        timeLeft--;
    }, 1000);
}



// Update faucet info cards
function updateFaucetInfo() {
    // Timer is now handled by startFaucetTimer()
    // This function can be used for other dynamic updates if needed
}

// Update time left countdown (legacy function - now handled by startFaucetTimer)
function updateTimeLeft() {
    // This function is now handled by startFaucetTimer()
    // Keeping for backward compatibility but not used
}

// Challenge specific functions
function initChallenge() {
    updateChallengeStats();
    loadChallenges();
    loadLeaderboard();
}

function updateChallengeStats() {
    animateCounter('challengesWon', 0, 0, 0);
    animateCounter('challengeEarnings', 0, 0.000, 3);
    document.getElementById('challengeLevel').textContent = '1';
}

function loadChallenges() {
    const challengesGrid = document.getElementById('challengesGrid');
    if (!challengesGrid) return;
    
    const challenges = [
        {
            title: 'Daily Quiz',
            difficulty: 'Easy',
            description: 'Answer 5 crypto-related questions correctly',
            reward: '0.001 BTC',
            time: '5 min',
            id: 'quiz'
        },
        {
            title: 'Memory Game',
            difficulty: 'Medium',
            description: 'Match crypto symbols in the correct order',
            reward: '0.002 BTC',
            time: '10 min',
            id: 'memory'
        },
        {
            title: 'Crypto Trivia',
            difficulty: 'Hard',
            description: 'Answer 10 advanced crypto questions',
            reward: '0.005 BTC',
            time: '15 min',
            id: 'trivia'
        }
    ];
    
    challengesGrid.innerHTML = challenges.map(challenge => `
        <div class="challenge-card" onclick="openChallenge('${challenge.id}')">
            <div class="challenge-header">
                <h3 class="challenge-title">${challenge.title}</h3>
                <span class="challenge-difficulty">${challenge.difficulty}</span>
            </div>
            <p class="challenge-description">${challenge.description}</p>
            <div class="challenge-reward">
                <span class="reward-amount">${challenge.reward}</span>
                <span class="challenge-time">${challenge.time}</span>
            </div>
            <button class="btn btn-primary challenge-btn">Start Challenge</button>
        </div>
    `).join('');
}

function openChallenge(challengeId) {
    const modal = new bootstrap.Modal(document.getElementById('challengeModal'));
    const modalTitle = document.getElementById('challengeModalTitle');
    const modalBody = document.getElementById('challengeModalBody');
    
    if (modalTitle) modalTitle.textContent = 'Challenge';
    if (modalBody) modalBody.innerHTML = '<p>Challenge content will be loaded here...</p>';
    
    modal.show();
}

function loadLeaderboard() {
    const leaderboardList = document.getElementById('leaderboardList');
    if (!leaderboardList) return;
    
    const players = [
        { rank: 1, name: 'CryptoMaster', score: 1250 },
        { rank: 2, name: 'BitcoinKing', score: 1100 },
        { rank: 3, name: 'EthereumPro', score: 950 },
        { rank: 4, name: 'BlockchainGuru', score: 800 },
        { rank: 5, name: 'CryptoNewbie', score: 650 }
    ];
    
    leaderboardList.innerHTML = players.map(player => `
        <div class="leaderboard-item">
            <div class="leaderboard-rank">${player.rank}</div>
            <div class="leaderboard-user">${player.name}</div>
            <div class="leaderboard-score">${player.score} pts</div>
        </div>
    `).join('');
}

// Contact specific functions
function initContact() {
    const contactForm = document.getElementById('contactForm');
    if (contactForm) {
        contactForm.addEventListener('submit', handleContactForm);
    }
}

function handleContactForm(e) {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData);
    
    // Simulate form submission
    const submitBtn = e.target.querySelector('.btn-submit');
    const originalText = submitBtn.innerHTML;
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
    
    setTimeout(() => {
        showToast('Message sent successfully! We\'ll get back to you soon.', 'success');
        e.target.reset();
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    }, 2000);
}

// FAQ specific functions
function initFAQ() {
    const searchInput = document.getElementById('faqSearch');
    const categoryTabs = document.querySelectorAll('.category-tab');
    
    if (searchInput) {
        searchInput.addEventListener('input', filterFAQs);
    }
    
    categoryTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // Remove active class from all tabs
            categoryTabs.forEach(t => t.classList.remove('active'));
            // Add active class to clicked tab
            this.classList.add('active');
            
            // Filter FAQs by category
            const category = this.dataset.category;
            filterFAQsByCategory(category);
        });
    });
}

function filterFAQs() {
    const searchTerm = document.getElementById('faqSearch').value.toLowerCase();
    const faqItems = document.querySelectorAll('.faq-item');
    
    faqItems.forEach(item => {
        const question = item.querySelector('.faq-question h3').textContent.toLowerCase();
        const answer = item.querySelector('.faq-answer p').textContent.toLowerCase();
        
        if (question.includes(searchTerm) || answer.includes(searchTerm)) {
            item.style.display = 'block';
        } else {
            item.style.display = 'none';
        }
    });
}

function filterFAQsByCategory(category) {
    const faqItems = document.querySelectorAll('.faq-item');
    
    faqItems.forEach(item => {
        if (category === 'all' || item.dataset.category === category) {
            item.style.display = 'block';
        } else {
            item.style.display = 'none';
        }
    });
}

function toggleFAQ(element) {
    const faqItem = element.closest('.faq-item');
    const isActive = faqItem.classList.contains('active');
    
    // Close all other FAQ items
    document.querySelectorAll('.faq-item').forEach(item => {
        item.classList.remove('active');
    });
    
    // Toggle current item
    if (!isActive) {
        faqItem.classList.add('active');
    }
}

// Shortlinks specific functions
function initShortlinks() {
    initModal();
}


function startShortlink(linkId) {
    const shortlinkItem = document.querySelector(`[data-id="${linkId}"]`);
    if (!shortlinkItem) return;
    
    // Add loading state
    shortlinkItem.classList.add('loading');
    const startBtn = shortlinkItem.querySelector('.shortlink-btn.primary');
    if (startBtn) {
        startBtn.disabled = true;
        startBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i><span>Starting...</span>';
    }
    
    // Make API call to start shortlink
    fetch(`/member/shortlinks/start/${linkId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        shortlinkItem.classList.remove('loading');
        
        if (data.success) {
            // Open the shortlink URL
            if (data.url && data.url !== '#') {
                window.open(data.url, '_blank');
                
                // Show completion modal or redirect after wait time
    setTimeout(() => {
                    completeShortlink(linkId);
                }, (data.waitTime || 30) * 60 * 1000); // Convert minutes to milliseconds
            } else {
                // If no URL, just complete immediately
                completeShortlink(linkId);
            }
        } else {
            showToast(data.message || 'Failed to start shortlink', 'error');
            if (startBtn) {
                startBtn.disabled = false;
                startBtn.innerHTML = '<i class="fas fa-play"></i><span>Start</span>';
            }
        }
    })
    .catch(error => {
        shortlinkItem.classList.remove('loading');
        showToast('Error starting shortlink', 'error');
        if (startBtn) {
            startBtn.disabled = false;
            startBtn.innerHTML = '<i class="fas fa-play"></i><span>Start</span>';
        }
    });
}

function completeShortlink(linkId) {
    // Make API call to complete shortlink
    fetch(`/member/shortlinks/complete/${linkId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({
            url: window.location.href // You might want to pass the actual URL
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const shortlinkItem = document.querySelector(`[data-id="${linkId}"]`);
            if (shortlinkItem) {
        shortlinkItem.classList.add('completed');
        
        // Disable buttons
        const buttons = shortlinkItem.querySelectorAll('.shortlink-btn');
        buttons.forEach(btn => {
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-check"></i><span>Completed</span>';
        });
            }
            
            showToast(data.message || 'Shortlink completed successfully!', 'success');
            updateTotals();
        } else {
            showToast(data.message || 'Failed to complete shortlink', 'error');
        }
    })
    .catch(error => {
        showToast('Error completing shortlink', 'error');
    });
}


function initModal() {
    // Modal functionality for shortlinks
    const completeBtn = document.getElementById('completeBtn');
    if (completeBtn) {
        completeBtn.addEventListener('click', completeShortlink);
    }
}

function completeShortlink() {
    showToast('Shortlink completed successfully!', 'success');
}

// Set active sidebar item based on current page
function setActiveSidebarItem() {
    const currentPage = getCurrentPage();
    const sidebarItems = document.querySelectorAll('.sidebar-item');
    
    // Remove active class from all items
    sidebarItems.forEach(item => {
        item.classList.remove('active');
    });
    
    // Add active class to current page item
    const currentPageItem = document.querySelector(`a[href="${currentPage}.html"]`);
    if (currentPageItem) {
        currentPageItem.classList.add('active');
    }
}

// Utility functions
function animateCounter(elementId, start, end, decimals) {
    const element = document.getElementById(elementId);
    if (!element) return;
    
    const duration = 2000;
    const startTime = performance.now();
    
    function updateCounter(currentTime) {
        const elapsed = currentTime - startTime;
        const progress = Math.min(elapsed / duration, 1);
        
        const current = start + (end - start) * progress;
        element.textContent = current.toFixed(decimals);
        
        if (progress < 1) {
            requestAnimationFrame(updateCounter);
        }
    }
    
    requestAnimationFrame(updateCounter);
}

function showToast(message, type = 'info') {
    // Create toast element
    const toast = document.createElement('div');
    toast.className = `toast-notification toast-${type}`;
    toast.innerHTML = `
        <div class="toast-content">
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
            <span>${message}</span>
        </div>
    `;
    
    // Add to page
    document.body.appendChild(toast);
    
    // Show toast
    setTimeout(() => toast.classList.add('show'), 100);
    
    // Remove toast
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => document.body.removeChild(toast), 300);
    }, 3000);
}

// Add CSS for toast notifications
const toastStyles = `
<style>
.toast-notification {
    position: fixed;
    top: 20px;
    right: 20px;
    background: var(--light-card);
    border: 1px solid var(--light-border);
    border-radius: var(--border-radius);
    padding: 1rem 1.5rem;
    box-shadow: var(--shadow-medium);
    z-index: 9999;
    transform: translateX(100%);
    transition: transform 0.3s ease;
    max-width: 300px;
}

.toast-notification.show {
    transform: translateX(0);
}

.toast-content {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    color: var(--text-primary);
    font-weight: 500;
}

.toast-success {
    border-left: 4px solid var(--success-color);
}

.toast-error {
    border-left: 4px solid #dc3545;
}

.toast-info {
    border-left: 4px solid var(--primary-blue);
}

.toast-content i {
    font-size: 1.1rem;
}

.toast-success .toast-content i {
    color: var(--success-color);
}

.toast-error .toast-content i {
    color: #dc3545;
}

.toast-info .toast-content i {
    color: var(--primary-blue);
}
</style>
`;

document.head.insertAdjacentHTML('beforeend', toastStyles);
