document.addEventListener('DOMContentLoaded', () => {
    console.log('🚀 DOM loaded, initializing AviaCoin presale...');
    
    // Wallet elements
    const connectPhantomBtn = document.getElementById('connect-phantom');
    const connectWalletConnectBtn = document.getElementById('connect-walletconnect');
    const disconnectWalletBtn = document.getElementById('disconnect-wallet');
    const walletInfo = document.getElementById('wallet-info');
    const walletAddress = document.getElementById('wallet-address');
    const presaleForm = document.getElementById('presale-form');
    const amountInput = document.getElementById('amount');
    const status = document.getElementById('status');
    
    // Trust Wallet element
    const connectTrustBtn = document.getElementById('connect-trustwallet');
    
    // Progress elements
    const progressFill = document.getElementById('progress-fill');
    const progressPercentage = document.querySelector('.progress-percentage');
    const raisedAmount = document.getElementById('raised-amount');
    const targetAmount = document.getElementById('target-amount');
    const totalRaised = document.getElementById('total-raised');
    const participants = document.getElementById('participants');
    const timeLeft = document.getElementById('time-left');

    console.log('Elements found:', {
        connectPhantomBtn: !!connectPhantomBtn,
        connectWalletConnectBtn: !!connectWalletConnectBtn,
        disconnectWalletBtn: !!disconnectWalletBtn,
        walletInfo: !!walletInfo,
        walletAddress: !!walletAddress,
        presaleForm: !!presaleForm,
        amountInput: !!amountInput,
        status: !!status
    });

    // Load configuration from config.js
    let presaleConfig = window.PRESALE_CONFIG || {
        targetAmount: 1000,
        raisedAmount: 0,
        participants: 0,
        endDate: '2026-01-31T23:59',
        receivingWallet: 'HmDSN72PGjwUMwMFm8KVboUfPZSD4XMFXSS4BHoV7VC8',
        walletConnectProjectId: 'fb6ef5ab35c64bde0f3f9574c97b3c31',
        exchangeRate: 128
    };

    // Debug: Check if config loaded correctly
    console.log('PRESALE_CONFIG object:', window.PRESALE_CONFIG);
    console.log('presaleConfig after loading:', presaleConfig);
    console.log('Exchange rate from config:', presaleConfig.exchangeRate);

    // Update exchange rate display
    const exchangeRateDisplay = document.getElementById('exchange-rate-display');
    console.log('presaleConfig.exchangeRate:', presaleConfig.exchangeRate);
    if (exchangeRateDisplay) {
        exchangeRateDisplay.textContent = presaleConfig.exchangeRate.toLocaleString() + ' US7';
        console.log('Exchange rate display updated to:', exchangeRateDisplay.textContent);
    }

    // Enhanced input field effects
    const inputContainer = amountInput.closest('.input-container');
    const tokenCalculation = document.getElementById('token-calculation');
    const calcAmount = document.getElementById('calc-amount');
    const amountLabel = document.getElementById('amount-label');
    const calcLabel = document.querySelector('.calc-label');
    const calcToken = document.querySelector('.calc-token');

    let currentMode = 'sol'; // 'sol' or 'us7'

    // Function to calculate and display tokens
    function calculateTokens() {
        const inputValue = parseFloat(amountInput.value);

        if (!isNaN(inputValue) && inputValue > 0) {
            let resultAmount, displayText, resultToken;

            if (currentMode === 'sol') {
                // Input is SOL, calculate US7
                resultAmount = inputValue * presaleConfig.exchangeRate;
                displayText = 'You\'ll receive:';
                resultToken = 'US7';
            } else {
                // Input is US7, calculate SOL
                resultAmount = inputValue / presaleConfig.exchangeRate;
                displayText = 'You\'ll pay:';
                resultToken = 'SOL';
            }

            calcLabel.textContent = displayText;
            calcAmount.textContent = resultAmount.toLocaleString(undefined, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 6
            });
            calcToken.textContent = resultToken;
            tokenCalculation.style.display = 'flex';
        } else {
            tokenCalculation.style.display = 'none';
        }
    }

    // Handle amount type toggle
    const amountTypeRadios = document.querySelectorAll('input[name="amount-type"]');
    const amountSuggestions = document.querySelector('.amount-suggestions');

    console.log('Amount type radios found:', amountTypeRadios.length);
    console.log('Amount suggestions element:', !!amountSuggestions);

    function updateAmountButtons() {
        console.log('Updating amount buttons for mode:', currentMode);

        if (currentMode === 'sol') {
            amountSuggestions.innerHTML = `
                <button type="button" class="amount-btn" onclick="document.getElementById('amount').value='0.1'">0.1 SOL</button>
                <button type="button" class="amount-btn" onclick="document.getElementById('amount').value='0.5'">0.5 SOL</button>
                <button type="button" class="amount-btn" onclick="document.getElementById('amount').value='1.0'">1.0 SOL</button>
                <button type="button" class="amount-btn" onclick="document.getElementById('amount').value='2.0'">2.0 SOL</button>
            `;
        } else {
            amountSuggestions.innerHTML = `
                <button type="button" class="amount-btn" onclick="document.getElementById('amount').value='128'">128 US7</button>
                <button type="button" class="amount-btn" onclick="document.getElementById('amount').value='256'">256 US7</button>
                <button type="button" class="amount-btn" onclick="document.getElementById('amount').value='512'">512 US7</button>
                <button type="button" class="amount-btn" onclick="document.getElementById('amount').value='1024'">1024 US7</button>
            `;
        }

        // Re-attach event listeners for new buttons
        const newAmountButtons = document.querySelectorAll('.amount-btn');
        console.log('New amount buttons created:', newAmountButtons.length);

        newAmountButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                console.log('Amount button clicked:', btn.textContent);
                // Remove active class from all buttons
                newAmountButtons.forEach(b => b.classList.remove('active'));
                // Add active class to clicked button
                btn.classList.add('active');
                // Focus the input
                amountInput.focus();
                // Calculate tokens immediately
                setTimeout(calculateTokens, 10);
            });
        });
    }

    amountTypeRadios.forEach(radio => {
        radio.addEventListener('change', (e) => {
            console.log('Amount type changed to:', e.target.value);
            currentMode = e.target.value;

            // Update label and input settings
            if (currentMode === 'sol') {
                amountLabel.textContent = 'Amount (SOL)';
                amountInput.placeholder = 'Enter SOL amount...';
                amountInput.min = '0.1';
                amountInput.step = '0.1';
            } else {
                amountLabel.textContent = 'Amount (US7)';
                amountInput.placeholder = 'Enter US7 amount...';
                amountInput.min = '1';
                amountInput.step = '1';
            }

            // Update amount buttons
            updateAmountButtons();

            // Clear input value when switching modes
            amountInput.value = '';
            tokenCalculation.style.display = 'none';
        });
    });

    // Initialize buttons for default mode
    updateAmountButtons();

    if (amountInput && inputContainer) {
        amountInput.addEventListener('focus', () => {
            inputContainer.classList.add('focused');
        });

        amountInput.addEventListener('blur', () => {
            inputContainer.classList.remove('focused');
        });

        // Calculate tokens on input
        amountInput.addEventListener('input', calculateTokens);

        // Clear active state when input is focused
        amountInput.addEventListener('focus', () => {
            const amountButtons = document.querySelectorAll('.amount-btn');
            amountButtons.forEach(b => b.classList.remove('active'));
        });
    }

    let wallet = null;
    let publicKey = null;

    // Load presale data from localStorage or use defaults
    let presaleData = JSON.parse(localStorage.getItem('presaleData')) || {
        targetAmount: presaleConfig.targetAmount,
        raisedAmount: presaleConfig.raisedAmount,
        participants: presaleConfig.participants,
        endDate: new Date(presaleConfig.endDate)
    };

    console.log('Loaded presale data:', presaleData);

    const presaleWallet = new solanaWeb3.PublicKey(presaleConfig.receivingWallet);
    
    // Update progress display
    function updateProgressDisplay() {
        const percentage = (presaleData.raisedAmount / presaleData.targetAmount) * 100;
        
        progressFill.style.width = `${Math.min(percentage, 100)}%`;
        progressPercentage.textContent = `${percentage.toFixed(1)}%`;
        raisedAmount.textContent = `${presaleData.raisedAmount} SOL`;
        targetAmount.textContent = `${presaleData.targetAmount} SOL`;
        totalRaised.textContent = presaleData.raisedAmount;
        participants.textContent = presaleData.participants;
        
        // Update time left
        const now = new Date();
        const timeDiff = presaleData.endDate - now;
        const daysLeft = Math.max(0, Math.ceil(timeDiff / (1000 * 60 * 60 * 24)));
        timeLeft.textContent = daysLeft;
    }
    
    // Update time every second
    setInterval(updateProgressDisplay, 1000);
    updateProgressDisplay();

    // Add Trust Wallet handler - Mobile-first approach with QR fallback
    connectTrustBtn.addEventListener('click', async () => {
        console.log('Trust Wallet button clicked');
        status.textContent = 'Preparing Trust Wallet connection...';

        try {
            // Detect if mobile device
            const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
            console.log('Device type:', isMobile ? 'Mobile' : 'Desktop');

            // Generate WalletConnect URI
            const topic = Math.random().toString(36).substring(7);
            const symKey = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
            const wcUri = `wc:${topic}@2?relay-protocol=irn&symKey=${symKey}&bridge=https%3A%2F%2Fbridge.walletconnect.org`;

            console.log('Generated WalletConnect URI:', wcUri);

            if (isMobile) {
                // Mobile: Try to open Trust Wallet app first
                console.log('Mobile device detected - attempting to open Trust Wallet app');

                const trustDeepLink = `trust://wc?uri=${encodeURIComponent(wcUri)}`;
                console.log('Trust Wallet deep link:', trustDeepLink);

                // Try to open Trust Wallet app
                window.location.href = trustDeepLink;

                // Show modal with QR code as fallback after a delay
                setTimeout(() => {
                    showTrustWalletModal(wcUri, true); // true = mobile mode
                }, 2000); // Give app 2 seconds to open

                status.textContent = 'Trust Wallet app opened. If app didn\'t open, check the QR code below.';
            } else {
                // Desktop: Show QR code directly
                console.log('Desktop device detected - showing QR code');
                showTrustWalletModal(wcUri, false); // false = desktop mode
                status.textContent = 'Trust Wallet QR code displayed. Scan with your mobile device.';
            }

        } catch (err) {
            console.error('Trust Wallet setup error:', err);
            status.textContent = 'Failed to setup Trust Wallet connection: ' + err.message;
        }
    });

    // Helper function to show Trust Wallet modal
    function showTrustWalletModal(wcUri, isMobileMode) {
        const qrModal = document.createElement('div');
        qrModal.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.9);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10000;
            color: white;
        `;

        const mobileInstructions = isMobileMode ? `
            <div style="background: #2d5a2d; color: #90EE90; padding: 10px; border-radius: 8px; margin-bottom: 15px; font-size: 14px;">
                ✅ Trust Wallet app should open automatically<br>
                If not, scan the QR code below manually
            </div>
        ` : '';

        qrModal.innerHTML = `
            <div style="background: #1a1a1a; padding: 30px; border-radius: 15px; text-align: center; max-width: 500px; box-shadow: 0 10px 30px rgba(0,0,0,0.5);">
                <h2 style="color: #F57017; margin-bottom: 20px;">🔗 Trust Wallet Connection</h2>
                ${mobileInstructions}
                <div style="font-size: 16px; line-height: 1.6; margin-bottom: 25px;">
                    <p><strong>To connect Trust Wallet:</strong></p>
                    <ol style="text-align: left; display: inline-block; margin: 15px 0;">
                        <li>1. Open Trust Wallet app on your phone</li>
                        <li>2. Tap the ⋮ menu (top right)</li>
                        <li>3. Select "WalletConnect"</li>
                        <li>4. Tap "New Connection"</li>
                        <li>5. Point camera at this QR code:</li>
                    </ol>
                </div>

                <div id="qr-code" style="margin: 20px 0; display: flex; justify-content: center; background: white; padding: 15px; border-radius: 10px;"></div>

                <div style="font-size: 14px; color: #ccc; margin: 15px 0;">
                    <p><strong>Important:</strong> Make sure Trust Wallet is set to Solana Devnet network</p>
                    <p>You can switch networks in Trust Wallet settings</p>
                </div>

                <div style="margin-top: 20px;">
                    <button id="close-qr" style="background: #F57017; color: white; border: none; padding: 12px 24px; border-radius: 8px; font-size: 16px; cursor: pointer; margin-right: 10px;">Close</button>
                    <button id="retry-qr" style="background: #333; color: white; border: none; padding: 12px 24px; border-radius: 8px; font-size: 16px; cursor: pointer;">Generate New QR</button>
                </div>
            </div>
        `;

        document.body.appendChild(qrModal);

        // Function to generate QR code
        const generateQR = () => {
            const qrContainer = qrModal.querySelector('#qr-code');
            qrContainer.innerHTML = '';

            try {
                const qr = qrcode(0, 'L');
                qr.addData(wcUri);
                qr.make();

                const qrCodeSize = qr.getModuleCount();
                const canvasSize = 180;
                const cellSize = canvasSize / qrCodeSize;

                const canvas = document.createElement('canvas');
                canvas.width = canvasSize;
                canvas.height = canvasSize;
                canvas.style.border = '3px solid #333';

                const ctx = canvas.getContext('2d');
                ctx.fillStyle = 'white';
                ctx.fillRect(0, 0, canvasSize, canvasSize);
                ctx.fillStyle = 'black';

                for (let row = 0; row < qrCodeSize; row++) {
                    for (let col = 0; col < qrCodeSize; col++) {
                        if (qr.isDark(row, col)) {
                            ctx.fillRect(col * cellSize, row * cellSize, cellSize, cellSize);
                        }
                    }
                }

                qrContainer.appendChild(canvas);

                // Add URI display
                const uriDisplay = document.createElement('div');
                uriDisplay.style.cssText = 'margin-top: 10px; font-size: 11px; color: #666; word-break: break-all; background: #f5f5f5; padding: 8px; border-radius: 4px;';
                uriDisplay.textContent = wcUri;
                qrContainer.appendChild(uriDisplay);

            } catch (error) {
                console.error('QR generation error:', error);
                qrContainer.innerHTML = '<p style="color: red;">Failed to generate QR code</p>';
            }
        };

        // Generate initial QR
        generateQR();

        // Event listeners
        qrModal.querySelector('#close-qr').addEventListener('click', () => {
            document.body.removeChild(qrModal);
            status.textContent = 'Trust Wallet connection cancelled.';
        });

        qrModal.querySelector('#retry-qr').addEventListener('click', () => {
            // Generate new URI and QR code
            const newTopic = Math.random().toString(36).substring(7);
            const newSymKey = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
            const newWcUri = `wc:${newTopic}@2?relay-protocol=irn&symKey=${newSymKey}&bridge=https%3A%2F%2Fbridge.walletconnect.org`;

            console.log('Generated new WalletConnect URI:', newWcUri);
            // Update the URI and regenerate QR
            showTrustWalletModal(newWcUri, isMobileMode);
            // Remove current modal
            document.body.removeChild(qrModal);
        });

        qrModal.addEventListener('click', (e) => {
            if (e.target === qrModal) {
                document.body.removeChild(qrModal);
                status.textContent = 'Trust Wallet connection cancelled.';
            }
        });
    }

    // Add click handlers with debugging
    if (connectPhantomBtn) {
        connectPhantomBtn.addEventListener('click', async () => {
            console.log('Phantom button clicked');
            console.log('window.solana:', !!window.solana);
            console.log('window.solana.isPhantom:', !!(window.solana && window.solana.isPhantom));

            status.textContent = 'Connecting to Phantom...';

            // Check if we're on HTTPS (required for Phantom)
            const isHttps = window.location.protocol === 'https:' || window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
            console.log('Is HTTPS/localhost:', isHttps);

            if (!isHttps) {
                status.textContent = 'Phantom requires HTTPS. Please use HTTPS or localhost.';
                alert('Phantom wallet requires HTTPS connection. Please access this site via HTTPS or use localhost.');
                return;
            }

            try {
                // Wait a bit for extension to load
                await new Promise(resolve => setTimeout(resolve, 100));

                if (window.solana && window.solana.isPhantom) {
                    console.log('Phantom found, connecting...');

                    // Check if already connected
                    if (window.solana.isConnected) {
                        console.log('Already connected to Phantom');
                        publicKey = window.solana.publicKey;
                        console.log('Existing public key:', publicKey);

                        // Use existing connection
                        wallet = {
                            signAndSendTransaction: async (transaction) => {
                                return await window.solana.signAndSendTransaction(transaction);
                            },
                            disconnect: () => {
                                window.solana.disconnect();
                            }
                        };
                        walletAddress.textContent = publicKey.toString();
                        walletInfo.style.display = 'block';
                        document.getElementById('wallet-selection').style.display = 'none';
                        status.textContent = 'Already connected to Phantom!';
                        return;
                    }

                    console.log('Calling window.solana.connect()...');

                    const response = await window.solana.connect();
                    console.log('Phantom connect() returned:', response);
                    console.log('Response type:', typeof response);
                    console.log('Response keys:', Object.keys(response || {}));

                    if (response && response.publicKey) {
                        console.log('Public key found:', response.publicKey);
                        publicKey = response.publicKey;
                    } else {
                        // Try alternative way to get public key
                        console.log('Trying alternative public key access...');
                        publicKey = window.solana.publicKey;
                        console.log('Alternative public key:', publicKey);
                    }

                    if (!publicKey) {
                        throw new Error('No public key received from Phantom');
                    }

                    wallet = {
                        signAndSendTransaction: async (transaction) => {
                            return await window.solana.signAndSendTransaction(transaction);
                        },
                        disconnect: () => {
                            window.solana.disconnect();
                        }
                    };
                    walletAddress.textContent = publicKey.toString();
                    walletInfo.style.display = 'block';
                    document.getElementById('wallet-selection').style.display = 'none';
                    status.textContent = 'Phantom wallet connected successfully!';
                    console.log('Phantom connection completed successfully');
                } else {
                    console.log('Phantom not found, checking alternatives...');

                    // Check if user has other Solana wallets
                    if (window.solana) {
                        console.log('Found solana object but not Phantom');
                        status.textContent = 'Found Solana wallet but not Phantom. Please use Phantom or try another wallet.';
                    } else {
                        console.log('No solana object found');
                        status.textContent = 'Phantom wallet not found. Please install Phantom extension from https://phantom.app';
                        alert('Phantom wallet not detected!\n\nPlease:\n1. Install Phantom from https://phantom.app\n2. Refresh this page\n3. Make sure you\'re on HTTPS or localhost');
                    }
                }
            } catch (err) {
                console.error('Phantom connection error:', err);

                if (err.message.includes('User rejected')) {
                    status.textContent = 'Connection cancelled by user.';
                } else if (err.message.includes('not installed')) {
                    status.textContent = 'Phantom not installed. Please install from https://phantom.app';
                } else {
                    status.textContent = 'Failed to connect Phantom: ' + err.message;
                }
            }
        });
    } else {
        console.error('Phantom button not found');
    }



    if (connectWalletConnectBtn) {
        connectWalletConnectBtn.addEventListener('click', () => {
            console.log('WalletConnect button clicked');
            status.textContent = 'Generating WalletConnect QR code...';

            try {
                // Generate proper WalletConnect v2 URI
                const topic = Math.random().toString(36).substring(7);
                const symKey = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
                const wcUrl = `wc:${topic}@2?relay-protocol=irn&symKey=${symKey}&bridge=https%3A%2F%2Fbridge.walletconnect.org`;

                console.log('WalletConnect URI:', wcUrl);

                // Create a modal to show QR code
                const qrModal = document.createElement('div');
                qrModal.style.cssText = `
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0,0,0,0.8);
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    z-index: 10000;
                `;

                qrModal.innerHTML = `
                    <div style="background: white; padding: 20px; border-radius: 10px; text-align: center; max-width: 400px;">
                        <h3>WalletConnect Connection</h3>
                        <div id="qr-code" style="margin: 20px 0; display: flex; justify-content: center;"></div>
                        <p>Scan this QR code with a WalletConnect-compatible wallet</p>
                        <p style="font-size: 12px; color: #666; margin: 10px 0;">Supported wallets: Trust Wallet, MetaMask, Coinbase Wallet, etc.</p>
                        <button id="close-qr" style="margin-top: 10px; background: #F57017; color: white; border: none; padding: 8px 16px; border-radius: 5px; cursor: pointer;">Close</button>
                    </div>
                `;

                document.body.appendChild(qrModal);

                // Generate QR code
                const qrContainer = qrModal.querySelector('#qr-code');

                try {
                    // Use proper QR code library
                    const qr = qrcode(0, 'L');
                    qr.addData(wcUrl);
                    qr.make();

                    const qrCodeSize = qr.getModuleCount();
                    const canvasSize = 200;
                    const cellSize = canvasSize / qrCodeSize;

                    const canvas = document.createElement('canvas');
                    canvas.width = canvasSize;
                    canvas.height = canvasSize;
                    canvas.style.border = '2px solid #333';
                    canvas.style.background = 'white';

                    const ctx = canvas.getContext('2d');
                    ctx.fillStyle = 'white';
                    ctx.fillRect(0, 0, canvasSize, canvasSize);

                    // Draw QR code
                    ctx.fillStyle = 'black';
                    for (let row = 0; row < qrCodeSize; row++) {
                        for (let col = 0; col < qrCodeSize; col++) {
                            if (qr.isDark(row, col)) {
                                ctx.fillRect(
                                    col * cellSize,
                                    row * cellSize,
                                    cellSize,
                                    cellSize
                                );
                            }
                        }
                    }

                    qrContainer.appendChild(canvas);

                    const instructions = document.createElement('div');
                    instructions.style.cssText = 'margin-top: 10px; text-align: center;';
                    instructions.innerHTML = `
                        <div style="background: #f0f0f0; padding: 10px; border-radius: 5px; margin: 5px 0;">
                            <div style="font-size: 8px; word-break: break-all; color: #666;">
                                ${wcUrl}
                            </div>
                            <button onclick="try { navigator.clipboard.writeText('${wcUrl}'); this.innerHTML='✅ Copied!'; } catch(e) { alert('URL: ${wcUrl}'); } this.style.background='#28a745';"
                                    style="margin-top: 5px; background: #F57017; color: white; border: none; padding: 4px 8px; border-radius: 3px; font-size: 10px; cursor: pointer;">
                                📋 Copy URL
                            </button>
                        </div>
                        <p style="font-size: 11px; color: #888; margin-top: 10px;">
                            Note: WalletConnect works with most mobile wallets supporting Solana.
                        </p>
                    `;
                    qrContainer.appendChild(instructions);

                    qrModal.querySelector('#close-qr').addEventListener('click', () => {
                        document.body.removeChild(qrModal);
                        status.textContent = 'WalletConnect QR code closed.';
                    });

                    qrModal.addEventListener('click', (e) => {
                        if (e.target === qrModal) {
                            document.body.removeChild(qrModal);
                            status.textContent = 'WalletConnect QR code closed.';
                        }
                    });

                    status.textContent = 'WalletConnect QR code displayed. Please scan with your mobile wallet.';

                } catch (qrErr) {
                    console.error('QR generation error:', qrErr);
                    status.textContent = 'Failed to generate QR code: ' + qrErr.message;
                }

            } catch (err) {
                console.error('WalletConnect setup error:', err);
                status.textContent = 'Failed to setup WalletConnect: ' + err.message;
            }
        });
    } else {
        console.error('WalletConnect button not found');
    }

    disconnectWalletBtn.addEventListener('click', () => {
        console.log('Disconnect button clicked');
        if (wallet) {
            wallet.disconnect();
            wallet = null;
        }
        publicKey = null;
        walletInfo.style.display = 'none';
        document.getElementById('wallet-selection').style.display = 'block';
        status.textContent = 'Wallet disconnected.';
    });

    presaleForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        console.log('Form submitted');

        if (!publicKey) {
            status.textContent = 'Please connect your wallet first.';
            return;
        }

        const inputAmount = parseFloat(amountInput.value);
        if (isNaN(inputAmount) || inputAmount <= 0) {
            status.textContent = 'Invalid amount.';
            return;
        }

        // Calculate amounts
        let solAmount, us7Amount;
        if (currentMode === 'sol') {
            solAmount = inputAmount;
            us7Amount = inputAmount * presaleConfig.exchangeRate;
        } else {
            us7Amount = inputAmount;
            solAmount = inputAmount / presaleConfig.exchangeRate;
        }

        console.log(`Purchase: ${us7Amount.toLocaleString()} US7 for ${solAmount.toFixed(4)} SOL`);
        console.log(`Exchange rate: 1 SOL = ${presaleConfig.exchangeRate.toLocaleString()} US7`);

        try {
            status.textContent = `Purchasing ${us7Amount.toLocaleString()} US7 tokens for ${solAmount.toFixed(4)} SOL...`;
            
            // Simple approach using Solana Web3.js with timeout
            console.log('Creating Solana connection with timeout...');
            
            // Set a timeout for the entire operation
            const timeout = setTimeout(() => {
                throw new Error('Transaction timeout - please try again');
            }, 120000); // 120 second timeout for devnet
            
            try {
                // Try multiple public RPC endpoints for better reliability
                const rpcEndpoints = [
                    'https://api.mainnet-beta.solana.com', // Official Solana RPC (user requested primary)
                    'https://rpc.ankr.com/solana_devnet/b8f4962a712859170c3ef5ed829514a37ace6f005f9c353838072ded1ea46f05', // User specified Ankr devnet endpoint
                    'https://solana.publicnode.com', // PublicNode
                    'https://mainnet-beta.solana.rpcpool.com', // RPC Pool
                    'https://solana-mainnet.rpc.extrnode.com', // Extrnode
                    'https://solana.api.onfinality.io/public', // OnFinality public endpoint
                    'https://solana-mainnet.g.alchemy.com/v2/demo', // Alchemy public endpoint
                    'https://rpc.ankr.com/solana' // Ankr public endpoint
                ];

                let connection;
                let connectionError;

                // Try each RPC endpoint until one works
                for (const endpoint of rpcEndpoints) {
                    try {
                        console.log(`Trying RPC endpoint: ${endpoint}`);
                        connection = new solanaWeb3.Connection(endpoint, {
                            commitment: 'processed',
                            confirmTransactionInitialTimeout: 60000,
                            disableRetryOnRateLimit: false
                        });

                        // Test connection with a simple request
                        await connection.getVersion();
                        console.log(`Successfully connected to: ${endpoint}`);
                        break;
                    } catch (err) {
                        console.log(`Failed to connect to ${endpoint}:`, err.message);
                        connectionError = err;
                        continue;
                    }
                }

                if (!connection) {
                    throw new Error(`Failed to connect to any RPC endpoint. Last error: ${connectionError.message}`);
                }
                
                // Create the transaction
                const transaction = new solanaWeb3.Transaction().add(
                    solanaWeb3.SystemProgram.transfer({
                        fromPubkey: publicKey,
                        toPubkey: presaleWallet,
                        lamports: solanaWeb3.LAMPORTS_PER_SOL * solAmount,
                    })
                );

                status.textContent = 'Getting blockhash...';
                
                // Get blockhash with timeout
                const blockhashPromise = connection.getLatestBlockhash();
                const timeoutPromise = new Promise((_, reject) => 
                    setTimeout(() => reject(new Error('RPC timeout')), 10000)
                );
                
                const { blockhash } = await Promise.race([blockhashPromise, timeoutPromise]);
                transaction.recentBlockhash = blockhash;
                transaction.feePayer = publicKey;

                status.textContent = 'Sending transaction...';
                console.log('Transaction created:', transaction);
                console.log('Wallet object:', wallet);
                console.log('Calling wallet.signAndSendTransaction...');

                // Send transaction with timeout
                const sendPromise = wallet.signAndSendTransaction(transaction);
                console.log('Send promise created');

                const sendTimeout = new Promise((_, reject) => {
                    console.log('Setting send timeout...');
                    setTimeout(() => {
                        console.log('Send timeout triggered - devnet transactions can be very slow');
                        reject(new Error('Transaction is taking longer than expected. Devnet can be very slow - please wait a few minutes and check your wallet for confirmation.'));
                    }, 300000); // Increased to 5 minutes (300 seconds) for devnet
                });

                console.log('Racing promises...');
                const signed = await Promise.race([sendPromise, sendTimeout]);
                console.log('Transaction signed result:', signed);
            clearTimeout(timeout);
            status.textContent = `Transaction sent: ${signed.signature}`;
            
            // Update presale data on successful transaction
            presaleData.raisedAmount += solAmount;
            presaleData.participants += 1;
            updateProgressDisplay();
            localStorage.setItem('presaleData', JSON.stringify(presaleData));
            
        } catch (innerErr) {
            clearTimeout(timeout);
            throw innerErr;
        }
            
        } catch (err) {
            console.error('Transaction error:', err);
            
            // Provide specific error messages based on error type
            if (err.message.includes('timeout') || err.message.includes('Timeout')) {
                status.textContent = 'Request timed out. The network may be busy. Please try again in a moment.';
            } else if (err.message.includes('403') || err.message.includes('Access forbidden') || err.message.includes('forbidden')) {
                status.textContent = 'Network access restricted. This might be due to VPN, firewall, or ISP restrictions. Please try from a different network.';
            } else if (err.message.includes('insufficient funds')) {
                status.textContent = 'Insufficient SOL balance. Please ensure you have enough SOL for the transaction + fees.';
            } else if (err.message.includes('block height') || err.message.includes('expired')) {
                status.textContent = 'Transaction expired. Please try again quickly.';
            } else if (err.message.includes('Failed to fetch') || err.message.includes('NetworkError') || err.message.includes('network')) {
                status.textContent = 'Network connection error. Please check your internet connection and try again.';
            } else if (err.message.includes('User rejected')) {
                status.textContent = 'Transaction was cancelled by user.';
            } else {
                status.textContent = `Transaction failed: ${err.message}`;
            }
        }
    });

    console.log('Event listeners attached');
});
