/**
 * Account - Manages user wallet and credits with two-address custody model
 *
 * Two Address Model:
 * - Fee Address: We store private key, used for strategy fees (max ~$50)
 * - Sweep Address: We don't store private key, user controls, receives excess
 */
class Account {
    constructor() {
        this.walletInfo = null;
        this.creditsBalance = 0;
        this.transactions = [];
        this.userProfile = null;
        this.initialized = false;
    }

    /**
     * Initialize the account panel
     */
    async initialize() {
        if (this.initialized) {
            return;
        }
        this.setupEventListeners();
        this.initialized = true;
    }

    /**
     * Show the account settings dialog
     */
    async showAccountSettings() {
        // Check if user is logged in (not a guest)
        const username = document.getElementById('username_display')?.textContent || '';
        if (username.startsWith('guest') || !username) {
            alert('Please sign in to access account settings.');
            return;
        }

        // Show dialog
        document.getElementById('account_settings_form').style.display = 'block';

        // Load profile and wallet data
        await Promise.all([
            this.loadProfile(),
            this.refresh()
        ]);

        // Default to profile tab
        this.switchTab('profile');
    }

    /**
     * Close the account settings dialog
     */
    closeAccountSettings() {
        document.getElementById('account_settings_form').style.display = 'none';
    }

    /**
     * Switch between tabs in the account settings
     */
    switchTab(tabName) {
        // Update tab buttons
        document.querySelectorAll('.account-tab').forEach(tab => {
            tab.classList.toggle('active', tab.dataset.tab === tabName);
        });

        // Update tab panels
        document.querySelectorAll('.tab-panel').forEach(panel => {
            panel.classList.toggle('active', panel.id === `${tabName}_tab`);
        });
    }

    /**
     * Load user profile data
     */
    async loadProfile() {
        try {
            const response = await fetch('/api/user/profile');
            const data = await response.json();

            if (data.success) {
                this.userProfile = data.profile;
                const emailEl = document.getElementById('current_email');
                if (emailEl) {
                    emailEl.textContent = data.profile.email || 'Not set';
                }
            }
        } catch (error) {
            console.error('Error loading profile:', error);
        }
    }

