function setCopyState(button, text) {
  if (!button) return;
  var original = button.getAttribute('data-original-label') || button.textContent;
  button.setAttribute('data-original-label', original);
  button.textContent = text;
  window.clearTimeout(button.vexonCopyTimer);
  button.vexonCopyTimer = window.setTimeout(function() {
    button.textContent = original;
  }, 1800);
}

function fallbackCopy(text) {
  var area = document.createElement('textarea');
  area.value = text;
  area.setAttribute('readonly', 'readonly');
  area.style.position = 'fixed';
  area.style.left = '-9999px';
  document.body.appendChild(area);
  area.select();
  var ok = false;
  try {
    ok = document.execCommand('copy');
  } catch (e) {
    ok = false;
  }
  document.body.removeChild(area);
  return ok;
}

function copyValue(selector, button) {
  var node = document.querySelector(selector);
  if (!node) return;
  var text = node.textContent.trim();
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(text).then(function() {
      setCopyState(button, 'Copied');
    }).catch(function() {
      setCopyState(button, fallbackCopy(text) ? 'Copied' : 'Copy failed');
    });
    return;
  }
  setCopyState(button, fallbackCopy(text) ? 'Copied' : 'Copy failed');
}

function updateEstimate() {
  var box = document.querySelector('.calculator');
  var hashrate = document.getElementById('hashrate');
  var network = document.getElementById('network');
  var output = document.getElementById('daily-estimate');
  if (!box || !hashrate || !network || !output) return;

  var minerThs = parseFloat(hashrate.value);
  var networkThs = parseFloat(network.value);
  var reward = parseFloat(box.getAttribute('data-reward'));
  var blockTime = parseFloat(box.getAttribute('data-block-time'));
  var fee = parseFloat(box.getAttribute('data-fee'));

  if (!minerThs || !networkThs || !reward || !blockTime) {
    output.textContent = 'Waiting for input';
    return;
  }

  var dailyBlocks = 86400 / blockTime;
  var estimate = minerThs / networkThs * dailyBlocks * reward * (1 - fee / 100);
  output.textContent = estimate >= 1 ? estimate.toFixed(4) + ' VEX' : estimate.toFixed(6) + ' VEX';
}

document.querySelectorAll('[data-copy]').forEach(function(button) {
  button.addEventListener('click', function() {
    copyValue(button.getAttribute('data-copy'), button);
  });
});

['hashrate', 'network'].forEach(function(id) {
  var input = document.getElementById(id);
  if (input) input.addEventListener('input', updateEstimate);
});

updateEstimate();
