import "@scss/product-edit-page/index.scss";

(function ($) {
  "use strict";

  const config = window.arraySubsductEdit || {};
  const currencySymbol = config.currencySymbol || "$";
  const locale = config.locale || "en-US";
  const i18n = config.i18n || {};

  function parseLoopFromName(name) {
    const match = String(name || "").match(/\[(\d+)\]/);
    return match ? match[1] : null;
  }

  function formatPrice(price) {
    if (!price || price === "" || Number.parseFloat(price) === 0) {
      return `<em>${i18n.notSet || "Not set"}</em>`;
    }

    const priceFormatted = Number.parseFloat(price).toFixed(2);
    return `<span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">${currencySymbol}</span>${priceFormatted}</bdi></span>`;
  }

  function formatDate(dateString) {
    if (!dateString) {
      return "";
    }

    const date = new Date(dateString);
    if (Number.isNaN(date.getTime())) {
      return "";
    }

    return date.toLocaleDateString(locale, {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  }

  function fallbackCopyText(text, input) {
    if (!input || !input.length) {
      return false;
    }

    input.trigger("focus");
    input.trigger("select");

    try {
      return document.execCommand("copy");
    } catch (error) {
      return false;
    }
  }

  async function copyTextToClipboard(text, input) {
    if (navigator.clipboard && window.isSecureContext) {
      try {
        await navigator.clipboard.writeText(text);
        return true;
      } catch (error) {
        return fallbackCopyText(text, input);
      }
    }

    return fallbackCopyText(text, input);
  }

  function initHelperLinkCopy() {
    $(document).on(
      "click",
      ".arraysubs-product-helper-links__copy-link",
      async function (event) {
        event.preventDefault();

        const $link = $(this);
        const $row = $link.closest(".arraysubs-product-helper-links__row");
        const $input = $row.find(".arraysubs-product-helper-links__input");
        const value = $input.val();

        if (!value) {
          return;
        }

        const originalText =
          $link.attr("data-copy-text") || i18n.copyToClipboard;
        const copiedText = $link.attr("data-copied-text") || i18n.copied;
        const failedText =
          $link.attr("data-copy-failed-text") || i18n.copyFailed;

        const copied = await copyTextToClipboard(String(value), $input);

        $link.text(copied ? copiedText : failedText);

        window.setTimeout(function () {
          $link.text(originalText);
        }, 1200);
      },
    );
  }

  function initSimpleSubscriptionFields() {
    function toggleShippingSection() {
      const isSubscription = $("#_is_subscription").is(":checked");
      const isVirtual = $("#_virtual").is(":checked");
      const isDownloadable = $("#_downloadable").is(":checked");

      if (isSubscription && !isVirtual && !isDownloadable) {
        $(".arraysubs-shipping-section").show();
      } else {
        $(".arraysubs-shipping-section").hide();
      }
    }

    function updateSimpleSaleSchedule() {
      const fromDate = $("#_sale_price_dates_from").val();
      const toDate = $("#_sale_price_dates_to").val();
      const $schedule = $("#arraysubs-sale-price-display .sale-schedule");

      if (fromDate || toDate) {
        const fromFormatted = formatDate(fromDate);
        const toFormatted = formatDate(toDate);
        let scheduleText = "";

        if (fromFormatted && toFormatted) {
          scheduleText = `<em>(${fromFormatted} - ${toFormatted})</em>`;
        } else if (fromFormatted) {
          scheduleText = `<em>(${i18n.from || "From"} ${fromFormatted})</em>`;
        } else if (toFormatted) {
          scheduleText = `<em>(${i18n.until || "Until"} ${toFormatted})</em>`;
        }

        $schedule.html(scheduleText).show();
      } else {
        $schedule.hide();
      }
    }

    function toggleSubscriptionTab() {
      const isChecked = $("#_is_subscription").is(":checked");
      const isSimple = $("select#product-type").val() === "simple";
      const $tab = $("ul.wc-tabs li.arraysubs_options");
      const $panel = $("#arraysubs_product_data");

      if (isChecked && isSimple) {
        $tab.show();
        $(".show_if_subscription").show();
        toggleShippingSection();
      } else {
        $tab.hide();
        $(".show_if_subscription").hide();
        // If subscription tab was active, switch to General tab
        if ($tab.hasClass("active")) {
          $("ul.wc-tabs li:visible:first a").trigger("click");
        }
      }
    }

    $("#_is_subscription").on("change", toggleSubscriptionTab);

    // Re-check tab visibility after product type changes (WC may re-show tabs)
    $("select#product-type").on("change", function () {
      setTimeout(toggleSubscriptionTab, 10);
    });

    // Set initial state
    toggleSubscriptionTab();

    $("#_enable_renewal_price")
      .on("change", function () {
        if ($(this).is(":checked")) {
          $(".show_if_renewal_price").removeClass("hidden");
        } else {
          $(".show_if_renewal_price").addClass("hidden");
        }
      })
      .trigger("change");

    $("#_arraysubs_shipping_type")
      .on("change", function () {
        if ($(this).val() === "recurring") {
          $(".show_if_recurring_shipping").removeClass("hidden");
        } else {
          $(".show_if_recurring_shipping").addClass("hidden");
        }
      })
      .trigger("change");

    $("#_virtual, #_downloadable").on("change", toggleShippingSection);

    $("#_regular_price").on("input change", function () {
      $("#arraysubs-regular-price-display .price-value").html(
        formatPrice($(this).val()),
      );
    });

    $("#_sale_price").on("input change", function () {
      const salePrice = $(this).val();
      if (salePrice && Number.parseFloat(salePrice) > 0) {
        $("#arraysubs-sale-price-display").show();
        $("#arraysubs-sale-price-display .price-value").html(
          formatPrice(salePrice),
        );
        updateSimpleSaleSchedule();
      } else {
        $("#arraysubs-sale-price-display").hide();
      }
    });

    $("#_sale_price_dates_from, #_sale_price_dates_to").on(
      "change",
      updateSimpleSaleSchedule,
    );

    // Disable billing interval when lifetime period is selected
    $("#_subscription_period")
      .on("change", function () {
        const isLifetime = $(this).val() === "lifetime";
        const $interval = $("#_subscription_interval");
        $interval
          .prop("disabled", isLifetime)
          .toggleClass("disabled", isLifetime);
        // Remove any existing hidden backup
        $interval.siblings("input.arraysubs-lifetime-interval-backup").remove();
        if (isLifetime) {
          $interval.val("1");
          // Add hidden field so value submits despite disabled state
          $interval.after(
            '<input type="hidden" class="arraysubs-lifetime-interval-backup" name="_subscription_interval" value="1" />',
          );
        }
      })
      .trigger("change");

    toggleShippingSection();
    updateSimpleSaleSchedule();
  }

  function updateVariationSaleSchedule($wrapper, loop) {
    const fromDate = $wrapper
      .find(`input[name="variable_sale_price_dates_from[${loop}]"]`)
      .val();
    const toDate = $wrapper
      .find(`input[name="variable_sale_price_dates_to[${loop}]"]`)
      .val();
    const $schedule = $wrapper.find(
      `.arraysubs-variation-sale-price-display[data-loop="${loop}"] .sale-schedule`,
    );

    if (fromDate || toDate) {
      const fromFormatted = formatDate(fromDate);
      const toFormatted = formatDate(toDate);
      let scheduleText = "";

      if (fromFormatted && toFormatted) {
        scheduleText = `<em>(${fromFormatted} - ${toFormatted})</em>`;
      } else if (fromFormatted) {
        scheduleText = `<em>(${i18n.from || "From"} ${fromFormatted})</em>`;
      } else if (toFormatted) {
        scheduleText = `<em>(${i18n.until || "Until"} ${toFormatted})</em>`;
      }

      $schedule.html(scheduleText).show();
    } else {
      $schedule.hide();
    }
  }

  function toggleVariationShippingSection($wrapper, loop) {
    const isVirtual = $wrapper
      .find(`input[name="variable_is_virtual[${loop}]"]`)
      .is(":checked");
    const isDownloadable = $wrapper
      .find(`input[name="variable_is_downloadable[${loop}]"]`)
      .is(":checked");
    const $shippingSection = $wrapper.find(
      `#arraysubs-variation-shipping-${loop}`,
    );

    if (isVirtual || isDownloadable) {
      $shippingSection.hide();
    } else {
      $shippingSection.show();
    }
  }

  function initVariationSubscriptionFields() {
    // Sync header checkbox state to all variation checkboxes
    function syncVariationSubscriptionCheckboxes() {
      const isChecked = $("#_is_subscription").is(":checked");

      $(".variation_is_subscription").each(function () {
        $(this).prop("checked", isChecked);
        const $wrapper = $(this).closest(".woocommerce_variation");

        // Manage hidden field for form submission (disabled checkboxes don't submit)
        $wrapper.find(".variation_is_subscription_hidden").remove();
        if (isChecked) {
          const name = $(this).attr("name");
          $(this)
            .closest("label")
            .append(
              `<input type="hidden" name="${name}" value="yes" class="variation_is_subscription_hidden" />`,
            );
        }

        // Toggle variation subscription fields visibility and name attrs
        const $subFields = $wrapper.find(".show_if_variation_subscription");
        const $switchingFields = $wrapper.find(
          ".arraysubs-variation-switching",
        );
        if (isChecked) {
          $subFields.show();
          $switchingFields.show();
          // Restore name attributes so data submits
          $subFields.find("[data-name]").each(function () {
            $(this).attr("name", $(this).attr("data-name"));
          });
          $switchingFields.find("[data-name]").each(function () {
            $(this).attr("name", $(this).attr("data-name"));
          });
        } else {
          $subFields.hide();
          $switchingFields.hide();
          // Strip name attributes so junk data doesn't submit
          $subFields
            .find("input[name], select[name], textarea[name]")
            .each(function () {
              $(this).attr("data-name", $(this).attr("name"));
              $(this).removeAttr("name");
            });
          $switchingFields
            .find("input[name], select[name], textarea[name]")
            .each(function () {
              $(this).attr("data-name", $(this).attr("name"));
              $(this).removeAttr("name");
            });
        }
      });
    }

    // Listen to header checkbox changes
    $("#_is_subscription").on("change", syncVariationSubscriptionCheckboxes);

    // When WooCommerce loads variations (AJAX), sync the checkboxes
    $("#woocommerce-product-data").on(
      "woocommerce_variations_loaded",
      function () {
        syncVariationSubscriptionCheckboxes();
        syncAllVariationLifetimeState();
      },
    );

    // When a new variation is added, sync after a short delay
    $("#woocommerce-product-data").on(
      "woocommerce_variations_added",
      function () {
        setTimeout(function () {
          syncVariationSubscriptionCheckboxes();
          syncAllVariationLifetimeState();
        }, 100);
      },
    );

    // Keep the change handler for show/hide (in case anything triggers it)
    $(document).on("change", ".variation_is_subscription", function () {
      const $wrapper = $(this).closest(".woocommerce_variation");
      if ($(this).is(":checked")) {
        $wrapper.find(".show_if_variation_subscription").show();
      } else {
        $wrapper.find(".show_if_variation_subscription").hide();
      }
    });

    $(document).on("change", ".variation_enable_renewal_price", function () {
      const $wrapper = $(this).closest(".woocommerce_variation");
      if ($(this).is(":checked")) {
        $wrapper.find(".show_if_variation_renewal_price").show();
      } else {
        $wrapper.find(".show_if_variation_renewal_price").hide();
      }
    });

    // Disable billing interval when lifetime period is selected (variations)
    function applyVariationLifetimeState($wrapper) {
      const $period = $wrapper.find("select[name^='_subscription_period[']");
      if (!$period.length) {
        return;
      }
      const isLifetime = $period.val() === "lifetime";
      const $interval = $wrapper.find("input[name^='_subscription_interval[']");
      // Remove any existing hidden backup
      $wrapper.find("input.arraysubs-lifetime-interval-backup").remove();
      $interval
        .prop("disabled", isLifetime)
        .toggleClass("disabled", isLifetime);
      if (isLifetime) {
        $interval.val("1");
        // Add hidden field so value submits despite disabled state
        const name = $interval.attr("name");
        if (name) {
          $interval.after(
            `<input type="hidden" class="arraysubs-lifetime-interval-backup" name="${name}" value="1" />`,
          );
        }
      }
    }

    function syncAllVariationLifetimeState() {
      $(".woocommerce_variation").each(function () {
        applyVariationLifetimeState($(this));
      });
    }

    $(document).on(
      "change",
      "select[name^='_subscription_period[']",
      function () {
        const $wrapper = $(this).closest(".woocommerce_variation");
        applyVariationLifetimeState($wrapper);
      },
    );

    $(document).on(
      "input change",
      "input[name^='variable_regular_price']",
      function () {
        const loop = parseLoopFromName($(this).attr("name"));
        if (!loop) {
          return;
        }

        const $wrapper = $(this).closest(".woocommerce_variation");
        $wrapper
          .find(
            `.arraysubs-variation-regular-price-display[data-loop="${loop}"] .price-value`,
          )
          .html(formatPrice($(this).val()));
      },
    );

    $(document).on(
      "input change",
      "input[name^='variable_sale_price[']",
      function () {
        const loop = parseLoopFromName($(this).attr("name"));
        if (!loop) {
          return;
        }

        const $wrapper = $(this).closest(".woocommerce_variation");
        const salePrice = $(this).val();
        const $display = $wrapper.find(
          `.arraysubs-variation-sale-price-display[data-loop="${loop}"]`,
        );

        if (salePrice && Number.parseFloat(salePrice) > 0) {
          $display.show();
          $display.find(".price-value").html(formatPrice(salePrice));
          updateVariationSaleSchedule($wrapper, loop);
        } else {
          $display.hide();
        }
      },
    );

    $(document).on(
      "change",
      "input[name^='variable_sale_price_dates_from'], input[name^='variable_sale_price_dates_to']",
      function () {
        const loop = parseLoopFromName($(this).attr("name"));
        if (!loop) {
          return;
        }

        const $wrapper = $(this).closest(".woocommerce_variation");
        updateVariationSaleSchedule($wrapper, loop);
      },
    );

    $(document).on(
      "change",
      "input[name^='variable_is_virtual'], input[name^='variable_is_downloadable']",
      function () {
        const loop = parseLoopFromName($(this).attr("name"));
        if (!loop) {
          return;
        }

        const $wrapper = $(this).closest(".woocommerce_variation");
        toggleVariationShippingSection($wrapper, loop);
      },
    );

    $(".woocommerce_variation").each(function () {
      const $wrapper = $(this);
      const name =
        $wrapper.find("input[name^='variable_regular_price']").attr("name") ||
        $wrapper.find("input[name^='variable_is_virtual']").attr("name") ||
        "";
      const loop = parseLoopFromName(name);

      if (!loop) {
        return;
      }

      updateVariationSaleSchedule($wrapper, loop);
      toggleVariationShippingSection($wrapper, loop);
    });
  }

  function initPlanSwitchingFields() {
    function togglePlanSwitchingFields() {
      const isSubscription = $("#_is_subscription").is(":checked");
      if (isSubscription) {
        $(".arraysubs-plan-switching").show();
      } else {
        $(".arraysubs-plan-switching").hide();
      }
    }

    $("#_is_subscription").on("change", togglePlanSwitchingFields);
    togglePlanSwitchingFields();
  }

  function initStoreCreditProductFields() {
    function updateCreditProductVisibility() {
      const isCredit =
        $("select#product-type").val() === "arraysubs_store_credit";

      $(".show_if_arraysubs_store_credit").toggle(isCredit);
      $(".hide_if_arraysubs_store_credit").toggle(!isCredit);

      if (isCredit) {
        $("ul.wc-tabs li.general_options").show();
        $("ul.wc-tabs li.general_options a").trigger("click");
      }
    }

    $("body").on(
      "change",
      "select#product-type",
      updateCreditProductVisibility,
    );

    $("#_arraysubs_credit_amount_type")
      .on("change", function () {
        const type = $(this).val();
        $("#_arraysubs_credit_amount")
          .closest(".form-field")
          .toggle(type === "fixed");
      })
      .trigger("change");

    setTimeout(updateCreditProductVisibility, 100);
  }

  $(function () {
    initSimpleSubscriptionFields();
    initVariationSubscriptionFields();
    initPlanSwitchingFields();
    initStoreCreditProductFields();
    initHelperLinkCopy();
  });
})(jQuery);
