(function ($) {
  function buildBlackoutRuleRow(hasTime) {
    var cells = '';
    cells += '<td><input type="text" class="chbk-datepicker" name="chbk_blackout_start_date[]" value=""></td>';
    if (hasTime) {
      cells += '<td><input type="time" name="chbk_blackout_start_time[]" value="00:00"></td>';
    }
    cells += '<td><input type="text" class="chbk-datepicker" name="chbk_blackout_end_date[]" value=""></td>';
    if (hasTime) {
      cells += '<td><input type="time" name="chbk_blackout_end_time[]" value="23:59"></td>';
    }
    cells += '<td><button type="button" class="button chbk-blackout-rules-remove">Remove</button></td>';
    return '<tr>' + cells + '</tr>';
  }

  function initCbkDatepickers(context) {
    var $context = context || $(document);
    $context.find('.chbk-datepicker').each(function () {
      var $input = $(this);
      if ($input.hasClass('hasDatepicker')) {
        return;
      }

      $input.datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        changeYear: true
      });
    });
  }

  function todayIsoDate() {
    var now = new Date();
    var y = now.getFullYear();
    var m = String(now.getMonth() + 1).padStart(2, '0');
    var d = String(now.getDate()).padStart(2, '0');
    return y + '-' + m + '-' + d;
  }

  function syncTripPricingUi($scope) {
    var $type = $scope.find('select[name="chbk_trip_type"]').first();
    if (!$type.length) {
      return;
    }

    var type = ($type.val() || '').trim();
    var $baseRow = $scope.find('.chbk-base-price-row').first();
    var $seatRow = $scope.find('.chbk-seat-price-row').first();
    var $includedWrap = $scope.find('.chbk-included-seats-wrap').first();
    var $includedToggle = $scope.find('input[name="chbk_included_seats_enabled"]').first();
    var $includedCount = $scope.find('input[name="chbk_included_seats_count"]').first();

    if (type === 'per-group') {
      $baseRow.show();
      $seatRow.hide();
      $includedWrap.hide();
    } else if (type === 'per-seat') {
      $baseRow.hide();
      $seatRow.show();
      $includedWrap.hide();
    } else if (type === 'hybrid') {
      $baseRow.show();
      $seatRow.show();
      $includedWrap.show();
    }

    if ($includedCount.length) {
      var enabled = $includedToggle.length && $includedToggle.is(':checked');
      $includedCount.prop('disabled', !enabled);
    }
  }

  function initTripPricingUi(context) {
    var $context = context || $(document);
    $context.find('select[name="chbk_trip_type"]').each(function () {
      syncTripPricingUi($(this).closest('.inside'));
    });
  }

  function syncOperatingDaysUi($scope) {
    var $root = $scope && $scope.length ? $scope : $(document);
    $root.find('.chbk-day-pill input[type="checkbox"]').each(function () {
      var $input = $(this);
      $input.closest('.chbk-day-pill').toggleClass('is-checked', $input.is(':checked'));
    });
  }

  function formatBookingCurrency(amount, currencyCode) {
    var value = Number(amount || 0);
    var code = (currencyCode || 'USD').toUpperCase();
    var fixed = value.toFixed(2);
    var parts = fixed.split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    var formatted = parts.join('.');
    if (code === 'USD') {
      return '$' + formatted;
    }
    return code + ' ' + formatted;
  }

  function computeLivePrice($form) {
    var type = ($form.attr('data-chbk-trip-type') || 'per-group').trim();
    var base = Number($form.attr('data-chbk-base-price') || 0);
    var seat = Number($form.attr('data-chbk-seat-price') || 0);
    var included = Number($form.attr('data-chbk-included-seats') || 0);
    var currency = ($form.attr('data-chbk-currency') || 'USD').trim();
    var onlineRequired = Number($form.attr('data-chbk-online-payment-required') || 0) === 1;
    var mustPayFull = Number($form.attr('data-chbk-online-must-pay-full') || 0) === 1;
    var depositType = ($form.attr('data-chbk-online-deposit-type') || 'fixed').trim();
    var depositAmount = Number($form.attr('data-chbk-online-deposit-amount') || 0);
    var $party = $form.find('input[name="chbk_party_size"]').first();
    var $value = $form.find('.chbk-live-price-value').first();
    var $due = $form.find('.chbk-due-at-booking-value').first();

    if (!$party.length || !$value.length) {
      return;
    }

    var size = Number($party.val() || 0);
    var min = Number($party.attr('min') || 1);
    var maxRaw = $party.attr('max');
    var max = maxRaw ? Number(maxRaw) : 0;
    if (size < min) {
      size = min;
      $party.val(String(min));
    }
    if (max > 0 && size > max) {
      size = max;
      $party.val(String(max));
    }

    var billable = Math.max(0, size - (type === 'hybrid' ? included : 0));
    var total = base;
    if (type === 'per-seat') {
      total = seat * size;
    } else if (type === 'hybrid') {
      total = base + (seat * billable);
    }

    $value.text(formatBookingCurrency(total, currency));

    if (onlineRequired && $due.length) {
      var dueAmount = mustPayFull ? total : (depositType === 'percentage' ? ((total * Math.max(0, depositAmount)) / 100) : Math.max(0, depositAmount));
      if (!mustPayFull) {
        dueAmount = Math.min(total, dueAmount);
      }
      $due.text(formatBookingCurrency(dueAmount, currency));
    }
  }

  function initLivePricing(context) {
    var $context = context || $(document);
    $context.find('.chbk-booking-form').each(function () {
      computeLivePrice($(this));
    });
  }

  $(function () {
    initCbkDatepickers($(document));
    initTripPricingUi($(document));
    syncOperatingDaysUi($(document));
    initLivePricing($(document));

    $(document).on('click', '.chbk-blackout-rules-add', function () {
      var $wrap = $(this).closest('.chbk-blackout-rules');
      var hasTime = ($wrap.attr('data-has-time') || '0') === '1';
      $wrap.find('.chbk-blackout-rules-rows').append(buildBlackoutRuleRow(hasTime));
      $(document).trigger('chbk:init-datepicker');
    });

    $(document).on('click', '.chbk-blackout-rules-remove', function () {
      var $rows = $(this).closest('.chbk-blackout-rules-rows');
      if ($rows.find('tr').length <= 1) {
        $(this).closest('tr').find('input').val('');
        return;
      }
      $(this).closest('tr').remove();
    });

    $(document).on('change', 'select[name="chbk_trip_type"]', function () {
      syncTripPricingUi($(this).closest('.inside'));
    });

    $(document).on('change', 'input[name="chbk_included_seats_enabled"]', function () {
      syncTripPricingUi($(this).closest('.inside'));
    });

    $(document).on('change', '.chbk-day-pill input[type="checkbox"]', function () {
      syncOperatingDaysUi($(this).closest('.inside'));
    });

    $(document).on('click', '.chbk-booking-edit-toggle', function (event) {
      event.preventDefault();
      var $btn = $(this);
      var target = ($btn.attr('data-target') || '').trim();
      var $card = $btn.closest('.chbk-booking-card');
      var $edit = $card.find('.chbk-booking-edit-' + target).first();
      if (!$edit.length) {
        return;
      }
      $edit.slideToggle(120);
      $btn.text($edit.is(':visible') ? 'Edit' : 'Done');
    });

    $(document).on('click', '.chbk-record-payment-btn', function (event) {
      event.preventDefault();
      var $btn = $(this);
      var bookingId = $btn.attr('data-booking-id') || '';
      var bookingTitle = $btn.attr('data-booking-title') || '';
      var $modal = $('#chbk-record-payment-modal');
      if (!$modal.length) {
        return;
      }
      $modal.find('input[name="booking_id"]').val(bookingId);
      $modal.find('.chbk-record-payment-booking').text(bookingTitle);
      var $dateInput = $modal.find('input[name="chbk_payment_date"]').first();
      if ($dateInput.length && !$dateInput.val()) {
        $dateInput.val(todayIsoDate());
      }
      $modal.addClass('is-open');
      $(document).trigger('chbk:init-datepicker');
    });

    $(document).on('click', '.chbk-edit-payment-btn', function (event) {
      event.preventDefault();
      var $btn = $(this);
      var $modal = $('#chbk-edit-payment-modal');
      if (!$modal.length) {
        return;
      }

      $modal.find('input[name="booking_id"]').val($btn.attr('data-booking-id') || '');
      $modal.find('input[name="entry_index"]').val($btn.attr('data-entry-index') || '');
      $modal.find('.chbk-edit-payment-booking').text($btn.attr('data-booking-title') || '');
      $modal.find('input[name="chbk_payment_amount"]').val($btn.attr('data-payment-amount') || '');
      $modal.find('input[name="chbk_payment_date"]').val($btn.attr('data-payment-date') || todayIsoDate());
      $modal.find('input[name="chbk_payment_time"]').val($btn.attr('data-payment-time') || '00:00');
      $modal.find('select[name="chbk_payment_method"]').val($btn.attr('data-payment-method') || 'cash');
      $modal.find('input[name="chbk_payment_reference"]').val($btn.attr('data-payment-reference') || '');
      $modal.find('input[name="chbk_payment_note"]').val($btn.attr('data-payment-note') || '');

      $modal.addClass('is-open');
      $(document).trigger('chbk:init-datepicker');
    });

    $(document).on('click', '.chbk-modal-close, .chbk-modal-cancel', function (event) {
      event.preventDefault();
      $(this).closest('.chbk-modal-backdrop').removeClass('is-open');
    });

    $(document).on('click', '.chbk-modal-backdrop', function (event) {
      var $backdrop = $(this);
      if ($(event.target).is($backdrop)) {
        $backdrop.removeClass('is-open');
      }
    });

    $(document).on('change', '.chbk-booking-status-select', function () {
      var $select = $(this);
      var bookingId = parseInt($select.attr('data-booking-id') || '0', 10);
      var nonce = $select.attr('data-nonce') || '';
      var status = $select.val() || '';
      var $feedback = $select.siblings('.chbk-booking-status-feedback').first();
      if (!bookingId || !status || !nonce || typeof ajaxurl === 'undefined') {
        return;
      }

      $select.prop('disabled', true);
      $feedback.stop(true, true).text('Saving...').css({ display: 'inline', color: '' });

      $.post(ajaxurl, {
        action: 'chbk_update_booking_status',
        booking_id: bookingId,
        booking_status: status,
        nonce: nonce
      }).done(function (response) {
        if (response && response.success) {
          $feedback.text('Updated').css({ color: '#2d8a39' }).delay(900).fadeOut(300);
          return;
        }
        var msg = (response && response.data && response.data.message) ? response.data.message : 'Update failed';
        $feedback.text(msg).css({ color: '#b32d2e' }).show();
      }).fail(function () {
        $feedback.text('Update failed').css({ color: '#b32d2e' }).show();
      }).always(function () {
        $select.prop('disabled', false);
      });
    });

    $(document).on('input change', '.chbk-booking-form input[name="chbk_party_size"]', function () {
      computeLivePrice($(this).closest('.chbk-booking-form'));
    });

  });

  $(document).on('chbk:init-datepicker', function () {
    initCbkDatepickers($(document));
    initTripPricingUi($(document));
    syncOperatingDaysUi($(document));
    initLivePricing($(document));
  });
})(jQuery);
