// Shared helpers for every page entry script.
// Exposes: window.yy = { goTo, getLang, setLang, getTheme, setTheme, applyStoredTheme, waitFor }

(function () {
  const LANG_KEY = 'yylearn.lang';
  const THEME_KEY = 'yylearn.theme';

  function getLang() {
    const stored = localStorage.getItem(LANG_KEY);
    if (stored) return stored;
    const fromData = (window.__DATA__ && window.__DATA__.lang) || null;
    if (fromData) return fromData;
    const htmlLang = (document.documentElement.lang || '').split('-')[0];
    if (htmlLang) return htmlLang;
    try { return (typeof detectLocale === 'function' ? detectLocale() : 'en'); }
    catch (_) { return 'en'; }
  }
  // Fire-and-forget PATCH /api/me so the signed-in user's preference is
  // mirrored into the users row. Uses sendBeacon when available so the
  // request survives location.reload(); otherwise plain fetch w/ keepalive.
  // Silent on 401/404 — guests just fall back to cookie + localStorage.
  function persistPref(patch) {
    try {
      const body = JSON.stringify(patch);
      const url = '/api/me';
      // Only attempt if we have some sign we're logged in. Server-rendered
      // pages stash user on window.__DATA__.user, and data-bootstrap sets
      // DEMO_USER. If neither is present, skip the network call.
      const signed = !!(window.__DATA__ && window.__DATA__.user)
                  || !!(window.DEMO_USER && window.DEMO_USER.email);
      if (!signed) return;
      if (navigator.sendBeacon) {
        const blob = new Blob([body], { type: 'application/json' });
        // sendBeacon only supports POST, so use fetch+keepalive for PATCH.
        fetch(url, { method: 'PATCH', body, headers: { 'Content-Type': 'application/json' }, credentials: 'include', keepalive: true })
          .catch(() => {});
      } else {
        fetch(url, { method: 'PATCH', body, headers: { 'Content-Type': 'application/json' }, credentials: 'include' })
          .catch(() => {});
      }
    } catch (_) { /* best-effort */ }
  }

  function setLang(lang) {
    try { localStorage.setItem(LANG_KEY, lang); } catch (_) {}
    document.cookie = 'yy_lang=' + encodeURIComponent(lang) + '; path=/; max-age=31536000';
    persistPref({ locale: lang });
    location.reload();
  }

  function getTheme() {
    return localStorage.getItem(THEME_KEY) || 'zen';
  }
  function setTheme(themeId) {
    try { localStorage.setItem(THEME_KEY, themeId); } catch (_) {}
    document.cookie = 'yy_theme=' + encodeURIComponent(themeId) + '; path=/; max-age=31536000';
    persistPref({ themePref: themeId });
    if (typeof applyTheme === 'function') applyTheme(themeId);
  }
  function applyStoredTheme(override) {
    const id = override || getTheme();
    if (typeof applyTheme === 'function') applyTheme(id);
  }

  function goTo(screen, opts) {
    const o = opts || {};
    switch (screen) {
      case 'home':
        location.href = '/'; break;
      case 'browse':
        location.href = o.channel ? '/browse/' + encodeURIComponent(o.channel) : '/browse'; break;
      case 'channel':
        location.href = '/browse/' + encodeURIComponent(o.channel || ''); break;
      case 'course':
        location.href = '/course/' + encodeURIComponent(o.course || o.courseId || ''); break;
      case 'player':
        location.href = '/player/' + encodeURIComponent(o.course || o.courseId || '')
          + (o.lesson ? '/' + encodeURIComponent(o.lesson) : ''); break;
      case 'pricing':
        location.href = '/pricing'; break;
      case 'auth':
      case 'signin': {
        const mode = o.authMode || o.mode;
        const qp = [];
        if (mode === 'signup') qp.push('mode=signup');
        if (o.returnTo) qp.push('returnTo=' + encodeURIComponent(o.returnTo));
        location.href = '/signin' + (qp.length ? '?' + qp.join('&') : '');
        break;
      }
      case 'user':
      case 'me':
        location.href = '/me'; break;
      case 'admin':
        location.href = '/admin'; break;
      case 'search':
        location.href = '/search?q=' + encodeURIComponent(o.q || ''); break;
      default:
        location.href = '/';
    }
  }

  // Poll until all named globals are defined; then call cb.
  function waitFor(names, cb, tries) {
    tries = tries || 0;
    const missing = names.filter(n => typeof window[n] === 'undefined');
    if (missing.length === 0) return cb();
    if (tries > 200) {
      console.error('[yylearn] gave up waiting for', missing, 'after', tries, 'tries');
      return;
    }
    setTimeout(() => waitFor(names, cb, tries + 1), 50);
  }

  window.yy = { goTo, getLang, setLang, getTheme, setTheme, applyStoredTheme, waitFor };
})();
