(() => {
  const service = document.getElementById('serviceSelect');
  const duration = document.getElementById('durationSelect');
  const date = document.getElementById('reservationDate');
  const time = document.getElementById('timeSelect');
  const message = document.getElementById('slotMessage');
  const sessionType = document.getElementById('sessionType');
  const therapistPreference = document.getElementById('therapistPreference');
  const form = document.getElementById('bookingForm');
  const error = document.getElementById('bookingError');
  const submit = document.getElementById('bookingSubmit');
  if (!form) return;

  async function loadDurations() {
    duration.innerHTML = '<option value="">Yükleniyor…</option>';
    time.innerHTML = '<option value="">Hizmet ve tarih seçin</option>';
    if (!service.value) { duration.innerHTML = '<option value="">Önce hizmet seçin</option>'; return; }
    try {
      const response = await fetch(`${form.dataset.durationsUrl}?service_id=${encodeURIComponent(service.value)}`, {headers:{Accept:'application/json'}});
      const data = await response.json();
      duration.innerHTML = '<option value="">Süre seçin</option>' + data.durations.map(d => `<option value="${d.id}">${d.label}${d.price ? ` — ${d.price} TL` : ''}</option>`).join('');
      const selected = duration.dataset.selected;
      if (selected && [...duration.options].some(o => o.value === selected)) duration.value = selected;
      await loadSlots();
    } catch { duration.innerHTML = '<option value="">Süreler yüklenemedi</option>'; }
  }

  async function loadSlots() {
    time.innerHTML = '<option value="">Yükleniyor…</option>';
    message.textContent = '';
    if (!duration.value || !date.value) { time.innerHTML = '<option value="">Hizmet ve tarih seçin</option>'; return; }
    try {
      const response = await fetch(`${form.dataset.availabilityUrl}?duration_id=${encodeURIComponent(duration.value)}&date=${encodeURIComponent(date.value)}&preference=${encodeURIComponent(therapistPreference?.value || 'no_preference')}&session_type=${encodeURIComponent(sessionType?.value || 'single')}`, {headers:{Accept:'application/json'}});
      const data = await response.json();
      if (!data.slots?.length) {
        time.innerHTML = '<option value="">Uygun saat bulunamadı</option>';
        message.textContent = 'Bu tarih için uygun saat kalmamış olabilir. Başka bir tarih seçin.';
        return;
      }
      time.innerHTML = '<option value="">Saat seçin</option>' + data.slots.map(s => `<option value="${s.value}">${s.label}</option>`).join('');
      message.textContent = `${data.slots.length} uygun saat bulundu.`;
    } catch { time.innerHTML = '<option value="">Saatler yüklenemedi</option>'; }
  }

  service.addEventListener('change', loadDurations);
  duration.addEventListener('change', loadSlots);
  date.addEventListener('change', loadSlots);
  sessionType?.addEventListener('change', loadSlots);
  therapistPreference?.addEventListener('change', loadSlots);
  form.addEventListener('submit', async (event) => {
    event.preventDefault(); error.textContent = '';
    if (!form.reportValidity()) return;
    submit.disabled = true; submit.textContent = 'Rezervasyon oluşturuluyor…';
    try {
      const response = await fetch(form.action, {method:'POST', body:new FormData(form), headers:{Accept:'application/json'}});
      const data = await response.json();
      if (!response.ok || !data.ok) throw new Error(data.message || 'Rezervasyon oluşturulamadı.');
      window.location.href = data.redirect;
    } catch (err) { error.textContent = err.message; submit.disabled = false; submit.textContent = 'Rezervasyon Talebi Oluştur'; }
  });
  if (service.value) loadDurations();
})();
