(function(){
  try {
    if (window.__stnfViewInit) return; // run once
    window.__stnfViewInit = 1;

    function parseISOToDate(iso) {
      if (!iso || typeof iso !== 'string') return null;
      var d = new Date(iso);
      if (!isNaN(d)) return d;
      // If ISO without timezone, assume UTC
      if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/.test(iso)) {
        var d2 = new Date(iso + 'Z');
        if (!isNaN(d2)) return d2;
      }
      return null;
    }

    function buildIntlOptions(df, tf){
      var opts = { year: 'numeric' };
      // Month from WP date format
      if (/F/.test(df)) opts.month = 'long';
      else if (/M/.test(df)) opts.month = 'short';
      else if (/m/.test(df)) opts.month = '2-digit';
      else if (/n/.test(df)) opts.month = 'numeric';
      // Day
      if (/d/.test(df)) opts.day = '2-digit';
      else if (/j/.test(df)) opts.day = 'numeric';
      // Year
      if (/y/.test(df) && !/Y/.test(df)) opts.year = '2-digit';
      // Time
      if (tf) {
        if (/H/.test(tf)) { opts.hourCycle = 'h23'; opts.hour = '2-digit'; }
        else if (/G/.test(tf)) { opts.hourCycle = 'h23'; opts.hour = 'numeric'; }
        else if (/h/.test(tf)) { opts.hourCycle = 'h12'; opts.hour = '2-digit'; }
        else if (/g/.test(tf)) { opts.hourCycle = 'h12'; opts.hour = 'numeric'; }
        if (/i/.test(tf)) opts.minute = '2-digit';
        if (/s/.test(tf)) opts.second = '2-digit';
      }
      return opts;
    }

    function getLocale(doc){
      try {
        var l = (doc && doc.documentElement && doc.documentElement.lang) ? doc.documentElement.lang : '';
        if (l && typeof l === 'string') return l;
      } catch(e){}
      try { return (doc && doc.defaultView && doc.defaultView.navigator && doc.defaultView.navigator.language) || navigator.language || 'en'; } catch(e) { return 'en'; }
    }

    function toText(d, df, tf, doc) {
      try {
        var opts = buildIntlOptions(df||'', tf||'');
        var loc = getLocale(doc || document);
        var fmt = new Intl.DateTimeFormat(loc, opts);
        return fmt.format(d);
      } catch (e) { return d.toLocaleString(); }
    }

    function localize(root) {
      var doc = (root && root.ownerDocument) ? root.ownerDocument : (root && root.nodeType === 9 ? root : document);
      (root || document).querySelectorAll('.stnf time[data-localize="1"]:not([data-localized])').forEach(function(el){
        var iso = el.getAttribute('datetime');
        var d = parseISOToDate(iso);
        if (!d) return;
        var df = el.getAttribute('data-df') || '';
        var tf = el.getAttribute('data-tf') || '';
        var tgt = el.querySelector('.stnf-date-txt') || el;
        tgt.textContent = toText(d, df, tf, doc);
        el.setAttribute('data-localized','1');
      });
    }

    function onReady(fn){
      if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fn);
      else fn();
    }

    onReady(function(){
      localize(document);
      // Observe for dynamic updates (e.g., editor SSR refreshes)
      try {
        var mo = new MutationObserver(function(muts){
          muts.forEach(function(m){ if (m.addedNodes && m.addedNodes.length) localize(m.target || document); });
        });
        mo.observe(document.body, { childList: true, subtree: true });
      } catch (e) {}
    });
  } catch (e) { /* noop */ }
})();
