const payoutPerShardUsd = 0.001;
const electricityCostPerHourUsd = 0.003;
const realtimeFactors = {
  "M1": 15,
  "M1 Pro": 25,
  "M2": 20,
  "M3": 22,
  "M3 Pro": 25,
  "M4": 28,
  "M4 Pro": 35,
};

function formatUsd(amount) {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    maximumFractionDigits: amount >= 100 ? 0 : 2,
  }).format(amount);
}

function monthlyEstimate(hoursPerDay, factor) {
  return hoursPerDay * (3600 / 60) * factor * payoutPerShardUsd * 30;
}

function updateCalculator() {
  const hoursInput = document.querySelector("#earnings-hours");
  const chipSelect = document.querySelector("#earnings-chip");
  if (!hoursInput || !chipSelect) {
    return;
  }

  const hoursPerDay = Number(hoursInput.value);
  const chip = chipSelect.value;
  const factor = realtimeFactors[chip];
  const monthlyPayout = monthlyEstimate(hoursPerDay, factor);
  const electricity = hoursPerDay * 30 * electricityCostPerHourUsd;

  document.querySelector("#earnings-hours-value").textContent = `${hoursPerDay} hours/day`;
  document.querySelector("#earnings-total").textContent = `${formatUsd(monthlyPayout)}/month`;
  document.querySelector("#earnings-electricity").textContent = formatUsd(electricity);
  document.querySelector("#earnings-summary").textContent =
    `Your ${chip} Mac could earn about ${formatUsd(monthlyPayout)}/month while it would otherwise sit idle.`;

  for (const row of document.querySelectorAll(".realtime-row")) {
    row.classList.toggle("active", row.dataset.chip === chip);
  }
}

window.addEventListener("DOMContentLoaded", () => {
  const hoursInput = document.querySelector("#earnings-hours");
  const chipSelect = document.querySelector("#earnings-chip");
  if (!hoursInput || !chipSelect) {
    return;
  }

  hoursInput.addEventListener("input", updateCalculator);
  chipSelect.addEventListener("change", updateCalculator);
  updateCalculator();
});
