/* Zabibu Residence - Main JS */
$(document).ready(function () {

  // Counter animation
  function animateCounters() {
    $('.counter-num').each(function () {
      var $el = $(this);
      var target = parseInt($el.data('target') || $el.text().replace(/\D/g, ''));
      if ($el.data('animated')) return;
      $el.data('animated', true);
      $({ val: 0 }).animate({ val: target }, {
        duration: 2000, easing: 'swing',
        step: function () { $el.text(Math.floor(this.val).toLocaleString()); },
        complete: function () { $el.text(target.toLocaleString()); }
      });
    });
  }

  // Intersection Observer for counters
  if ('IntersectionObserver' in window) {
    var observer = new IntersectionObserver(function (entries) {
      entries.forEach(function (e) { if (e.isIntersecting) animateCounters(); });
    }, { threshold: 0.3 });
    document.querySelectorAll('.counters-section').forEach(function (el) { observer.observe(el); });
  }

  // Scroll navbar effect
  $(window).on('scroll', function () {
    if ($(this).scrollTop() > 60) {
      $('#mainNav').addClass('shadow');
    } else {
      $('#mainNav').removeClass('shadow');
    }
  });

  // Property type filter
  $(document).on('click', '.property-type-filter .btn', function () {
    $('.property-type-filter .btn').removeClass('active');
    $(this).addClass('active');
    var type = $(this).data('type');
    if (type === 'all') {
      $('.property-item').fadeIn(300);
    } else {
      $('.property-item').hide();
      $('.property-item[data-type="' + type + '"]').fadeIn(300);
    }
  });

  // AJAX search
  $('#searchForm').on('submit', function (e) {
    e.preventDefault();
    var data = $(this).serialize();
    window.location.href = APP_URL + '/search?' + data;
  });

  // Dynamic district loading
  $('#region_id').on('change', function () {
    var regionId = $(this).val();
    if (!regionId) return;
    $.get(APP_URL + '/api/v1/regions/' + regionId + '/districts', function (res) {
      var $dist = $('#district_id');
      $dist.html('<option value="">Select District</option>');
      if (res.data) {
        $.each(res.data, function (i, d) {
          $dist.append('<option value="' + d.id + '">' + d.name + '</option>');
        });
      }
    });
  });

  // Favourite toggle
  $(document).on('click', '.property-fav', function () {
    $(this).toggleClass('text-danger').find('i').toggleClass('bi-heart bi-heart-fill');
  });

  // Image preview on file input
  $(document).on('change', '.img-preview-input', function () {
    var file = this.files[0];
    if (file) {
      var reader = new FileReader();
      reader.onload = function (e) {
        $(this).closest('.img-preview-wrap').find('.img-preview').attr('src', e.target.result).show();
      }.bind(this);
      reader.readAsDataURL(file);
    }
  });

  // Dark mode (admin pages use data attribute; landing uses class)
  var savedTheme = localStorage.getItem('zabibu_theme') || 'light';
  $('html').attr('data-bs-theme', savedTheme);
  updateDarkIcon(savedTheme);

  $('#darkModeBtn').on('click', function () {
    var current = $('html').attr('data-bs-theme');
    var next = current === 'dark' ? 'light' : 'dark';
    $('html').attr('data-bs-theme', next);
    localStorage.setItem('zabibu_theme', next);
    updateDarkIcon(next);
  });

  function updateDarkIcon(theme) {
    var $icon = $('#darkModeIcon');
    if (theme === 'dark') {
      $icon.removeClass('bi-moon-fill').addClass('bi-sun-fill');
    } else {
      $icon.removeClass('bi-sun-fill').addClass('bi-moon-fill');
    }
  }

  // Auto-dismiss alerts
  setTimeout(function () {
    $('.alert.auto-dismiss').fadeOut();
  }, 5000);

  // Tooltips
  $('[data-bs-toggle="tooltip"]').each(function () {
    new bootstrap.Tooltip(this);
  });

  // Confirm delete
  $(document).on('click', '.btn-confirm-delete', function (e) {
    if (!confirm('Are you sure you want to delete this record? This action cannot be undone.')) {
      e.preventDefault();
    }
  });
});

var APP_URL = (function () {
  var m = document.querySelector('meta[name="app-url"]');
  return m ? m.content : window.location.origin;
}());
