/* ===== FUNNEL STATE ===== */
const funnelState = {
  currentStep: 1,
  userData: { name: '', email: '', whatsapp: '' },
  survey: { concern: '', duration: '', previousTreatment: '', previousTreatmentDetails: '', urgency: '', openToPlan: '', preference: '' },
  booking: { date: null, time: null }
};

/* ===== DOM REFS ===== */
const $ = (sel) => document.querySelector(sel);
const $$ = (sel) => document.querySelectorAll(sel);

/* ===== INIT ===== */
document.addEventListener('DOMContentLoaded', () => {
  initHeader();
  initFAQ();
  initOptinForm();
  initSurvey();
  initCalendar();
  initTimeSlots();
  initPayment();
});

/* ===== HEADER SCROLL ===== */
function initHeader() {
  const header = $('.header');
  window.addEventListener('scroll', () => {
    header.classList.toggle('scrolled', window.scrollY > 20);
  });
  // Book Now button scrolls to form
  $('.btn-book').addEventListener('click', (e) => {
    e.preventDefault();
    if (funnelState.currentStep === 1) {
      $('#optin-form').scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  });
}

/* ===== FAQ ACCORDION ===== */
function initFAQ() {
  $$('.faq-question').forEach(btn => {
    btn.addEventListener('click', () => {
      const item = btn.closest('.faq-item');
      const isOpen = item.classList.contains('open');
      // Close all
      $$('.faq-item').forEach(i => i.classList.remove('open'));
      // Toggle clicked
      if (!isOpen) item.classList.add('open');
    });
  });
}

/* ===== OPT-IN FORM ===== */
function initOptinForm() {
  const form = $('#optin-form');
  form.addEventListener('submit', (e) => {
    e.preventDefault();
    const name = $('#input-name').value.trim();
    const email = $('#input-email').value.trim();
    const whatsapp = $('#input-whatsapp').value.trim();

    if (!name || !email || !whatsapp) {
      shakeButton($('#btn-optin-submit'));
      return;
    }

    funnelState.userData = { name, email, whatsapp };
    goToStep(2);
  });
}

/* ===== STEP NAVIGATION ===== */
function goToStep(step) {
  funnelState.currentStep = step;
  // Hide all sections
  $$('.funnel-step').forEach(s => s.classList.add('hidden'));
  // Update step dots
  $$('.step-dot').forEach((dot, i) => {
    dot.classList.remove('active', 'completed');
    if (i + 1 < step) dot.classList.add('completed');
    if (i + 1 === step) dot.classList.add('active');
  });
  $$('.step-line').forEach((line, i) => {
    line.classList.toggle('active', i + 1 < step);
  });
  // Show target step
  const target = $(`#step-${step}`);
  if (target) {
    target.classList.remove('hidden');
    target.classList.add('fade-in');
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
}

/* ===== SURVEY ===== */
const surveyQuestions = [
  {
    id: 'concern',
    num: 'Question 1 of 5',
    text: 'What skin concern would you like to treat?',
    options: ['Acne scars', 'Hyperpigmentation', 'Fine lines/wrinkles', 'Stretch marks', 'Uneven skin texture', 'Other']
  },
  {
    id: 'duration',
    num: 'Question 2 of 5',
    text: 'How long have you been dealing with this concern?',
    options: ['Less than 3 months', '3–12 months', 'Over 1 year']
  },
  {
    id: 'previousTreatment',
    num: 'Question 3 of 5',
    text: 'Have you tried any treatments for this before?',
    options: ['Yes (please specify)', 'No'],
    hasTextInput: true,
    textTrigger: 'Yes (please specify)'
  },
  {
    id: 'urgency',
    num: 'Question 4 of 5',
    text: 'How soon are you looking to start treatment?',
    options: ['ASAP', 'Within 1–2 weeks', 'Just researching']
  },
  {
    id: 'openToPlan',
    num: 'Question 5 of 5',
    text: 'Microneedling typically requires multiple sessions for best results. Are you open to a treatment plan?',
    options: ['Yes', 'Maybe', 'No'],
    followUp: {
      id: 'preference',
      text: 'Would you like to book a consultation or speak with a specialist first?',
      options: ['Book consultation', 'Speak to someone first']
    }
  }
];
let currentQuestion = 0;
const totalVisibleQuestions = 5;

function initSurvey() {
  renderQuestion(0);
  // Set up the text input submit handler
  $('#btn-specify-submit').addEventListener('click', () => {
    const specifyVal = $('#specify-input').value.trim();
    if (!specifyVal) {
      shakeButton($('#btn-specify-submit'));
      return;
    }
    funnelState.survey.previousTreatmentDetails = specifyVal;
    $('#survey-text-input').classList.add('hidden');
    advanceQuestion();
  });
  // Also allow Enter key on the text input
  $('#specify-input').addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      $('#btn-specify-submit').click();
    }
  });
}

