(function ($) {
  // ---------------- PAYMENT TIMER (legacy; safe if timer HTML is not present) ----------------
  let spgTimerInterval = null;
  let spgTimerEndsAt = null;

  function formatMMSS(sec) {
    sec = Math.max(0, Math.floor(sec));
    const m = Math.floor(sec / 60);
    const s = sec % 60;
    return String(m).padStart(2, "0") + ":" + String(s).padStart(2, "0");
  }

  function setPlaceOrderDisabled(disabled) {
    const $btn = $("#place_order");
    if (!$btn.length) return;
    $btn.prop("disabled", !!disabled);
    $btn.toggleClass("disabled", !!disabled);
  }

  function renderTimer(secLeft) {
    const $wrap = $("#spg_timer_wrap");
    if (!$wrap.length) return;

    const $hm = $wrap.find(".mcc_payment_timer .hours_minutes");
    if ($hm.length) $hm.text(formatMMSS(secLeft));
  }

  function showTimerExpired() {
    renderTimer(0);
    setPlaceOrderDisabled(true);
  }

  function stopPaymentTimer() {
    if (spgTimerInterval) {
      clearInterval(spgTimerInterval);
      spgTimerInterval = null;
    }
    spgTimerEndsAt = null;
    setPlaceOrderDisabled(false);
    renderTimer(0);
  }

  function startPaymentTimer() {
    if (!window.SPG_DATA || !SPG_DATA.timer_enabled) return;

    const mins = parseInt(SPG_DATA.timer_minutes, 10);
    if (!isFinite(mins) || mins <= 0) return;

    if (spgTimerEndsAt) return;

    spgTimerEndsAt = Date.now() + mins * 60 * 1000;
    setPlaceOrderDisabled(false);

    renderTimer(mins * 60);

    spgTimerInterval = setInterval(() => {
      const leftMs = spgTimerEndsAt - Date.now();
      const leftSec = Math.ceil(leftMs / 1000);

      if (leftSec <= 0) {
        stopPaymentTimer();
        showTimerExpired();
        return;
      }

      renderTimer(leftSec);
    }, 1000);
  }

  function isCdpSelected() {
    return (
      $('input[name="payment_method"]:checked').val() === "spg_crypto_manual"
    );
  }

  function updateTimerVisibility() {
    const $wrap = $("#spg_timer_wrap");
    if (!$wrap.length) return; // timer not rendered on checkout anymore

    const hasWallet = !!$("#spg_wallet_choice").val();
    if (
      isCdpSelected() &&
      hasWallet &&
      window.SPG_DATA &&
      SPG_DATA.timer_enabled
    ) {
      $wrap.show();
      startPaymentTimer();
    } else {
      $wrap.hide();
      stopPaymentTimer();
    }
  }

  // ---------------- helpers ----------------
  function wallets() {
    return window.SPG_DATA && Array.isArray(SPG_DATA.wallets)
      ? SPG_DATA.wallets
      : [];
  }

  function getWallet(key) {
    return wallets().find((w) => String(w.key) === String(key));
  }

  function rates() {
    return window.SPG_DATA && SPG_DATA.rates_usd ? SPG_DATA.rates_usd : {};
  }

  function getUsdTotalRaw() {
    const v = ($("#spg_order_total_raw").val() || "").trim();
    const n = parseFloat(v.replace(",", "."));
    return isFinite(n) ? n : 0;
  }

  function fmtCoin(x) {
    const s = (Math.round(x * 1e8) / 1e8).toFixed(8);
    return s.replace(/\.?0+$/, "");
  }

  function isRateCoin(coin) {
    coin = String(coin || "")
      .toUpperCase()
      .trim();
    return [
      "BTC",
      "LTC",
      "BCH",
      "DOGE",
      "DASH",
      "DGB",
      "ETH",
      "BNB",
      "MATIC",
      "SOL",
      "MAZA",
    ].includes(coin);
  }

  function legacyCopy(text) {
    const ta = document.createElement("textarea");
    ta.value = text;
    ta.setAttribute("readonly", "");
    ta.style.position = "fixed";
    ta.style.left = "-9999px";
    ta.style.top = "0";
    document.body.appendChild(ta);
    ta.focus();
    ta.select();
    ta.setSelectionRange(0, ta.value.length);
    try {
      document.execCommand("copy");
    } catch (e) {}
    document.body.removeChild(ta);
    return Promise.resolve();
  }

  function copyText(text) {
    text = (text || "").trim();
    if (!text) return Promise.resolve(false);

    if (navigator.clipboard && window.isSecureContext) {
      return navigator.clipboard
        .writeText(text)
        .then(() => true)
        .catch(() => legacyCopy(text).then(() => true));
    }
    return legacyCopy(text).then(() => true);
  }

  function renderUsdOnly(usd) {
    const u = isFinite(usd) && usd > 0 ? usd : getUsdTotalRaw();
    return '<span style="color:gray;">amount: USD </span> ' + u.toFixed(2);
  }

  function renderUsdPlusEstimate(usd, coin, est) {
    return (
      '<span style="color:gray;">amount: USD </span> ' +
      usd.toFixed(2) +
      '<br><span style="color:gray;">≈ </span> ' +
      fmtCoin(est) +
      " " +
      coin
    );
  }

  function renderIconsForWallet(w) {
    const iconsOn = !!(window.SPG_DATA && SPG_DATA.icons_enabled);

    const $iconTop = $("#spg_coin_icon");
    const $iconPrev = $("#spg_preview_icon");
    const $labelPrev = $("#spg_preview_label");

    if (!iconsOn) {
      if ($iconTop.length) $iconTop.hide().attr("src", "");
      if ($iconPrev.length) $iconPrev.hide().attr("src", "");
      if ($labelPrev.length) $labelPrev.text("");
      return;
    }

    if (!w || !w.icon) {
      if ($iconTop.length) $iconTop.hide().attr("src", "");
      if ($iconPrev.length) $iconPrev.hide().attr("src", "");
      if ($labelPrev.length) $labelPrev.text("");
      return;
    }

    if ($iconTop.length) $iconTop.attr("src", w.icon).show();
    if ($iconPrev.length) $iconPrev.attr("src", w.icon).show();
    if ($labelPrev.length)
      $labelPrev.text(((w.coin || "") + " " + (w.network || "")).trim());
  }

  function showWallet(w) {
    const $qr = $("#spg_qr");

    // apply QR display size
    if ($qr.length && window.SPG_DATA && SPG_DATA.qr_size_px) {
      $qr.css(
        "max-width",
        String(parseInt(SPG_DATA.qr_size_px, 10) || 220) + "px",
      );
      $qr.css("height", "auto");
    }

    // icons
    renderIconsForWallet(w);

    if (!w) {
      $("#spg_preview").hide();
      if ($qr.length) $qr.attr("src", "");

      $("#spg_network").text("");
      $("#spg_address").html('<span style="color:gray;">address: </span>');
      $("#spg_note_row").text("");

      $("#spg_wallet_coin").val("");
      $("#spg_wallet_network").val("");
      $("#spg_wallet_address").val("");
      $("#spg_wallet_qr").val("");
      $("#spg_wallet_contract").val("");
      $("#spg_wallet_decimals").val("");
      $("#spg_wallet_tag").val("");
      const usd = getUsdTotalRaw();
      $("#spg_amount").html(renderUsdOnly(usd));
      $("#spg_amount").data("usd", usd.toFixed(2));
      $("#spg_amount").data("coin", "");

      updateTimerVisibility();
      return;
    }

    const usd = getUsdTotalRaw();
    const coin = (w.coin || "").toUpperCase().trim();

    $("#spg_amount").html(renderUsdOnly(usd));
    $("#spg_amount").data("usd", usd.toFixed(2));
    $("#spg_amount").data("coin", "");

    if (usd > 0 && isRateCoin(coin)) {
      const r = rates();
      const price = parseFloat(r[coin]);
      if (isFinite(price) && price > 0) {
        const est = usd / price;
        $("#spg_amount").html(renderUsdPlusEstimate(usd, coin, est));
        $("#spg_amount").data("coin", fmtCoin(est) + " " + coin);
      }
    }

    $("#spg_preview").show();
    if ($qr.length) $qr.attr("src", w.qr || "");

    $("#spg_network").text(w.network || "");
    $("#spg_address").html(
      '<span style="color:gray;">address: </span>' + (w.address || ""),
    );
    $("#spg_note_row").text(w.note || "");

    $("#spg_wallet_coin").val(w.coin || "");
    $("#spg_wallet_network").val(w.network || "");
    $("#spg_wallet_address").val(w.address || "");
    $("#spg_wallet_qr").val(w.qr || "");
    $("#spg_wallet_contract").val(w.contract || "");
    $("#spg_wallet_decimals").val(w.decimals || "");
    $("#spg_wallet_tag").val(w.tag || "");
    updateTimerVisibility();
  }

  function ensurePrimaryIsShown() {
    if (!isCdpSelected()) return;

    const $sel = $("#spg_wallet_choice");
    if (!$sel.length) return;

    const key = ($sel.val() || "").toString().trim();
    if (key) {
      showWallet(getWallet(key));
    } else {
      showWallet(null);
    }
  }

  // ---------------- Events ----------------
  $(document).on("change", "#spg_wallet_choice", function () {
    showWallet(getWallet(this.value));
  });

  $(document).on("click", "#spg_copy_address", function (e) {
    e.preventDefault();
    e.stopPropagation();

    const $icon = $(this);
    const addr = ($("#spg_wallet_address").val() || "").trim();

    copyText(addr).then((ok) => {
      if (!ok) return;
      $icon.css("opacity", "0.4");
      setTimeout(() => $icon.css("opacity", ""), 250);
    });
  });

  $(document).on("click", "#spg_copy_amount", function (e) {
    e.preventDefault();
    e.stopPropagation();

    const $icon = $(this);
    const coinVal = ($("#spg_amount").data("coin") || "").toString().trim();
    const usdVal = ($("#spg_amount").data("usd") || "").toString().trim();
    const toCopy = coinVal ? coinVal : usdVal;

    copyText(toCopy).then((ok) => {
      if (!ok) return;
      $icon.css("opacity", "0.4");
      setTimeout(() => $icon.css("opacity", ""), 250);
    });
  });

  $(document).on("change", 'input[name="payment_method"]', function () {
    updateTimerVisibility();
    setTimeout(ensurePrimaryIsShown, 0);
    setTimeout(ensurePrimaryIsShown, 150);
  });

  $(function () {
    updateTimerVisibility();
    setTimeout(ensurePrimaryIsShown, 0);
    setTimeout(ensurePrimaryIsShown, 150);
    setTimeout(ensurePrimaryIsShown, 400);
  });

  $(document.body).on("updated_checkout", function () {
    updateTimerVisibility();
    setTimeout(ensurePrimaryIsShown, 0);
    setTimeout(ensurePrimaryIsShown, 150);
  });
  function dedupeWalletSelect() {
  const $sel = $("#spg_wallet_choice");
  if (!$sel.length) return;

  const seen = new Set();
  $sel.find("option").each(function () {
    const v = String($(this).attr("value") || "");
    if (!v) return; // keep placeholder

    if (seen.has(v)) {
      $(this).remove();
    } else {
      seen.add(v);
    }
  });
}

// run on load + every Woo refresh
$(function () {
  dedupeWalletSelect();
});

$(document.body).on("updated_checkout", function () {
  dedupeWalletSelect();
});
})(jQuery);
