function initializeDatetimePicker(input) {
  const type = input.getAttribute('data-type') || 'date'; // Default to "date"
  const format = input.getAttribute('data-format') || 'mm/dd/yy'; // Default format
  const calendar = document.createElement('div');
  calendar.classList.add('calendar');
  calendar.style.display = 'none';
  calendar.setAttribute('id', 'vformcalendar');
  calendar.innerHTML = `
    <div class="calendar-header" ${type === 'time' ? 'style="display: none;"' : ''}>
      <button class="prev-month" type="button">◀</button>
      <div class="month-year">
        <select class="month-select"></select>
        <select class="year-select"></select>
      </div>
      <button class="next-month" type="button">▶</button>
    </div>
    ${type !== 'time' ? `
    <table>
      <thead>
        <tr>
          <th>Sun</th>
          <th>Mon</th>
          <th>Tue</th>
          <th>Wed</th>
          <th>Thu</th>
          <th>Fri</th>
          <th>Sat</th>
        </tr>
      </thead>
      <tbody class="calendar-body"></tbody>
    </table>` : ''}
    ${(type === 'time' || type === 'datetime') ? `
    <div class="time-picker">
      <label>Hour:</label>
      <select class="hours"></select>
      <label>Minute:</label>
      <select class="minutes"></select>
    </div>` : ''}
    `;
    // <button class="set-datetime" type="button">Set</button>
  input.parentElement.appendChild(calendar);

  let currentDate = new Date();

  function generateMonthYearSelectors() {
    const monthSelect = calendar.querySelector('.month-select');
    const yearSelect = calendar.querySelector('.year-select');

    if (!monthSelect || !yearSelect) return;

    monthSelect.innerHTML = '';
    yearSelect.innerHTML = '';
    const months = [
      'January', 'February', 'March', 'April', 'May', 'June',
      'July', 'August', 'September', 'October', 'November', 'December'
    ];

    months.forEach((month, index) => {
      const option = document.createElement('option');
      option.value = index;
      option.textContent = month;
      if (index === currentDate.getMonth()) option.selected = true;
      monthSelect.appendChild(option);
    });

    const startYear = currentDate.getFullYear() - 150;
    const endYear = currentDate.getFullYear() + 50;
    for (let year = startYear; year <= endYear; year++) {
      const option = document.createElement('option');
      option.value = year;
      option.textContent = year;
      if (year === currentDate.getFullYear()) option.selected = true;
      yearSelect.appendChild(option);
    }

    monthSelect.addEventListener('change', generateCalendar);
    yearSelect.addEventListener('change', generateCalendar);
  }

  function generateCalendar() {
    if (type === 'time') return;

    const monthSelect = calendar.querySelector('.month-select');
    const yearSelect = calendar.querySelector('.year-select');
    const calendarBody = calendar.querySelector('.calendar-body');

    const selectedMonth = parseInt(monthSelect.value);
    const selectedYear = parseInt(yearSelect.value);
    currentDate = new Date(selectedYear, selectedMonth);

    const firstDay = new Date(selectedYear, selectedMonth, 1).getDay();
    const daysInMonth = new Date(selectedYear, selectedMonth + 1, 0).getDate();

    calendarBody.innerHTML = '';
    let row = document.createElement('tr');
    for (let i = 0; i < firstDay; i++) {
      row.appendChild(document.createElement('td'));
    }

    for (let day = 1; day <= daysInMonth; day++) {
      const cell = document.createElement('td');
      cell.textContent = day;
      cell.addEventListener('click', () => {

        const selectedDate = new Date(selectedYear, selectedMonth, day);
        input.dataset.selectedDate = `${selectedYear}-${String(selectedMonth + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
        highlightSelectedDate(calendarBody, day);

              // Format and set input value immediately
      if (type === 'datetime') {
        const selectedDateStr = `${selectedYear}-${String(selectedMonth + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
        input.dataset.selectedDate = selectedDateStr;

        const hours = calendar.querySelector('.hours')?.value;
        const minutes = calendar.querySelector('.minutes')?.value;
        const ampm = calendar.querySelector('.ampm')?.value;

        // if (hours && minutes && ampm) {
          let h = parseInt(hours);
          if (ampm === 'PM' && h < 12) h += 12;
          if (ampm === 'AM' && h === 12) h = 0;
          
          const fullDate = new Date(`${selectedDateStr}T${String(h).padStart(2, '0')}:${minutes}`);
          // console.log(fullDate);
          if (!isNaN(fullDate.getTime())) {
            const displayHour = h % 12 === 0 ? 12 : h % 12;
            const displayAmpm = h >= 12 ? 'PM' : 'AM';

            const value = `${formatDate(fullDate, format)} ${displayHour}:${minutes.padStart(2, '0')} ${displayAmpm}`;
            input.value = value;
          }else{
            const fallbackDate = new Date(selectedDateStr);
          input.value = formatDate(fallbackDate, format);
          }
        // } else {
        //   // fallback to just date for now
        //   const fallbackDate = new Date(selectedDateStr);
        //   input.value = formatDate(fallbackDate, format);
        // }
      } else {
              const selectedDate = new Date(selectedYear, selectedMonth, day);
              const value = formatDate(selectedDate, format);
              input.value = value;
              calendar.style.display = 'none';
      }


      });




      row.appendChild(cell);
      if ((day + firstDay) % 7 === 0 || day === daysInMonth) {
        calendarBody.appendChild(row);
        row = document.createElement('tr');
      }
    }
  }

  function highlightSelectedDate(calendarBody, selectedDay) {
    calendarBody.querySelectorAll('td').forEach(td => {
      td.classList.remove('selected-date');
      if (parseInt(td.textContent) === selectedDay) {
        td.classList.add('selected-date');
      }
    });
  }

 
  function formatDate(date, format) {
    const day = date.getDate();
    const month = date.getMonth() + 1; // Months are 0-indexed
    const year = date.getFullYear();
    const shortYear = String(year).slice(-2);
    const dayName = date.toLocaleString('default', { weekday: 'long' }); // Full day name
    const monthName = date.toLocaleString('default', { month: 'long' }); // Full month name
    const shortMonthName = date.toLocaleString('default', { month: 'short' }); // Short month name

    // Use a map for replacements
    const replacements = {
        'DD': dayName,                       // Full day name (e.g., "Wednesday")
        'd': day,                            // Day without leading zero
        'dd': String(day).padStart(2, '0'),  // Day with leading zero
        'MM': monthName,                     // Full month name (e.g., "December")
        'M': shortMonthName,                 // Short month name (e.g., "Dec")
        'mm': String(month).padStart(2, '0'), // Month with leading zero
        'm': month,                          // Month without leading zero
        'yy': year,                          // Full year
        'y': shortYear                       // Two-digit year
    };

    // Handle single-quoted text by skipping replacement inside quotes
    return format.replace(/'([^']*)'|DD|mm|m|d{1,2}|MM|M|yy|y/g, (match, quotedText) => {
        if (quotedText !== undefined) {
            // Return quoted text without changes
            return quotedText;
        }
        // Otherwise, replace the token
        return replacements[match] || match;
    });
  }







  

