(function(){"use strict";if(window.__ZV_WPP_BRIDGE_LOADED__)return;window.__ZV_WPP_BRIDGE_LOADED__=!0;const S=3e4,b=500,P=12e4,A=()=>localStorage.getItem("zvWppBridgeDebug")==="1",l=(...t)=>{A()&&console.log("[ZV:WppBridge]",...t)};function w(){try{const t=document.z_v_debug;if(typeof t=="function")return t()}catch(t){l("getDebug",t)}return null}function p(){try{const t=w();if(t?.WPP?.chat?.list)return t.WPP}catch(t){l("getWppApi",t)}return null}function E(){try{const t=w();if(t?.WAPI)return t.WAPI;if(window.WAPI?.ChatStore)return window.WAPI}catch{}return null}function d(t){const e=t?.id;return e?typeof e=="string"?e:typeof e.toString=="function"?e.toString():e._serialized?String(e._serialized):e.user&&e.server?e.user+"@"+e.server:String(e):""}function I(t){return t?.name||t?.formattedTitle||t?.contact?.name||t?.contact?.formattedName||d(t)||"Grupo"}function W(t,e){const r=d(t);if(!r)return!1;if(t.isGroup===!0||r.includes("@g.us"))return!0;try{if(e?.Wid?.isGroup&&e.Wid.isGroup(r))return!0}catch{}try{if(e?.getIsGroup&&t.contact&&e.getIsGroup(t.contact))return!0}catch{}return!1}function u(t,e){try{document.documentElement.setAttribute(t,e)}catch{}}function h(t,e,r,n){u("data-zv-groups",JSON.stringify(t||[])),u("data-zv-labels",JSON.stringify(e||[])),u("data-zv-wpp-ready",r?"1":"0"),u("data-zv-groups-count",String((t||[]).length)),r&&u("data-zv-wpp-bridge-ts",String(Date.now())),n&&u("data-zv-wpp-bridge-status",JSON.stringify(n))}async function z(t){const e=E(),r=new Set,n=[];function s(o){if(!o||!W(o,e))return;const a=d(o);!a||r.has(a)||(r.add(a),n.push({id:a,name:I(o)}))}const f=[async()=>{(await t.chat.list({onlyGroups:!0})||[]).forEach(s)},async()=>{(await t.chat.list()||[]).forEach(s)},async()=>{const o=e?.ChatStore;o?.getModelsArray&&o.getModelsArray().forEach(s)}];for(const o of f){if(n.length>0)break;try{await o()}catch(a){l("loadGroups strategy",a)}}return n.sort((o,a)=>o.name.localeCompare(a.name,"pt-BR"))}async function D(t){const e=[];try{t.labels?.getAllLabelsWithChatAssociations&&(await t.labels.getAllLabelsWithChatAssociations()).forEach(n=>e.push({id:String(n.id),name:n.name||String(n.id)}))}catch(r){l("loadLabels",r)}return e}let v=!1;async function y(){if(v)return!1;v=!0;try{const t=p();if(!t)return h([],[],!1,{phase:"waiting",reason:"z_v_debug indispon\xEDvel"}),!1;const[e,r]=await Promise.all([z(t),D(t)]);h(e,r,!0,{phase:"ready",groups:e.length,labels:r.length,at:Date.now()}),l("cache",e.length,"grupos",r.length,"etiquetas");try{document.dispatchEvent(new CustomEvent("zv:groups-updated"))}catch{}try{const n=t.chat?.getActiveChat?.(),s=d(n);s&&u("data-zv-active-chat",s)}catch{}return!0}catch(t){return l("refreshCache",t),h([],[],!1,{phase:"error",reason:t?.message||String(t)}),!1}finally{v=!1}}async function _(t){try{const e=p(),r=d(t)||String(t||"");if(r.includes("@lid")&&e?.contact?.getPnLidEntry){const s=await e.contact.getPnLidEntry(r),f=s?.phoneNumber?._serialized||s?.phoneNumber?.user;if(f)return String(f).replace(/\D/g,"")}const n=t?.id?.user||r.split("@")[0];return String(n).replace(/\D/g,"")}catch{return""}}async function L(t){const e=t?.requestId||"default",r={ok:!1,contacts:[],error:null};try{const n=p();if(!n)throw new Error("WPP n\xE3o dispon\xEDvel");const s=t?.mode,f=new Set,o=[],a=(i,c)=>{!i||i.length<8||f.has(i)||(f.add(i),o.push({number:i,name:c||i}))};if(s==="labels"&&t?.labelIds?.length){const i=await n.chat.getAllChatsByLabels(t.labelIds.map(Number));for(const c of i){const g=await _(c.contact||c.id);a(g,c.name||c.formattedTitle||g)}}else if(s==="groups"&&t?.groupIds?.length)for(const i of t.groupIds){let c=[];n.group?.getParticipants?c=await n.group.getParticipants(i):n.group?.ensureGroup&&(c=(await n.group.ensureGroup(i))?.groupMetadata?.participants?.getModelsArray?.()||[]);let g=0;for(const m of c){g+=1;const M=await _(m);a(M,(t?.prefix||"")+"_"+g)}}else throw new Error("Modo de exporta\xE7\xE3o inv\xE1lido");r.ok=!0,r.contacts=o}catch(n){r.error=n?.message||String(n)}return u("data-zv-export-result-"+e,JSON.stringify(r)),r}document.addEventListener("zv:req-refresh-groups",()=>{y()}),document.addEventListener("zv:req-export",t=>{L(t?.detail||{})});function G(){const t=Date.now(),e=setInterval(async()=>{const r=p();if(r){clearInterval(e),C(r),await y(),setInterval(y,S);return}Date.now()-t>=P&&(clearInterval(e),h([],[],!1,{phase:"timeout",reason:"WPP n\xE3o ficou pronto em 120s"}))},b)}function C(t){try{t?.ev?.addListener&&t.ev.addListener("conn.main_ready",()=>y())}catch{}}G(),l("ativo v2 \u2014 z_v_debug + multi-strategy grupos")})();
