/**
 * Payout Controller
 * Manages randomize vs custom payout percentage system
 */

class PayoutController {
    constructor() {
        this.config = null;
        this.init();
    }

    async init() {
        await this.loadConfig();
        this.setupEventListeners();
        this.restoreMode();
    }

    async loadConfig() {
        try {
            const response = await fetch('./php/config_manager.php?action=load');
            const result = await response.json();
            if (result.success) {
                this.config = result.data;
                window.payoutConfig = this.config;
            }
        } catch (error) {
            console.error('Error loading config:', error);
        }
    }

    setupEventListeners() {
        // Mode update button
        document.getElementById('payout-mode-update-button')?.addEventListener('click', () => {
            this.updateMode();
        });

        // Asset dropdown
        document.getElementById('payout-asset-dropdown-header')?.addEventListener('click', () => {
            this.toggleAssetDropdown();
        });

        // Percentage save button
        document.getElementById('payout-save-button')?.addEventListener('click', () => {
            this.savePercentage();
        });

        // Input validation
        document.getElementById('payout-percentage-input')?.addEventListener('input', (e) => {
            this.validateInput(e.target);
        });
    }

    restoreMode() {
        if (!this.config) return;
        
        const isRandomize = this.config.modes.randomizePayoutControl;
        
        if (isRandomize) {
            document.getElementById('payout-randomize').checked = true;
            document.getElementById('payout-custom-section').style.display = 'none';
        } else {
            document.getElementById('payout-custom').checked = true;
            document.getElementById('payout-custom-section').style.display = 'block';
            this.loadAssetCards();
        }
    }