function generateTimeSelectors() {
  if (type === 'date') return;

  const hoursSelect = calendar.querySelector('.hours');
  const minutesSelect = calendar.querySelector('.minutes');

  hoursSelect.innerHTML = '';
  minutesSelect.innerHTML = '';

  // Generate 12-hour format (1-12)
  for (let h = 1; h <= 12; h++) {
    const option = document.createElement('option');
    option.value = h;
    option.textContent = String(h).padStart(2, '0');
    hoursSelect.appendChild(option);
  }

  for (let m = 0; m < 60; m++) {
    const option = document.createElement('option');
    option.value = m;
    option.textContent = String(m).padStart(2, '0');
    minutesSelect.appendChild(option);
  }

  // Add AM/PM selector
  let ampmSelect = calendar.querySelector('.ampm');
  if (!ampmSelect) {
    ampmSelect = document.createElement('select');
    ampmSelect.classList.add('ampm');

    ['AM', 'PM'].forEach(period => {
      const option = document.createElement('option');
      option.value = period;
      option.textContent = period;
      ampmSelect.appendChild(option);
    });

    const timePickerDiv = calendar.querySelector('.time-picker');
    timePickerDiv.appendChild(ampmSelect);
  }

  // ✅ Set selected time based on input value or current time
  let hours, minutes, ampm;

  if (input.value) {
    // Match HH:MM AM/PM anywhere in input.value
    const match = input.value.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);
    if (match) {
      hours = parseInt(match[1]);
      minutes = parseInt(match[2]);
      ampm = match[3].toUpperCase();
    }
  }

  // Fallback to current time if not parsed
  if (hours === undefined || minutes === undefined || ampm === undefined) {
    const now = new Date();
    hours = now.getHours();
    minutes = now.getMinutes();
    ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12 === 0 ? 12 : hours % 12;
  }

  hoursSelect.value = hours;
  minutesSelect.value = minutes;
  ampmSelect.value = ampm;
}




  function attachTimeChangeHandlers() {
    if (type === 'datetime') {
  const hoursSelect = calendar.querySelector('.hours');
  const minutesSelect = calendar.querySelector('.minutes');
  var ampmSelect = calendar.querySelector('.ampm');

  const updateDateTimeValue = () => {
    var selectedDate = input.dataset.selectedDate;
    // console.log(selectedDate);
    // if (!selectedDate) return; // Only proceed if date is selected

    if (!selectedDate){
      var selectedDate = input.value;
    }else{
      var selectedDate = input.dataset.selectedDate;
    }
    
    let hours = parseInt(hoursSelect.value);
    const minutes = minutesSelect.value;
    const ampm = calendar.querySelector('.ampm')?.value || 'AM';
    
    if (ampm === 'PM' && hours < 12) hours += 12;
    if (ampm === 'AM' && hours === 12) hours = 0;

    const displayHour = ((hours % 12 === 0) ? 12 : hours % 12);
    const displayAmpm = (hours >= 12 ? 'PM' : 'AM');


    const formattedDate = formatDate(new Date(selectedDate), format);
    input.value = `${formattedDate} ${displayHour}:${String(minutes).padStart(2, '0')} ${ampm}`;

    // Close the calendar after selecting time
    // calendar.style.display = 'none';
  };

  hoursSelect.addEventListener('change', updateDateTimeValue);
  minutesSelect.addEventListener('change', updateDateTimeValue);
  ampmSelect.addEventListener('change', updateDateTimeValue);
  
    }

if (type === 'time') {
  const hoursSelect = calendar.querySelector('.hours');
  const minutesSelect = calendar.querySelector('.minutes');
  const ampmSelect = calendar.querySelector('.ampm');

  const updateTimeValue = () => {
    let hours = parseInt(hoursSelect.value);
    const minutes = minutesSelect.value;
    const ampm = ampmSelect.value;

    // Convert to 24-hour format if needed
    if (ampm === 'PM' && hours < 12) hours += 12;
    if (ampm === 'AM' && hours === 12) hours = 0;

    const displayHour = (hours % 12 === 0) ? 12 : hours % 12;
    const displayAmpm = (hours >= 12 ? 'PM' : 'AM');

    input.value = `${displayHour}:${String(minutes).padStart(2, '0')} ${displayAmpm}`;
  };

  hoursSelect.addEventListener('change', updateTimeValue);
  minutesSelect.addEventListener('change', updateTimeValue);
  ampmSelect.addEventListener('change', updateTimeValue);
}

}



  // Navigation buttons
  calendar.querySelector('.prev-month').addEventListener('click', () => {
    const monthSelect = calendar.querySelector('.month-select');
    const yearSelect = calendar.querySelector('.year-select');

    let selectedMonth = parseInt(monthSelect.value);
    let selectedYear = parseInt(yearSelect.value);

    // Decrease month
    selectedMonth -= 1;
    if (selectedMonth < 0) {
      selectedMonth = 11;
      selectedYear -= 1;
    }

    monthSelect.value = selectedMonth;
    yearSelect.value = selectedYear;
    generateCalendar();
  });

  calendar.querySelector('.next-month').addEventListener('click', () => {
    const monthSelect = calendar.querySelector('.month-select');
    const yearSelect = calendar.querySelector('.year-select');

    let selectedMonth = parseInt(monthSelect.value);
    let selectedYear = parseInt(yearSelect.value);

    // Increase month
    selectedMonth += 1;
    if (selectedMonth > 11) {
      selectedMonth = 0;
      selectedYear += 1;
    }

    monthSelect.value = selectedMonth;
    yearSelect.value = selectedYear;
    generateCalendar();
  });

  input.addEventListener('click', (e) => {
    e.stopPropagation();
    calendar.style.display = calendar.style.display === 'none' ? 'block' : 'none';
    // if (type !== 'time') {
    if (type === 'date' || type === 'datetime') {
      generateMonthYearSelectors();
      generateCalendar();
    }
    generateTimeSelectors();
    attachTimeChangeHandlers();
  });

  document.addEventListener('click', (e) => {
    if (!calendar.contains(e.target) && e.target !== input) {
      calendar.style.display = 'none';
    }
  });



//   generateMonthYearSelectors();
//   generateCalendar();
//   generateTimeSelectors();



// Set current date/time by default when initialized
if (!input.value) {
  const now = new Date();

  if (type === 'date') {
    input.value = formatDate(now, format);
  }

  if (type === 'time') {
    let hours = now.getHours();
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const ampm = hours >= 12 ? 'PM' : 'AM';
    const displayHour = hours % 12 === 0 ? 12 : hours % 12;

    input.value = `${displayHour}:${minutes} ${ampm}`;
  }

  if (type === 'datetime') {
    const formattedDate = formatDate(now, format);
    let hours = now.getHours();
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const ampm = hours >= 12 ? 'PM' : 'AM';
    const displayHour = hours % 12 === 0 ? 12 : hours % 12;

    input.value = `${formattedDate} ${displayHour}:${minutes} ${ampm}`;
  }
}

}


// document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('.datetime-input').forEach(input => {
    initializeDatetimePicker(input);
  });
// });