/* === PHYSL 210 — persisted course progress + "start from scratch" reset ===

   Module progress and the schedule's "done" states are otherwise hardcoded /
   date-derived (see data-modules.jsx `progress` and data-schedule.jsx). This
   thin layer lets a student wipe all of that and restart the course from
   lecture 1, regardless of where the calendar/deadlines say they should be.

   Storage: physl.progress.v1 = { freshStart: bool, modules?: {id: 0..1}, ts }
     - absent            → use the shipped defaults (course mid-progress)
     - { freshStart }    → every module 0%, schedule reset to day one
     - { modules: {...} } → per-module overrides (room for real tracking later)
*/
const PROGRESS_KEY = 'physl.progress.v1';

function readProgress() {
  try { return JSON.parse(localStorage.getItem(PROGRESS_KEY)) || null; }
  catch (e) { return null; }
}

/* fresh-start mode = the student chose to restart the course from scratch */
function isFreshStart() {
  const p = readProgress();
  return !!(p && p.freshStart);
}

/* Apply any persisted overrides onto the MODULES globals (mutates in place at
   load). No-op when nothing is stored, so the shipped state is untouched. */
function applyProgress() {
  const p = readProgress();
  if (!p || typeof MODULES === 'undefined') return;
  MODULES.forEach((m) => {
    if (p.freshStart) m.progress = 0;
    else if (p.modules && typeof p.modules[m.id] === 'number') m.progress = p.modules[m.id];
  });
}

/* Replace local course progress from a server-provided object (cloud-sync hydrate on
   login) and re-apply it onto MODULES. null/absent → leave shipped defaults. */
function hydrateProgress(obj) {
  try {
    if (obj && typeof obj === 'object') localStorage.setItem(PROGRESS_KEY, JSON.stringify(obj));
    else localStorage.removeItem(PROGRESS_KEY);
    applyProgress();
  } catch (e) {}
}

/* Wipe all course progress and restart from the beginning, ignoring the real
   calendar date so deadlines/schedule no longer mark anything done or overdue.
   Personal Notes (physl.notes.v1) are intentionally left intact. */
function resetAllProgress() {
  try {
    localStorage.setItem(PROGRESS_KEY, JSON.stringify({ freshStart: true, ts: Date.now() }));
    localStorage.removeItem('physl.stats.v1');  // wipe study analytics too (notes are kept)
    localStorage.removeItem('physl.page');      // land back on the dashboard
  } catch (e) {}
  try { window.__physlSyncBeacon && window.__physlSyncBeacon(); } catch (e) {}  // push reset to the server before reload
  location.reload();
}

/* Undo a fresh start — restore the course to its shipped schedule/progress. */
function restoreProgress() {
  try { localStorage.removeItem(PROGRESS_KEY); } catch (e) {}
  try { window.__physlSyncBeacon && window.__physlSyncBeacon(); } catch (e) {}
  location.reload();
}

applyProgress();
Object.assign(window, { isFreshStart, resetAllProgress, restoreProgress, readProgress, hydrateProgress, applyProgress });