    async updateMode() {
        const randomizeChecked = document.getElementById('payout-randomize').checked;
        const customChecked = document.getElementById('payout-custom').checked;

        const mode = randomizeChecked ? 'randomize' : 'custom';
        console.log('Updating mode to:', mode);

        try {
            const response = await fetch('./php/config_manager.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'updatePayoutMode',
                    mode: mode
                })
            });

            console.log('Response status:', response.status);
            const result = await response.json();
            console.log('Response result:', result);

            if (result.success) {
                this.config = result.data;
                window.payoutConfig = this.config;

                if (randomizeChecked) {
                    document.getElementById('payout-custom-section').style.display = 'none';
                    this.showStatus('Randomize mode activated', 'success');
                } else {
                    document.getElementById('payout-custom-section').style.display = 'block';
                    this.loadAssetCards();
                    this.showStatus('Custom mode activated', 'success');
                }
            } else {
                console.error('Update failed:', result.message);
                this.showStatus(result.message || 'Failed to update mode', 'error');
            }
        } catch (error) {
            console.error('Error updating mode:', error);
            this.showStatus('Error updating mode', 'error');
        }
    }

    async loadAssetCards() {
        try {
            const response = await fetch('./php/asset_card_manager.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'load' })
            });

            const result = await response.json();

            if (result.success) {
                this.populateAssetDropdown(result.data);
            }
        } catch (error) {
            console.error('Error loading asset cards:', error);
        }
    }

    populateAssetDropdown(assets) {
        const dropdown = document.getElementById('payout-asset-dropdown-list');
        dropdown.innerHTML = '';

        const assetNames = Object.keys(assets);

        if (assetNames.length === 0) {
            dropdown.innerHTML = '<div class="payout-dropdown-item" style="color: #a0a4b8;">No assets available</div>';
            return;
        }

        assetNames.forEach(assetName => {
            const item = document.createElement('div');
            item.className = 'payout-dropdown-item';
            item.textContent = assetName;
            item.addEventListener('click', () => {
                this.selectAsset(assetName, assets[assetName]);
            });
            dropdown.appendChild(item);
        });
    }

    selectAsset(assetName, assetData) {
        // Update dropdown header
        document.querySelector('#payout-asset-dropdown-header span').textContent = assetName;
        document.getElementById('payout-asset-dropdown-list').style.display = 'none';

        // Show percentage input
        document.getElementById('payout-percentage-group').style.display = 'block';
        document.getElementById('payout-save-button').style.display = 'flex';

        // Set current percentage if exists
        const currentPercentage = assetData.manualPercentage?.percentage || 80;
        document.getElementById('payout-percentage-input').value = currentPercentage;

        // Store selected asset
        this.selectedAsset = assetName;
    }

    async toggleAssetDropdown() {
        const dropdown = document.getElementById('payout-asset-dropdown-list');
        const arrow = document.querySelector('#payout-asset-dropdown-header .dropdown-arrow');
        
        if (dropdown.style.display === 'none') {
            await this.loadAssetCards();
            dropdown.style.display = 'block';
            arrow.style.transform = 'rotate(180deg)';
        } else {
            dropdown.style.display = 'none';
            arrow.style.transform = 'rotate(0deg)';
        }
    }

    validateInput(input) {
        const value = parseInt(input.value);
        const errorMsg = document.getElementById('payout-error-message');

        if (isNaN(value) || value < 20 || value > 93) {
            input.classList.add('error');
            errorMsg.textContent = 'Enter value between 20-93';
            errorMsg.style.display = 'block';
            return false;
        } else {
            input.classList.remove('error');
            errorMsg.style.display = 'none';
            return true;
        }
    }

    async savePercentage() {
        const input = document.getElementById('payout-percentage-input');
        const percentage = parseInt(input.value);

        if (!this.validateInput(input)) {
            return;
        }

        if (!this.selectedAsset) {
            this.showStatus('Please select an asset first', 'error');
            return;
        }

        try {
            const response = await fetch('./php/asset_card_manager.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'updatePercentage',
                    assetName: this.selectedAsset,
                    percentage: percentage,
                    status: true
                })
            });

            const result = await response.json();

            if (result.success) {
                this.showStatus(`Payout set to ${percentage}% for ${this.selectedAsset}`, 'success');
                
                // Update payout display if asset is active
                this.updatePayoutDisplay(this.selectedAsset, percentage);
            } else {
                this.showStatus(result.message || 'Failed to update percentage', 'error');
            }
        } catch (error) {
            console.error('Error saving percentage:', error);
            this.showStatus('Error saving percentage', 'error');
        }
    }

    updatePayoutDisplay(assetName, percentage) {
        // Update asset card payout display using card.id (full asset name)
        const assetCards = document.querySelectorAll('.asset-card-tab');
        assetCards.forEach(card => {
            if (card.id === assetName) {
                const payoutElement = card.querySelector('.asset-card-payout');
                if (payoutElement) {
                    payoutElement.textContent = `${percentage}%`;
                }
            }
        });

        // Update sidebar payout display if this asset is active
        const activeCard = document.querySelector('.asset-card-tab.active');
        if (activeCard && activeCard.id === assetName) {
            const sidebarPayout = document.querySelector('.asset-return');
            if (sidebarPayout) {
                sidebarPayout.textContent = `${percentage}%`;
            }
        }
    }

    showStatus(message, type) {
        const status = document.getElementById('payout-status');
        status.textContent = message;
        status.className = `payout-status ${type}`;
        status.style.display = 'block';

        setTimeout(() => {
            status.style.display = 'none';
        }, 3000);
    }

    // Get payout percentage for an asset
    static async getPayoutPercentage(assetName) {
        const config = window.payoutConfig;
        
        if (!config || config.modes.randomizePayoutControl) {
            // Use random algorithm (68-93%)
            return Math.floor(Math.random() * 26) + 68;
        } else {
            // Use custom percentage from database
            try {
                const response = await fetch('./php/asset_card_manager.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ action: 'load' })
                });

                const result = await response.json();

                if (result.success && result.data[assetName]) {
                    const manualPercentage = result.data[assetName].manualPercentage;
                    if (manualPercentage && manualPercentage.status) {
                        return manualPercentage.percentage;
                    }
                }
            } catch (error) {
                console.error('Error fetching payout percentage:', error);
            }

            // Fallback to random if custom not found
            return Math.floor(Math.random() * 26) + 68;
        }
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    window.payoutController = new PayoutController();
});

// Export for use in other scripts
window.PayoutController = PayoutController;
