/* ============================================
   NYAYA GURU - Main JavaScript
   ============================================ */

$(document).ready(function () {

  // ---- NAVBAR SCROLL ----
  $(window).on('scroll', function () {
    if ($(this).scrollTop() > 80) {
      $('.main-navbar').addClass('scrolled');
    } else {
      $('.main-navbar').removeClass('scrolled');
    }
  });

  // ---- SELECT2 INIT ----
  if ($('.select2-multi').length) {
    $('.select2-multi').select2({
      placeholder: $(this).data('placeholder') || 'Select options',
      allowClear: true,
      width: '100%'
    });
  }

  if ($('.select2-single').length) {
    $('.select2-single').select2({
      placeholder: 'Select an option',
      allowClear: true,
      width: '100%'
    });
  }

  // ---- FADE UP ANIMATION (Intersection Observer) ----
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('visible');
      }
    });
  }, { threshold: 0.12 });

  document.querySelectorAll('.fade-up').forEach(el => observer.observe(el));

  // ---- DYNAMIC CITY DROPDOWN (State → City) ----
  $(document).on('change', '#state_id', function () {
    const stateId = $(this).val();
    const citySelect = $('#city_id');
    citySelect.html('<option value="">Loading...</option>').prop('disabled', true);
    if (!stateId) {
      citySelect.html('<option value="">Select City</option>').prop('disabled', false);
      return;
    }
    $.ajax({
      url: SITE_URL + '/api/get_cities.php',
      type: 'GET',
      data: { state_id: stateId },
      success: function (res) {
        citySelect.html('<option value="">Select City</option>');
        if (res.success && res.data.length) {
          res.data.forEach(city => {
            citySelect.append(`<option value="${city.id}">${city.name}</option>`);
          });
        }
        citySelect.prop('disabled', false);
        if (citySelect.hasClass('select2-single') || citySelect.hasClass('select2-hidden-accessible')) {
          citySelect.trigger('change');
        }
      },
      error: function () {
        citySelect.html('<option value="">Error loading cities</option>').prop('disabled', false);
      }
    });
  });

  // ---- LAWYER REGISTRATION FORM - Multi-Step ----
  let currentStep = 1;
  const totalSteps = 4;

  function showStep(step) {
    $('.form-section').hide();
    $(`#step-${step}`).show();
    currentStep = step;
    updateStepUI(step);
    $('html, body').animate({ scrollTop: $('.form-steps').offset()?.top - 100 || 0 }, 300);
  }

  function updateStepUI(step) {
    $('.form-step').each(function (i) {
      const stepNum = i + 1;
      $(this).removeClass('active completed');
      if (stepNum < step) $(this).addClass('completed');
      else if (stepNum === step) $(this).addClass('active');
    });
    $('#prevBtn').toggle(step > 1);
    $('#nextBtn').toggle(step < totalSteps);
    $('#submitBtn').toggle(step === totalSteps);
  }

  $('#nextBtn').on('click', function () {
    if (validateStep(currentStep)) showStep(currentStep + 1);
  });
  $('#prevBtn').on('click', function () { showStep(currentStep - 1); });

  function validateStep(step) {
    let valid = true;
    $(`#step-${step} [required]`).each(function () {
      if (!$(this).val()) {
        $(this).addClass('is-invalid');
        valid = false;
      } else {
        $(this).removeClass('is-invalid');
      }
    });
    if (!valid) showToast('Please fill all required fields.', 'warning');
    return valid;
  }

  // ---- FILE UPLOAD PREVIEW ----
  $(document).on('change', '.file-input', function () {
    const file = this.files[0];
    const previewId = $(this).data('preview');
    if (file && previewId) {
      const reader = new FileReader();
      reader.onload = function (e) {
        $(`#${previewId}`).attr('src', e.target.result).show();
      };
      reader.readAsDataURL(file);
    }
    const labelId = $(this).data('label');
    if (file && labelId) {
      $(`#${labelId}`).text(file.name);
    }
  });

  // ---- AJAX FORM SUBMISSIONS ----
  $(document).on('submit', '.ajax-form', function (e) {
    e.preventDefault();
    const form = $(this);
    const url = form.attr('action');
    const btn = form.find('[type="submit"]');
    const originalText = btn.html();

    btn.html('<i class="fas fa-spinner fa-spin me-2"></i>Processing...').prop('disabled', true);

    const formData = new FormData(this);
    formData.append('csrf_token', CSRF_TOKEN);

    $.ajax({
      url: url,
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function (res) {
        if (res.success) {
          showToast(res.message || 'Success!', 'success');
          if (res.redirect) setTimeout(() => window.location.href = res.redirect, 1200);
          if (res.reset) form[0].reset();
        } else {
          showToast(res.message || 'Something went wrong.', 'danger');
        }
      },
      error: function () {
        showToast('Server error. Please try again.', 'danger');
      },
      complete: function () {
        btn.html(originalText).prop('disabled', false);
      }
    });
  });

  // ---- LAWYER SEARCH ----
  $('#lawyerSearchForm').on('submit', function (e) {
    e.preventDefault();
    const params = new URLSearchParams();
    $(this).serializeArray().forEach(({ name, value }) => {
      if (value) params.append(name, value);
    });
    window.location.href = SITE_URL + '/lawyers.php?' + params.toString();
  });

  // ---- HERO SEARCH ----
  $('#heroSearchBtn').on('click', function () {
    const category = $('#heroCategory').val();
    const city = $('#heroCity').val();
    const params = new URLSearchParams();
    if (category) params.append('category', category);
    if (city) params.append('city', city);
    window.location.href = SITE_URL + '/lawyers.php?' + (params.toString() || '');
  });

  // ---- BOOKING MODAL ----
  $(document).on('click', '.btn-book-consultation', function () {
    const lawyerId = $(this).data('lawyer-id');
    const fee = $(this).data('fee');
    const name = $(this).data('name');
    $('#bookLawyerId').val(lawyerId);
    $('#bookFeeDisplay').text('₹' + parseFloat(fee).toFixed(2));
    $('#bookLawyerName').text(name);
    $('#consultationModal').modal('show');
  });

  // ---- RAZORPAY PAYMENT ----
  $(document).on('click', '#payNowBtn', function () {
    const appointmentId = $(this).data('appointment-id');
    const amount = $(this).data('amount');
    const lawyerName = $(this).data('lawyer-name');
    const userEmail = $(this).data('user-email');
    const userName = $(this).data('user-name');

    const options = {
      key: window.RAZORPAY_KEY_ID || 'rzp_test_XXXXXX',
      amount: Math.round(amount * 100),
      currency: 'INR',
      name: 'Nyaya Guru',
      description: 'Legal Consultation - ' + lawyerName,
      image: SITE_URL + '/assets/images/logo.png',
      handler: function (response) {
        $.post(SITE_URL + '/api/payment_verify.php', {
          razorpay_payment_id: response.razorpay_payment_id,
          razorpay_order_id: response.razorpay_order_id,
          razorpay_signature: response.razorpay_signature,
          appointment_id: appointmentId,
          csrf_token: CSRF_TOKEN
        }, function (res) {
          if (res.success) {
            showToast('Payment successful! Consultation confirmed.', 'success');
            setTimeout(() => window.location.reload(), 1500);
          } else {
            showToast('Payment verification failed. Contact support.', 'danger');
          }
        });
      },
      prefill: { name: userName, email: userEmail },
      theme: { color: '#0A2342' },
      modal: { escape: false }
    };
    const rzp = new Razorpay(options);
    rzp.open();
  });

  // ---- REVIEW FORM ----
  $(document).on('click', '.star-rating-input label', function () {
    const val = $(this).prev('input').val();
    $(this).closest('.star-rating-input').find('label').each(function (i) {
      if (i < val) $(this).find('i').removeClass('far').addClass('fas');
      else $(this).find('i').removeClass('fas').addClass('far');
    });
  });

  // ---- COUNTER ANIMATION ----
  function animateCounters() {
    $('.counter-number').each(function () {
      const target = parseInt($(this).data('target'));
      const duration = 2000;
      const step = target / (duration / 16);
      let current = 0;
      const el = $(this);
      const timer = setInterval(() => {
        current += step;
        if (current >= target) { current = target; clearInterval(timer); }
        el.text(Math.floor(current).toLocaleString('en-IN') + (el.data('suffix') || ''));
      }, 16);
    });
  }

  const counterObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        animateCounters();
        counterObserver.disconnect();
      }
    });
  }, { threshold: 0.5 });

  if ($('.counter-number').length) {
    counterObserver.observe($('.counter-number')[0]);
  }

  // ---- TOAST NOTIFICATION ----
  window.showToast = function (message, type = 'info') {
    const colors = { success: '#28a745', danger: '#dc3545', warning: '#ffc107', info: '#0A2342' };
    const icons = { success: 'fa-check-circle', danger: 'fa-exclamation-circle', warning: 'fa-exclamation-triangle', info: 'fa-info-circle' };
    const toastEl = $(`
      <div class="toast align-items-center text-white border-0 show" role="alert"
           style="background:${colors[type]};border-radius:10px;min-width:280px;box-shadow:0 8px 24px rgba(0,0,0,0.2);">
        <div class="d-flex">
          <div class="toast-body">
            <i class="fas ${icons[type]} me-2"></i>${message}
          </div>
          <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
      </div>
    `);

    if (!$('#toastContainer').length) {
      $('body').append('<div id="toastContainer" class="toast-container position-fixed top-0 end-0 p-3" style="z-index:9999;"></div>');
    }
    $('#toastContainer').append(toastEl);
    setTimeout(() => toastEl.fadeOut(400, () => toastEl.remove()), 4000);
  };

  // ---- ADMIN: CONFIRM ACTIONS ----
  $(document).on('click', '.btn-danger-confirm', function (e) {
    if (!confirm('Are you sure? This action cannot be undone.')) e.preventDefault();
  });

  // ---- SEARCH SUGGESTIONS (Autocomplete) ----
  let searchTimer;
  $('#lawyerSearchInput').on('input', function () {
    clearTimeout(searchTimer);
    const q = $(this).val().trim();
    if (q.length < 2) { $('#searchSuggestions').hide(); return; }
    searchTimer = setTimeout(() => {
      $.get(SITE_URL + '/api/search_suggestions.php', { q }, function (res) {
        if (res.success && res.data.length) {
          let html = '';
          res.data.forEach(item => {
            html += `<div class="suggestion-item p-2 px-3 border-bottom" style="cursor:pointer" data-val="${item.name}">
              <i class="fas fa-search me-2 text-muted small"></i>${item.name}
            </div>`;
          });
          $('#searchSuggestions').html(html).show();
        } else {
          $('#searchSuggestions').hide();
        }
      });
    }, 300);
  });

  $(document).on('click', '.suggestion-item', function () {
    $('#lawyerSearchInput').val($(this).data('val'));
    $('#searchSuggestions').hide();
    $('#lawyerSearchForm').submit();
  });

  $(document).on('click', function (e) {
    if (!$(e.target).closest('.search-autocomplete-wrap').length) {
      $('#searchSuggestions').hide();
    }
  });

  // ---- CHAT POLLING ----
  if ($('#chatMessages').length) {
    const appointmentId = $('#chatMessages').data('appointment-id');
    let lastId = 0;

    function pollMessages() {
      $.get(SITE_URL + '/api/get_messages.php', { appointment_id: appointmentId, last_id: lastId }, function (res) {
        if (res.success && res.data.length) {
          res.data.forEach(msg => {
            lastId = Math.max(lastId, msg.id);
            appendMessage(msg);
          });
          scrollChatBottom();
        }
      });
    }

    function appendMessage(msg) {
      const isMe = (msg.sender_type === window.SENDER_TYPE);
      const html = `
        <div class="chat-message ${isMe ? 'message-me' : 'message-other'} mb-3">
          <div class="message-bubble">${msg.message}</div>
          <div class="message-time">${msg.created_at}</div>
        </div>`;
      $('#chatMessages').append(html);
    }

    function scrollChatBottom() {
      const el = document.getElementById('chatMessages');
      el.scrollTop = el.scrollHeight;
    }

    setInterval(pollMessages, 3000);

    $('#chatForm').on('submit', function (e) {
      e.preventDefault();
      const msg = $('#messageInput').val().trim();
      if (!msg) return;
      $.post(SITE_URL + '/api/send_message.php', {
        appointment_id: appointmentId,
        message: msg,
        csrf_token: CSRF_TOKEN
      }, function (res) {
        if (res.success) {
          $('#messageInput').val('');
          appendMessage(res.data);
          scrollChatBottom();
          lastId = res.data.id;
        }
      });
    });
  }

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

  // ---- POPOVER ----
  $('[data-bs-toggle="popover"]').each(function () {
    new bootstrap.Popover(this);
  });

});

// ---- PAGE LOADER ----
window.addEventListener('load', function () {
  const loader = document.getElementById('pageLoader');
  if (loader) {
    loader.style.opacity = '0';
    setTimeout(() => loader.style.display = 'none', 400);
  }
});
