/* schedule-widget.jsx — Webinar schedule utilities (no React component)
   Computes the next live session from a recurring weekly schedule.
   Loaded before app.jsx so wsGetAllSessions() is available globally.

   To change schedule: edit WEBINAR_SCHEDULE in config.js only.
   day: 0=Sun 1=Mon 2=Tue 3=Wed 4=Thu 5=Fri 6=Sat  |  hour/minute in IST 24h
*/

// Schedule is defined in config.js
const WEBINAR_SCHEDULE = window.APP_CONFIG.WEBINAR_SCHEDULE;

const _IST_MS    = 19800000; // 5h 30m in ms
const _WS_SHORT  = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
const _WS_FULL   = ['January','February','March','April','May','June','July','August','September','October','November','December'];

/* Returns a Date whose .getDay()/.getHours() reflect IST regardless of visitor timezone */
function wsNowIST() {
  return new Date(Date.now() + _IST_MS + new Date().getTimezoneOffset() * 60000);
}

/* Returns all sessions sorted soonest-first. [0] = next upcoming session. */
function wsGetAllSessions() {
  const istNow = wsNowIST();
  const nowMs  = istNow.getTime();
  const tzMs   = new Date().getTimezoneOffset() * 60000;

  const list = WEBINAR_SCHEDULE.map(slot => {
    const c = new Date(nowMs);
    c.setHours(slot.hour, slot.minute, 0, 0);

    const dayDiff = (slot.day - istNow.getDay() + 7) % 7;
    c.setDate(c.getDate() + dayDiff);

    // Same day but already past → next week
    if (dayDiff === 0 && c.getTime() <= nowMs) {
      c.setDate(c.getDate() + 7);
    }

    const targetUTC = c.getTime() - _IST_MS - tzMs;
    const dd        = String(c.getDate()).padStart(2, '0');

    return {
      targetUTC,
      dayLabel:     slot.dayLabel,
      timeLabel:    slot.timeLabel,
      fullDate:     `${c.getDate()} ${_WS_FULL[c.getMonth()]} ${c.getFullYear()}`,
      // Matches the format used by window.WEBINAR_DATE consumers:
      displayLabel: `${slot.dayLabel}, ${_WS_SHORT[c.getMonth()]} ${dd}, ${slot.timeLabel}`,
    };
  });

  return list.sort((a, b) => a.targetUTC - b.targetUTC);
}
