var MetaCAPIModule=function(t){"use strict";var e=function(){return e=Object.assign||function(t){for(var e,o=1,n=arguments.length;o<n;o++)for(var r in e=arguments[o])Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t},e.apply(this,arguments)};function o(t,e,o,n){return new(o||(o=Promise))(function(r,i){function a(t){try{s(n.next(t))}catch(t){i(t)}}function c(t){try{s(n.throw(t))}catch(t){i(t)}}function s(t){var e;t.done?r(t.value):(e=t.value,e instanceof o?e:new o(function(t){t(e)})).then(a,c)}s((n=n.apply(t,e||[])).next())})}function n(t,e){var o,n,r,i={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=c(0),a.throw=c(1),a.return=c(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function c(c){return function(s){return function(c){if(o)throw new TypeError("Generator is already executing.");for(;a&&(a=0,c[0]&&(i=0)),i;)try{if(o=1,n&&(r=2&c[0]?n.return:c[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,c[1])).done)return r;switch(n=0,r&&(c=[2&c[0],r.value]),c[0]){case 0:case 1:r=c;break;case 4:return i.label++,{value:c[1],done:!1};case 5:i.label++,n=c[1],c=[0];continue;case 7:c=i.ops.pop(),i.trys.pop();continue;default:if(!(r=i.trys,(r=r.length>0&&r[r.length-1])||6!==c[0]&&2!==c[0])){i=0;continue}if(3===c[0]&&(!r||c[1]>r[0]&&c[1]<r[3])){i.label=c[1];break}if(6===c[0]&&i.label<r[1]){i.label=r[1],r=c;break}if(r&&i.label<r[2]){i.label=r[2],i.ops.push(c);break}r[2]&&i.ops.pop(),i.trys.pop();continue}c=e.call(t,i)}catch(t){c=[6,t],n=0}finally{o=r=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,s])}}}function r(t,e,o){if(o||2===arguments.length)for(var n,r=0,i=e.length;r<i;r++)!n&&r in e||(n||(n=Array.prototype.slice.call(e,0,r)),n[r]=e[r]);return t.concat(n||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError;var i,a=function(){function t(){this.queue=[],this.processing=!1,this.initialized=!1,this.WEBHOOK_URL="https://n8nid360.onrender.com/webhook/capi-setin",this.X_API_KEY="GIHQ&VjEtdOgqiJpLNxXW7mrfD",this.config={clientId:"",debug:!1,flushDelay:1500}}return t.prototype.init=function(t){this.initialized?this.log("Tracker já inicializado"):("string"==typeof t?this.config.clientId=t:this.config=e(e({},this.config),t),this.config.clientId?(this.initialized=!0,this.log("Tracker inicializado:",this.config.clientId),this.captureFbclid(),this.startFlushTimer(),this.setupUnloadHandler()):this.logError("clientId é obrigatório"))},t.prototype.track=function(t){return o(this,arguments,void 0,function(t,e,o){var r;return void 0===e&&(e={}),n(this,function(n){switch(n.label){case 0:return this.initialized?[4,this.createEvent(t,e,o)]:(this.logError("Tracker não inicializado. Chame init() primeiro."),[2]);case 1:return r=n.sent(),this.addToQueue(r),this.log("Evento ".concat(t," adicionado à fila")),[2]}})})},t.prototype.trackSync=function(t,e,o){var n=this;void 0===e&&(e={}),this.initialized?this.track(t,e,o).catch(function(t){n.log("Erro no track assíncrono:",t)}):this.logError("Tracker não inicializado. Chame init() primeiro.")},t.prototype.debug=function(){return this.getDebugInfo()},t.prototype.captureFbclidFromUrl=function(){var t=new URLSearchParams(window.location.search).get("fbclid");return t?(this.captureFbclid(),this.log("FBCLID capturado manualmente:",t),!0):(this.log("Nenhum FBCLID encontrado na URL"),!1)},t.prototype.waitForPixelData=function(){return o(this,void 0,void 0,function(){var t;return n(this,function(e){switch(e.label){case 0:return t={},[4,this.waitForFBP()];case 1:return[2,(t.fbp=e.sent(),t.fbc=this.getFBC(),t)]}})})},t.prototype.pageView=function(){return o(this,arguments,void 0,function(t){return void 0===t&&(t={}),n(this,function(e){switch(e.label){case 0:return[4,this.track("PageView",t)];case 1:return e.sent(),[2]}})})},t.prototype.viewContent=function(t){return o(this,void 0,void 0,function(){return n(this,function(e){switch(e.label){case 0:return[4,this.track("ViewContent",t)];case 1:return e.sent(),[2]}})})},t.prototype.createEvent=function(t,r,i){return o(this,void 0,void 0,function(){var o,a,c,s,u;return n(this,function(n){switch(n.label){case 0:return this.captureFbclid(),o=this.getHubIdUserData(),[4,this.processUserData(o)];case 1:return a=n.sent(),this.config.debug&&(c=this.getDebugInfo(),this.log("Debug Info:",c)),s={event_name:t,event_time:Math.floor(Date.now()/1e3)-30,event_id:i||this.generateId(t),event_source_url:window.location.href,action_source:"website"},u={client_user_agent:navigator.userAgent},[4,this.waitForFBP()];case 2:return[2,(s.user_data=e.apply(void 0,[(u.fbp=n.sent(),u.fbc=this.getFBC(),u),a]),s.custom_data=e(e({page_title:document.title,referrer:document.referrer},this.getUTMParams()),r),s._meta={client_id:this.config.clientId,domain:window.location.hostname,timestamp:Date.now()},s)]}})})},t.prototype.addToQueue=function(t){this.queue.push(t),this.log("Evento adicionado:",t.event_name)},t.prototype.processQueue=function(){return o(this,void 0,void 0,function(){var t,e,o,r,i;return n(this,function(n){switch(n.label){case 0:if(this.processing||0===this.queue.length)return[2];this.processing=!0,t=this.queue.splice(0,10),n.label=1;case 1:return n.trys.push([1,3,4,5]),e={client_id:this.config.clientId,domain:window.location.hostname,events:t},[4,fetch(this.WEBHOOK_URL,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":this.X_API_KEY},body:JSON.stringify(e),keepalive:!0})];case 2:if(!(o=n.sent()).ok)throw new Error("HTTP ".concat(o.status));return this.log("".concat(t.length," eventos enviados")),[3,5];case 3:return r=n.sent(),(i=this.queue).unshift.apply(i,t),this.logWarn("Falha ao enviar eventos:",r),[3,5];case 4:return this.processing=!1,[7];case 5:return[2]}})})},t.prototype.startFlushTimer=function(){var t=this,e=function(){t.processQueue(),t.flushTimer=setTimeout(e,t.config.flushDelay)};e()},t.prototype.setupUnloadHandler=function(){var t=this;window.addEventListener("beforeunload",function(){if(t.queue.length>0){var e={client_id:t.config.clientId,domain:window.location.hostname,events:t.queue};navigator.sendBeacon(t.WEBHOOK_URL,JSON.stringify(e))}})},t.prototype.generateId=function(t){var e=window.location.pathname.replace(/[^a-zA-Z0-9]/g,"-").replace(/-+/g,"-").replace(/(?:^-|-$)/g,"")||"home";return"".concat(Date.now().toString(36),"_").concat(t,"_").concat(e)},t.prototype.getCookie=function(t){var e=new RegExp("(^| )"+t+"=([^;]+)").exec(document.cookie);return e&&"string"==typeof e[2]?e[2]:null},t.prototype.getUTMParams=function(){var t={},e=new URLSearchParams(window.location.search);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(function(o){var n=e.get(o);n&&(t[o]=n)}),t},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.config.debug&&console.log.apply(console,r(["[MetaCAPI]"],t,!1))},t.prototype.logError=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];console.error.apply(console,r(["[MetaCAPI]"],t,!1))},t.prototype.logWarn=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];console.warn.apply(console,r(["[MetaCAPI]"],t,!1))},t.prototype.sha256=function(t){return o(this,void 0,void 0,function(){var e,o,r,i,a,c,s;return n(this,function(n){switch(n.label){case 0:if(!(e=t.trim().toLowerCase()))return[2,""];n.label=1;case 1:return n.trys.push([1,3,,4]),o=new TextEncoder,r=o.encode(e),[4,crypto.subtle.digest("SHA-256",r)];case 2:return i=n.sent(),a=Array.from(new Uint8Array(i)),c=a.map(function(t){return t.toString(16).padStart(2,"0")}).join(""),this.log('Hash gerado para "'.concat(e.substring(0,3),'...": ').concat(c.substring(0,8),"...")),[2,c];case 3:return s=n.sent(),this.logWarn("Erro ao gerar hash SHA-256:",s),[2,""];case 4:return[2]}})})},t.prototype.processUserData=function(t){return o(this,void 0,void 0,function(){var e,o,r,i,a,c,s,u,l,d,h;return n(this,function(n){switch(n.label){case 0:e={},n.label=1;case 1:return n.trys.push([1,10,,11]),t.email?(o=e,[4,this.sha256(t.email)]):[3,3];case 2:o.em=n.sent(),n.label=3;case 3:return t.phone&&(r=t.phone.replace(/[^\d]/g,""))?(i=e,[4,this.sha256(r)]):[3,5];case 4:i.ph=n.sent(),n.label=5;case 5:return t.name?(a=t.name.split(" ")[0],c=e,[4,this.sha256(a)]):[3,7];case 6:c.fn=n.sent(),n.label=7;case 7:return(null===(h=t.name)||void 0===h?void 0:h.includes(" "))&&(s=t.name.split(" ")).length>1?(u=s[s.length-1],l=e,[4,this.sha256(u)]):[3,9];case 8:l.ln=n.sent(),n.label=9;case 9:return this.log("Dados do usuário processados:",{emailHash:e.em?e.em.substring(0,8)+"...":"não disponível",phoneHash:e.ph?e.ph.substring(0,8)+"...":"não disponível",firstNameHash:e.fn?e.fn.substring(0,8)+"...":"não disponível",lastNameHash:e.ln?e.ln.substring(0,8)+"...":"não disponível"}),[2,e];case 10:return d=n.sent(),this.logWarn("Erro ao processar dados do usuário:",d),[2,{}];case 11:return[2]}})})},t.prototype.areCookiesEnabled=function(){try{var t="__test_cookie__";document.cookie="".concat(t,"=test; path=/");var e=-1!==document.cookie.indexOf(t);return e&&(document.cookie="".concat(t,"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/")),e}catch(t){return this.log("Erro ao verificar cookies:",t),!1}},t.prototype.captureFbclid=function(){var t=new URLSearchParams(window.location.search).get("fbclid");if(t)try{var e=Math.floor(Date.now()/1e3),o="fb.1.".concat(e,".").concat(t),n=new Date;n.setDate(n.getDate()+7),document.cookie="_fbc=".concat(o,"; expires=").concat(n.toUTCString(),"; domain=.setin.com.br; path=/");try{sessionStorage.setItem("_fbc_fallback",o)}catch(t){this.logWarn("Erro ao salvar FBC no sessionStorage:",t)}this.log("FBCLID capturado e FBC criado:",o)}catch(e){this.logWarn("Erro ao salvar fbclid:",e);try{sessionStorage.setItem("_fbclid_fallback",t),sessionStorage.setItem("_fbclid_timestamp",Date.now().toString())}catch(t){this.logWarn("Erro no fallback para sessionStorage:",t)}}},t.prototype.waitForFBP=function(){return o(this,void 0,void 0,function(){var t,e,o,r;return n(this,function(n){switch(n.label){case 0:t=5e3,e=100,o=Date.now(),n.label=1;case 1:return Date.now()-o<t?(r=this.getCookie("_fbp"))?(this.log("FBP encontrado:",r),[2,r]):[4,new Promise(function(t){return setTimeout(t,e)})]:[3,3];case 2:return n.sent(),[3,1];case 3:return this.log("FBP não encontrado após timeout, usando fallback"),[2,this.getFbpFallback()]}})})},t.prototype.getFbpFallback=function(){if(!this.areCookiesEnabled())return this.logWarn("Cookies bloqueados - não é possível gerar FBP"),null;try{var t="fb.1.".concat(Math.floor(Date.now()/1e3),".").concat(Math.random().toString(36).substring(2,11));return this.log("FBP temporário gerado:",t),t}catch(t){return this.logWarn("Erro ao gerar FBP temporário:",t),null}},t.prototype.getFBC=function(){var t=this.getCookie("_fbc");if(t)return this.log("FBC encontrado no cookie:",t),t;try{if(t=sessionStorage.getItem("_fbc_fallback"))return this.log("FBC encontrado no sessionStorage:",t),t}catch(t){this.logWarn("Erro ao acessar sessionStorage para FBC:",t)}return(t=this.buildFbc())?(this.log("FBC construído do fbclid do localStorage:",t),t):(t=this.buildFbcFromSession())?(this.log("FBC construído do fbclid do sessionStorage:",t),t):(this.log("FBC não disponível em nenhum fallback"),null)},t.prototype.buildFbcFromSession=function(){try{var t=sessionStorage.getItem("_fbclid_fallback"),e=sessionStorage.getItem("_fbclid_timestamp");if(!t||!e)return null;var o=Math.floor(parseInt(e)/1e3);return"fb.1.".concat(o,".").concat(t)}catch(t){return this.logWarn("Erro ao construir FBC do sessionStorage:",t),null}},t.prototype.buildFbc=function(){try{var t=localStorage.getItem("_fbclid"),e=localStorage.getItem("_fbclid_timestamp");if(!t||!e)return null;if(Date.now()-parseInt(e)>6048e5)return localStorage.removeItem("_fbclid"),localStorage.removeItem("_fbclid_timestamp"),null;var o=Math.floor(parseInt(e)/1e3);return"fb.1.".concat(o,".").concat(t)}catch(t){return this.logWarn("Erro ao construir FBC:",t),null}},t.prototype.getHubIdUserData=function(){try{var t=this.getCookie("hubid_user");if(!t)return{};var e=atob(t),o=JSON.parse(e);return this.log("Dados do usuário extraídos:",o),o}catch(t){return this.logWarn("Erro ao extrair dados do usuário:",t),{}}},t.prototype.getDebugInfo=function(){var t=this.areCookiesEnabled(),e=this.getCookie("_fbp"),o=this.getCookie("_fbc"),n=new URLSearchParams(window.location.search).has("fbclid"),r=!!localStorage.getItem("_fbclid"),i=this.getHubIdUserData();return{cookiesEnabled:t,fbpFound:!!e,fbcFound:!!o,fbclidInUrl:n,fbclidInStorage:r,hubidUserFound:Object.keys(i).length>0,userDataExtracted:i}},t}(),c={clientId:"",debug:!1,flushDelay:1500,autoInit:!0};function s(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];(window.TRACKER_CONFIG||c).debug&&console.log.apply(console,r(["[MetaCAPI]"],t,!1))}function u(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];console.error.apply(console,r(["[MetaCAPI]"],t,!1))}var l=!1,d=!1;function h(){return i}function f(){return o(this,void 0,void 0,function(){var t;return n(this,function(o){if(l)return s("Inicialização já em andamento, aguardando..."),[2,i];if(i)return[2,i];l=!0;try{return(t=e(e({},c),window.TRACKER_CONFIG)).clientId?((i=new a).init(t),s("Tracker inicializado com clientId:",t.clientId),[2,i]):(u("clientId é obrigatório. Defina window.TRACKER_CONFIG.clientId ou use data-client-id"),u('Exemplo: window.TRACKER_CONFIG = { clientId: "SEU_CLIENT_ID_AQUI" };'),[2,null])}finally{l=!1}return[2]})})}function p(){return o(this,void 0,void 0,function(){var t,o,r;return n(this,function(n){switch(n.label){case 0:if(d)return s("Init já foi executado, ignorando..."),[2];d=!0,n.label=1;case 1:return n.trys.push([1,3,,4]),(t=document.currentScript)&&(o=t.getAttribute("data-client-id"))&&!(null===(r=window.TRACKER_CONFIG)||void 0===r?void 0:r.clientId)&&(window.TRACKER_CONFIG=e(e({},window.TRACKER_CONFIG),{clientId:o})),[4,f()];case 2:return n.sent(),function(){if(window.metaCAPIQueue&&Array.isArray(window.metaCAPIQueue)){var t=window.metaCAPIQueue;window.metaCAPIQueue=[],t.forEach(function(t){var e,o=t.method,n=t.args;if(i&&"function"==typeof i[o])try{(e=i)[o].apply(e,n)}catch(t){u("Erro ao processar comando da fila:",t)}})}if(window._metaCAPIQueue&&Array.isArray(window._metaCAPIQueue)){s("Processando fila do stub anti-race condition...");var e=window._metaCAPIQueue;window._metaCAPIQueue=[],e.forEach(function(t){var e,o=t.method,n=t.args;if(t.timestamp,i&&"function"==typeof i[o])try{s("Executando comando do stub: ".concat(o),n),(e=i)[o].apply(e,n)}catch(t){u("Erro ao processar comando do stub:",t)}})}}(),[3,4];case 3:return u("Erro na inicialização:",n.sent()),[3,4];case 4:return[2]}})})}if("undefined"!=typeof window){console.log("[INDEX] Criando MetaCAPI proxy..."),console.log("[INDEX] Document readyState:",document.readyState),console.log("[INDEX] Funções disponíveis:",{init:typeof p,getTracker:typeof h});var g=p,b=h;window.MetaCAPI=new Proxy({},{get:function(t,e){try{var o=String(e);if(console.log("[INDEX-PROXY] Acessando: ".concat(o)),"__debug"===o)return function(){var t=b();return{hasTracker:!!t,tracker:t,methods:t?Object.getOwnPropertyNames(Object.getPrototypeOf(t)):[]}};if("init"===o)return console.log("[INDEX-PROXY] Retornando função init"),g;var n=b();return n&&"function"==typeof n[e]?(console.log("[INDEX-PROXY] Retornando método ".concat(o," do tracker")),n[e].bind(n)):(console.log("[INDEX-PROXY] Tracker não disponível, criando wrapper para ".concat(o)),function(){for(var t,n,r,i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];console.log("[INDEX-PROXY] Executando wrapper para ".concat(o));var c=b();if(c&&"function"==typeof c[e])return console.log("[INDEX-PROXY] Tracker agora disponível, executando ".concat(o)),(t=c)[e].apply(t,i);console.log("[INDEX-PROXY] Adicionando ".concat(o," à fila")),null!==(n=(r=window).metaCAPIQueue)&&void 0!==n||(r.metaCAPIQueue=[]),window.metaCAPIQueue.push({method:o,args:i})})}catch(t){return console.error("[INDEX-PROXY] Erro no get handler para ".concat(String(e),":"),t),function(){console.error("[INDEX-PROXY] Função ".concat(String(e)," não disponível devido a erro"))}}}}),"complete"===document.readyState||"interactive"===document.readyState?g():document.addEventListener("DOMContentLoaded",g)}return t.getTracker=h,t.init=p,t}({});