(()=>{
  const region=document.querySelector('[data-reconciliation-live-region]');
  if(!region)return;
  const endpoint=new URL('api/reconciliation_revision.php',window.location.href);
  const branch=new URL(window.location.href).searchParams.get('branch_id')||document.body.dataset.branchId||'';
  if(branch)endpoint.searchParams.set('branch_id',branch);
  let revision='';let busy=false;let stopped=false;let failures=0;let pending=false;
  const badge=document.createElement('div');badge.className='reconciliation-live-status';badge.setAttribute('role','status');badge.setAttribute('aria-live','polite');badge.innerHTML='<i aria-hidden="true"></i><span>Reconciliation live</span>';document.body.append(badge);
  const set=(state,text)=>{badge.dataset.state=state;badge.querySelector('span').textContent=text;};
  const isEditing=()=>Boolean(document.querySelector('dialog[open]')||region.querySelector('form[data-reconciliation-dirty="1"]')||(document.activeElement&&region.contains(document.activeElement)&&/INPUT|TEXTAREA|SELECT|BUTTON/.test(document.activeElement.tagName)));
  region.addEventListener('input',event=>event.target.closest('form')?.setAttribute('data-reconciliation-dirty','1'));
  region.addEventListener('change',event=>event.target.closest('form')?.setAttribute('data-reconciliation-dirty','1'));
  region.addEventListener('submit',event=>event.target.closest('form')?.removeAttribute('data-reconciliation-dirty'),true);
  region.addEventListener('click',event=>{
    const expand=event.target.closest('[data-critical-expand-all]');
    const collapse=event.target.closest('[data-critical-collapse-all]');
    if(!expand&&!collapse)return;
    const open=Boolean(expand);
    region.querySelectorAll('[data-critical-group]').forEach(group=>{group.open=open;});
  });
  const openKeys=root=>[...root.querySelectorAll('details[open]')].map((item,index)=>item.id||item.dataset.liveKey||`${index}`);
  const restore=(root,keys)=>[...root.querySelectorAll('details')].forEach((item,index)=>{const key=item.id||item.dataset.liveKey||`${index}`;item.open=keys.includes(key);});
  const refresh=async()=>{
    if(busy||stopped)return;if(isEditing()){pending=true;set('pending','Update waiting for current entry');return;}
    busy=true;set('syncing','Updating reconciliation…');
    try{
      const url=new URL(window.location.href);url.searchParams.set('_reconciliation_live',String(Date.now()));
      const response=await fetch(url,{headers:{Accept:'text/html','X-Dental-Reconciliation':'1'},cache:'no-store',credentials:'same-origin'});
      if(response.status===401||response.status===403){stopped=true;set('offline','Sign in again');return;}
      if(!response.ok)throw new Error('Refresh failed');
      const parsed=new DOMParser().parseFromString(await response.text(),'text/html');const next=parsed.querySelector('[data-reconciliation-live-region]');if(!next)throw new Error('Region missing');
      const scrollY=window.scrollY;const keys=openKeys(region);region.replaceChildren(...[...next.childNodes].map(node=>document.importNode(node,true)));restore(region,keys);window.scrollTo({top:scrollY});pending=false;failures=0;set('live','Reconciliation live');document.dispatchEvent(new CustomEvent('dental:reconciliation-updated'));
    }catch(error){failures++;set('offline',failures>2?'Reconciliation reconnecting':'Live update retrying');}finally{busy=false;}
  };
  const check=async(force=false)=>{
    if(stopped||busy||document.hidden)return;
    try{
      const url=new URL(endpoint);url.searchParams.set('_',String(Date.now()));const response=await fetch(url,{headers:{Accept:'application/json'},cache:'no-store',credentials:'same-origin'});
      if(response.status===401||response.status===403){stopped=true;set('offline','Sign in again');return;}if(!response.ok)throw new Error('Revision failed');const data=await response.json();if(!data.ok)throw new Error(data.message||'Revision failed');
      if(revision===''&&!force){revision=data.revision;set('live','Reconciliation live');return;}
      if(force||data.revision!==revision){revision=data.revision;await refresh();}else if(pending&&!isEditing()){await refresh();}else{failures=0;set('live','Reconciliation live');}
    }catch(error){failures++;set('offline',failures>2?'Reconciliation reconnecting':'Live update retrying');}
  };
  document.addEventListener('visibilitychange',()=>{if(!document.hidden)check(true);});window.addEventListener('focus',()=>check(true));setInterval(()=>check(false),5000);check(false);
})();
