(function () {
  'use strict';

  var COINS = {
    BTC: {
      name: 'Bitcoin',
      rate: 96450.32,
      decimals: 8,
      networks: [
        { id: 'BTC', label: 'Bitcoin', address: 'bc1qt6epcqt04v5fezkw8y8pclm2gkl5rkpsj94fwm' }
      ]
    },
    ETH: {
      name: 'Ethereum',
      rate: 3380.15,
      decimals: 6,
      networks: [
        { id: 'ERC20', label: 'Ethereum (ERC-20)', address: '0x100489f96Df93f745b3F9bC62ebCa5571d1a27eC' }
      ]
    },
    USDT: {
      name: 'USDT',
      rate: 1,
      decimals: 2,
      networks: [
        { id: 'ERC20', label: 'Ethereum (ERC-20)', address: '0x100489f96Df93f745b3F9bC62ebCa5571d1a27eC' },
        { id: 'TRC20', label: 'Tron (TRC-20)', address: 'TYLeYuyuKKZe2ofvrSvAN7UGTyp36L79PW' }
      ]
    },
    USDC: {
      name: 'USDC',
      rate: 1,
      decimals: 2,
      networks: [
        { id: 'ERC20', label: 'Ethereum (ERC-20)', address: '0x100489f96Df93f745b3F9bC62ebCa5571d1a27eC' },
        { id: 'SOL', label: 'Solana', address: 'HWyRfSxZSbEXEtTyQjo6ctbuBtqLZHqKmtcmYSrMrKoh' }
      ]
    },
    SOL: {
      name: 'Solana',
      rate: 178.62,
      decimals: 5,
      networks: [
        { id: 'SOL', label: 'Solana', address: 'HWyRfSxZSbEXEtTyQjo6ctbuBtqLZHqKmtcmYSrMrKoh' }
      ]
    }
  };

  var MIN_AMOUNT = 1000;
  var TIMER_SECONDS = 10 * 60;

  var state = {
    coin: 'BTC',
    network: 'BTC',
    amountUsd: 0
  };

  var els = {};

  function fmtUsd(n) {
    return '$' + n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  }

  function fmtCrypto(n, decimals) {
    return n.toLocaleString('en-US', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
  }

  function currentCoin() {
    return COINS[state.coin];
  }

  function currentNetwork() {
    var coin = currentCoin();
    var net = coin.networks.filter(function (n) { return n.id === state.network; })[0];
    return net || coin.networks[0];
  }

  function render() {
    var coin = currentCoin();
    var net = currentNetwork();
    var hasAmount = state.amountUsd > 0;
    var cryptoAmount = state.amountUsd / coin.rate;

    document.querySelectorAll('.cx-coin').forEach(function (el) {
      el.classList.toggle('is-active', el.dataset.coin === state.coin);
    });

    if (els.networkRow) {
      els.networkRow.innerHTML = '';
      if (coin.networks.length > 1) {
        els.networkRow.style.display = 'flex';
        coin.networks.forEach(function (n) {
          var pill = document.createElement('button');
          pill.type = 'button';
          pill.className = 'cx-network-pill' + (n.id === state.network ? ' is-active' : '');
          pill.textContent = n.label;
          pill.dataset.network = n.id;
          pill.addEventListener('click', function () {
            state.network = n.id;
            render();
          });
          els.networkRow.appendChild(pill);
        });
      } else {
        els.networkRow.style.display = 'none';
      }
    }

    if (els.orderAmountFiat) els.orderAmountFiat.textContent = hasAmount ? fmtUsd(state.amountUsd) : '—';
    if (els.orderCoin) els.orderCoin.textContent = coin.name + ' (' + net.label + ')';
    if (els.orderCryptoAmount) els.orderCryptoAmount.textContent = hasAmount ? (fmtCrypto(cryptoAmount, coin.decimals) + ' ' + state.coin) : '—';
    if (els.orderTotal) els.orderTotal.textContent = hasAmount ? fmtUsd(state.amountUsd) : '—';

    if (els.address) els.address.textContent = net.address;
    if (els.qr) {
      var qrData = encodeURIComponent(net.address);
      els.qr.src = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&margin=0&data=' + qrData;
    }
    if (els.amountToSend) els.amountToSend.textContent = hasAmount ? (fmtCrypto(cryptoAmount, coin.decimals) + ' ' + state.coin) : '—';

    if (els.rightCoin) els.rightCoin.textContent = coin.name;
    if (els.rightNetwork) els.rightNetwork.textContent = net.label;
    if (els.rightRate) els.rightRate.textContent = '1 ' + state.coin + ' = ' + fmtUsd(coin.rate);
    if (els.rightAmountDue) els.rightAmountDue.textContent = hasAmount ? fmtUsd(state.amountUsd) : '—';
  }

  function selectCoin(symbol) {
    state.coin = symbol;
    state.network = COINS[symbol].networks[0].id;
    render();
  }

  function initCoinSelector() {
    document.querySelectorAll('.cx-coin').forEach(function (el) {
      el.addEventListener('click', function () {
        selectCoin(el.dataset.coin);
      });
    });
  }

  function initCopyButton() {
    if (!els.copyBtn) return;
    els.copyBtn.addEventListener('click', function () {
      var text = els.address ? els.address.textContent : '';
      var done = function () {
        els.copyBtn.classList.add('is-copied');
        els.copyBtn.innerHTML = '<i class="fas fa-check"></i>';
        setTimeout(function () {
          els.copyBtn.classList.remove('is-copied');
          els.copyBtn.innerHTML = '<i class="fas fa-copy"></i>';
        }, 1600);
      };
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(done).catch(function () {});
      } else {
        var ta = document.createElement('textarea');
        ta.value = text;
        document.body.appendChild(ta);
        ta.select();
        try { document.execCommand('copy'); } catch (e) {}
        document.body.removeChild(ta);
        done();
      }
    });
  }

  function updateCtaState() {
    var isValid = state.amountUsd >= MIN_AMOUNT;
    if (els.amountHint) {
      els.amountHint.classList.toggle('is-error', state.amountUsd > 0 && !isValid);
      els.amountHint.textContent = isValid
        ? 'Minimum payment amount is ' + fmtUsd(MIN_AMOUNT) + '.'
        : 'Amount must be at least ' + fmtUsd(MIN_AMOUNT) + '.';
    }
    if (els.ctaBtn) els.ctaBtn.disabled = !isValid || timerExpired;
  }

  function initAmountInput() {
    if (!els.amountInput) return;
    els.amountInput.addEventListener('input', function () {
      var val = parseFloat(els.amountInput.value);
      state.amountUsd = isNaN(val) ? 0 : val;
      updateCtaState();
      render();
    });
  }

  var timerExpired = false;
  var secondsLeft = TIMER_SECONDS;
  var timerInterval = null;

  function formatTime(s) {
    var m = Math.floor(s / 60);
    var sec = s % 60;
    return m + ':' + (sec < 10 ? '0' : '') + sec;
  }

  function updateTimerUi() {
    if (!els.timerValue) return;
    els.timerValue.textContent = formatTime(secondsLeft);
    els.rightTimerValue && (els.rightTimerValue.textContent = formatTime(secondsLeft));

    var ratio = secondsLeft / TIMER_SECONDS;
    els.timer.classList.remove('is-warning', 'is-danger');
    if (ratio <= 0.15) {
      els.timer.classList.add('is-danger');
    } else if (ratio <= 0.5) {
      els.timer.classList.add('is-warning');
    }
  }

  function startTimer() {
    updateTimerUi();
    timerInterval = setInterval(function () {
      secondsLeft -= 1;
      if (secondsLeft <= 0) {
        secondsLeft = 0;
        timerExpired = true;
        clearInterval(timerInterval);
        if (els.ctaBtn) els.ctaBtn.disabled = true;
        if (els.expiryNotice) {
          els.expiryNotice.innerHTML = '<i class="fas fa-triangle-exclamation"></i> This payment session has expired. Please create a new payment request to continue.';
        }
      }
      updateTimerUi();
    }, 1000);
  }

  function initCta() {
    if (!els.ctaBtn) return;
    els.ctaBtn.addEventListener('click', function () {
      if (state.amountUsd < MIN_AMOUNT || timerExpired) return;
      clearInterval(timerInterval);
      if (els.checkoutWrap) els.checkoutWrap.style.display = 'none';
      if (els.topbar) els.topbar.style.display = 'none';
      if (els.success) els.success.classList.add('is-visible');
    });
  }

  function cacheEls() {
    els.networkRow = document.getElementById('cx-network-row');
    els.orderAmountFiat = document.getElementById('cx-order-amount-fiat');
    els.orderCoin = document.getElementById('cx-order-coin');
    els.orderCryptoAmount = document.getElementById('cx-order-crypto-amount');
    els.orderTotal = document.getElementById('cx-order-total');
    els.address = document.getElementById('cx-address');
    els.qr = document.getElementById('cx-qr-img');
    els.copyBtn = document.getElementById('cx-copy-btn');
    els.amountToSend = document.getElementById('cx-amount-to-send');
    els.rightCoin = document.getElementById('cx-right-coin');
    els.rightNetwork = document.getElementById('cx-right-network');
    els.rightRate = document.getElementById('cx-right-rate');
    els.rightAmountDue = document.getElementById('cx-right-amount-due');
    els.amountInput = document.getElementById('cx-amount-input');
    els.amountHint = document.getElementById('cx-amount-hint');
    els.timer = document.getElementById('cx-timer');
    els.timerValue = document.getElementById('cx-timer-value');
    els.rightTimerValue = document.getElementById('cx-right-timer-value');
    els.expiryNotice = document.getElementById('cx-expiry-notice');
    els.ctaBtn = document.getElementById('cx-cta-btn');
    els.checkoutWrap = document.getElementById('cx-checkout-wrap');
    els.topbar = document.getElementById('cx-topbar');
    els.success = document.getElementById('cx-success');
  }

  document.addEventListener('DOMContentLoaded', function () {
    cacheEls();
    initCoinSelector();
    initCopyButton();
    initAmountInput();
    initCta();
    render();
    updateCtaState();
    startTimer();
  });
})();
