/* V6.21 — Cloudflare Pages Direct Upload static runtime.
   This package intentionally avoids _worker.js and Service Worker dependencies.
   Optional API requests are resolved immediately with browser-local fallbacks. */
(()=>{
  'use strict';
  const nativeFetch = window.fetch.bind(window);
  const json = (data, init={}) => Promise.resolve(new Response(JSON.stringify(data), {
    status: init.status || 200,
    headers: {'content-type':'application/json; charset=utf-8','cache-control':'no-store',...(init.headers||{})}
  }));
  const KEY='apu_v621_static_links';
  const seed=[{id:1,originalUrl:'https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps',customAlias:'mdn-pwa',category:'training',owner:'AI Project Universe',campaignName:'PWA Documentation',expiryDate:null,accessStatus:'active',clickCount:0,createdAt:'2026-06-15T00:00:00.000Z'}];
  const readLinks=()=>{try{const v=JSON.parse(localStorage.getItem(KEY)||'null');return Array.isArray(v)&&v.length?v:seed.slice()}catch(_){return seed.slice()}};
  const writeLinks=v=>{try{localStorage.setItem(KEY,JSON.stringify(v))}catch(_){}};
  const bodyJson=async init=>{try{return JSON.parse(init?.body||'null')}catch(_){return null}};
  window.fetch=async(input,init={})=>{
    let url;
    try{url=new URL(typeof input==='string'?input:input.url,location.href)}catch(_){return nativeFetch(input,init)}
    if(url.origin===location.origin&&['/api/apu-translate','/api/link-config'].includes(url.pathname))return nativeFetch(input,init);
    if(url.origin===location.origin && url.pathname==='/api/visit'){
      return json({configured:false,total:null,counted:false,staticDirectUpload:true});
    }
    if(url.origin===location.origin && (url.pathname==='/api/links'||/^\/api\/links\/\d+$/.test(url.pathname))){
      const method=(init.method||(typeof input!=='string'&&input.method)||'GET').toUpperCase();
      let links=readLinks();
      if(method==='GET') return json(links);
      const payload=await bodyJson(init);
      if(method==='POST'){
        const next={...payload,id:Math.max(0,...links.map(x=>Number(x.id)||0))+1,clickCount:0,createdAt:new Date().toISOString()};
        links.unshift(next);writeLinks(links);return json(next,{status:201});
      }
      const id=Number(url.pathname.split('/').pop());
      if(method==='DELETE'){links=links.filter(x=>Number(x.id)!==id);writeLinks(links);return json({success:true});}
      if(method==='PATCH'){
        const idx=links.findIndex(x=>Number(x.id)===id);
        if(idx<0)return json({error:'not_found'},{status:404});
        links[idx]={...links[idx],...payload,id};writeLinks(links);return json(links[idx]);
      }
      return json({error:'method_not_allowed'},{status:405});
    }
    if(url.origin===location.origin && url.pathname.startsWith('/api/')){
      return json({configured:false,error:'static_direct_upload_mode'},{status:503});
    }
    const controller=new AbortController();
    const timer=setTimeout(()=>controller.abort(),12000);
    try{return await nativeFetch(input,{...init,signal:init.signal||controller.signal})}
    finally{clearTimeout(timer)}
  };

  // Remove stale registrations from older builds. This avoids old cached shells
  // showing an endless loading state after a fresh Direct Upload deployment.
  if('serviceWorker' in navigator){
    navigator.serviceWorker.getRegistrations?.().then(list=>list.forEach(r=>r.unregister())).catch(()=>{});
  }
  if('caches' in window){
    caches.keys().then(keys=>Promise.all(keys.filter(k=>/apu|workbox|project/i.test(k)).map(k=>caches.delete(k)))).catch(()=>{});
  }

  const finish=()=>document.documentElement.setAttribute('data-apu-static-ready','true');
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',finish,{once:true});else finish();

  // A last-resort watchdog: only replaces a genuinely empty/loading-only root.
  setTimeout(()=>{
    const root=document.querySelector('#root,#app,[data-reactroot]');
    if(!root)return;
    const text=(root.textContent||'').replace(/\s+/g,' ').trim();
    const onlyLoading=!text || /^(loading|memuat|please wait|preparing|menyiapkan)[….! ]*$/i.test(text);
    if(onlyLoading && root.children.length<3){
      root.innerHTML='<main style="min-height:100vh;display:grid;place-items:center;padding:24px;background:#0b1220;color:#fff;font-family:system-ui"><section style="max-width:720px;border:2px solid #fff;border-radius:24px;padding:28px;background:#111c31"><h1 style="margin:0 0 12px">Project ready in static mode</h1><p style="line-height:1.7;margin:0 0 18px">A cached older deployment was cleared. Reload once to open the current standalone build.</p><button onclick="location.reload()" style="padding:12px 18px;border:2px solid #fff;border-radius:12px;background:#fff;color:#0b1220;font-weight:800">Reload project</button></section></main>';
    }
  },10000);
})();
