$(function () {
  AOS.init({ duration: 750, once: true, offset: 60 });
  GLightbox({ selector: '.glightbox' });

  $('#openInvitation').on('click', function () {
    $('#cover').fadeOut(700, function () {
      $('#invitation').removeClass('d-none');
      AOS.refresh();
    });
  });

  const target = new Date(document.body.dataset.eventDate.replace(' ', 'T')).getTime();
  function tick() {
    const difference = Math.max(0, target - Date.now());
    const values = [
      Math.floor(difference / 86400000),
      Math.floor((difference % 86400000) / 3600000),
      Math.floor((difference % 3600000) / 60000),
      Math.floor((difference % 60000) / 1000)
    ];
    ['days', 'hours', 'minutes', 'seconds'].forEach((id, index) => {
      $('#' + id).text(String(values[index]).padStart(2, '0'));
    });
  }
  tick();
  setInterval(tick, 1000);

  function ajaxForm(selector) {
    $(selector).on('submit', function (event) {
      event.preventDefault();
      const $form = $(this);
      const $button = $form.find('button[type=submit],button:not([type])');
      const $message = $form.find('.form-message');
      $button.prop('disabled', true);

      $.ajax({
        url: $form.attr('action'),
        method: 'POST',
        data: $form.serialize(),
        dataType: 'json'
      }).done(function (response) {
        $message.html($('<div>', { class: 'alert alert-success', text: response.message }));
        if (selector === '#wishForm') {
          $form.find('textarea').val('');
        }
      }).fail(function (xhr) {
        const response = xhr.responseJSON || {};
        const errors = Object.values(response.errors || {}).join(' ');
        $message.html($('<div>', {
          class: 'alert alert-danger',
          text: response.message || errors || 'Terjadi kesalahan. Silakan coba kembali.'
        }));
      }).always(function () {
        $button.prop('disabled', false);
      });
    });
  }
  ajaxForm('#rsvpForm');
  ajaxForm('#wishForm');

  function refreshWishes() {
    $.getJSON(window.invitationConfig.latestWishesUrl).done(function (items) {
      const $list = $('#wishList').empty();
      items.forEach(function (item) {
        const $article = $('<article>', { class: 'wish' });
        $('<div>', {
          class: 'wish-avatar',
          text: String(item.nama_pengirim || '?').charAt(0).toUpperCase()
        }).appendTo($article);
        const $content = $('<div>').appendTo($article);
        $('<h3>', { text: item.nama_pengirim }).appendTo($content);
        $('<p>', { text: item.ucapan }).appendTo($content);
        $('<small>', { text: item.tanggal }).appendTo($content);
        $article.appendTo($list);
      });
    });
  }
  setInterval(refreshWishes, 15000);

  $('#shareWhatsapp').on('click', function () {
    window.open(
      'https://wa.me/?text=' + encodeURIComponent(window.invitationConfig.shareText + ' ' + window.invitationConfig.shareUrl),
      '_blank',
      'noopener'
    );
  });
});
