/* EireneEduCloud — ProgressTracker
   Eirene Technologies Limited
   Persists lesson completion and quiz scores to localStorage (per device, no server). */
(function (w) {
  var KEY = 'eirene.educloud.progress.v1';

  function load() {
    try { return JSON.parse(w.localStorage.getItem(KEY)) || {}; }
    catch (e) { return {}; }
  }
  function save(data) {
    try { w.localStorage.setItem(KEY, JSON.stringify(data)); } catch (e) {}
  }

  var ProgressTracker = {
    _d: load(),

    // Mark a lesson as visited/completed
    markLesson: function (lessonId) {
      if (!this._d.lessons) this._d.lessons = {};
      this._d.lessons[lessonId] = { done: true, ts: this._stamp() };
      save(this._d);
    },
    isLessonDone: function (lessonId) {
      return !!(this._d.lessons && this._d.lessons[lessonId] && this._d.lessons[lessonId].done);
    },

    // Record a quiz score (keeps the best attempt)
    recordQuiz: function (lessonId, score, total) {
      if (!this._d.quizzes) this._d.quizzes = {};
      var prev = this._d.quizzes[lessonId];
      var pct = total ? Math.round((score / total) * 100) : 0;
      if (!prev || pct > prev.pct) {
        this._d.quizzes[lessonId] = { score: score, total: total, pct: pct, ts: this._stamp() };
      }
      this._d.quizzes[lessonId].attempts = ((prev && prev.attempts) || 0) + 1;
      this.markLesson(lessonId);
      save(this._d);
      return this._d.quizzes[lessonId];
    },
    getQuiz: function (lessonId) {
      return (this._d.quizzes && this._d.quizzes[lessonId]) || null;
    },

    // Count completed lessons for a list of lesson ids
    subjectProgress: function (lessonIds) {
      var done = 0;
      for (var i = 0; i < lessonIds.length; i++) if (this.isLessonDone(lessonIds[i])) done++;
      return { done: done, total: lessonIds.length, pct: lessonIds.length ? Math.round(done / lessonIds.length * 100) : 0 };
    },

    // Overall progress across every lesson in the curriculum
    overall: function () {
      var ids = [];
      var c = w.CURRICULUM;
      if (c) c.subjects.forEach(function (s) {
        s.units.forEach(function (u) { u.lessons.forEach(function (l) { ids.push(l.id); }); });
      });
      return this.subjectProgress(ids);
    },

    reset: function () { this._d = {}; save(this._d); },

    _stamp: function () { return (w.performance && w.performance.now) ? Math.round(w.performance.now()) : 0; }
  };

  w.ProgressTracker = ProgressTracker;
})(window);
