jQuery(($) => {
  const subscriptionInfoContainer = $(".arraysubs-variable-subscription-info");

  if (!subscriptionInfoContainer.length) {
    return;
  }

  const i18n = window.arraySubsVariableProduct?.i18n || {};

  const formatString = (template, ...args) => {
    let formatted = template || "";
    args.forEach((arg, index) => {
      formatted = formatted.replace(
        new RegExp(`%${index + 1}\\$[sd]`, "g"),
        String(arg),
      );
    });
    return formatted;
  };

  const renderPricingHtml = (data) => {
    if (data.enable_different_renewal_price && data.different_renewal_price) {
      if (data.different_renewal_price_after > 1) {
        return formatString(
          i18n.pricingAfterN,
          data.price_html,
          data.billing_schedule,
          data.different_renewal_price_after,
          data.different_renewal_price_html,
        );
      }

      return formatString(
        i18n.pricingFirstThen,
        data.price_html,
        data.different_renewal_price_html,
        data.billing_schedule,
      );
    }

    if (data.is_on_sale) {
      return formatString(
        i18n.pricingOnSale,
        data.price_html,
        data.billing_schedule,
        data.regular_price_html,
      );
    }

    return formatString(
      i18n.pricingDefault,
      data.price_html,
      data.billing_schedule,
    );
  };

  $("form.variations_form").on("found_variation", (event, variation) => {
    if (!variation.arraysubs_is_subscription || !variation.arraysubs_data) {
      subscriptionInfoContainer.hide().empty();
      return;
    }

    const data = variation.arraysubs_data;
    let html =
      '<div class="arraysubs-product-info"><div class="subscription-terms">';

    html += `<p class="subscription-pricing">${renderPricingHtml(data)}</p>`;

    if (data.signup_fee > 0) {
      html += `<p class="subscription-signup-fee">${formatString(
        i18n.signupFee,
        data.signup_fee_html,
      )}</p>`;
    }

    if (data.trial_length > 0) {
      html += `<p class="subscription-trial">${formatString(
        i18n.trialInfo,
        data.trial_length,
        data.trial_period,
      )}</p>`;
    }

    if (data.length > 0) {
      const totalPeriods = data.length * data.interval;
      const period = `${data.period}${totalPeriods > 1 ? "s" : ""}`;
      html += `<p class="subscription-length">${formatString(
        i18n.subscriptionLength,
        totalPeriods,
        period,
      )}</p>`;
    }

    html += "</div></div>";

    subscriptionInfoContainer.html(html).show();
  });

  $("form.variations_form").on("reset_data", () => {
    subscriptionInfoContainer.hide().empty();
  });
});