function renderQuestion(idx) {
  const q = surveyQuestions[idx];
  // Update progress
  $$('.progress-segment').forEach((seg, i) => {
    seg.classList.toggle('filled', i <= idx);
  });
  // Hide text input
  $('#survey-text-input').classList.add('hidden');
  // Render question
  $('.survey-question-num').textContent = q.num || '';
  $('.survey-card h3').textContent = q.text;
  const optionsEl = $('.survey-options');
  optionsEl.innerHTML = '';
  optionsEl.classList.remove('hidden');
  q.options.forEach(opt => {
    const btn = document.createElement('button');
    btn.className = 'survey-option';
    btn.textContent = opt;
    btn.addEventListener('click', () => handleAnswer(q, opt, btn));
    optionsEl.appendChild(btn);
  });
}

function handleAnswer(q, value, btn) {
  // Visual selection
  $$('.survey-option').forEach(o => o.classList.remove('selected'));
  btn.classList.add('selected');
  funnelState.survey[q.id] = value;

  // Check if this option triggers a text input
  if (q.hasTextInput && value === q.textTrigger) {
    setTimeout(() => {
      $('.survey-options').classList.add('hidden');
      $('#survey-text-input').classList.remove('hidden');
      $('#specify-input').value = '';
      $('#specify-input').focus();
    }, 300);
    return;
  }

  // Check if this is the last numbered question and it has a follow-up
  if (q.followUp) {
    setTimeout(() => {
      renderFollowUp(q.followUp);
    }, 400);
    return;
  }

  setTimeout(() => advanceQuestion(), 400);
}

function renderFollowUp(fq) {
  // Don't advance the progress bar — keep it at 5/5
  $('.survey-question-num').textContent = '';
  $('.survey-card h3').textContent = fq.text;
  const optionsEl = $('.survey-options');
  optionsEl.innerHTML = '';
  optionsEl.classList.remove('hidden');
  fq.options.forEach(opt => {
    const btn = document.createElement('button');
    btn.className = 'survey-option';
    btn.textContent = opt;
    btn.addEventListener('click', () => {
      $$('.survey-option').forEach(o => o.classList.remove('selected'));
      btn.classList.add('selected');
      funnelState.survey[fq.id] = opt;
      setTimeout(() => showLoader(), 400);
    });
    optionsEl.appendChild(btn);
  });
}

function advanceQuestion() {
  currentQuestion++;
  if (currentQuestion < surveyQuestions.length) {
    renderQuestion(currentQuestion);
  } else {
    showLoader();
  }
}

function showLoader() {
  $$('.funnel-step').forEach(s => s.classList.add('hidden'));
  $('#loader').classList.remove('hidden');
  $('#loader').classList.add('fade-in');
  setTimeout(() => goToStep(3), 2000);
}

/* ===== CALENDAR ===== */
function initCalendar() {
  renderCalendar(2026, 4); // May 2026
}

