// Main JavaScript file for Cyber Invest platform
$(document).ready(function() {

    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // Initialize popovers
    $('[data-toggle="popover"]').popover();

    // Auto-hide alerts after 5 seconds
    setTimeout(function() {
        $('.alert').fadeOut('slow');
    }, 5000);

    // Confirm delete actions
    $('.confirm-delete').on('click', function(e) {
        if (!confirm('Are you sure you want to delete this item?')) {
            e.preventDefault();
        }
    });

    // Copy to clipboard functionality
    $('.copy-to-clipboard').on('click', function(e) {
        e.preventDefault();
        const textToCopy = $(this).data('clipboard-text') || $(this).text();
        navigator.clipboard.writeText(textToCopy).then(function() {
            // Show success message
            const originalText = $(this).text();
            $(this).text('Copied!');
            setTimeout(() => {
                $(this).text(originalText);
            }, 2000);
        }.bind(this));
    });

    // Format currency inputs
    $('.currency-input').on('input', function() {
        let value = $(this).val().replace(/[^0-9.]/g, '');
        if (value) {
            $(this).val(parseFloat(value).toFixed(2));
        }
    });

    // Investment calculator
    function calculateInvestment() {
        const amount = parseFloat($('#investment-amount').val()) || 0;
        const planId = $('#investment-plan').val();

        if (amount > 0 && planId) {
            $.ajax({
                url: 'api/get-investment-calculation.php',
                method: 'POST',
                data: { amount: amount, plan_id: planId },
                success: function(response) {
                    if (response.success) {
                        $('#expected-profit').text('$' + response.profit.toFixed(2));
                        $('#total-return').text('$' + response.total.toFixed(2));
                        $('#investment-summary').show();
                    }
                }
            });
        }
    }

    $('#investment-amount, #investment-plan').on('change input', calculateInvestment);

    // Deposit form validation
    $('#deposit-form').on('submit', function(e) {
        const amount = parseFloat($('#deposit-amount').val());
        const method = $('#deposit-method').val();

        if (!amount || amount < 10) {
            e.preventDefault();
            alert('Minimum deposit amount is $10');
            return false;
        }

        if (!method) {
            e.preventDefault();
            alert('Please select a payment method');
            return false;
        }
    });

    // Withdrawal form validation
    $('#withdrawal-form').on('submit', function(e) {
        const amount = parseFloat($('#withdrawal-amount').val());
        const method = $('#withdrawal-method').val();

        if (!amount || amount < 1) {
            e.preventDefault();
            alert('Minimum withdrawal amount is $1');
            return false;
        }

        if (!method) {
            e.preventDefault();
            alert('Please select a withdrawal method');
            return false;
        }
    });

    // Profile picture preview
    $('#profile-picture').on('change', function() {
        const file = this.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#profile-preview').attr('src', e.target.result).show();
            };
            reader.readAsDataURL(file);
        }
    });

    // Password strength indicator
    $('#new-password').on('input', function() {
        const password = $(this).val();
        const strength = calculatePasswordStrength(password);

        $('#password-strength').removeClass('weak medium strong').addClass(strength);
        $('#password-strength-text').text(strength.charAt(0).toUpperCase() + strength.slice(1));
    });

    function calculatePasswordStrength(password) {
        let score = 0;
        if (password.length >= 8) score++;
        if (/[a-z]/.test(password)) score++;
        if (/[A-Z]/.test(password)) score++;
        if (/[0-9]/.test(password)) score++;
        if (/[^A-Za-z0-9]/.test(password)) score++;

        if (score <= 2) return 'weak';
        if (score <= 4) return 'medium';
        return 'strong';
    }

    // Real-time balance updates
    function updateBalance() {
        $.ajax({
            url: 'api/get-balance.php',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    $('.balance-amount').text('$' + response.balance.toFixed(2));
                    $('.available-balance').text('$' + response.available_balance.toFixed(2));
                }
            }
        });
    }

    // Update balance every 30 seconds
    setInterval(updateBalance, 30000);

    // Notification system
    function loadNotifications() {
        $.ajax({
            url: 'api/get-notifications.php',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    updateNotificationBadge(response.notifications);
                }
            }
        });
    }

    function updateNotificationBadge(notifications) {
        const unreadCount = notifications.filter(n => !n.is_read).length;
        if (unreadCount > 0) {
            $('.notification-badge').text(unreadCount).show();
        } else {
            $('.notification-badge').hide();
        }
    }

    // Load notifications on page load
    loadNotifications();

    // Mark notification as read
    $(document).on('click', '.notification-item', function() {
        const notificationId = $(this).data('id');
        $.ajax({
            url: 'api/mark-notification-read.php',
            method: 'POST',
            data: { id: notificationId },
            success: function() {
                loadNotifications();
            }
        });
    });

    // Form submission with loading states
    $('form').on('submit', function() {
        const submitBtn = $(this).find('button[type="submit"]');
        const originalText = submitBtn.text();

        submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Processing...');

        // Re-enable after 10 seconds as fallback
        setTimeout(() => {
            submitBtn.prop('disabled', false).text(originalText);
        }, 10000);
    });

    // Smooth scrolling for anchor links
    $('a[href^="#"]').on('click', function(e) {
        const target = $(this.getAttribute('href'));
        if (target.length) {
            e.preventDefault();
            $('html, body').animate({
                scrollTop: target.offset().top - 70
            }, 500);
        }
    });

    // Mobile menu toggle
    $('.mobile-menu-toggle').on('click', function() {
        $('.mobile-menu').toggleClass('active');
    });

    // Close mobile menu when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.mobile-menu, .mobile-menu-toggle').length) {
            $('.mobile-menu').removeClass('active');
        }
    });

    // Initialize any charts if Chart.js is loaded
    if (typeof Chart !== 'undefined') {
        initializeCharts();
    }

    // Search functionality
    $('.search-input').on('input', function() {
        const query = $(this).val().toLowerCase();
        $('.searchable-item').each(function() {
            const text = $(this).text().toLowerCase();
            $(this).toggle(text.includes(query));
        });
    });

    // Table sorting
    $('.sortable').on('click', function() {
        const table = $(this).closest('table');
        const index = $(this).index();
        const rows = table.find('tbody tr').toArray();

        rows.sort((a, b) => {
            const aVal = $(a).find('td').eq(index).text();
            const bVal = $(b).find('td').eq(index).text();
            return aVal.localeCompare(bVal);
        });

        table.find('tbody').empty().append(rows);
    });

    console.log('Cyber Invest main.js loaded successfully');
});