/* V6.18 — computed contrast repair. It changes text only when the rendered contrast is genuinely too low. */
(()=>{
  'use strict';
  const root=document.documentElement;
  const selector='h1,h2,h3,h4,h5,h6,p,span,small,strong,b,em,label,legend,button,a,th,td,li,dt,dd,input,textarea,select,option,[role="button"],[role="tab"],[role="menuitem"]';
  const fixed=new Set();
  let pending=false;
  const rgb=s=>{const m=String(s||'').match(/rgba?\(([^)]+)\)/i);if(!m)return null;const p=m[1].split(/[ ,/]+/).map(Number);return {r:p[0],g:p[1],b:p[2],a:Number.isFinite(p[3])?p[3]:1};};
  const lum=c=>{const f=v=>{v/=255;return v<=.04045?v/12.92:Math.pow((v+.055)/1.055,2.4)};return .2126*f(c.r)+.7152*f(c.g)+.0722*f(c.b)};
  const contrast=(a,b)=>{const x=lum(a),y=lum(b);return (Math.max(x,y)+.05)/(Math.min(x,y)+.05)};
  const effectiveBackground=el=>{
    let n=el;
    while(n&&n.nodeType===1){const c=rgb(getComputedStyle(n).backgroundColor);if(c&&c.a>.12)return c;n=n.parentElement;}
    return {r:5,g:5,b:5,a:1};
  };
  const hasText=el=>{
    if(/^(INPUT|TEXTAREA|SELECT|OPTION)$/.test(el.tagName))return true;
    return Array.from(el.childNodes).some(n=>n.nodeType===3&&n.textContent.trim());
  };
  const clear=()=>{fixed.forEach(el=>{if(el&&el.isConnected){el.style.removeProperty('color');el.style.removeProperty('-webkit-text-fill-color');delete el.dataset.apuAutoContrast;}});fixed.clear();};
  const repair=()=>{
    pending=false;
    if(root.dataset.apuTheme!=='dark'){clear();return;}
    document.querySelectorAll(selector).forEach(el=>{
      if(!hasText(el)||el.closest('[aria-hidden="true"],script,style,svg,[data-apu-contrast-lock],.apu-cookie-panel,.zip-access__panel'))return;
      const cs=getComputedStyle(el);if(cs.display==='none'||cs.visibility==='hidden'||Number(cs.opacity)<.08)return;
      const fg=rgb(cs.color),bg=effectiveBackground(el);if(!fg||!bg)return;
      const ratio=contrast(fg,bg);
      if(ratio>=4.15)return;
      const black={r:9,g:13,b:21,a:1},white={r:248,g:250,b:252,a:1};
      const useInk=contrast(black,bg)>=contrast(white,bg);
      const value=useInk?'#090d15':'#f8fafc';
      el.style.setProperty('color',value,'important');
      el.style.setProperty('-webkit-text-fill-color',value,'important');
      el.dataset.apuAutoContrast=useInk?'ink':'paper';
      fixed.add(el);
    });
  };
  const schedule=()=>{if(!pending){pending=true;requestAnimationFrame(repair)}};
  new MutationObserver(schedule).observe(document.documentElement,{subtree:true,childList:true,attributes:true,attributeFilter:['class','style','data-apu-theme']});
  addEventListener('load',()=>{schedule();setTimeout(schedule,400);setTimeout(schedule,1400)},{once:true});
  addEventListener('resize',schedule,{passive:true});
  schedule();
})();
