(()=>{
  const regions=[...document.querySelectorAll('[data-live-queue-region]')];
  if(!regions.length)return;

  const revisionUrl=new URL('api/queue_revision.php',window.location.href);
  const branch=new URL(window.location.href).searchParams.get('branch_id')||document.body.dataset.branchId||'';
  if(branch)revisionUrl.searchParams.set('branch_id',branch);
  let knownRevision='';
  let refreshing=false;
  let stopped=false;
  let failureCount=0;
  let pending=false;

  const status=document.createElement('div');
  status.className='live-queue-status';
  status.setAttribute('role','status');
  status.setAttribute('aria-live','polite');
  status.innerHTML='<i aria-hidden="true"></i><span>Queue live</span>';
  document.body.append(status);

  const setStatus=(mode,label)=>{
    status.dataset.state=mode;
    status.querySelector('span').textContent=label;
  };
  const isBusy=region=>{
    const active=document.activeElement;
    return Boolean(
      document.querySelector('dialog[open]') ||
      (active && region.contains(active) && /INPUT|TEXTAREA|SELECT|BUTTON/.test(active.tagName)) ||
      region.querySelector('[data-live-queue-pause="true"]')
    );
  };
  const regionKey=region=>region.getAttribute('data-live-queue-region')||'';
  const preserveDetails=region=>[...region.querySelectorAll('details[open]')].map((item,index)=>item.id||item.dataset.liveKey||String(index));
  const restoreDetails=(region,keys)=>{
    const details=[...region.querySelectorAll('details')];
    details.forEach((item,index)=>{
      const key=item.id||item.dataset.liveKey||String(index);
      item.open=keys.includes(key);
    });
  };
  document.addEventListener('input',event=>{
    const form=event.target.closest?.('form');
    if(form?.closest('[data-live-queue-region]'))form.dataset.liveQueuePause='true';
  });
  document.addEventListener('change',event=>{
    const form=event.target.closest?.('form');
    if(form?.closest('[data-live-queue-region]'))form.dataset.liveQueuePause='true';
  });
  document.addEventListener('submit',event=>{
    const form=event.target.closest?.('form');
    if(form)delete form.dataset.liveQueuePause;
  },true);
  document.addEventListener('reset',event=>{
    const form=event.target.closest?.('form');
    if(form)delete form.dataset.liveQueuePause;
  },true);

  const replaceRegion=(current,next)=>{
    if(isBusy(current)){pending=true;return false;}
    const scrollTop=current.scrollTop;
    const openDetails=preserveDetails(current);
    current.replaceChildren(...[...next.childNodes].map(node=>document.importNode(node,true)));
    current.scrollTop=scrollTop;
    restoreDetails(current,openDetails);
    document.dispatchEvent(new CustomEvent('dental:live-queue-updated',{detail:{region:current,key:regionKey(current)}}));
    return true;
  };
  const refreshRegions=async()=>{
    if(refreshing||stopped)return;
    refreshing=true;setStatus('syncing','Updating queue…');
    try{
      const url=new URL(window.location.href);
      url.searchParams.set('_queue_live',String(Date.now()));
      const response=await fetch(url,{headers:{Accept:'text/html','X-Dental-Live-Queue':'1'},cache:'no-store',credentials:'same-origin'});
      if(response.status===401||response.status===403){stopped=true;setStatus('offline','Sign in again');return;}
      if(!response.ok)throw new Error('Page refresh failed');
      const html=await response.text();
      const parsed=new DOMParser().parseFromString(html,'text/html');
      let changed=0;
      regions.forEach(current=>{
        const key=regionKey(current);
        if(!key)return;
        const next=[...parsed.querySelectorAll('[data-live-queue-region]')].find(candidate=>regionKey(candidate)===key);
        if(!next)return;
        if(current.innerHTML===next.innerHTML)return;
        if(replaceRegion(current,next))changed++;
      });
      failureCount=0;
      setStatus(pending?'pending':'live',pending?'Update waiting for current entry':'Queue live');
      if(changed)status.classList.add('just-updated');
      setTimeout(()=>status.classList.remove('just-updated'),1200);
    }catch(error){
      failureCount++;
      setStatus('offline',failureCount>2?'Queue reconnecting':'Live queue retrying');
    }finally{refreshing=false;}
  };
  const checkRevision=async(force=false)=>{
    if(stopped||refreshing||document.hidden)return;
    try{
      const url=new URL(revisionUrl);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;setStatus('offline','Sign in again');return;}
      if(!response.ok)throw new Error('Revision check failed');
      const data=await response.json();
      if(!data.ok)throw new Error(data.message||'Revision check failed');
      if(knownRevision===''&&!force){knownRevision=data.revision;setStatus('live','Queue live');return;}
      if(force||data.revision!==knownRevision){knownRevision=data.revision;pending=false;await refreshRegions();}
      else if(pending&&!document.querySelector('dialog[open]')){pending=false;await refreshRegions();}
      else{failureCount=0;setStatus('live','Queue live');}
    }catch(error){failureCount++;setStatus('offline',failureCount>2?'Queue reconnecting':'Live queue retrying');}
  };

  document.addEventListener('visibilitychange',()=>{if(!document.hidden)checkRevision(true);});
  window.addEventListener('focus',()=>checkRevision(true));
  document.addEventListener('dental:queue-change',()=>checkRevision(true));
  setInterval(()=>checkRevision(false),3000);
  checkRevision(false);
})();
