(function(){
  'use strict';
  const body=document.body;
  const reduced=window.matchMedia&&window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const coarse=window.matchMedia&&window.matchMedia('(pointer: coarse)').matches;
  const mobile=window.matchMedia&&window.matchMedia('(max-width: 899px)').matches;
  const liteMotion=reduced||coarse||mobile;
  if(liteMotion) body.classList.add('lite-motion');

  const isPublicPage=body.classList.contains('public-body');
  const stored=localStorage.getItem('linkexpress-theme');
  // O tema claro/escuro pertence ao painel. A vitrine pública mantém o tema premium
  // para evitar que cards claros recebam textos/estilos pensados para o modo escuro.
  if(isPublicPage){
    body.removeAttribute('data-theme');
  }else if(stored){
    body.dataset.theme=stored;
  }
  const syncThemeUi=()=>{
    const light=!isPublicPage&&body.dataset.theme==='light';
    document.documentElement.style.colorScheme=light?'light':'dark';
    const meta=document.querySelector('meta[name="theme-color"]');
    if(meta)meta.setAttribute('content',light?'#f3f5fb':'#111221');
  };
  syncThemeUi();
  document.querySelectorAll('[data-theme-toggle]').forEach(btn=>btn.addEventListener('click',()=>{
    const next=body.dataset.theme==='light'?'dark':'light';
    body.dataset.theme=next;localStorage.setItem('linkexpress-theme',next);syncThemeUi();
  }));

  const overlay=document.querySelector('[data-sidebar-overlay]');
  const closeSidebar=()=>body.classList.remove('sidebar-open');
  document.querySelectorAll('[data-sidebar-toggle]').forEach(btn=>btn.addEventListener('click',()=>body.classList.toggle('sidebar-open')));
  if(overlay) overlay.addEventListener('click',closeSidebar);
  document.querySelectorAll('[data-alert] button').forEach(btn=>btn.addEventListener('click',()=>btn.parentElement.remove()));
  document.querySelectorAll('[data-confirm]').forEach(el=>el.addEventListener('click',e=>{if(el.dataset.confirmPhrase)return;if(!confirm(el.dataset.confirm||'Confirmar esta ação?'))e.preventDefault();}));
  document.querySelectorAll('[data-confirm-phrase]').forEach(el=>el.addEventListener('click',e=>{
    const phrase=(el.dataset.confirmPhrase||'EXCLUIR').trim();
    const message=el.dataset.confirmMessage||`Digite ${phrase} para confirmar esta exclusão.`;
    const typed=window.prompt(message,'');
    if((typed||'').trim().toUpperCase()!==phrase.toUpperCase()){e.preventDefault();return;}
    const form=el.closest('form');if(form){let input=form.querySelector('input[name="confirmed_delete_phrase"]');if(!input){input=document.createElement('input');input.type='hidden';input.name='confirmed_delete_phrase';form.appendChild(input);}input.value=phrase;}
  }));

  const menuBtn=document.querySelector('[data-public-menu]');
  const publicNav=document.querySelector('[data-public-nav]');
  if(menuBtn&&publicNav) menuBtn.addEventListener('click',()=>publicNav.classList.toggle('open'));
  document.querySelectorAll('[data-auto-submit]').forEach(el=>el.addEventListener('change',()=>el.form.submit()));

  document.addEventListener('click',async e=>{
    const copy=e.target.closest('[data-copy-text]');
    if(!copy)return;
    e.preventDefault();
    const text=copy.dataset.copyText||'';
    try{await navigator.clipboard.writeText(text);const old=copy.textContent;copy.textContent='Copiado!';setTimeout(()=>copy.textContent=old,1300);}catch(err){window.prompt('Copie o ID:',text);}
  });

  const closeModal=modal=>{
    if(!modal)return;
    modal.classList.remove('open');
    if(!document.querySelector('.modal.open'))body.classList.remove('modal-open');
  };
  const openModal=selector=>{
    const modal=document.querySelector(selector);
    if(!modal)return;
    // Modais renderizados dentro de tabelas/cards podem ser reposicionados pelo navegador.
    // Mover para o body garante position:fixed correto em celular e evita a tela ficar só desfocada.
    if(modal.parentElement!==body)body.appendChild(modal);
    modal.classList.add('open');
    body.classList.add('modal-open');
    const card=modal.querySelector('.modal-card');
    if(card)card.scrollTop=0;
    const geo=modal.querySelector('[data-auto-geolocate]');
    if(geo&&!geo.dataset.located){geo.dataset.located='1';setTimeout(()=>geo.click(),180);}
    const first=modal.querySelector('input:not([type="hidden"]),select,textarea,button[data-modal-close]');
    if(first)setTimeout(()=>first.focus({preventScroll:true}),40);
  };
  document.addEventListener('click',e=>{
    const opener=e.target.closest('[data-modal-open]');
    if(opener){
      e.preventDefault();
      const selector=opener.dataset.modalOpen;
      openModal(selector);
      const orderMode=opener.dataset.orderMode;
      if(orderMode){
        const modal=document.querySelector(selector);const select=modal?.querySelector('[data-fulfillment-select]');
        if(select){select.value=orderMode;select.dispatchEvent(new Event('change',{bubbles:true}));}
      }
      return;
    }
    const closer=e.target.closest('[data-modal-close]');
    if(closer){e.preventDefault();closeModal(closer.closest('.modal'));return;}
    if(e.target.classList&&e.target.classList.contains('modal'))closeModal(e.target);
  });
  document.addEventListener('keydown',e=>{if(e.key==='Escape')document.querySelectorAll('.modal.open').forEach(closeModal);});

  document.querySelectorAll('[data-count]').forEach(el=>{
    const target=parseFloat(el.dataset.count||'0');
    if(liteMotion){el.textContent=Math.round(target).toLocaleString('pt-BR');return;}
    let start=0;const step=Math.max(target/40,1);
    const tick=()=>{start=Math.min(target,start+step);el.textContent=Math.round(start).toLocaleString('pt-BR');if(start<target)requestAnimationFrame(tick)};
    tick();
  });

  document.querySelectorAll('[data-image-input]').forEach(input=>input.addEventListener('change',()=>{
    const file=input.files&&input.files[0];
    const wrapper=input.closest('.image-upload-row')||input.closest('.compact-upload')||input.parentElement.parentElement;
    const nameTarget=wrapper?wrapper.querySelector('[data-file-name]'):null;
    if(!file){if(nameTarget)nameTarget.textContent='Nenhuma imagem selecionada';return;}
    if(nameTarget)nameTarget.textContent=file.name;
    if(!/^image\/(jpeg|png|webp)$/.test(file.type)){alert('Escolha uma imagem JPG, PNG ou WebP.');input.value='';return;}
    if(file.size>8*1024*1024){alert('A imagem deve ter no máximo 8 MB.');input.value='';return;}
    const preview=wrapper?wrapper.querySelector('[data-image-preview]'):null;
    if(!preview)return;
    const reader=new FileReader();reader.onload=e=>{preview.innerHTML='<img src="'+e.target.result+'" alt="Prévia da imagem">';};reader.readAsDataURL(file);
  }));

  function cpfValid(value){
    const cpf=(value||'').replace(/\D/g,'');
    if(cpf.length!==11||/^(\d)\1{10}$/.test(cpf))return false;
    for(let t=9;t<11;t++){
      let sum=0;for(let i=0;i<t;i++)sum+=Number(cpf[i])*((t+1)-i);
      const digit=((10*sum)%11)%10;if(Number(cpf[t])!==digit)return false;
    }
    return true;
  }
  document.querySelectorAll('[data-document-mask]').forEach(input=>{
    const apply=()=>{
      let digits=input.value.replace(/\D/g,'').slice(0,14);
      if(digits.length<=11){
        digits=digits.replace(/(\d{3})(\d)/,'$1.$2').replace(/(\d{3})(\d)/,'$1.$2').replace(/(\d{3})(\d{1,2})$/,'$1-$2');
      }else{
        digits=digits.replace(/(\d{2})(\d)/,'$1.$2').replace(/(\d{3})(\d)/,'$1.$2').replace(/(\d{3})(\d)/,'$1/$2').replace(/(\d{4})(\d{1,2})$/,'$1-$2');
      }
      input.value=digits;
    };
    input.addEventListener('input',apply);apply();
    input.addEventListener('blur',()=>{
      const digits=input.value.replace(/\D/g,'');
      input.setCustomValidity(digits.length===11&&!cpfValid(digits)?'CPF inválido. Verifique o número informado.':'');
    });
  });

  const notificationButton=document.querySelector('.notification-button span');
  if(notificationButton&&notificationButton.textContent.trim()!=='0'&&!liteMotion)notificationButton.closest('.notification-button').classList.add('has-new');

  const reveals=document.querySelectorAll('.reveal');
  if('IntersectionObserver' in window&&!liteMotion){
    const observer=new IntersectionObserver(entries=>entries.forEach(entry=>{
      if(entry.isIntersecting){entry.target.classList.add('is-visible');observer.unobserve(entry.target);}
    }),{threshold:.08,rootMargin:'0px 0px -20px'});
    reveals.forEach(el=>observer.observe(el));
  }else reveals.forEach(el=>el.classList.add('is-visible'));

  if(!liteMotion){
    document.querySelectorAll('[data-parallax-root]').forEach(root=>{
      const items=root.querySelectorAll('[data-parallax]');
      let frame=0;
      root.addEventListener('pointermove',event=>{
        if(frame)return;
        frame=requestAnimationFrame(()=>{
          frame=0;const box=root.getBoundingClientRect();const x=(event.clientX-box.left)/box.width-.5;const y=(event.clientY-box.top)/box.height-.5;
          items.forEach(item=>{const depth=parseFloat(item.dataset.parallax||8);item.style.translate=`${x*depth}px ${y*depth}px`;});
        });
      },{passive:true});
      root.addEventListener('pointerleave',()=>items.forEach(item=>item.style.translate='0 0'));
    });
    document.querySelectorAll('[data-tilt]').forEach(card=>{
      let frame=0;
      card.addEventListener('pointermove',event=>{
        if(frame)return;frame=requestAnimationFrame(()=>{frame=0;const box=card.getBoundingClientRect();const x=(event.clientX-box.left)/box.width;const y=(event.clientY-box.top)/box.height;card.style.setProperty('--mx',`${x*100}%`);card.style.setProperty('--my',`${y*100}%`);card.style.transform=`perspective(900px) rotateX(${(.5-y)*5}deg) rotateY(${(x-.5)*6}deg) translateY(-7px)`;});
      },{passive:true});
      card.addEventListener('pointerleave',()=>card.style.transform='');
    });
  }


  const maskPhone=value=>{let d=(value||'').replace(/\D/g,'');if((d.length===12||d.length===13)&&d.startsWith('55'))d=d.slice(2);d=d.slice(0,11);if(d.length>10)return d.replace(/^(\d{2})(\d{5})(\d{0,4}).*/, '($1) $2-$3');if(d.length>6)return d.replace(/^(\d{2})(\d{4})(\d{0,4}).*/, '($1) $2-$3');if(d.length>2)return d.replace(/^(\d{2})(\d*)/, '($1) $2');return d;};
  document.querySelectorAll('[data-phone-mask],input[name="phone"],input[name="whatsapp"]').forEach(el=>{el.value=maskPhone(el.value);el.addEventListener('input',()=>el.value=maskPhone(el.value));});
  document.querySelectorAll('[data-fill-favorite-address]').forEach(sel=>sel.addEventListener('change',()=>{const form=sel.closest('form'),opt=sel.options[sel.selectedIndex];if(!form||!opt.value)return;form.elements.destination.value=opt.value;if(form.elements.destination_lat)form.elements.destination_lat.value=opt.dataset.lat||'';if(form.elements.destination_lng)form.elements.destination_lng.value=opt.dataset.lng||'';form.dispatchEvent(new Event('address-selected'));}));


  document.querySelectorAll('[data-fulfillment-form]').forEach(form=>{
    const select=form.querySelector('[data-fulfillment-select]');
    const address=form.querySelector('[data-delivery-address]');
    if(!select||!address)return;
    const sync=()=>{const delivery=select.value==='delivery';address.hidden=!delivery;const input=address.querySelector('input');if(input)input.required=delivery;};
    select.addEventListener('change',sync);sync();
  });

  document.querySelectorAll('[data-fulfillment-form]').forEach(form=>{
    const select=form.querySelector('[data-fulfillment-select]');
    const schedule=form.querySelector('[data-pickup-schedule]');
    if(!select||!schedule)return;
    const dateInput=schedule.querySelector('input[name="pickup_date"]');
    const timeInput=schedule.querySelector('[name="pickup_time"]');
    const message=schedule.querySelector('[data-pickup-schedule-message]');
    const allowed=(schedule.dataset.pickupDays||'').split(',').filter(Boolean).map(Number);
    const sync=()=>{
      const active=select.value==='pickup';schedule.hidden=!active;
      if(dateInput)dateInput.required=active;if(timeInput)timeInput.required=active;
      if(!active&&message)message.textContent='';
    };
    const validateDay=()=>{
      if(!dateInput||!dateInput.value||!allowed.length){if(message)message.textContent='';return;}
      const parts=dateInput.value.split('-').map(Number);const day=new Date(parts[0],parts[1]-1,parts[2]).getDay();
      if(!allowed.includes(day)){dateInput.setCustomValidity('A empresa não libera retirada neste dia.');if(message)message.textContent='⚠ A empresa não libera retiradas neste dia.';}
      else{dateInput.setCustomValidity('');if(message)message.textContent='✓ Dia disponível para retirada.';}
    };
    select.addEventListener('change',sync);dateInput?.addEventListener('change',validateDay);sync();validateDay();
  });

  document.querySelectorAll('[data-state-mask],input[name="state"]').forEach(el=>{
    const apply=()=>{el.value=(el.value||'').replace(/[^A-Za-z]/g,'').toUpperCase().slice(0,2);};
    el.addEventListener('input',apply);apply();
  });

  let userPreviewTimer=0;
  document.querySelectorAll('[data-user-id-preview]').forEach(input=>{
    input.setAttribute('maxlength','13');
    input.setAttribute('autocomplete','off');
    input.addEventListener('input',()=>{input.value=(input.value||'').toUpperCase().replace(/[^A-Z0-9-]/g,'').slice(0,13);});
    const group=input.closest('.form-group');
    const output=group?.querySelector('[data-user-preview-output]');
    const driverCard=group?.querySelector('[data-driver-id-card]');
    const lookup=()=>{
      const value=(input.value||'').trim();
      if(driverCard)driverCard.innerHTML='';
      if(output)output.textContent=value?'Localizando usuário...':'Digite o ID para confirmar somente o nome.';
      if(!/^LXU-[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/i.test(value)){if(output&&value)output.textContent='Use o formato LXU-AB7K-9Q2M.';return;}
      const purpose=input.dataset.userPreviewPurpose||'';
      let url='user_lookup.php?id='+encodeURIComponent(value)+(purpose?'&purpose='+encodeURIComponent(purpose):'');
      if(purpose==='delivery'){
        const companyId=input.closest('form')?.elements?.company_id?.value||'';
        if(companyId)url+='&company_id='+encodeURIComponent(companyId);
      }
      if(purpose==='ride_driver'){
        const type=input.closest('form')?.querySelector('[data-ride-type-select]')?.value||'';
        if(type)url+='&ride_type='+encodeURIComponent(type);
      }
      fetch(url,{credentials:'same-origin',headers:{'Accept':'application/json'}})
        .then(r=>r.json()).then(data=>{
          if(data.ok){
            if(output)output.textContent=purpose==='delivery'?(data.message||('Usuário: '+data.name)):('Usuário: '+data.name);
            if(purpose==='delivery'){
              const form=input.closest('form');
              const nameField=form?.querySelector('[data-delivery-client-name]');
              const phoneField=form?.querySelector('[data-delivery-client-phone]');
              const addressField=form?.querySelector('[data-delivery-address]');
              const distanceField=form?.querySelector('[data-delivery-distance]');
              if(nameField)nameField.value=data.name||'';
              if(phoneField&&data.phone)phoneField.value=maskPhone(data.phone||'');
              if(data.authorized){
                if(addressField&&data.address)addressField.value=data.address;
                if(form?.elements?.latitude&&data.lat!==null&&data.lat!==undefined)form.elements.latitude.value=data.lat;
                if(form?.elements?.longitude&&data.lng!==null&&data.lng!==undefined)form.elements.longitude.value=data.lng;
                if(distanceField&&data.distance_km!==null&&data.distance_km!==undefined)distanceField.value=Number(data.distance_km).toFixed(2).replace('.',',');
                if(addressField)addressField.dispatchEvent(new Event('address-selected',{bubbles:true}));
                if(distanceField&&(data.distance_km===null||data.distance_km===undefined||Number(data.distance_km)<=0)&&data.address&&data.company_address){
                  const geocode=async text=>{const r=await fetch('https://nominatim.openstreetmap.org/search?format=jsonv2&limit=1&countrycodes=br&accept-language=pt-BR&q='+encodeURIComponent(text),{headers:{Accept:'application/json'}});const rows=await r.json();return rows&&rows[0]?{lat:parseFloat(rows[0].lat),lng:parseFloat(rows[0].lon)}:null;};
                  const hav=(a,b)=>{const R=6371,toRad=x=>x*Math.PI/180,dLat=toRad(b.lat-a.lat),dLon=toRad(b.lng-a.lng);const v=Math.sin(dLat/2)**2+Math.cos(toRad(a.lat))*Math.cos(toRad(b.lat))*Math.sin(dLon/2)**2;return R*2*Math.atan2(Math.sqrt(v),Math.sqrt(1-v));};
                  (async()=>{try{let a=(Number.isFinite(Number(data.company_lat))&&Number.isFinite(Number(data.company_lng)))?{lat:Number(data.company_lat),lng:Number(data.company_lng)}:await geocode(data.company_address);let b=(Number.isFinite(Number(data.lat))&&Number.isFinite(Number(data.lng)))?{lat:Number(data.lat),lng:Number(data.lng)}:await geocode(data.address);if(!a||!b)return;if(form?.elements?.latitude&&!form.elements.latitude.value)form.elements.latitude.value=b.lat;if(form?.elements?.longitude&&!form.elements.longitude.value)form.elements.longitude.value=b.lng;let km=0;try{const rr=await fetch(`https://router.project-osrm.org/route/v1/driving/${a.lng},${a.lat};${b.lng},${b.lat}?overview=false`);const jj=await rr.json();if(jj.routes&&jj.routes[0])km=jj.routes[0].distance/1000;}catch(e){}if(!(km>0))km=hav(a,b)*1.25;if(km>0)distanceField.value=km.toFixed(2).replace('.',',');}catch(e){}})();
                }
              }else{
                if(addressField)addressField.value='';
                if(form?.elements?.latitude)form.elements.latitude.value='';
                if(form?.elements?.longitude)form.elements.longitude.value='';
                if(distanceField)distanceField.value='';
              }
            }
            if(driverCard&&purpose==='ride_driver'){
              driverCard.innerHTML='';
              const avatarBox=document.createElement('div');avatarBox.className='driver-id-avatar';
              if(data.avatar){const img=document.createElement('img');img.alt='';try{const u=new URL(String(data.avatar),window.location.href);if(u.protocol==='http:'||u.protocol==='https:')img.src=u.href;}catch(e){}if(img.src)avatarBox.appendChild(img);else avatarBox.textContent=String(data.name||'?').trim().charAt(0).toUpperCase();}
              else avatarBox.textContent=String(data.name||'?').trim().charAt(0).toUpperCase();
              const info=document.createElement('div');const strong=document.createElement('strong');strong.textContent=String(data.name||'');const small=document.createElement('small');small.textContent=String(data.role||'');info.append(strong,small);
              const ok=document.createElement('b');ok.textContent='✓ Compatível';driverCard.append(avatarBox,info,ok);driverCard.classList.add('is-valid');
            }
          }else{
            if(output)output.textContent=data.not_allowed?(data.message||'Usuário incompatível.'):'Usuário não encontrado.';
            if(driverCard){driverCard.classList.remove('is-valid');driverCard.innerHTML='';}
          }
        })
        .catch(()=>{if(output)output.textContent='Não foi possível consultar agora.';if(driverCard)driverCard.innerHTML='';});
    };
    input._linkExpressLookup=lookup;
    input.addEventListener('input',()=>{clearTimeout(userPreviewTimer);userPreviewTimer=setTimeout(lookup,350);});
    input.addEventListener('blur',lookup);
    if((input.value||'').trim())setTimeout(lookup,80);
  });

  document.querySelectorAll('[data-ride-type-select]').forEach(typeSelect=>{
    const form=typeSelect.closest('form');const companySelect=form?.querySelector('[data-ride-company-select]');if(!companySelect)return;
    const pickup=form?.querySelector('input[name="pickup"]');
    const hint=form?.querySelector('[data-ride-company-hint]');
    const norm=value=>(value||'').normalize('NFD').replace(/[\u0300-\u036f]/g,'').toLowerCase().trim();
    const sync=()=>{
      const type=typeSelect.value;const location=norm(pickup?.value||'');
      const compatible=Array.from(companySelect.options).filter((opt,index)=>index>0&&opt.dataset.rideType===type);
      const local=compatible.filter(opt=>{const city=norm(opt.dataset.companyCity||'');return city!==''&&location.includes(city);});
      const useLocal=local.length>0;
      Array.from(companySelect.options).forEach((opt,index)=>{
        if(index===0){opt.hidden=false;return;}
        const sameType=opt.dataset.rideType===type;
        const city=norm(opt.dataset.companyCity||'');
        const hide=!sameType||(useLocal&&city!==''&&!location.includes(city));opt.hidden=hide;opt.disabled=hide;
      });
      if(companySelect.selectedOptions[0]?.hidden)companySelect.value='';
      if(hint){
        if(compatible.length===0)hint.textContent='Nenhuma empresa desse tipo foi cadastrada ainda. A corrida continuará aberta para profissionais autônomos.';
        else if(useLocal)hint.textContent=`${local.length} empresa(s) da sua região encontrada(s).`;
        else hint.textContent=`${compatible.length} empresa(s) compatível(is) disponível(is). Use Localizar para priorizar as mais próximas.`;
      }
    };
    typeSelect.addEventListener('change',()=>{sync();const driverInput=form?.querySelector('[data-user-preview-purpose="ride_driver"]');if(driverInput&&driverInput.value&&driverInput._linkExpressLookup)driverInput._linkExpressLookup();});
    pickup?.addEventListener('input',sync);
    pickup?.addEventListener('address-selected',sync);
    form?.addEventListener('location-ready',()=>setTimeout(sync,50));
    sync();
  });

  document.querySelectorAll('[data-fulfillment-select]').forEach(select=>{
    const form=select.closest('form');const address=form?.querySelector('[data-delivery-address]');if(!address)return;
    const sync=()=>{const delivery=select.value==='delivery';address.hidden=!delivery;const input=address.querySelector('input');if(input)input.required=delivery;};
    select.addEventListener('change',sync);sync();
  });

  // Visualizador global de imagens: fotos de perfil, veículos, empresas, imóveis e demais uploads.
  let imageViewer=document.querySelector('[data-image-viewer]');
  const openImageViewer=(src,alt='Imagem')=>{
    if(!src)return;
    if(!imageViewer){
      imageViewer=document.createElement('div');imageViewer.className='image-viewer';imageViewer.dataset.imageViewer='1';
      imageViewer.innerHTML='<button type="button" class="image-viewer-close" aria-label="Fechar">×</button><img alt="">';
      document.body.appendChild(imageViewer);
      imageViewer.addEventListener('click',e=>{if(e.target===imageViewer||e.target.closest('.image-viewer-close'))imageViewer.classList.remove('open');});
    }
    const img=imageViewer.querySelector('img');img.src=src;img.alt=alt||'Imagem';imageViewer.classList.add('open');
  };
  document.addEventListener('click',e=>{
    const img=e.target.closest('img');if(!img||img.closest('.brand')||img.dataset.noZoom==='1'||img.closest('[data-image-viewer]'))return;
    const src=img.currentSrc||img.src;if(!src)return;e.preventDefault();openImageViewer(src,img.alt);
  });

  // Toque duplo rápido em um atalho abre a personalização da própria conta.
  // O primeiro toque aguarda alguns milissegundos; se não houver segundo toque,
  // navega normalmente para o módulo.
  let quickTapTimer=null,quickTapLink=null,quickTapAt=0;
  document.addEventListener('click',e=>{
    const link=e.target.closest('.mobile-floating-actions .quick-action[data-quick-edit-url]');
    if(!link||!link.href||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;
    e.preventDefault();
    const now=Date.now();
    if(quickTapLink===link && now-quickTapAt<=380){
      if(quickTapTimer)clearTimeout(quickTapTimer);quickTapTimer=null;quickTapLink=null;quickTapAt=0;
      window.location.href=link.dataset.quickEditUrl;return;
    }
    if(quickTapTimer)clearTimeout(quickTapTimer);
    quickTapLink=link;quickTapAt=now;
    const icon=link.querySelector('span');if(icon)icon.classList.add('icon-entering');
    quickTapTimer=setTimeout(()=>{window.location.href=link.href;},330);
  });

  // Animações leves dos atalhos: centralizam a atenção sem efeitos pesados no celular.
  document.querySelectorAll('.mobile-nav-card .mobile-nav-icon,.quick-action span').forEach((icon,index)=>{
    icon.style.setProperty('--icon-delay',Math.min(index,12)*28+'ms');
    requestAnimationFrame(()=>icon.classList.add('icon-ready'));
  });
  document.addEventListener('click',e=>{
    const link=e.target.closest('.mobile-nav-card,.mobile-floating-actions .quick-action');
    if(!link||!link.href||e.defaultPrevented||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;
    if(window.matchMedia&&window.matchMedia('(prefers-reduced-motion: reduce)').matches)return;
    const icon=link.querySelector('.mobile-nav-icon,span');
    if(!icon)return;
    e.preventDefault();icon.classList.add('icon-entering');
    setTimeout(()=>{window.location.href=link.href;},160);
  });

  if('serviceWorker' in navigator){window.addEventListener('load',()=>navigator.serviceWorker.register('sw.js?v=2.9.12').catch(()=>{}));}
})();

// LinkExpress 2.9.12 — player do manual com modo flutuante persistente entre páginas.
(function(){
  const storageKey='linkexpress_manual_floating_video';
  function mediaData(shell){const iframe=shell.querySelector('iframe'),video=shell.querySelector('video');return iframe?{kind:'iframe',url:iframe.src,title:iframe.title||'Manual LinkExpress'}:video?{kind:'video',url:video.currentSrc||video.src,title:'Manual LinkExpress'}:null;}
  function addFloatingControls(shell){if(shell.querySelector('[data-manual-close]'))return;const actions=shell.querySelector('.manual-video-actions')||shell.appendChild(document.createElement('div'));actions.classList.add('manual-video-actions');const close=document.createElement('button');close.type='button';close.className='btn btn-danger btn-sm';close.dataset.manualClose='1';close.textContent='× Fechar';actions.appendChild(close);}
  function floatShell(shell,persist=true){if(!shell||shell.classList.contains('manual-video-floating'))return;const data=mediaData(shell);if(!data)return;const placeholder=document.createComment('manual-video-placeholder');shell.parentNode?.insertBefore(placeholder,shell);shell.__manualPlaceholder=placeholder;shell.classList.add('manual-video-floating');document.body.appendChild(shell);addFloatingControls(shell);if(persist)sessionStorage.setItem(storageKey,JSON.stringify(data));}
  function closeFloating(shell){shell.classList.remove('manual-video-floating');sessionStorage.removeItem(storageKey);const close=shell.querySelector('[data-manual-close]');if(close)close.remove();if(shell.__manualPlaceholder?.parentNode){shell.__manualPlaceholder.parentNode.insertBefore(shell,shell.__manualPlaceholder);shell.__manualPlaceholder.remove();}else shell.remove();}
  function restoreFloating(){if(document.querySelector('.manual-video-floating'))return;let data=null;try{data=JSON.parse(sessionStorage.getItem(storageKey)||'null');}catch(e){}if(!data||!/^https:\/\//i.test(String(data.url||'')))return;const shell=document.createElement('div');shell.className='manual-video-shell';shell.dataset.manualVideo='1';if(data.kind==='video'){const video=document.createElement('video');video.src=data.url;video.controls=true;video.playsInline=true;shell.appendChild(video);}else{const frame=document.createElement('iframe');frame.src=data.url;frame.title=data.title||'Manual LinkExpress';frame.allow='autoplay; encrypted-media; picture-in-picture';frame.allowFullscreen=true;shell.appendChild(frame);}const actions=document.createElement('div');actions.className='manual-video-actions';actions.innerHTML='<button class="btn btn-secondary btn-sm" type="button" data-manual-fullscreen>⛶ Tela cheia</button>';shell.appendChild(actions);document.body.appendChild(shell);floatShell(shell,false);}
  document.addEventListener('click',event=>{const floatButton=event.target.closest('[data-manual-float]');if(floatButton){event.preventDefault();const shell=floatButton.closest('[data-manual-video]');if(shell?.classList.contains('manual-video-floating'))closeFloating(shell);else floatShell(shell);return;}const close=event.target.closest('[data-manual-close]');if(close){closeFloating(close.closest('[data-manual-video]'));return;}const full=event.target.closest('[data-manual-fullscreen]');if(full){const shell=full.closest('[data-manual-video]');const video=shell?.querySelector('video');if(video&&document.pictureInPictureEnabled&&video.requestPictureInPicture){video.requestPictureInPicture().catch(()=>shell.requestFullscreen?.());}else shell?.requestFullscreen?.();}});
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',restoreFloating);else restoreFloating();
})();

// V2.8.24: datas horizontais rolam somente dentro da faixa, sem mover/encolher a página.
document.addEventListener('DOMContentLoaded',()=>{
  document.querySelectorAll('[data-auto-scroll-available]').forEach(strip=>{
    const target=strip.querySelector('.date-chip.active')||strip.querySelector('.date-chip[data-available="1"]');
    if(!target)return;
    setTimeout(()=>{
      const left=Math.max(0,target.offsetLeft-(strip.clientWidth-target.offsetWidth)/2);
      if(typeof strip.scrollTo==='function') strip.scrollTo({left,behavior:'smooth'});
      else strip.scrollLeft=left;
    },160);
  });
});


// V2.8.37: exibe somente os campos necessários para o público da notificação.
document.addEventListener('DOMContentLoaded',()=>{
  document.querySelectorAll('[data-notification-audience]').forEach(select=>{
    const form=select.closest('form');if(!form)return;
    const sync=()=>{form.querySelectorAll('[data-notification-field]').forEach(field=>{field.hidden=field.dataset.notificationField!==select.value;});};
    select.addEventListener('change',sync);sync();
  });
});


// V2.8.44: cadastro em duas etapas — mostra apenas segmentos compatíveis com o perfil.
document.addEventListener('DOMContentLoaded',()=>{
  document.querySelectorAll('[data-registration-complete-form]').forEach(form=>{
    const role=form.querySelector('[data-registration-role],input[name="role"]');
    const wrap=form.querySelector('[data-registration-segment-wrap]');
    const segment=form.querySelector('[data-registration-segment]');
    if(!role||!wrap||!segment)return;
    const sync=()=>{
      const current=String(role.value||'client');
      const needsSegment=current!=='client';
      wrap.hidden=!needsSegment;
      wrap.style.display=needsSegment?'':'';
      segment.required=needsSegment;
      let selectedAllowed=false;
      Array.from(segment.options).forEach((opt,index)=>{
        if(index===0){opt.hidden=false;opt.disabled=false;return;}
        const roles=String(opt.dataset.roles||'').split(',').map(v=>v.trim()).filter(Boolean);
        const allowed=roles.includes(current);
        opt.hidden=!allowed;opt.disabled=!allowed;
        if(opt.selected&&allowed)selectedAllowed=true;
      });
      if(!needsSegment)segment.value='';
      else if(segment.value&&!selectedAllowed)segment.value='';
    };
    role.addEventListener('change',sync);sync();
  });

  document.querySelectorAll('[data-service-booking-form]').forEach(form=>{
    const toggle=form.querySelector('[data-service-booking-toggle]');
    const fields=form.querySelector('[data-service-booking-fields]');
    if(!toggle||!fields)return;
    const sync=()=>{
      fields.hidden=!toggle.checked;
      fields.querySelectorAll('input[name="availability_days[]"]').forEach(input=>input.disabled=!toggle.checked);
      fields.querySelectorAll('input[type="time"]').forEach(input=>input.disabled=!toggle.checked);
    };
    toggle.addEventListener('change',sync);sync();
  });

  document.querySelectorAll('[data-service-booking-form]').forEach(form=>{
    const toggle=form.querySelector('[data-service-fixed-toggle]');
    const fields=form.querySelector('[data-service-fixed-fields]');
    if(!toggle||!fields)return;
    const sync=()=>{
      fields.hidden=!toggle.checked;
      const address=fields.querySelector('input[name="fixed_address"]');
      if(address)address.required=toggle.checked;
      fields.querySelectorAll('input,button').forEach(input=>{
        if(input===address)return;
        if(input.matches('input[type="hidden"]'))input.disabled=!toggle.checked;
      });
    };
    toggle.addEventListener('change',sync);sync();
  });
});


// SuperLoja V2.8.47 — elementos públicos surgem suavemente durante o scroll.
(function(){
  function initPublicReveal(){if(!document.body.classList.contains('public-body'))return;var els=document.querySelectorAll('main .section,main .panel,main .service-card,main .premium-service-card,main .premium-plan,main .step,main .market-card');els.forEach(function(el){el.classList.add('public-reveal')});if(!('IntersectionObserver'in window)){els.forEach(function(el){el.classList.add('reveal-visible')});return;}var io=new IntersectionObserver(function(entries){entries.forEach(function(e){if(e.isIntersecting){e.target.classList.add('reveal-visible');io.unobserve(e.target);}})},{threshold:.08,rootMargin:'0px 0px -5% 0px'});els.forEach(function(el){io.observe(el)});}
  function parseMoney(v){return parseFloat(String(v||'').replace(/\./g,'').replace(',','.'))||0}
  function initFeeSim(){document.querySelectorAll('[data-fee-simulator]').forEach(function(box){var input=box.querySelector('[data-fee-sim-amount]'),out=box.querySelector('[data-fee-sim-result]');if(!input||!out)return;function calc(){var amount=Math.max(0,parseMoney(input.value));var tx=0;if(box.dataset.txEnabled==='1'){var tv=parseFloat(box.dataset.txValue||0)||0;tx=box.dataset.txType==='percent'?amount*tv/100:tv;tx=Math.max(0,Math.min(amount,tx));}var wv=parseFloat(box.dataset.withdrawValue||0)||0;var wf=box.dataset.withdrawType==='percent'?amount*wv/100:wv;wf=Math.max(0,Math.min(amount,wf));var payer=box.dataset.feePayer==='provider'?'prestador/empresa':'cliente';var providerNet=box.dataset.feePayer==='provider'?Math.max(0,amount-tx):amount;var clientTotal=box.dataset.feePayer==='client'?amount+tx:amount;var payout=Math.max(0,amount-wf);out.innerHTML='<strong>Transação:</strong> taxa R$ '+tx.toFixed(2).replace('.',',')+' paga por '+payer+' • cliente paga R$ '+clientTotal.toFixed(2).replace('.',',')+' • carteira recebe R$ '+providerNet.toFixed(2).replace('.',',')+'<br><strong>Saque:</strong> tarifa R$ '+wf.toFixed(2).replace('.',',')+' • líquido R$ '+payout.toFixed(2).replace('.',',');}input.addEventListener('input',calc);calc();});}
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',function(){initPublicReveal();initFeeSim();});else{initPublicReveal();initFeeSim();}
})();


// LinkExpress 2.9.07 — botão próprio de instalação para Chrome/PWA.
(function(){
  let deferredInstallPrompt=null;
  const buttons=()=>Array.from(document.querySelectorAll('[data-pwa-install]'));
  const isStandalone=()=>window.matchMedia?.('(display-mode: standalone)').matches||window.navigator.standalone===true;
  const hide=()=>buttons().forEach(btn=>{btn.hidden=true;btn.setAttribute('aria-hidden','true');});
  const show=()=>{if(isStandalone()||!deferredInstallPrompt)return hide();buttons().forEach(btn=>{btn.hidden=false;btn.removeAttribute('aria-hidden');});};
  window.addEventListener('beforeinstallprompt',event=>{
    event.preventDefault();
    deferredInstallPrompt=event;
    show();
  });
  window.addEventListener('appinstalled',()=>{deferredInstallPrompt=null;hide();});
  document.addEventListener('click',async event=>{
    const btn=event.target.closest('[data-pwa-install]');
    if(!btn)return;
    event.preventDefault();
    if(!deferredInstallPrompt){hide();return;}
    const prompt=deferredInstallPrompt;
    deferredInstallPrompt=null;
    hide();
    try{await prompt.prompt();await prompt.userChoice;}catch(e){}
  });
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',()=>{if(isStandalone())hide();});else if(isStandalone())hide();
})();