    /**
     * Update user email
     */
    async updateEmail() {
        const newEmail = document.getElementById('new_email').value.trim();
        if (!newEmail) {
            alert('Please enter a new email address.');
            return;
        }

        // Basic email validation
        if (!newEmail.includes('@') || !newEmail.includes('.')) {
            alert('Please enter a valid email address.');
            return;
        }

        try {
            const response = await fetch('/api/user/email', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email: newEmail })
            });

            const data = await response.json();

            if (data.success) {
                alert('Email updated successfully.');
                document.getElementById('current_email').textContent = newEmail;
                document.getElementById('new_email').value = '';
            } else {
                alert('Failed to update email: ' + (data.error || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error updating email:', error);
            alert('Failed to update email: ' + error.message);
        }
    }

    /**
     * Update user password
     */
    async updatePassword() {
        const currentPassword = document.getElementById('current_password').value;
        const newPassword = document.getElementById('new_password').value;
        const confirmPassword = document.getElementById('confirm_password').value;

        if (!currentPassword || !newPassword || !confirmPassword) {
            alert('Please fill in all password fields.');
            return;
        }

        if (newPassword !== confirmPassword) {
            alert('New passwords do not match.');
            return;
        }

        if (newPassword.length < 6) {
            alert('Password must be at least 6 characters.');
            return;
        }

        try {
            const response = await fetch('/api/user/password', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    current_password: currentPassword,
                    new_password: newPassword
                })
            });

            const data = await response.json();

            if (data.success) {
                alert('Password updated successfully.');
                document.getElementById('current_password').value = '';
                document.getElementById('new_password').value = '';
                document.getElementById('confirm_password').value = '';
            } else {
                alert('Failed to update password: ' + (data.error || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error updating password:', error);
            alert('Failed to update password: ' + error.message);
        }
    }

    /**
     * Setup checkbox event listeners for modals
     */
    setupEventListeners() {
        // Terms checkbox enables create button
        const termsCheckbox = document.getElementById('terms_checkbox');
        const createBtn = document.getElementById('create_wallet_btn');
        if (termsCheckbox && createBtn) {
            termsCheckbox.addEventListener('change', () => {
                createBtn.disabled = !termsCheckbox.checked;
            });
        }

        // Keys saved checkbox enables close button
        const keysSavedCheckbox = document.getElementById('keys_saved_checkbox');
        const closeKeysBtn = document.getElementById('close_keys_btn');
        if (keysSavedCheckbox && closeKeysBtn) {
            keysSavedCheckbox.addEventListener('change', () => {
                closeKeysBtn.disabled = !keysSavedCheckbox.checked;
            });
        }
    }

    /**
     * Refresh wallet info, credits balance, and transactions
     */
    async refresh() {
        try {
            // Load wallet and credits in parallel
            const [walletRes, creditsRes, txRes] = await Promise.all([
                fetch('/api/wallet'),
                fetch('/api/wallet/credits'),
                fetch('/api/wallet/transactions?limit=20')
            ]);

            const walletData = await walletRes.json();
            const creditsData = await creditsRes.json();
            const txData = await txRes.json();

            if (walletData.success && walletData.wallet) {
                this.walletInfo = walletData.wallet;
                this.displayWallet();
            } else {
                this.walletInfo = null;
                this.displayNoWallet();
            }

            if (creditsData.success) {
                this.creditsBalance = creditsData.balance || 0;
                this.updateCreditsDisplay();
            }

            if (txData.success) {
                this.transactions = txData.transactions || [];
                this.displayTransactions();
            }
        } catch (error) {
            console.error('Error refreshing account:', error);
        }
    }

    /**
     * Display wallet info
     */
    displayWallet() {
        const noWallet = document.getElementById('no_wallet');
        const walletInfo = document.getElementById('wallet_info');

        if (noWallet) noWallet.style.display = 'none';
        if (walletInfo) walletInfo.style.display = 'block';

        const addressEl = document.getElementById('btc_address');
        const sweepAddressEl = document.getElementById('sweep_address');
        const networkEl = document.getElementById('wallet_network');
        const warningEl = document.getElementById('wallet_disabled_warning');

        if (addressEl) {
            addressEl.textContent = this.walletInfo.fee_address || this.walletInfo.address;
        }
        if (sweepAddressEl) {
            sweepAddressEl.textContent = this.walletInfo.sweep_address || 'Not configured';
        }
        if (networkEl) {
            networkEl.textContent = this.walletInfo.network === 'testnet' ? '(Testnet)' : '(Mainnet)';
        }
        if (warningEl) {
            warningEl.style.display = this.walletInfo.is_disabled ? 'block' : 'none';
        }
    }

    /**
     * Display no wallet state
     */
    displayNoWallet() {
        const noWallet = document.getElementById('no_wallet');
        const walletInfo = document.getElementById('wallet_info');

        if (noWallet) noWallet.style.display = 'block';
        if (walletInfo) walletInfo.style.display = 'none';
    }

    /**
     * Update credits balance display
     */
    updateCreditsDisplay() {
        const balanceEl = document.getElementById('credits_balance');
        if (balanceEl) {
            balanceEl.textContent = this.formatSatoshis(this.creditsBalance);
        }
    }

    /**
     * Format satoshis as BTC with appropriate precision
     */
    formatSatoshis(satoshis) {
        const btc = satoshis / 100000000;
        if (btc === 0) return '0';
        if (btc < 0.0001) return btc.toFixed(8);
        if (btc < 1) return btc.toFixed(6);
        return btc.toFixed(4);
    }

    /**
     * Display transaction history
     */
    displayTransactions() {
        const tbody = document.getElementById('transactions_body');
        if (!tbody) return;

        if (!this.transactions || this.transactions.length === 0) {
            tbody.innerHTML = '<tr class="no-transactions"><td colspan="4">No transactions yet</td></tr>';
            return;
        }

        tbody.innerHTML = this.transactions.map(tx => {
            const date = this.escapeHtml(new Date(tx.date).toLocaleString());
            const amountClass = tx.amount >= 0 ? 'tx-positive' : 'tx-negative';
            const amountStr = (tx.amount >= 0 ? '+' : '') + this.formatSatoshis(tx.amount);
            const typeDisplay = this.formatTxType(tx.type);
            const refFull = this.escapeHtml(tx.reference || '');
            const refShort = tx.reference ? this.escapeHtml(tx.reference.substring(0, 16)) + '...' : '-';

            return `
                <tr>
                    <td>${date}</td>
                    <td>${typeDisplay}</td>
                    <td class="${amountClass}">${amountStr}</td>
                    <td title="${refFull}">${refShort}</td>
                </tr>
            `;
        }).join('');
    }

    /**
     * Format transaction type for display
     */
    formatTxType(type) {
        const typeMap = {
            'deposit': 'Deposit',
            'withdrawal': 'Withdrawal',
            'fee_paid': 'Fee Paid',
            'fee_received': 'Fee Received',
            'admin_credit': 'Credit',
            'withdrawal_reversal': 'Reversal',
            'auto_sweep': 'Auto-Sweep'
        };
        return typeMap[type] || this.escapeHtml(type);
    }

    /**
     * Escape HTML to prevent XSS attacks
     */
    escapeHtml(text) {
        if (text === null || text === undefined) return '';
        const div = document.createElement('div');
        div.textContent = String(text);
        return div.innerHTML;
    }

    /**
     * Show wallet setup dialog with terms
     */
    showSetupDialog() {
        // Reset checkbox
        const termsCheckbox = document.getElementById('terms_checkbox');
        const createBtn = document.getElementById('create_wallet_btn');
        if (termsCheckbox) termsCheckbox.checked = false;
        if (createBtn) createBtn.disabled = true;

        // Reset sweep option to "generate"
        const generateRadio = document.querySelector('input[name="sweep_option"][value="generate"]');
        if (generateRadio) generateRadio.checked = true;
        this.toggleSweepOption();

        // Clear any previous user input
        const userAddressInput = document.getElementById('user_sweep_address');
        if (userAddressInput) userAddressInput.value = '';

        document.getElementById('wallet_setup_modal').style.display = 'block';
    }

    /**
     * Toggle sweep address input visibility based on radio selection
     */
    toggleSweepOption() {
        const ownRadio = document.querySelector('input[name="sweep_option"][value="own"]');
        const ownAddressSection = document.getElementById('own_address_input');

        if (ownRadio && ownAddressSection) {
            ownAddressSection.style.display = ownRadio.checked ? 'block' : 'none';
        }
    }

    /**
     * Close wallet setup dialog
     */
    closeSetupDialog() {
        document.getElementById('wallet_setup_modal').style.display = 'none';
    }

    /**
     * Create a new wallet (two-address model)
     */
    async createWallet() {
        const termsCheckbox = document.getElementById('terms_checkbox');
        if (!termsCheckbox || !termsCheckbox.checked) {
            alert('Please agree to the terms before creating a wallet.');
            return;
        }

        // Check if user is providing their own sweep address
        const ownRadio = document.querySelector('input[name="sweep_option"][value="own"]');
        const userSweepAddress = document.getElementById('user_sweep_address');
        let sweepAddress = null;

        if (ownRadio && ownRadio.checked) {
            sweepAddress = userSweepAddress ? userSweepAddress.value.trim() : '';
            if (!sweepAddress) {
                alert('Please enter your Bitcoin address for the sweep address.');
                return;
            }
        }

        const btn = document.getElementById('create_wallet_btn');
        btn.disabled = true;
        btn.textContent = 'Generating...';

        try {
            const requestBody = {};
            if (sweepAddress) {
                requestBody.user_sweep_address = sweepAddress;
            }

            const response = await fetch('/api/wallet/create', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(requestBody)
            });
            const data = await response.json();

            if (data.success) {
                // Close setup dialog
                this.closeSetupDialog();

                // Show keys modal - requires acknowledgment before closing
                document.getElementById('modal_network').textContent = data.network;
                document.getElementById('modal_fee_address').textContent = data.fee_address;
                document.getElementById('modal_fee_private_key').textContent = data.fee_private_key;
                document.getElementById('modal_sweep_address').textContent = data.sweep_address;

                // Handle sweep private key - only shown if we generated it
                const sweepPrivateKeyEl = document.getElementById('modal_sweep_private_key');
                const sweepPrivateKeyRow = sweepPrivateKeyEl ? sweepPrivateKeyEl.closest('.key-row') : null;

                if (data.sweep_private_key) {
                    // We generated the sweep address - show private key
                    sweepPrivateKeyEl.textContent = data.sweep_private_key;
                    if (sweepPrivateKeyRow) sweepPrivateKeyRow.style.display = 'flex';
                } else {
                    // User provided their own address - no private key to show
                    if (sweepPrivateKeyRow) sweepPrivateKeyRow.style.display = 'none';
                }

                // Update the sweep section header based on whether we generated it
                const sweepSection = document.querySelector('.key-section.sweep-section h5');
                if (sweepSection) {
                    if (data.sweep_private_key) {
                        sweepSection.textContent = 'Sweep Address (You Control - SAVE THIS KEY!)';
                    } else {
                        sweepSection.textContent = 'Sweep Address (Your Provided Address)';
                    }
                }

                // Reset checkbox and button
                const keysSavedCheckbox = document.getElementById('keys_saved_checkbox');
                const closeKeysBtn = document.getElementById('close_keys_btn');
                if (keysSavedCheckbox) keysSavedCheckbox.checked = false;
                if (closeKeysBtn) closeKeysBtn.disabled = true;

                document.getElementById('wallet_keys_modal').style.display = 'block';

                // Update wallet info
                this.walletInfo = {
                    fee_address: data.fee_address,
                    sweep_address: data.sweep_address,
                    network: data.network,
                    is_disabled: false
                };
                this.creditsBalance = 0;
                this.displayWallet();
                this.updateCreditsDisplay();
            } else {
                alert('Failed to create wallet: ' + (data.error || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error creating wallet:', error);
            alert('Failed to create wallet: ' + error.message);
        } finally {
            btn.disabled = false;
            btn.textContent = 'Create Wallet';
        }
    }

    /**
     * Close the keys modal (only if acknowledged)
     */
    closeKeysModal() {
        const keysSavedCheckbox = document.getElementById('keys_saved_checkbox');
        if (!keysSavedCheckbox || !keysSavedCheckbox.checked) {
            alert('Please confirm that you have saved your keys before closing.');
            return;
        }
        document.getElementById('wallet_keys_modal').style.display = 'none';
    }

    /**
     * Show view keys dialog (for fee address only - sweep key not stored)
     */
    async showViewKeysDialog() {
        try {
            const response = await fetch('/api/wallet/keys');
            const data = await response.json();

            if (data.success) {
                document.getElementById('view_network').textContent = data.network;
                document.getElementById('view_fee_address').textContent = data.fee_address;
                document.getElementById('view_fee_private_key').textContent = data.fee_private_key;
                document.getElementById('view_keys_modal').style.display = 'block';
            } else {
                alert('Failed to retrieve keys: ' + (data.error || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error retrieving keys:', error);
            alert('Failed to retrieve keys: ' + error.message);
        }
    }

    /**
     * Close view keys dialog
     */
    closeViewKeysDialog() {
        document.getElementById('view_keys_modal').style.display = 'none';
    }

    /**
     * Copy wallet address to clipboard
     */
    copyAddress(type) {
        if (!this.walletInfo) return;

        const address = type === 'sweep'
            ? (this.walletInfo.sweep_address || '')
            : (this.walletInfo.fee_address || this.walletInfo.address);

        if (!address) return;

        navigator.clipboard.writeText(address).then(() => {
            // Brief visual feedback would be nice here
        }).catch(err => {
            console.error('Failed to copy:', err);
        });
    }

    /**
     * Copy a key value to clipboard
     */
    copyKey(elementId) {
        const el = document.getElementById(elementId);
        if (!el) return;

        navigator.clipboard.writeText(el.textContent).then(() => {
            // Could add visual feedback
        }).catch(err => {
            console.error('Failed to copy:', err);
        });
    }

    /**
     * Show withdrawal dialog
     */
    showWithdrawDialog() {
        document.getElementById('withdraw_amount').value = '';
        document.getElementById('withdraw_address').value = '';
        document.getElementById('withdraw_modal').style.display = 'block';
    }

    /**
     * Close withdrawal dialog
     */
    closeWithdrawDialog() {
        document.getElementById('withdraw_modal').style.display = 'none';
    }

    /**
     * Submit withdrawal request
     */
    async submitWithdrawal() {
        const amountStr = document.getElementById('withdraw_amount').value.trim();
        const address = document.getElementById('withdraw_address').value.trim();

        if (!amountStr || !address) {
            alert('Please enter amount and destination address');
            return;
        }

        const btcAmount = parseFloat(amountStr);
        if (isNaN(btcAmount) || btcAmount <= 0) {
            alert('Invalid amount');
            return;
        }

        const satoshis = Math.floor(btcAmount * 100000000);

        try {
            const response = await fetch('/api/wallet/withdraw', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    amount_satoshis: satoshis,
                    destination_address: address
                })
            });

            const data = await response.json();

            if (data.success) {
                alert('Withdrawal request submitted. It will be processed shortly.');
                this.closeWithdrawDialog();
                this.refresh();
            } else {
                alert('Withdrawal failed: ' + (data.error || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error requesting withdrawal:', error);
            alert('Withdrawal failed: ' + error.message);
        }
    }

    /**
     * Show test credit dialog
     */
    showCreditDialog() {
        document.getElementById('credit_amount').value = '10000';
        document.getElementById('credit_modal').style.display = 'block';
    }

    /**
     * Close test credit dialog
     */
    closeCreditDialog() {
        document.getElementById('credit_modal').style.display = 'none';
    }

    /**
     * Submit test credit
     */
    async submitCredit() {
        const amountStr = document.getElementById('credit_amount').value.trim();
        const amount = parseInt(amountStr);

        if (isNaN(amount) || amount <= 0) {
            alert('Invalid amount');
            return;
        }

        try {
            const response = await fetch('/api/admin/credit', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    amount_satoshis: amount,
                    reason: 'POC test credit from UI'
                })
            });

            const data = await response.json();

            if (data.success) {
                alert(`Added ${amount} satoshis to your credits`);
                this.closeCreditDialog();
                this.refresh();
            } else {
                alert('Credit failed: ' + (data.error || 'Unknown error'));
            }
        } catch (error) {
            console.error('Error adding credit:', error);
            alert('Credit failed: ' + error.message);
        }
    }
}

// Export for use in UI namespace
if (typeof window !== 'undefined') {
    window.Account = Account;
}