function renderCalendar(year, month) {
  const monthNames = ['January','February','March','April','May','June','July','August','September','October','November','December'];
  $('.cal-header h4').textContent = `${monthNames[month]} ${year}`;

  const grid = $('.cal-grid');
  // Keep day labels
  const labels = grid.querySelectorAll('.cal-day-label');
  grid.innerHTML = '';
  labels.forEach(l => grid.appendChild(l));

  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const today = new Date();

  // Empty cells before first day
  for (let i = 0; i < firstDay; i++) {
    const empty = document.createElement('button');
    empty.className = 'cal-day empty';
    grid.appendChild(empty);
  }
  // Day cells
  for (let d = 1; d <= daysInMonth; d++) {
    const dayBtn = document.createElement('button');
    dayBtn.className = 'cal-day';
    dayBtn.textContent = d;
    const cellDate = new Date(year, month, d);
    if (cellDate < today || cellDate.getDay() === 0) {
      dayBtn.classList.add('disabled');
    }
    dayBtn.addEventListener('click', () => selectDate(dayBtn, year, month, d));
    grid.appendChild(dayBtn);
  }

  // Nav buttons
  $('#cal-prev').onclick = () => {
    const m = month === 0 ? 11 : month - 1;
    const y = month === 0 ? year - 1 : year;
    renderCalendar(y, m);
  };
  $('#cal-next').onclick = () => {
    const m = month === 11 ? 0 : month + 1;
    const y = month === 11 ? year + 1 : year;
    renderCalendar(y, m);
  };
}

function selectDate(btn, year, month, day) {
  $$('.cal-day').forEach(d => d.classList.remove('selected'));
  btn.classList.add('selected');
  const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  funnelState.booking.date = `${monthNames[month]} ${day}, ${year}`;
  updateSummary();
}

/* ===== TIME SLOTS ===== */
function initTimeSlots() {
  $$('.time-slot').forEach(slot => {
    slot.addEventListener('click', () => {
      $$('.time-slot').forEach(s => s.classList.remove('selected'));
      slot.classList.add('selected');
      funnelState.booking.time = slot.textContent;
      updateSummary();
    });
  });
}

/* ===== UPDATE BOOKING SUMMARY ===== */
function updateSummary() {
  const nameEl = $('#summary-name');
  const dateEl = $('#summary-date');
  const timeEl = $('#summary-time');
  if (nameEl) nameEl.textContent = funnelState.userData.name || '—';
  if (dateEl) dateEl.textContent = funnelState.booking.date || 'Select a date';
  if (timeEl) timeEl.textContent = funnelState.booking.time || 'Select a time';
}

/* ===== PAYMENT ===== */
function initPayment() {
  $('#btn-pay').addEventListener('click', () => {
    if (!funnelState.booking.date || !funnelState.booking.time) {
      alert('Please select a date and time before proceeding.');
      return;
    }
    // Paystack/Flutterwave integration point
    simulatePayment();
  });
}

function simulatePayment() {
  const btn = $('#btn-pay');
  btn.innerHTML = '<div class="loader-spinner" style="width:22px;height:22px;margin:0;border-width:2px;"></div> Processing...';
  btn.disabled = true;

  setTimeout(() => {
    // Show confirmation
    $$('.funnel-step').forEach(s => s.classList.add('hidden'));
    $('#step-confirm').classList.remove('hidden');
    $('#step-confirm').classList.add('fade-in');

    // Fill confirmation data
    $('#confirm-name').textContent = funnelState.userData.name;
    $('#confirm-email').textContent = funnelState.userData.email;
    $('#confirm-date').textContent = funnelState.booking.date;
    $('#confirm-time').textContent = funnelState.booking.time;
    $('#confirm-concern').textContent = funnelState.survey.concern;
    $('#confirm-preference').textContent = funnelState.survey.preference;

    // Update step indicators to all completed
    $$('.step-dot').forEach(d => { d.classList.remove('active'); d.classList.add('completed'); });
    $$('.step-line').forEach(l => l.classList.add('active'));

    // Hide Book Now button on confirmation
    $('.btn-book').classList.add('hidden');

    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, 1500);
}

/* ===== UTILITY ===== */
function shakeButton(btn) {
  btn.style.animation = 'none';
  btn.offsetHeight;
  btn.style.animation = 'shake 0.4s ease';
  setTimeout(() => btn.style.animation = '', 400);
}
