/* ── CUSTOM LESSONS MERGE ──
   Loads after all lesson packs — merges admin-created lessons
   (localStorage / assets/content.js) into window.LESSONS_DATA
   and removes lessons hidden from the Admin panel. */

(function () {
  if (!window.TFE_getContent || !window.LESSONS_DATA) return;
  var c = window.TFE_getContent();

  /* localized-field normalizer: "text" → {en,ar,tr} */
  function loc(v) {
    if (v == null) return { en: '', ar: '', tr: '' };
    if (typeof v === 'string') return { en: v, ar: v, tr: v };
    return { en: v.en || '', ar: v.ar || v.en || '', tr: v.tr || v.en || '' };
  }

  var groupIds = (window.LESSON_GROUPS || []).map(function (g) { return g.id; });
  var usedCustomGroup = false;

  (c.customLessons || []).forEach(function (l) {
    if (!l || !l.id || !l.title) return;
    var group = l.group && groupIds.indexOf(l.group) >= 0 ? l.group : 'custom';
    if (group === 'custom') usedCustomGroup = true;
    window.LESSONS_DATA.push({
      id: l.id,
      level: l.level || 'A2',
      icon: l.icon || '⭐',
      image: l.image || '',
      group: group,
      custom: true,
      title: loc(l.title),
      summary: loc(l.summary),
      sections: (l.sections || []).map(function (s) {
        if (s.type === 'table') {
          return { type: 'table', title: loc(s.title), headers: s.headers || [], rows: s.rows || [] };
        }
        if (s.type === 'examples') {
          return { type: 'examples', title: loc(s.title), items: (s.items || []).map(function (it) {
            return { en: it.en || '', ar: it.ar || it.en || '', ctx: it.ctx || '' };
          }) };
        }
        return { type: s.type === 'note' ? 'note' : 'concept', title: loc(s.title), body: loc(s.body) };
      }),
      practice: (l.practice || []).map(function (q) {
        if (q.type === 'fill') {
          return { type: 'fill', q: q.q || '', a: q.a || '', explainEn: q.explain || '', explainAr: q.explain || '' };
        }
        return { type: 'mcq', q: q.q || '', options: q.options || [], a: q.a || 0, explainEn: q.explain || '', explainAr: q.explain || '' };
      }),
    });
  });

  if (usedCustomGroup && window.LESSON_GROUPS) {
    window.LESSON_GROUPS.push({ id: 'custom', emoji: '⭐', en: 'My Lessons', ar: 'دروسي', tr: 'Derslerim' });
  }

  var hidden = c.hiddenLessons || [];
  if (hidden.length) {
    window.LESSONS_DATA = window.LESSONS_DATA.filter(function (l) {
      return hidden.indexOf(l.id) < 0;
    });
  }
})();
