// share.js — Satyr Satire share bar
// Layers Web Share API (native mobile sheet) on top of sharer.js.
// sharer.js handles all platform popups; we handle Copy Link + native share.

(function () {
  var bar = document.querySelector('.share-bar');
  if (!bar) return;

  var pageUrl   = window.location.href;
  var pageTitle = document.title.replace(' \u2014 Satyr Satire', '').trim();

  // Populate data-url / data-title on all sharer.js buttons
  bar.querySelectorAll('[data-sharer]').forEach(function (btn) {
    if (!btn.getAttribute('data-url'))   btn.setAttribute('data-url',   pageUrl);
    if (!btn.getAttribute('data-title')) btn.setAttribute('data-title', pageTitle);
    if (!btn.getAttribute('data-subject')) btn.setAttribute('data-subject', pageTitle);
    if (!btn.getAttribute('data-body'))    btn.setAttribute('data-body', pageTitle + '\n\n' + pageUrl);
  });

  // ── Native share (Web Share API) — mobile primary ──────────────
  var nativeBtn = bar.querySelector('.share-native');
  if (nativeBtn) {
    if (navigator.share) {
      nativeBtn.style.display = 'inline-block';
      nativeBtn.addEventListener('click', function (e) {
        e.preventDefault();
        navigator.share({ title: pageTitle, url: pageUrl }).catch(function () {});
      });
    } else {
      nativeBtn.style.display = 'none';
    }
  }

  // ── Copy link ──────────────────────────────────────────────────
  var copyBtn = bar.querySelector('.share-copy');
  if (copyBtn) {
    copyBtn.addEventListener('click', function (e) {
      e.preventDefault();
      var label = copyBtn.textContent;
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(pageUrl).then(function () {
          copyBtn.textContent = 'Copied!';
          setTimeout(function () { copyBtn.textContent = label; }, 2000);
        });
      } else {
        var ta = document.createElement('textarea');
        ta.value = pageUrl;
        ta.style.cssText = 'position:fixed;opacity:0';
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
        copyBtn.textContent = 'Copied!';
        setTimeout(function () { copyBtn.textContent = label; }, 2000);
      }
    });
  }
})();

// ── Sticky language session (Web Storage, NOT cookies) ───────────
// When a reader clicks a flag in the language switcher, remember that
// language for the rest of their session and auto-serve every other
// article in it. Uses sessionStorage: never sent to the server, never
// used for cross-site tracking, and cleared automatically when the tab
// / session ends — so the choice "expires when the session expires."
// Redirects via the switcher's own relative links, so it works
// identically on file:// review and on production.
(function () {
  var LANGS = ['es','fr','pt','zh','hi','ar','ru','id','de','ja','ko','it'];
  var KEY = 'satyrLang';

  // Derive a lang code from a switcher anchor's raw href.
  //   "slug.html" / "../slug.html"        -> 'en'   (root / x-default)
  //   "zh/slug.html" / "../zh/slug.html"  -> 'zh'
  //   "alien/slug.html" (Saturnian, etc.) -> null   (unmanaged: ignore)
  // An unknown subdir must return null, NOT 'en' — otherwise clicking the
  // Saturnian flag would store 'en' and the enforcer would bounce the alien
  // page back to English.
  function langFromHref(href) {
    if (!href) return null;
    var p = href.replace(/^\.\//, '').replace(/^\.\.\//, '');
    var slash = p.indexOf('/');
    if (slash === -1) return 'en';            // root-level page = English
    var seg = p.slice(0, slash);
    return LANGS.indexOf(seg) !== -1 ? seg : null;  // unknown subdir -> ignore
  }

  function currentLang() {
    return ((document.documentElement.getAttribute('lang') || 'en')
      .slice(0, 2).toLowerCase()) || 'en';
  }

  var sw = document.querySelector('.lang-switch');
  if (!sw) return; // no per-page switcher (e.g. front page) -> nothing to do

  // 1) Capture the reader's pick on flag click.
  sw.addEventListener('click', function (e) {
    var a = e.target.closest('a[href]');
    if (!a || !sw.contains(a)) return;
    var lang = langFromHref(a.getAttribute('href'));
    if (lang) { try { sessionStorage.setItem(KEY, lang); } catch (err) {} }
    // navigation then proceeds normally to the chosen language version
  });

  // 2) Enforce the pick on load: if a preference exists and this page is in
  //    a different language, jump to the same article in the chosen language.
  //    If no such version exists in the switcher, stay put (graceful).
  var pref = null;
  try { pref = sessionStorage.getItem(KEY); } catch (err) {}
  if (!pref || (pref !== 'en' && LANGS.indexOf(pref) === -1)) return;
  // Never enforce on a page whose own language we don't manage (e.g. the
  // Saturnian alien edition, lang="x-saturn"). The reader chose to be here;
  // bouncing them away is the bug we're preventing.
  var cur = currentLang();
  if (cur !== 'en' && LANGS.indexOf(cur) === -1) return;
  if (pref === cur) return;

  var target = null;
  sw.querySelectorAll('a[href]').forEach(function (a) {
    if (langFromHref(a.getAttribute('href')) === pref) target = a.href; // resolved absolute URL
  });
  if (target && target !== window.location.href) window.location.replace(target);
})();

// ── XMR tip jar ──────────────────────────────────────────────────
// Address resolution: REQUIRE the per-strip data-xmr-address attribute (a
// per-article subaddress, embedded at deploy time by publish-article.py).
// No fallback — never inline the master wallet in client-side JS.
window.copyXmr = function (btn) {
  var strip = btn.closest('.xmr-inline');
  var addr = strip && strip.getAttribute('data-xmr-address');
  var orig = btn.textContent;
  function flash(msg) {
    btn.textContent = msg;
    setTimeout(function () { btn.textContent = orig; }, 2000);
  }
  // Refuse to copy if the address is missing or still a build-time placeholder
  if (!addr || addr.indexOf('{{') === 0) {
    flash('Address unavailable');
    return;
  }
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(addr).then(function () { flash('Copied'); });
  } else {
    var ta = document.createElement('textarea');
    ta.value = addr;
    ta.style.cssText = 'position:fixed;opacity:0';
    document.body.appendChild(ta);
    ta.select();
    document.execCommand('copy');
    document.body.removeChild(ta);
    flash('Copied');
  }
};
