// Runtime fixes: wrap images in .img-wrap, add lazy loading and fallbacks
(function(){
  const PLACEHOLDER = 'images/placeholder.svg';

  function processImg(img){
    if(!img || img.__handled) return;
    try{
      img.setAttribute('loading','lazy');
      img.setAttribute('decoding','async');
      // log errors and replace with local placeholder
      const _origSrc = img.currentSrc || img.src;
      img.addEventListener('error', (ev)=>{
        try{ console.warn('Image failed to load:', _origSrc, ev); }catch(e){}
        img.onerror = null; img.src = PLACEHOLDER;
      });
      // wrap
      const parent = img.parentElement;
      if(!(parent && parent.classList && parent.classList.contains('img-wrap'))){
        const wrap = document.createElement('div');
        wrap.className = 'img-wrap';
        img.replaceWith(wrap);
        wrap.appendChild(img);
      }
      img.__handled = true;
    }catch(e){ console.warn('image-fixes process error', e); }
  }

  // process existing images on DOMContentLoaded
  document.addEventListener('DOMContentLoaded', ()=>{
    const existing = document.querySelectorAll('img');
    existing.forEach(processImg);
  });

  // observe for new images added to the DOM (e.g. by main.js)
  const obs = new MutationObserver(muts=>{
    for(const m of muts){
      if(m.type === 'childList'){
        m.addedNodes.forEach(node=>{
          if(node.nodeType !== 1) return;
          if(node.tagName === 'IMG') processImg(node);
          else {
            // find imgs inside added subtree
            node.querySelectorAll && node.querySelectorAll('img').forEach(processImg);
          }
        });
      }
    }
  });

  obs.observe(document.documentElement || document.body, {childList:true, subtree:true});

  // safety: after 5s, disconnect observer to avoid long-lived observers
  setTimeout(()=>obs.disconnect(), 5000);

  // global capture for resource loading errors (catches images that fail before handlers attach)
  window.addEventListener('error', function(e){
    const t = e.target || e.srcElement;
    if(t && t.tagName === 'IMG'){
      try{ console.warn('Resource error on image (global):', t.src, e); }catch(err){}
      // ensure a fallback is applied
      if(t.src && !t.src.includes(PLACEHOLDER)) try{ t.src = PLACEHOLDER; }catch(ignore){}
    }
  }, true);
})();

