/**
 * Coupon edit page: toggle subscription cycle fields visibility.
 *
 * @package ArraySubs
 */

(function () {
  const applyField = document.getElementById(
    "_arraysubs_apply_to_subscriptions",
  );
  const durationField = document.getElementById("_arraysubs_discount_duration");
  const cyclesRow = document.getElementById("_arraysubs_discount_cycles");
  const countInitialField = document.getElementById(
    "_arraysubs_count_initial_checkout",
  );

  if (!applyField || !durationField) {
    return;
  }

  const cyclesRowParent = cyclesRow ? cyclesRow.closest("p.form-field") : null;
  const countInitialRowParent = countInitialField
    ? countInitialField.closest("p.form-field")
    : null;
  const durationRowParent = durationField.closest("p.form-field");

  function toggleFields() {
    const isApply = applyField.checked;
    const isRecurring = durationField.value === "recurring";

    if (durationRowParent) {
      durationRowParent.style.display = isApply ? "" : "none";
    }

    if (cyclesRowParent) {
      cyclesRowParent.style.display = isApply && isRecurring ? "" : "none";
    }

    if (countInitialRowParent) {
      // Show count-initial only when recurring AND cycles > 0.
      const cycles = cyclesRow ? parseInt(cyclesRow.value, 10) || 0 : 0;
      countInitialRowParent.style.display =
        isApply && isRecurring && cycles > 0 ? "" : "none";
    }
  }

  applyField.addEventListener("change", toggleFields);
  durationField.addEventListener("change", toggleFields);

  if (cyclesRow) {
    cyclesRow.addEventListener("input", toggleFields);
  }

  // Initial state.
  toggleFields();
})();
