function normalizeLang(lang = 'en') {
  // تحويل القيمة مثل en_US أو fr-fr إلى en-US أو fr-FR
  if (typeof lang !== 'string') return 'en-US';

  const parts = lang.replace('_', '-').split('-');
  if (parts.length === 1) {
    return parts[0].toLowerCase() === 'ar' ? 'ar-EG' : parts[0] + '-' + parts[0].toUpperCase();
  }

  return parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
}
function initDateSelector({
  selector = '.date-selector input',
  startDate = null,
  maxDays = null,
  maxDate = null,
  showToday = true,
  lang = 'en'  // نمرر lang بدلاً من locale
} = {}) {
  const input = document.querySelector(selector);
  if (!input) return;

  input.classList.add('hide');

  const container = document.createElement('div');
  container.className = 'date-options';

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const start = startDate instanceof Date ? new Date(startDate) : new Date(today);
  start.setHours(0, 0, 0, 0);

  let end;
  if (maxDays && Number.isInteger(maxDays)) {
    end = new Date(start);
    end.setDate(end.getDate() + maxDays);
  } else if (maxDate instanceof Date) {
    end = new Date(maxDate);
    end.setHours(0, 0, 0, 0);
  } else {
    console.warn('initDateSelector: يجب تحديد maxDays أو maxDate');
    return;
  }

  const locale = normalizeLang(lang);

  let current = new Date(start);
  while (current <= end) {
    const isToday = current.getTime() === today.getTime();
    if (!isToday || showToday) {
      const option = document.createElement('div');
      option.className = 'date-option';

      const dayName = current.toLocaleDateString(locale, { weekday: 'long' });
      const day = current.getDate().toString().padStart(2, '0');
      const month = (current.getMonth() + 1).toString().padStart(2, '0');
      const year = current.getFullYear();

      option.innerHTML = `
        <span class="wd">${dayName}</span>
        <span class="sep a1"> – </span>
        <span class="d">${day}</span>
        <span class="sep a2">-</span>
        <span class="m">${month}</span>
        <span class="sep a3">-</span>
        <span class="y">${year}</span>
      `;
      option.dataset.value = `${day}-${month}-${year}`;

      option.addEventListener('click', () => {
        container.querySelectorAll('.date-option').forEach(opt => opt.classList.remove('selected'));
        option.classList.add('selected');
        input.value = option.dataset.value;
      });

      container.appendChild(option);
    }

    current.setDate(current.getDate() + 1);
  }

  input.insertAdjacentElement('afterend', container);
}

function initTimeSelector({
  selector = '.time-selector input',
  startTime = '08:00',
  endTime = '20:00',
  stepMinutes = 30,
  lang = 'en',
} = {}) {
  const input = document.querySelector(selector);
  if (!input) return;

  input.classList.add('hide');

  const container = document.createElement('div');
  container.className = 'time-options';

  const locale = normalizeLang(lang); // استخدم الدالة التي عرفناها سابقاً

  const parseTime = (str) => {
    const [h, m] = str.split(':').map(Number);
    const date = new Date();
    date.setHours(h, m, 0, 0);
    return date;
  };

  const start = parseTime(startTime);
  const end = parseTime(endTime);

  const current = new Date(start);

  while (current <= end) {
    const option = document.createElement('div');
    option.className = 'time-option';

    const parts = current.toLocaleTimeString(locale, {
      hour: 'numeric',
      minute: '2-digit',
      hour12: true,
    });

    // نحصل على الأجزاء بشكل يدوي لو أردت مزيداً من التحكم
    const hour = current.getHours();
    const minute = current.getMinutes();
    const isPM = hour >= 12;

    let hour12 = hour % 12 || 12;
    let minuteStr = minute.toString().padStart(2, '0');

    const ampm = current.toLocaleTimeString(locale, {
      hour: 'numeric',
      hour12: true
    }).replace(/[0-9\s:]/g, '').trim(); // نأخذ فقط AM أو PM بالصيغة المحلية

    option.innerHTML = `
      <span class="hour">${hour12}</span>
      <span class="sep">:</span>
      <span class="minute">${minuteStr}</span>
      <span class="ampm">${ampm}</span>
    `;

    option.dataset.value = `${hour12}:${minuteStr} ${ampm}`;

    option.addEventListener('click', () => {
      container.querySelectorAll('.time-option').forEach(opt => opt.classList.remove('selected'));
      option.classList.add('selected');
      input.value = option.dataset.value;
    });

    container.appendChild(option);
    current.setMinutes(current.getMinutes() + stepMinutes);
  }

  input.insertAdjacentElement('afterend', container);
}


initTimeSelector({
  selector: '.time-selector input',
  startTime: '09:00',
  endTime: '22:00',
  stepMinutes: 60,
  lang: document.documentElement.lang || 'en'
});


initDateSelector({
  selector: '.date-selector input',
  maxDays: 10,
  lang: lang,
  showToday: true
});

// Examples 

// من اليوم الى 10 أيام 
// initDateSelector({
//   selector: '.date-selector input',
//   maxDays: 10,
//   lang: lang,
//   showToday: true
// });

// بدء من تاريخ معين الى تاريخ معين - او يمكن الاكتفاء ب الى تاريخ معين فقط ويكون البدء اليوم دائماً
// initDateSelector({
//   selector: '.date-selector input',
//   startDate: new Date('2025-06-10'),
//   maxDate: new Date('2025-06-20'),
//   showToday: false
// });