/* EireneEduCloud — external enrichment helpers
   Eirene Technologies Limited
   - EireneWiki: pull a short Wikipedia summary on demand (graceful offline fallback to a link).
   - EireneLabs: build embeds for free HTML5 virtual labs / simulations (PhET, PhET-derived),
     which can also be downloaded and bundled for fully-offline use.
   All external calls degrade gracefully so the platform never breaks offline. */
(function (w, d) {

  var EireneWiki = {
    // Returns a Promise resolving to {title, extract, url, thumb} or {url, title} on failure.
    summary: function (title) {
      // Offline replica: use the bundled summaries (window.EE_WIKI) — no network, file://-safe.
      if (w.EE_WIKI && w.EE_WIKI[title]) {
        var b = w.EE_WIKI[title];
        return Promise.resolve({ title: title, extract: b.extract || '', url: b.url || ('' + title.replace(/\s/g, '_')), thumb: b.thumb || '' });
      }
      var url = '' + encodeURIComponent(title);
      var page = '' + encodeURIComponent(title.replace(/\s/g, '_'));
      var fallback = { title: title, url: page, extract: '', offline: true };
      if (w.EE_OFFLINE || !w.fetch || (w.navigator && w.navigator.onLine === false)) return Promise.resolve(fallback);
      return fetch(url, { headers: { 'Api-User-Agent': 'EireneEduCloud/1.0 (education; cbc.eirene.co.ke)' } })
        .then(function (r) { if (!r.ok) throw 0; return r.json(); })
        .then(function (j) {
          return {
            title: j.title || title,
            extract: j.extract || '',
            url: (j.content_urls && j.content_urls.desktop && j.content_urls.desktop.page) || page,
            thumb: (j.thumbnail && j.thumbnail.source) || ''
          };
        })
        .catch(function () { return fallback; });
    },

    // Render into a container element
    render: function (el, title) {
      el.innerHTML = '<span class="muted">Loading from Wikipedia…</span>';
      this.summary(title).then(function (s) {
        if (s.extract) {
          el.innerHTML = (s.thumb ? '<img class="wiki-thumb" src="' + s.thumb + '" alt="">' : '') +
            '<p>' + s.extract + '</p>' +
            '<a class="wiki-link" href="' + s.url + '" target="_blank" rel="noopener">Read more on Wikipedia ↗</a>';
        } else {
          el.innerHTML = '<a class="wiki-link" href="' + s.url + '" target="_blank" rel="noopener">Open “' + s.title + '” on Wikipedia ↗</a>' +
            '<span class="muted"> (connect to the internet for an in-page summary)</span>';
        }
      });
    }
  };

  // Curated free, HTML5, CC-licensed virtual labs (also downloadable for offline bundling).
  var EireneLabs = {
    phetUrl: function (sim) { return '' + sim + '/latest/' + sim + '_en.html'; },
    // a small starter registry keyed by topic; the curriculum can reference a provider+id directly too
    registry: {
      'build-an-atom':        { provider: 'phet', id: 'build-an-atom',        title: 'Build an Atom' },
      'states-of-matter':     { provider: 'phet', id: 'states-of-matter-basics', title: 'States of Matter' },
      'circuit-construction': { provider: 'phet', id: 'circuit-construction-kit-dc', title: 'Circuit Construction Kit (DC)' },
      'ph-scale':             { provider: 'phet', id: 'ph-scale',             title: 'pH Scale (Acids & Bases)' },
      'forces-and-motion':    { provider: 'phet', id: 'forces-and-motion-basics', title: 'Forces and Motion' },
      'graphing-lines':       { provider: 'phet', id: 'graphing-lines',       title: 'Graphing Lines (Algebra)' },
      'area-builder':         { provider: 'phet', id: 'area-builder',         title: 'Area Builder (Geometry)' },
      'fraction-matcher':     { provider: 'phet', id: 'fractions-intro',      title: 'Fractions Intro' },
      'natural-selection':    { provider: 'phet', id: 'natural-selection',    title: 'Natural Selection (Genetics)' },
      'plate-tectonics':      { provider: 'phet', id: 'plate-tectonics',      title: 'Plate Tectonics (Geography)' }
    },
    resolve: function (lab) {
      // lab may be {provider, id, url, title, note}
      if (!lab) return null;
      if (lab.url) return lab;
      if (lab.provider === 'phet' && lab.id) return { url: this.phetUrl(lab.id), title: lab.title || lab.id, note: lab.note };
      if (this.registry[lab.id]) { var r = this.registry[lab.id]; return { url: this.phetUrl(r.id), title: r.title, note: lab.note }; }
      return lab.url ? lab : null;
    },
    embed: function (el, lab) {
      var r = this.resolve(lab);
      if (!r) { el.innerHTML = ''; return; }
      el.innerHTML =
        '<div class="lab-head"><span class="lab-ic">🧪</span><strong>Virtual Lab: ' + (r.title || 'Interactive simulation') + '</strong></div>' +
        '<div class="lab-frame"><iframe loading="lazy" src="' + r.url + '" title="' + (r.title || 'Virtual lab') + '" allowfullscreen></iframe></div>' +
        '<div class="lab-actions"><a class="btn btn-ghost btn-sm" href="' + r.url + '" target="_blank" rel="noopener">Open full screen ↗</a>' +
        '<span class="muted">' + (r.note || 'Free HTML5 simulation (PhET, University of Colorado). Can be downloaded for offline use.') + '</span></div>';
    },
    // sim id (for the bundled local PhET file name)
    simId: function (lab) {
      if (!lab) return null;
      if (lab.provider === 'phet' && lab.id) return lab.id;
      if (this.registry[lab.id]) return this.registry[lab.id].id;
      return lab.id || null;
    },
    localUrl: function (lab) { var id = this.simId(lab); return id ? ('assets/labs/' + id + '.html') : null; },
    // Offline replica: iframe the locally-bundled PhET HTML — runs with no internet.
    embedLocal: function (el, lab) {
      var r = this.resolve(lab), url = this.localUrl(lab);
      if (!url) { el.innerHTML = ''; return; }
      el.innerHTML =
        '<div class="lab-head"><span class="lab-ic">🧪</span><strong>Virtual Lab: ' + ((r && r.title) || 'Interactive simulation') + '</strong></div>' +
        '<div class="lab-frame"><iframe loading="lazy" src="' + url + '" title="' + ((r && r.title) || 'Virtual lab') + '" allowfullscreen></iframe></div>' +
        '<div class="lab-actions"><span class="muted">Offline interactive simulation (PhET, University of Colorado, CC&nbsp;BY) — runs locally, no internet required.</span></div>';
    }
  };

  w.EireneWiki = EireneWiki;
  w.EireneLabs = EireneLabs;
})(window, document);
