/* FLOWhatsapp v1.5 pt-BR default patch */
(()=>{const k="flowhatsapp_ptbr_default_migrated_v15",d="pt";try{const c=globalThis.chrome;function m(v,x){return!v||(!x&&/^en([_-]|$)?/i.test(String(v)))}c&&c.storage&&c.storage.local&&c.storage.local.get(["wa_language","wa_ui_language",k],r=>{const p={};if(m(r?.wa_language,r?.[k]))p.wa_language=d;if(m(r?.wa_ui_language,r?.[k]))p.wa_ui_language=d;if(!r?.[k])p[k]=true;if(Object.keys(p).length)c.storage.local.set(p)})}catch(e){}})();
try{importScripts("flowhatsapp-license-config.js","flowhatsapp-license-service.js")}catch(e){console.warn("FLOWhatsapp license service unavailable",e)}
/* FLOWhatsapp trial bootstrap patch:start */
/* FLOWhatsapp trial bootstrap patch */
(() => {
  "use strict";

  const INSTALL_KEY = "flowhatsapp_install_state";
  const LAST_PHONE_KEY = "flowhatsapp_last_detected_phone";
  const LAST_STATUS_KEY = "flowhatsapp_license_status";
  const LAST_CHECK_KEY = "flowhatsapp_trial_last_check";
  const CHECK_THROTTLE_MS = 5 * 60 * 1000;
  let lastCheckAt = 0;

  const runtime = globalThis.chrome && chrome.runtime;
  const storage = globalThis.chrome && chrome.storage && chrome.storage.local;
  if (!runtime || !storage) return;

  function storageSet(values) {
    return storage.set(values);
  }

  async function ensureLicensedCore(sender) {
    const tabId = sender?.tab?.id;
    const url = String(sender?.url || sender?.tab?.url || '');
    if (!tabId) return;
    const isWhatsApp = /^https:\/\/[^/]*whatsapp\.com\//i.test(url);
    const isMaps = /^https:\/\/[^/]*google\.com\/maps/i.test(url);
    if (!isWhatsApp && !isMaps) return;
    const marker = isMaps ? '__FLOWHATSAPP_MAPS_CORE_LOADED__' : '__FLOWHATSAPP_CORE_LOADED__';
    const target = { tabId };
    const state = await chrome.scripting.executeScript({
      target,
      func: (key) => Boolean(globalThis[key]),
      args: [marker]
    });
    if (state?.[0]?.result) return;
    await chrome.scripting.executeScript({ target, func: (key) => { globalThis[key] = true; }, args: [marker] });
    try {
      await chrome.scripting.executeScript({
        target,
        files: isMaps ? ['gmapsEarly.bundle.js', 'gmapsContent.bundle.js'] : ['contentScript.bundle.js']
      });
    } catch (error) {
      await chrome.scripting.executeScript({ target, func: (key) => { delete globalThis[key]; }, args: [marker] }).catch(() => {});
      throw error;
    }
  }

  async function ensureTrialForPhone(phoneNumber, force, sender, explicitMachineId) {
    const phone = String(phoneNumber || "").trim();
    const service = globalThis.FLOWhatsappLicenseService;
    // Trials are always bound to the fingerprint generated in the WhatsApp
    // content context. Never mint one from the service-worker fallback ID.
    const machineId = String(explicitMachineId || '').toLowerCase();
    if (!phone || !/^[a-f0-9]{24,64}$/.test(machineId) || !service || !service.configured || !service.getStatus) return null;
    if (!service.configured()) return null;

    const now = Date.now();
    const storedCheck = await new Promise((resolve) => {
      storage.get([LAST_CHECK_KEY], (result) => resolve(result?.[LAST_CHECK_KEY] || null));
    });
    const storedAt = Number(storedCheck?.checkedAt || 0);
    const samePhone = storedCheck?.phone === phone;
    const mostRecentCheck = Math.max(lastCheckAt, samePhone ? storedAt : 0);
    if (!force && now - mostRecentCheck < CHECK_THROTTLE_MS) {
      const cachedStatus = await service.getStatus(machineId);
      if (cachedStatus?.isValid || cachedStatus?.lastStatus?.isValid) await ensureLicensedCore(sender);
      return cachedStatus;
    }
    lastCheckAt = now;

    const status = await service.getStatus(machineId);
    await storageSet({
      [LAST_PHONE_KEY]: phone,
      [LAST_STATUS_KEY]: status,
      [LAST_CHECK_KEY]: { phone, checkedAt: now }
    });

    // Never reload WhatsApp as part of automatic license/trial detection.
    // Injecting the licensed core in-place avoids a reload loop when the MV3
    // service worker is suspended and started again.
    if (status?.isValid) await ensureLicensedCore(sender);
    return status;
  }

  runtime.onInstalled.addListener((details) => {
    storageSet({
      [INSTALL_KEY]: {
        reason: details.reason,
        installedAt: Date.now(),
        appName: "FLOWhatsapp",
        appVersion: "2.4.5"
      }
    }).catch(() => {});
  });

  runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message && message.action === "phoneDetected" && message.phoneNumber) {
      // A phone number is not a machine identity. The content bridge starts
      // the server-side trial with its explicit fingerprint.
      storageSet({ [LAST_PHONE_KEY]: String(message.phoneNumber).trim() }).catch(() => {});
      return undefined;
    }

    if (message && message.type === "FLOWHATSAPP_FORCE_LICENSE_CHECK") {
      ensureTrialForPhone(message.phoneNumber, true, sender, message.machineId)
        .then((status) => sendResponse({ success: true, status }))
        .catch((error) => sendResponse({ success: false, error: error.message || String(error) }));
      return true;
    }

    if (message && typeof message.type === "string" && message.type.startsWith("FLOWHATSAPP_LICENSE_")) {
      const service = globalThis.FLOWhatsappLicenseService;
      if (!service) {
        sendResponse({ transportError: "Serviço de licença indisponível." });
        return undefined;
      }
      let operation;
      switch (message.type) {
        case "FLOWHATSAPP_LICENSE_GET_STATE": operation = service.getStatus(message.machineId); break;
        case "FLOWHATSAPP_LICENSE_ACTIVATE": operation = service.activate(message.key, null, message.machineId); break;
        case "FLOWHATSAPP_LICENSE_TRIAL": operation = service.requestTrial(null, message.machineId, {
          name: message.leadName || '', contact: message.leadContact || ''
        }); break;
        case "FLOWHATSAPP_LICENSE_PUBLIC_CONFIG": operation = service.publicConfig(); break;
        case "FLOWHATSAPP_LICENSE_ACCESS_TOKEN": operation = service.getAccessToken(); break;
        case "FLOWHATSAPP_LICENSE_HEARTBEAT": operation = service.reportHeartbeat(message); break;
        case "FLOWHATSAPP_LICENSE_DEACTIVATE": operation = service.deactivate(); break;
        default:
          sendResponse({ transportError: "Operação de licença desconhecida." });
          return undefined;
      }
      Promise.resolve(operation)
        .then(async (result) => {
          if (result?.valid === true) await ensureLicensedCore(sender);
          if (message.type === "FLOWHATSAPP_LICENSE_DEACTIVATE" && sender?.tab?.id) {
            await chrome.tabs.reload(sender.tab.id).catch(() => {});
          }
          sendResponse({ result });
        })
        .catch((error) => sendResponse({ transportError: error.message || String(error) }));
      return true;
    }

    return undefined;
  });
})();
/* FLOWhatsapp trial bootstrap patch:end */
(()=>{var e={4042(e,t,a){"use strict";a.d(t,{GM:()=>w,Iy:()=>y,M0:()=>m,Pk:()=>b,YZ:()=>p,_K:()=>A,createValidationToken:()=>_,decryptLicenseFromStorage:()=>f,encryptLicenseForStorage:()=>h,getWasmExpectedHash:()=>T,hashPhoneNumber:()=>g,zW:()=>l});var s=a(6815),n=a.n(s),r=a(1319);const i=6e5,o=18e5;let c=null,d=null;async function l(){if(!c)try{self.__WASM_BASE_URL__=n().runtime.getURL("./");/* FLOWhatsapp v2.0: WASM replaced by Firebase */ c={validateLicense:async(sig)=>{const status=await self.FLOWhatsappLicenseService?.check(false);return Boolean(status?.isValid)}},d=null}catch(e){throw e}}async function u(e,t){c||await l();try{const a=JSON.stringify(e),s=c.validate_offline(a,t);return JSON.parse(s)}catch(e){return{valid:!1,message:"Validation error: "+e.message,expires_in_days:null,validation_level:"error",features_enabled:[],last_validated:Math.floor(Date.now()/1e3)}}}async function m(e,t,a=!1){const s=await u(e,t);if(!s.valid)return s;const m=await async function(){return(await n().storage.local.get(["last_validation"])).last_validation||0}(),p=Date.now(),h=p-m;if(!a&&m>0&&h<o){Math.floor((o-h)/6e4);return s}try{const a=await async function(e,t){c||await l();try{const a=await u(e,t);if(!a.valid)return a;if(!d){const e=n().runtime.id,t=`${e}|unknown|unknown|unknown|unknown|unknown|unknown`,a={device_uuid:e,extension_id:e,browser_version:"unknown",os_platform:"unknown",screen_resolution:"unknown",timezone:"unknown",language:"unknown",fingerprint_hash:await g(t)};d=JSON.stringify(a)}const s=JSON.stringify(e),i=c.prepare_server_validation_v2(s,t,d),o=JSON.parse(i),{shared_secret:l,...m}=o,p=(0,r.lW)(),h=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)});if(!h.ok){const e=await h.text();throw new Error(`Server returned ${h.status}: ${e}`)}const f=await h.json(),w=JSON.stringify(f),A=c.decrypt_server_response(w,l,s);return JSON.parse(A)}catch(a){return await u(e,t)}}(e,t);return a.valid&&await async function(e){await n().storage.local.set({last_validation:e})}(Date.now()),a}catch(e){if(m>0&&h<i){Math.floor((i-h)/6e4);return s}return{valid:!1,message:"Online validation required. Please check your internet connection and try again.",expires_in_days:null,validation_level:"blocked",features_enabled:[],last_validated:Math.floor(p/1e3)}}}async function g(e){return c||await l(),c.hash_phone_number(e)}async function p(e){return c||await l(),c.hash_string(e)}async function h(e,t,a){return c||await l(),c.encrypt_license_for_storage(e,t,a)}async function f(e,t,a){return c||await l(),c.decrypt_license_from_storage(e,t,a)}async function w(e,t){return c||await l(),c.encrypt_api_payload(e,t)}async function A(e,t){return c||await l(),c.decrypt_api_payload(e,t)}async function y(e){return c||await l(),c.encrypt_for_server_generic(e)}async function b(e,t){return c||await l(),c.decrypt_server_response_generic(e,t)}async function _(e,t){return c||await l(),c.create_validation_token(e,t)}async function T(){c||await l();try{return"function"==typeof c.get_wasm_expected_hash?c.get_wasm_expected_hash():null}catch{return null}}},1319(e,t,a){"use strict";a.d(t,{Tt:()=>c,du:()=>l,fI:()=>o,lW:()=>d});const s="",n="",r={base:s,api:n,validate:"",templates:"",quickReply:"",autoTrial:""},i=[""],o=()=>{const e=i[0];return/^\d+$/.test(e)?e:""},c=()=>r.base,d=()=>r.validate,l=()=>r.autoTrial},6815(e,t){var a,s,n;"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self&&self,s=[e],a=function(e){"use strict";if(!globalThis.chrome?.runtime?.id)throw new Error("This script should only be loaded in a browser extension.");if(void 0===globalThis.browser||Object.getPrototypeOf(globalThis.browser)!==Object.prototype){const t="The message port closed before a response was received.",a=e=>{const a={alarms:{clear:{minArgs:0,maxArgs:1},clearAll:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getAll:{minArgs:0,maxArgs:0}},bookmarks:{create:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},getChildren:{minArgs:1,maxArgs:1},getRecent:{minArgs:1,maxArgs:1},getSubTree:{minArgs:1,maxArgs:1},getTree:{minArgs:0,maxArgs:0},move:{minArgs:2,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeTree:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}},browserAction:{disable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},enable:{minArgs:0,maxArgs:1,fallbackToNoCallback:!0},getBadgeBackgroundColor:{minArgs:1,maxArgs:1},getBadgeText:{minArgs:1,maxArgs:1},getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},openPopup:{minArgs:0,maxArgs:0},setBadgeBackgroundColor:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setBadgeText:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},browsingData:{remove:{minArgs:2,maxArgs:2},removeCache:{minArgs:1,maxArgs:1},removeCookies:{minArgs:1,maxArgs:1},removeDownloads:{minArgs:1,maxArgs:1},removeFormData:{minArgs:1,maxArgs:1},removeHistory:{minArgs:1,maxArgs:1},removeLocalStorage:{minArgs:1,maxArgs:1},removePasswords:{minArgs:1,maxArgs:1},removePluginData:{minArgs:1,maxArgs:1},settings:{minArgs:0,maxArgs:0}},commands:{getAll:{minArgs:0,maxArgs:0}},contextMenus:{remove:{minArgs:1,maxArgs:1},removeAll:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},cookies:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:1,maxArgs:1},getAllCookieStores:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},devtools:{inspectedWindow:{eval:{minArgs:1,maxArgs:2,singleCallbackArg:!1}},panels:{create:{minArgs:3,maxArgs:3,singleCallbackArg:!0},elements:{createSidebarPane:{minArgs:1,maxArgs:1}}}},downloads:{cancel:{minArgs:1,maxArgs:1},download:{minArgs:1,maxArgs:1},erase:{minArgs:1,maxArgs:1},getFileIcon:{minArgs:1,maxArgs:2},open:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},pause:{minArgs:1,maxArgs:1},removeFile:{minArgs:1,maxArgs:1},resume:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},extension:{isAllowedFileSchemeAccess:{minArgs:0,maxArgs:0},isAllowedIncognitoAccess:{minArgs:0,maxArgs:0}},history:{addUrl:{minArgs:1,maxArgs:1},deleteAll:{minArgs:0,maxArgs:0},deleteRange:{minArgs:1,maxArgs:1},deleteUrl:{minArgs:1,maxArgs:1},getVisits:{minArgs:1,maxArgs:1},search:{minArgs:1,maxArgs:1}},i18n:{detectLanguage:{minArgs:1,maxArgs:1},getAcceptLanguages:{minArgs:0,maxArgs:0}},identity:{launchWebAuthFlow:{minArgs:1,maxArgs:1}},idle:{queryState:{minArgs:1,maxArgs:1}},management:{get:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},getSelf:{minArgs:0,maxArgs:0},setEnabled:{minArgs:2,maxArgs:2},uninstallSelf:{minArgs:0,maxArgs:1}},notifications:{clear:{minArgs:1,maxArgs:1},create:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:0},getPermissionLevel:{minArgs:0,maxArgs:0},update:{minArgs:2,maxArgs:2}},pageAction:{getPopup:{minArgs:1,maxArgs:1},getTitle:{minArgs:1,maxArgs:1},hide:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setIcon:{minArgs:1,maxArgs:1},setPopup:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},setTitle:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0},show:{minArgs:1,maxArgs:1,fallbackToNoCallback:!0}},permissions:{contains:{minArgs:1,maxArgs:1},getAll:{minArgs:0,maxArgs:0},remove:{minArgs:1,maxArgs:1},request:{minArgs:1,maxArgs:1}},runtime:{getBackgroundPage:{minArgs:0,maxArgs:0},getPlatformInfo:{minArgs:0,maxArgs:0},openOptionsPage:{minArgs:0,maxArgs:0},requestUpdateCheck:{minArgs:0,maxArgs:0},sendMessage:{minArgs:1,maxArgs:3},sendNativeMessage:{minArgs:2,maxArgs:2},setUninstallURL:{minArgs:1,maxArgs:1}},sessions:{getDevices:{minArgs:0,maxArgs:1},getRecentlyClosed:{minArgs:0,maxArgs:1},restore:{minArgs:0,maxArgs:1}},storage:{local:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}},managed:{get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1}},sync:{clear:{minArgs:0,maxArgs:0},get:{minArgs:0,maxArgs:1},getBytesInUse:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}}},tabs:{captureVisibleTab:{minArgs:0,maxArgs:2},create:{minArgs:1,maxArgs:1},detectLanguage:{minArgs:0,maxArgs:1},discard:{minArgs:0,maxArgs:1},duplicate:{minArgs:1,maxArgs:1},executeScript:{minArgs:1,maxArgs:2},get:{minArgs:1,maxArgs:1},getCurrent:{minArgs:0,maxArgs:0},getZoom:{minArgs:0,maxArgs:1},getZoomSettings:{minArgs:0,maxArgs:1},goBack:{minArgs:0,maxArgs:1},goForward:{minArgs:0,maxArgs:1},highlight:{minArgs:1,maxArgs:1},insertCSS:{minArgs:1,maxArgs:2},move:{minArgs:2,maxArgs:2},query:{minArgs:1,maxArgs:1},reload:{minArgs:0,maxArgs:2},remove:{minArgs:1,maxArgs:1},removeCSS:{minArgs:1,maxArgs:2},sendMessage:{minArgs:2,maxArgs:3},setZoom:{minArgs:1,maxArgs:2},setZoomSettings:{minArgs:1,maxArgs:2},update:{minArgs:1,maxArgs:2}},topSites:{get:{minArgs:0,maxArgs:0}},webNavigation:{getAllFrames:{minArgs:1,maxArgs:1},getFrame:{minArgs:1,maxArgs:1}},webRequest:{handlerBehaviorChanged:{minArgs:0,maxArgs:0}},windows:{create:{minArgs:0,maxArgs:1},get:{minArgs:1,maxArgs:2},getAll:{minArgs:0,maxArgs:1},getCurrent:{minArgs:0,maxArgs:1},getLastFocused:{minArgs:0,maxArgs:1},remove:{minArgs:1,maxArgs:1},update:{minArgs:2,maxArgs:2}}};if(0===Object.keys(a).length)throw new Error("api-metadata.json has not been included in browser-polyfill");class s extends WeakMap{constructor(e,t=void 0){super(t),this.createItem=e}get(e){return this.has(e)||this.set(e,this.createItem(e)),super.get(e)}}const n=e=>e&&"object"==typeof e&&"function"==typeof e.then,r=(t,a)=>(...s)=>{e.runtime.lastError?t.reject(new Error(e.runtime.lastError.message)):a.singleCallbackArg||s.length<=1&&!1!==a.singleCallbackArg?t.resolve(s[0]):t.resolve(s)},i=e=>1==e?"argument":"arguments",o=(e,t)=>function(a,...s){if(s.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${i(t.minArgs)} for ${e}(), got ${s.length}`);if(s.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${i(t.maxArgs)} for ${e}(), got ${s.length}`);return new Promise((n,i)=>{if(t.fallbackToNoCallback)try{a[e](...s,r({resolve:n,reject:i},t))}catch(r){a[e](...s),t.fallbackToNoCallback=!1,t.noCallback=!0,n()}else t.noCallback?(a[e](...s),n()):a[e](...s,r({resolve:n,reject:i},t))})},c=(e,t,a)=>new Proxy(t,{apply:(t,s,n)=>a.call(s,e,...n)});let d=Function.call.bind(Object.prototype.hasOwnProperty);const l=(e,t={},a={})=>{let s=Object.create(null),n={has:(t,a)=>a in e||a in s,get(n,r,i){if(r in s)return s[r];if(!(r in e))return;let u=e[r];if("function"==typeof u)if("function"==typeof t[r])u=c(e,e[r],t[r]);else if(d(a,r)){let t=o(r,a[r]);u=c(e,e[r],t)}else u=u.bind(e);else if("object"==typeof u&&null!==u&&(d(t,r)||d(a,r)))u=l(u,t[r],a[r]);else{if(!d(a,"*"))return Object.defineProperty(s,r,{configurable:!0,enumerable:!0,get:()=>e[r],set(t){e[r]=t}}),u;u=l(u,t[r],a["*"])}return s[r]=u,u},set:(t,a,n,r)=>(a in s?s[a]=n:e[a]=n,!0),defineProperty:(e,t,a)=>Reflect.defineProperty(s,t,a),deleteProperty:(e,t)=>Reflect.deleteProperty(s,t)},r=Object.create(e);return new Proxy(r,n)},u=e=>({addListener(t,a,...s){t.addListener(e.get(a),...s)},hasListener:(t,a)=>t.hasListener(e.get(a)),removeListener(t,a){t.removeListener(e.get(a))}}),m=new s(e=>"function"!=typeof e?e:function(t){const a=l(t,{},{getContent:{minArgs:0,maxArgs:0}});e(a)}),g=new s(e=>"function"!=typeof e?e:function(t,a,s){let r,i,o=!1,c=new Promise(e=>{r=function(t){o=!0,e(t)}});try{i=e(t,a,r)}catch(e){i=Promise.reject(e)}const d=!0!==i&&n(i);if(!0!==i&&!d&&!o)return!1;const l=e=>{e.then(e=>{s(e)},e=>{let t;t=e&&(e instanceof Error||"string"==typeof e.message)?e.message:"An unexpected error occurred",s({__mozWebExtensionPolyfillReject__:!0,message:t})}).catch(e=>{})};return l(d?i:c),!0}),p=({reject:a,resolve:s},n)=>{e.runtime.lastError?e.runtime.lastError.message===t?s():a(new Error(e.runtime.lastError.message)):n&&n.__mozWebExtensionPolyfillReject__?a(new Error(n.message)):s(n)},h=(e,t,a,...s)=>{if(s.length<t.minArgs)throw new Error(`Expected at least ${t.minArgs} ${i(t.minArgs)} for ${e}(), got ${s.length}`);if(s.length>t.maxArgs)throw new Error(`Expected at most ${t.maxArgs} ${i(t.maxArgs)} for ${e}(), got ${s.length}`);return new Promise((e,t)=>{const n=p.bind(null,{resolve:e,reject:t});s.push(n),a.sendMessage(...s)})},f={devtools:{network:{onRequestFinished:u(m)}},runtime:{onMessage:u(g),onMessageExternal:u(g),sendMessage:h.bind(null,"sendMessage",{minArgs:1,maxArgs:3})},tabs:{sendMessage:h.bind(null,"sendMessage",{minArgs:2,maxArgs:3})}},w={clear:{minArgs:1,maxArgs:1},get:{minArgs:1,maxArgs:1},set:{minArgs:1,maxArgs:1}};return a.privacy={network:{"*":w},services:{"*":w},websites:{"*":w}},l(e,f,a)};e.exports=a(chrome)}else e.exports=globalThis.browser},void 0===(n="function"==typeof a?a.apply(t,s):a)||(e.exports=n)}},t={};function a(s){var n=t[s];if(void 0!==n)return n.exports;var r=t[s]={exports:{}};return e[s].call(r.exports,r,r.exports,a),r.exports}a.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return a.d(t,{a:t}),t},a.d=(e,t)=>{for(var s in t)a.o(t,s)&&!a.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";var e=a(6815),t=a.n(e),s=a(4042),n=a(1319);async function r(e){return(0,s.YZ)(e)}let i=null,o=null;const c=async()=>null!==i?i:new Promise(e=>{try{"undefined"!=typeof chrome&&chrome.management?chrome.management.get(chrome.runtime.id,t=>{if(chrome.runtime.lastError)return i=!1,void e(!1);i="development"===t?.installType,e(i)}):(i=!1,e(!1))}catch(t){i=!1,e(!1)}});(async()=>{await c(),setTimeout(async()=>{o=await(async()=>{try{const e=t().runtime.getURL("pkg/wasm_license_bg.wasm"),s=await fetch(e),n=await s.arrayBuffer(),r=await crypto.subtle.digest("SHA-256",n),i=Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join(""),{getWasmExpectedHash:o}=await Promise.resolve().then(a.bind(a,4042)),c=await o();return!c||i===c}catch(e){return!0}})()},2e3)})();let d=null,l=0;const u=3e5,m="last_validation_time";async function g(){l=Date.now(),await t().storage.local.set({[m]:l})}t().storage.local.get(m).then(e=>{e[m]&&(l=e[m])});const p="wa_crm_data_sync";(0,s.zW)().then(()=>{}).catch(e=>{});let h={running:!1,paused:!1,campaignId:null};async function f(){try{return await self.FLOWhatsappLicenseService.quickValidate(!0)}catch(e){return!1}}async function w(){try{const e=await t().tabs.query({url:["https://web.whatsapp.com/*","https://web.whatsapp.com/"]});for(const a of e)a.id&&await t().tabs.reload(a.id)}catch(e){}}(async()=>{try{const e=(await t().storage.local.get("wa_active_campaign")).wa_active_campaign;e&&"running"===e.status&&(e.status="stopped",e.isPaused=!1,await t().storage.local.set({wa_active_campaign:e}))}catch(e){}})(),t().storage.onChanged.addListener((e,t)=>{if("local"===t&&e.wa_active_campaign){const t=e.wa_active_campaign.newValue;t&&(h.running&&h.campaignId!==t.id&&(h.campaignId=t.id),!0===t.isPaused?h.paused=!0:!1===t.isPaused&&(h.paused=!1),"stopped"!==t.status&&"completed"!==t.status&&"cancelled"!==t.status||(h.running=!1))}}),t().runtime.onMessage.addListener((e,a,s)=>{if("PAUSE_BROADCAST"===e.type)return h.paused=!0,s({success:!0}),!0;if("RESUME_BROADCAST"===e.type)return h.paused=!1,s({success:!0}),!0;if("STOP_BROADCAST"===e.type)return h.running=!1,h.paused=!1,s({success:!0}),!0;if("phoneDetected"===e.action&&e.phoneNumber){d=e.phoneNumber;const t=Date.now();if(t-l>=u)g(),f();else{Math.ceil((u-(t-l))/1e3)}}if("openKanban"===e.action&&t().tabs.create({url:t().runtime.getURL("kanban.html")}).then(()=>{}).catch(e=>{}),"openFluxo"===e.action&&t().tabs.create({url:t().runtime.getURL("fluxo.html")}).then(()=>{}).catch(e=>{}),"scheduleBroadcast"===e.action){const{broadcastId:a,scheduledTime:s}=e;s-Date.now()>0&&(t().alarms.create(`broadcast_${a}`,{when:s}),t().alarms.get(`broadcast_${a}`).then(e=>{}))}if("cancelScheduledBroadcast"===e.action){const{broadcastId:a}=e;t().alarms.clear(`broadcast_${a}`)}if("SEND_WEBHOOK"===e.type){const{url:a,payload:s,eventType:n}=e;(async()=>{try{const e=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(e.ok)try{const e=(await t().storage.local.get("webhook_settings")).webhook_settings||{};e[n]&&(e[n].lastUploads=[{timestamp:Date.now(),status:"success"},...(e[n].lastUploads||[]).slice(0,29)],await t().storage.local.set({webhook_settings:e}))}catch(e){}else{await e.text();try{const a=(await t().storage.local.get("webhook_settings")).webhook_settings||{};a[n]&&(a[n].lastUploads=[{timestamp:Date.now(),status:"failed",data:{error:`HTTP ${e.status}`}},...(a[n].lastUploads||[]).slice(0,29)],await t().storage.local.set({webhook_settings:a}))}catch(e){}}}catch(e){try{const a=(await t().storage.local.get("webhook_settings")).webhook_settings||{};a[n]&&(a[n].lastUploads=[{timestamp:Date.now(),status:"failed",data:{error:e.message}},...(a[n].lastUploads||[]).slice(0,29)],await t().storage.local.set({webhook_settings:a}))}catch(e){}}})()}if("KANBAN_STAGE_CHANGED"===e.type)return(async()=>{try{const a=await t().tabs.query({url:"*://web.whatsapp.com/*"});for(const s of a)if(s.id)try{await t().tabs.sendMessage(s.id,{type:"KANBAN_STAGE_CHANGED_FORWARD",chatId:e.chatId,stageId:e.stageId,crmId:e.crmId,action:e.action})}catch(e){}}catch(e){}})(),s({success:!0}),!0;if("SYNC_WHATSAPP_GROUPS"===e.type)return(async()=>{try{const e=await t().tabs.query({url:"*://web.whatsapp.com/*"});if(0===e.length)return void s({success:!1,error:"No WhatsApp Web tab found. Please open WhatsApp Web first."});for(const a of e)if(a.id)try{await t().tabs.sendMessage(a.id,{type:"TRIGGER_GROUPS_SYNC"})}catch(e){}s({success:!0,tabsCount:e.length})}catch(e){s({success:!1,error:String(e)})}})(),!0;if("SYNC_WHATSAPP_LABELS"===e.type)return(async()=>{try{const e=await t().tabs.query({url:"*://web.whatsapp.com/*"});if(0===e.length)return void s({success:!1,error:"No WhatsApp Web tab found. Please open WhatsApp Web first."});for(const a of e)if(a.id)try{await t().tabs.sendMessage(a.id,{type:"TRIGGER_LABELS_SYNC"})}catch(e){}s({success:!0,tabsCount:e.length})}catch(e){s({success:!1,error:String(e)})}})(),!0;if("AI_TRANSLATE"===e.type){const{text:t,targetLang:a,provider:s,apiKey:n}=e;return(async()=>{try{const e=`Translate the following text to ${{en:"English",es:"Spanish",fr:"French",de:"German",hi:"Hindi",pt:"Portuguese",ru:"Russian",zh:"Chinese",ja:"Japanese",ar:"Arabic",ko:"Korean",it:"Italian",nl:"Dutch",pl:"Polish",tr:"Turkish",vi:"Vietnamese",th:"Thai",id:"Indonesian",bn:"Bengali",ur:"Urdu"}[a]||a}. Only respond with the translation, no explanations:\n\n${t}`;let r="";const i=s||"gemini";if("gemini"===i){const t=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${n}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:[{parts:[{text:e}]}],generationConfig:{temperature:.3,maxOutputTokens:2048}})});if(!t.ok){await t.text();return{success:!1,error:`Gemini API error: ${t.status}`}}const a=await t.json();r=a.candidates?.[0]?.content?.parts?.[0]?.text?.trim()||""}else if("chatgpt"===i){const t=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({model:"gpt-4o-mini",messages:[{role:"user",content:e}],temperature:.3})});if(!t.ok){await t.text();return{success:!1,error:`ChatGPT API error: ${t.status}`}}const a=await t.json();r=a.choices?.[0]?.message?.content?.trim()||""}else if("deepseek"===i){const t=await fetch("https://api.deepseek.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({model:"deepseek-chat",messages:[{role:"user",content:e}],temperature:.3})});if(!t.ok){await t.text();return{success:!1,error:`DeepSeek API error: ${t.status}`}}const a=await t.json();r=a.choices?.[0]?.message?.content?.trim()||""}return r?{success:!0,translation:r}:{success:!1,error:"No translation result"}}catch(e){return{success:!1,error:e.message||"Translation failed"}}})()}if("AUDIO_TRANSCRIBE"===e.type){const{audioUrl:t,apiKey:a}=e;return(async()=>{try{const e=await fetch(t);if(!e.ok)throw new Error(`Failed to fetch audio: ${e.status}`);const s=await e.blob(),n=new FormData;n.append("file",s,"audio.ogg"),n.append("model","whisper-1");const r=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${a}`},body:n});if(!r.ok){await r.text();return{success:!1,error:`Whisper API error: ${r.status}`}}return{success:!0,transcription:(await r.json()).text}}catch(e){return{success:!1,error:e.message||"Transcription failed"}}})()}}),t().alarms.onAlarm.addListener(async e=>{if(e.name.startsWith("broadcast_")){const a=e.name.replace("broadcast_","");try{const e=(await t().storage.local.get("wa_scheduled_broadcasts")).wa_scheduled_broadcasts||[],s=e.findIndex(e=>e.id===a),n=s>=0?e[s]:null;if(n){if(n.skipNextOccurrence&&n.isRecurring){n.skipNextOccurrence=!1;const a=new Date,r=n.originalScheduledTime?new Date(n.originalScheduledTime):new Date(n.scheduledTime||a.getTime());let i;switch(n.recurringInterval){case"daily":default:i=new Date(a.getTime()+864e5);break;case"weekly":i=new Date(a.getTime()+6048e5);break;case"monthly":i=new Date(a),i.setMonth(i.getMonth()+1);break;case"yearly":i=new Date(a),i.setFullYear(i.getFullYear()+1)}return i.setHours(r.getHours()),i.setMinutes(r.getMinutes()),i.setSeconds(r.getSeconds()),i.setMilliseconds(0),n.recurringEndDate&&i.getTime()>n.recurringEndDate?(e.splice(s,1),void await t().storage.local.set({wa_scheduled_broadcasts:e})):(n.scheduledTime=i.getTime(),n.nextOccurrence=i.getTime(),e[s]=n,await t().storage.local.set({wa_scheduled_broadcasts:e}),void await t().alarms.create(`broadcast_${n.id}`,{when:i.getTime()}))}if("paused"===n.status)return;if("running"===n.status||"completed"===n.status)return;n.status="running",e[s]=n,await t().storage.local.set({wa_scheduled_broadcasts:e});const a=await t().tabs.query({url:"*://web.whatsapp.com/*"});if(a.length>0&&a[0].id){await t().tabs.sendMessage(a[0].id,{action:"executeBroadcast",broadcast:n})}}}catch(e){}}}),t().alarms.getAll().then(e=>{e.forEach(e=>{})}),t().runtime.onStartup.addListener(async()=>{g(),f(),await w()}),t().runtime.onInstalled.addListener(async e=>{"install"===e.reason?t().storage.local.set({firstInstall:Date.now(),version:t().runtime.getManifest().version}):"update"===e.reason&&(g(),f(),await w())});async function A(e){try{const a=await t().tabs.query({url:["https://web.whatsapp.com/*","https://web.whatsapp.com/"]});if(0===a.length)return{success:!1,error:"No WhatsApp Web tab open"};const s=a[0];if(!s.id)return{success:!1,error:"WhatsApp tab not ready"};try{return await t().tabs.sendMessage(s.id,e)}catch(a){if(a.message?.includes("Receiving end does not exist")){await t().scripting.executeScript({target:{tabId:s.id},files:["contentScript.bundle.js"]}),await new Promise(e=>setTimeout(e,1e3));return await t().tabs.sendMessage(s.id,e)}throw a}}catch(e){return{success:!1,error:e.message||"Failed to send message"}}}async function y(e,n,r=!1){return await self.FLOWhatsappLicenseService.activate(e,n,r)}setInterval(()=>{g(),f()},36e5),t().runtime.onMessage.addListener((e,r,i)=>{if("activateLicense"===e.action&&e.license)return(async()=>{try{const t=await y(e.license,e.phoneNumber,!1);i(t)}catch(e){i({success:!1,isValid:!1,message:e.message||"Validation error occurred"})}})(),!0;if("requestAutoTrial"===e.action&&e.phoneNumber)return(async()=>{try{i(await self.FLOWhatsappLicenseService.requestTrial(e.phoneNumber,e.adminId))}catch(e){i({success:!1,isValid:!1,message:e.message||"Auto-trial failed"})}})(),!0;if("checkLicense"===e.action)return(async()=>{try{i(await self.FLOWhatsappLicenseService.check(!0===e.force))}catch(e){i({validationToken:null,isValid:!1,message:e.message||"Check failed"})}})(),!0;if("validateLicense"===e.action)return(async()=>{try{const t=await self.FLOWhatsappLicenseService.quickValidate(!0===e.force);i({isValid:t})}catch(e){i({isValid:!1})}})(),!0;return"getMachineCode"===e.action?((async()=>{try{const id=await self.FLOWhatsappLicenseService?.getMachineId?.();const code=await self.FLOWhatsappLicenseService?.getInstallationCode?.();i({machineId:id||"",installationCode:code||""})}catch(e){i({machineId:"",installationCode:""})}})(),!0):"getLicenseStatus"===e.action?((async()=>{try{i(await self.FLOWhatsappLicenseService.getStatus())}catch(e){i({hasLicense:!1,error:e.message})}})(),!0):"getApiCredentials"===e.action?((async()=>{try{i(await self.FLOWhatsappLicenseService.getApiCredentials())}catch(e){i({success:!1,error:e.message||"Failed to get credentials"})}})(),!0):"licenseDeactivated"===e.action?((async()=>{try{i(await self.FLOWhatsappLicenseService.deactivate())}catch(e){i({success:!1,error:e.message||"Failed to deactivate"})}})(),!0):(e.action,"openTemplateEditor"===e.action?((async()=>{try{const a=900,s=700,n=Math.round((screen.width-a)/2),r=Math.round((screen.height-s)/2);await t().windows.create({url:t().runtime.getURL("popup.html")+(e.preSelectQuickReply?"?preselect=quick-reply":""),type:"popup",width:a,height:s,left:n,top:r})}catch(e){}})(),!0):"proxyApiCall"===e.action?((async()=>{try{const t=await fetch(e.url,{method:e.method||"POST",headers:e.headers||{"Content-Type":"application/json"},body:e.body?JSON.stringify(e.body):void 0});if(!t.ok)return void i({success:!1,error:`HTTP ${t.status}: ${t.statusText}`});const a=await t.json();i({success:!0,data:a})}catch(e){i({success:!1,error:e.message||"API call failed"})}})(),!0):"APPLY_WHATSAPP_LABEL"===e.type?((async()=>{try{const t=await A({type:"APPLY_WHATSAPP_LABEL",chatId:e.chatId,labelId:e.labelId});i(t)}catch(e){i({success:!1,error:e.message||"Label application failed"})}})(),!0):("UPDATE_KANBAN_CHAT_LABEL"===e.type&&(async()=>{try{const{chatId:a,labelId:s,action:n}=e,r=(await t().storage.local.get("kanban_chats")).kanban_chats||[],i=r.findIndex(e=>e.id===a);-1!==i&&(r[i].whatsappLabels||(r[i].whatsappLabels=[]),"add"===n?r[i].whatsappLabels.includes(s)||r[i].whatsappLabels.push(s):"remove"===n&&(r[i].whatsappLabels=r[i].whatsappLabels.filter(e=>e!==s)),await t().storage.local.set({kanban_chats:r,kanban_chats_timestamp:Date.now()}))}catch(e){}})(),"KANBAN_MOVE_TO_STAGE"===e.type?((async()=>{try{const{chatId:a,stageId:s,crmId:n}=e,r=(await t().storage.local.get("wa_kanban_crm_data_sync")).wa_kanban_crm_data_sync||{crms:[],stages:{},assignments:[]};r.assignments=(r.assignments||[]).filter(e=>!(e.chatId===a&&e.crmId===n)),r.assignments.push({id:`assign_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,chatId:a,stageId:s,crmId:n,assignedAt:Date.now()}),await t().storage.local.set({wa_kanban_crm_data_sync:r}),i({success:!0})}catch(e){i({success:!1,error:e.message})}})(),!0):"KANBAN_REMOVE_FROM_CRM"===e.type?((async()=>{try{const{chatId:a,crmId:s}=e,n=(await t().storage.local.get("wa_kanban_crm_data_sync")).wa_kanban_crm_data_sync||{crms:[],stages:{},assignments:[]};n.assignments=(n.assignments||[]).filter(e=>!(e.chatId===a&&e.crmId===s)),await t().storage.local.set({wa_kanban_crm_data_sync:n}),i({success:!0})}catch(e){i({success:!1,error:e.message})}})(),!0):"KANBAN_LABEL_TOGGLE"===e.type?((async()=>{try{const{chatId:a,labelId:s,action:n}=e,r=await A({type:"add"===n?"LABEL_SERVICE_ADD":"LABEL_SERVICE_REMOVE",chatId:a,labelId:s});r&&r.success;const o=(await t().storage.local.get("kanban_chats")).kanban_chats||[],c=o.findIndex(e=>e.id===a);-1!==c&&(o[c].whatsappLabels||(o[c].whatsappLabels=[]),"add"===n?o[c].whatsappLabels.includes(s)||o[c].whatsappLabels.push(s):"remove"===n&&(o[c].whatsappLabels=o[c].whatsappLabels.filter(e=>e!==s)),await t().storage.local.set({kanban_chats:o,kanban_chats_timestamp:Date.now()})),i({success:!0})}catch(e){i({success:!1,error:e.message})}})(),!0):"FIND_OR_CREATE_TAB"===e.type?((async()=>{try{const t=await A({type:"FIND_OR_CREATE_TAB",tabName:e.tabName,stageId:e.stageId});i(t)}catch(e){i({success:!1,error:e.message||"Find/create tab failed"})}})(),!0):"CREATE_TAB_FROM_STAGE"===e.type?((async()=>{try{const t=await A({type:"CREATE_TAB_FROM_STAGE",tabName:e.tabName,stageId:e.stageId});i(t)}catch(e){i({success:!1,error:e.message||"Tab creation failed"})}})(),!0):"UPDATE_TAB_NAME"===e.type?((async()=>{try{const t=await A({type:"UPDATE_TAB_NAME",tabId:e.tabId,newName:e.newName});i(t)}catch(e){i({success:!1,error:e.message||"Tab name update failed"})}})(),!0):"DELETE_TAB_FROM_STAGE"===e.type?((async()=>{try{const t=await A({type:"DELETE_TAB_FROM_STAGE",tabId:e.tabId});i(t)}catch(e){i({success:!1,error:e.message||"Tab deletion failed"})}})(),!0):"ADD_CHAT_TO_TAB"===e.type?((async()=>{try{const t=await A({type:"ADD_CHAT_TO_TAB",tabId:e.tabId,chat:e.chat});i(t)}catch(e){i({success:!1,error:e.message||"Add chat failed"})}})(),!0):"REMOVE_CHAT_FROM_TAB"===e.type?((async()=>{try{const t=await A({type:"REMOVE_CHAT_FROM_TAB",tabId:e.tabId,chatId:e.chatId});i(t)}catch(e){i({success:!1,error:e.message||"Remove chat failed"})}})(),!0):void 0))});async function b(){try{const e=(await t().storage.local.get(p))[p];if(!e||!e.contacts)return;const a=Date.now(),s=[];for(const[t,n]of Object.entries(e.contacts))if(n.reminders)for(const e of n.reminders)e.isStopped||"stopped"!==e.status&&"dismissed"!==e.status&&"completed"!==e.status&&"pending"===e.status&&!e.notified&&e.datetime<=a&&s.push({contactId:t,contactName:n.profile?.name||"Unknown",reminder:e});for(const{contactId:a,contactName:n,reminder:r}of s){try{await t().notifications.create(`reminder_${r.id}`,{type:"basic",iconUrl:t().runtime.getURL("icons/icon-128.png"),title:`Reminder: ${n}`,message:r.topic,priority:2})}catch(e){}e.contacts[a].reminders=e.contacts[a].reminders.map(e=>e.id===r.id?{...e,notified:!0}:e),await _("due",a,n,{id:r.id,topic:r.topic,datetime:r.datetime,details:r.details,repeatInterval:r.repeatInterval,snoozeCount:r.snoozeCount});try{await A({type:"CRM_REMINDER_DUE",reminder:r,contactId:a,contactName:n})}catch(e){}}s.length>0&&await t().storage.local.set({[p]:e})}catch(e){}}async function _(e,a,s,n){try{const r=(await t().storage.local.get("webhook_settings")).webhook_settings;if(!r)return;const i=r.reminder;if(!i||!i.active||!i.url)return;const o={};(i.dataFields||[]).forEach(t=>{if(t.enabled)switch(t.id){case"event_details":o.event={type:"reminder",action:e,timestamp:Date.now()};break;case"number":o.number=a.split("@")[0];break;case"name":o.name=s;break;case"reminder_topic":o.reminderTopic=n.topic;break;case"reminder_time":o.reminderTime=n.datetime,o.reminderTimeFormatted=new Date(n.datetime).toLocaleString();break;case"reminder_details":o.reminderDetails=n.details||null;break;case"contact_profile":o.contactProfile={name:s}}}),o.reminder={id:n.id||null,topic:n.topic,datetime:n.datetime,datetimeFormatted:new Date(n.datetime).toLocaleString(),details:n.details||null,repeatInterval:n.repeatInterval||null,status:"stopped"===e?"stopped":"snoozed"===e?"snoozed":"due",snoozeCount:n.snoozeCount||0};try{(await fetch(i.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).ok&&(i.lastUploads=[{timestamp:Date.now(),status:"success"},...(i.lastUploads||[]).slice(0,29)],await t().storage.local.set({webhook_settings:r}))}catch(e){}}catch(e){}}setInterval(()=>{b()},15e3),setTimeout(b,5e3),t().notifications.onClicked.addListener(async e=>{if(e.startsWith("reminder_")){const e=await t().tabs.query({url:["https://web.whatsapp.com/*","https://web.whatsapp.com/"]});e.length>0&&e[0].id?(await t().tabs.update(e[0].id,{active:!0}),e[0].windowId&&await t().windows.update(e[0].windowId,{focused:!0})):await t().tabs.create({url:"https://web.whatsapp.com/"})}}),t().runtime.onMessage.addListener((e,a,s)=>"CRM_REMINDER_SNOOZE"===e.type?((async()=>{try{const a=(await t().storage.local.get(p))[p];if(!a||!a.contacts||!a.contacts[e.contactId])return void s({success:!1,error:"Contact not found"});const n=a.contacts[e.contactId],r=n.reminders.findIndex(t=>t.id===e.reminderId);if(-1===r)return void s({success:!1,error:"Reminder not found"});const i=n.reminders[r],o=i.repeatInterval||5,c=Date.now()+60*o*1e3,d=(i.snoozeCount||0)+1;a.contacts[e.contactId].reminders[r]={...i,datetime:c,notified:!1,status:"pending",snoozeCount:d},await t().storage.local.set({[p]:a}),await _("snoozed",e.contactId,n.profile?.name||"Unknown",{id:i.id,topic:i.topic,datetime:c,details:i.details,repeatInterval:i.repeatInterval,snoozeCount:d}),s({success:!0,nextTrigger:c})}catch(e){s({success:!1,error:e.message})}})(),!0):"CRM_REMINDER_STOP"===e.type?((async()=>{try{const a=(await t().storage.local.get(p))[p];if(!a||!a.contacts||!a.contacts[e.contactId])return void s({success:!1,error:"Contact not found"});const n=a.contacts[e.contactId],r=n.reminders.findIndex(t=>t.id===e.reminderId);if(-1===r)return void s({success:!1,error:"Reminder not found"});const i=n.reminders[r];a.contacts[e.contactId].reminders[r]={...i,isStopped:!0,status:"stopped",notified:!0},await t().storage.local.set({[p]:a}),await _("stopped",e.contactId,n.profile?.name||"Unknown",{id:i.id,topic:i.topic,datetime:i.datetime,details:i.details,repeatInterval:i.repeatInterval,snoozeCount:i.snoozeCount}),s({success:!0})}catch(e){s({success:!1,error:e.message})}})(),!0):void 0);async function T(){try{const e=(await t().storage.local.get(p))[p];if(!e||!e.contacts)return;const a=Date.now(),s=[];for(const[t,n]of Object.entries(e.contacts))if(n.appointments)for(const e of n.appointments){if("scheduled"!==e.status)continue;const r=e.datetime,i=r-60*e.reminderBefore*1e3;!e.userReminderNotified&&a>=i&&a<=i+6e4&&s.push({contactId:t,contactName:n.profile?.name||"Unknown",appointment:e,type:"reminder"}),!e.meetingStartNotified&&a>=r&&a<=r+6e4&&s.push({contactId:t,contactName:n.profile?.name||"Unknown",appointment:e,type:"meeting_start"})}for(const{contactId:a,contactName:n,appointment:r,type:i}of s){const s="reminder"===i,o=s?`Meeting Reminder: ${r.title}`:`Meeting Starting: ${r.title}`,c=s?`Meeting starts in ${r.reminderBefore} minutes with ${r.attendees?.length||0} attendee(s)`:`Your meeting "${r.title}" is starting now!`;try{await t().notifications.create(`appointment_${i}_${r.id}`,{type:"basic",iconUrl:t().runtime.getURL("icons/icon-128.png"),title:o,message:c,priority:2})}catch(e){}const d=e.contacts[a].appointments.findIndex(e=>e.id===r.id);-1!==d&&(s?e.contacts[a].appointments[d].userReminderNotified=!0:e.contacts[a].appointments[d].meetingStartNotified=!0);try{await A({type:"CRM_APPOINTMENT_NOTIFICATION",appointment:r,contactId:a,contactName:n,notificationType:i})}catch(e){}if(s&&!r.attendeeReminderSent&&r.attendees?.length>0){const t=[];for(const e of r.attendees){const a=new Date(r.datetime),s=a.toLocaleDateString("pt-BR",{weekday:"long",year:"numeric",month:"long",day:"numeric"}),n=a.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",hour12:!0});let i=r.message.replace(/\{name\}/g,e.name||"there").replace(/\{date\}/g,s).replace(/\{time\}/g,n).replace(/\{link\}/g,r.meetLink||"");t.push({attendeeId:e.id,attendeeName:e.name,message:i})}try{await A({type:"CRM_SEND_APPOINTMENT_MESSAGES",appointmentId:r.id,contactId:a,messages:t}),-1!==d&&(e.contacts[a].appointments[d].attendeeReminderSent=!0)}catch(e){}}if(!s&&!r.attendeeMeetingStartSent&&r.attendees?.length>0){const t=!1!==r.useSameMessage?r.message:r.meetingStartMessage||r.message,s=[];for(const e of r.attendees){const a=new Date(r.datetime),n=a.toLocaleDateString("pt-BR",{weekday:"long",year:"numeric",month:"long",day:"numeric"}),i=a.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",hour12:!0});let o=t.replace(/\{name\}/g,e.name||"there").replace(/\{date\}/g,n).replace(/\{time\}/g,i).replace(/\{link\}/g,r.meetLink||"");s.push({attendeeId:e.id,attendeeName:e.name,message:o})}try{await A({type:"CRM_SEND_APPOINTMENT_MESSAGES",appointmentId:r.id,contactId:a,messages:s}),-1!==d&&(e.contacts[a].appointments[d].attendeeMeetingStartSent=!0)}catch(e){}}}s.length>0&&await t().storage.local.set({[p]:e})}catch(e){}}setInterval(()=>{T()},3e4),setTimeout(T,7e3),t().notifications.onClicked.addListener(async e=>{if(e.startsWith("appointment_")){const a=e.split("_"),s=(a.length>=3&&a.slice(2).join("_"),await t().tabs.query({url:["https://web.whatsapp.com/*","https://web.whatsapp.com/"]}));s.length>0&&s[0].id?(await t().tabs.update(s[0].id,{active:!0}),s[0].windowId&&await t().windows.update(s[0].windowId,{focused:!0})):await t().tabs.create({url:"https://web.whatsapp.com/"})}});async function v(){try{const e=await t().tabs.query({url:["https://web.whatsapp.com/*","https://web.whatsapp.com/"]});if(0===e.length||!e[0].id)return;try{await t().tabs.sendMessage(e[0].id,{type:"CHECK_SCHEDULED_STATUSES"})}catch(e){}}catch(e){}}setInterval(()=>{v()},3e4),setTimeout(v,1e4);async function x(){try{const e=(await t().storage.local.get(p))[p];if(!e||!e.contacts)return;const a=Date.now();let s=!1;for(const t in e.contacts){const n=e.contacts[t];if(n.incomes){const e=[];for(const t of n.incomes)if(t.isRecurring&&t.nextOccurrence&&t.nextOccurrence<=a){if(t.recurringEndDate&&t.recurringEndDate<a)continue;const n={id:`income-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,amount:t.amount,category:t.category,paymentMethod:t.paymentMethod,description:t.description,reference:t.reference,date:t.nextOccurrence,status:"pending",createdAt:a,updatedAt:a,recurringParentId:t.id};e.push(n),t.nextOccurrence=k(t.nextOccurrence,t.recurringInterval),t.updatedAt=a,s=!0}n.incomes.push(...e)}if(n.expenses){const e=[];for(const t of n.expenses)if(t.isRecurring&&t.nextOccurrence&&t.nextOccurrence<=a){if(t.recurringEndDate&&t.recurringEndDate<a)continue;const n={id:`expense-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,amount:t.amount,category:t.category,paymentMethod:t.paymentMethod,description:t.description,reference:t.reference,date:t.nextOccurrence,status:"pending",createdAt:a,updatedAt:a,recurringParentId:t.id};e.push(n),t.nextOccurrence=k(t.nextOccurrence,t.recurringInterval),t.updatedAt=a,s=!0}n.expenses.push(...e)}}s&&await t().storage.local.set({[p]:e})}catch(e){}}function k(e,t){const a=new Date(e);switch(t){case"daily":a.setDate(a.getDate()+1);break;case"weekly":a.setDate(a.getDate()+7);break;case"monthly":default:a.setMonth(a.getMonth()+1);break;case"quarterly":a.setMonth(a.getMonth()+3);break;case"yearly":a.setFullYear(a.getFullYear()+1)}return a.getTime()}setInterval(()=>{x()},3e5),setTimeout(x,15e3);const S="api_polling_settings";let E=null,I=!1;async function N(){E||(I=!0,E=setInterval(()=>{D()},P(3e5)),D())}async function D(){try{const e=(await t().storage.local.get(S))[S];if(!e||!e.enabled)return;const n=await t().storage.local.get(["wa_session_data","phoneNumber"]);if(!n.wa_session_data||!n.phoneNumber)return;const i=t().runtime.id;let o;try{const{decryptLicenseFromStorage:e}=await Promise.resolve().then(a.bind(a,4042)),t=await e(n.wa_session_data,n.phoneNumber,i);o=JSON.parse(t)}catch(e){return}const c=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(n.phoneNumber)),d=Array.from(new Uint8Array(c)).map(e=>e.toString(16).padStart(2,"0")).join(""),l=e.apiBaseUrl||"";if(!l)return;const u={action:"poll",phone_hash:d,signature_hash:await r(o.signature),timestamp:Date.now(),limit:10},p=await fetch(`${l}/webhook-poll.php`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(!p.ok)return;const h=await p.json();if(!h.success)return void h.error;let f;if(h.encrypted)try{const e=await(0,s._K)(h.encrypted,o.signature);f=JSON.parse(e)}catch(e){return}else f=h;if(!f.actions||0===f.actions.length)return;for(const e of f.actions)await R(e,d,o.signature,l)}catch(e){}}async function R(e,t,a,s){try{const n=["send_image","send_video","send_audio","send_document","send_file","send_voice","send_sticker"];let r={...e.payload};if(n.includes(e.action)&&r.url){const e=await async function(e){try{const t=await fetch(e,{method:"GET",headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",Accept:"*/*","Accept-Language":"en-US,en;q=0.9","Cache-Control":"no-cache"},mode:"cors",credentials:"omit"});if(!t.ok)return null;const a=await t.blob();return a.type,new Promise((e,t)=>{const s=new FileReader;s.onloadend=()=>{const t=s.result;e(t)},s.onerror=()=>{e(null)},s.readAsDataURL(a)})}catch(e){return null}}(r.url);if(!e)throw new Error("Media URL could not be fetched. The server is blocking the request (403/CORS). Please use a publicly accessible URL or send the file as base64.");r.base64=e,delete r.url}const i=await A({type:"API_SEND_MESSAGE",action:e.action,payload:r,queueId:e.queue_id}),o=i&&i.success?"completed":"failed",c=i&&!i.success?i.error||"Unknown error":null;await O(e.queue_id,o,c,i?.messageId||null,t,a,s)}catch(n){await O(e.queue_id,"failed",n.message||"Processing failed",null,t,a,s)}}async function O(e,t,a,n,i,o,c){try{const d={action:"ack",phone_hash:i,queue_id:e,status:t,error:a,result:n?{messageId:n}:null,signature_hash:await r(o),timestamp:Date.now()};await fetch(`${c}/webhook-poll.php`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})}catch(e){}}t().runtime.onMessage.addListener((e,t,a)=>"API_POLLING_START"===e.type?(N(),a({success:!0,message:"API polling started"}),!0):"API_POLLING_STOP"===e.type?(E&&(clearInterval(E),E=null),I=!1,a({success:!0,message:"API polling stopped"}),!0):"API_POLLING_STATUS"===e.type?(a({success:!0,isActive:I}),!0):void 0),(async()=>{try{const e=(await t().storage.local.get(S))[S];e&&e.enabled&&N()}catch(e){}})();const M=12e4,C="wa_agent_settings",L={};function P(e){const t=.2*e;return e+(2*Math.random()-1)*t}function F(e,t,a){L[e]||(L[e]={failures:0,nextAllowedAt:0});const s=L[e];if(t)s.failures=0,s.nextAllowedAt=0;else{s.failures++;let e=Math.min(1e3*Math.pow(2,s.failures),3e5);503!==a&&429!==a||(e=Math.max(e,6e4)),s.nextAllowedAt=Date.now()+e,s.failures>=5&&(s.nextAllowedAt=Date.now()+3e5)}}let $=null;async function U(){try{const e=(await t().storage.local.get(C))[C];return e?.agentName?.trim()||null}catch{return null}}let B=null,H=!1;async function G(e,i){if(!function(e){const t=L[e];return!t||!(t.failures>=5&&Date.now()<t.nextAllowedAt)}(e))return{success:!1,error:"Circuit breaker open - server overloaded"};try{const o=await async function(){try{const e=await t().storage.local.get(["wa_session_data","phoneNumber"]);if(!e.wa_session_data||!e.phoneNumber)return null;const s=t().runtime.id,{decryptLicenseFromStorage:n}=await Promise.resolve().then(a.bind(a,4042)),r=await n(e.wa_session_data,e.phoneNumber,s),i=JSON.parse(r),o=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e.phoneNumber)),c=Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join("");return{signature:i.signature,phoneHash:c}}catch(e){return null}}();if(!o||!o.signature||!o.phoneHash)return{success:!1,error:"No valid license"};const c=o.phoneHash,d=await r(o.signature),l=await async function(){try{const e=(await t().storage.local.get("webhook_settings")).webhook_settings;return e?.apiSettings?.baseUrl?e.apiSettings.baseUrl.replace(/\/$/,""):(0,n.Tt)()}catch{return(0,n.Tt)()}}(),u=await(0,s.GM)(JSON.stringify(i),o.signature),m=await fetch(`${l}/api/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({encrypted:u,phone_hash:c,signature_hash:d})});if(!m.ok)return F(e,!1,m.status),{success:!1,error:`HTTP ${m.status}`};const g=await m.json();if(!g.success)return F(e,!1),{success:!1,error:g.error||"API call failed"};if(F(e,!0),g.encrypted)try{const e=await(0,s._K)(g.encrypted,o.signature);return JSON.parse(e)}catch(e){return{success:!1,error:"Decryption failed"}}return g}catch(t){return F(e,!1),{success:!1,error:"Network error"}}}async function j(e,t="online"){const a=await G("agent-register.php",{action:"register",agent_name:e,status:t});return a.success&&(H=!0,function(){if($)return;$=setInterval(q,P(M))}(),function(){if(B)return;V(),B=setInterval(V,P(6e4))}()),a}async function W(){J(),B&&(clearInterval(B),B=null),H=!1;const e=await U();return await G("agent-register.php",{action:"unregister",agent_name:e||""})}async function q(){if(H)try{const e=(await t().storage.local.get(C))[C];if(!e||!e.enabled||!e.agentName)return void J();await G("agent-register.php",{action:"heartbeat",agent_name:e.agentName,status:e.status||"online"})}catch(e){}}function J(){$&&(clearInterval($),$=null)}async function V(){if(H)try{const e=await U();if(!e)return;const a=await G("service-transfer.php",{action:"poll",agent_name:e,limit:10,include_sent:!0});if(a.success){const e=a.transfers||[],s=a.active_services||[],n=a.sent_transfers||[];e.length>0||s.length>0||n.length;const r=await t().tabs.query({url:"*://web.whatsapp.com/*"});for(const a of r)if(a.id)try{await t().tabs.sendMessage(a.id,{type:"INCOMING_TRANSFERS",transfers:e,activeServices:s,sentTransfers:n})}catch(e){}}}catch(e){}}t().runtime.onMessage.addListener((e,a,s)=>{if("AGENT_REGISTER"===e.type)return j(e.agentName,e.status||"online").then(e=>s(e)).catch(e=>s({success:!1,error:e.message})),!0;if("AGENT_UNREGISTER"===e.type)return W().then(e=>s(e)).catch(e=>s({success:!1,error:e.message})),!0;if("AGENT_SYNC"===e.type){const t=e.settings;return t&&t.enabled&&t.agentName?H?s({success:!0,message:"Agent already active"}):j(t.agentName,t.status||"online").then(e=>s(e)).catch(e=>s({success:!1,error:e.message})):s({success:!1,message:"Agent not enabled"}),!0}return"AGENT_LIST_ONLINE"===e.type?(async function(e=!0,t){const a=t||await U()||"";return await G("agent-list.php",{action:"list",agent_name:a,include_busy:e})}(!1!==e.includeBusy,e.agentName).then(e=>s(e)).catch(e=>s({success:!1,error:e.message})),!0):"TRANSFER_CREATE"===e.type?(async function(e,t){const a=t||await U()||"";return await G("service-transfer.php",{action:"create",agent_name:a,chat_id:e.chatId,chat_name:e.chatName,to_agent_name:e.toAgentName,reason:e.reason,priority:e.priority})}(e.data,e.agentName).then(e=>s(e)).catch(e=>s({success:!1,error:e.message})),!0):"TRANSFER_ACCEPT"===e.type?(async function(e){const t=await U();return await G("service-transfer.php",{action:"accept",agent_name:t||"",transfer_id:e})}(e.transferId).then(e=>s(e)).catch(e=>s({success:!1,error:e.message})),!0):"TRANSFER_DECLINE"===e.type?(async function(e){const t=await U();return await G("service-transfer.php",{action:"decline",agent_name:t||"",transfer_id:e})}(e.transferId).then(e=>s(e)).catch(e=>s({success:!1,error:e.message})),!0):"TRANSFER_START_SERVICE"===e.type?(async function(e){const t=await U();return await G("service-transfer.php",{action:"start_service",agent_name:t||"",transfer_id:e})}(e.transferId).then(async e=>{if(e.success&&e.chat_id){const a=await t().tabs.query({url:"*://web.whatsapp.com/*"});for(const s of a)if(s.id)try{await t().tabs.sendMessage(s.id,{type:"PIN_CHAT",chatId:e.chat_id})}catch(e){}}s(e)}).catch(e=>s({success:!1,error:e.message})),!0):"TRANSFER_END_SERVICE"===e.type?(async function(e,t){const a=await U();return await G("service-transfer.php",{action:"end_service",agent_name:a||"",transfer_id:e,completion_notes:t})}(e.transferId,e.completionNotes).then(async a=>{const n=e.chatId||a.chat_id;if(a.success&&n){const e=await t().tabs.query({url:"*://web.whatsapp.com/*"});for(const a of e)if(a.id)try{await t().tabs.sendMessage(a.id,{type:"UNPIN_CHAT",chatId:n})}catch(e){}}s(a)}).catch(e=>s({success:!1,error:e.message})),!0):"TRANSFER_HISTORY"===e.type?(async function(e="all",t,a=20,s=0){const n=await U();return await G("service-transfer.php",{action:"history",agent_name:n||"",type:e,status:t,limit:a,offset:s})}(e.historyType,e.status,e.limit,e.offset).then(e=>s(e)).catch(e=>s({success:!1,error:e.message})),!0):"OPEN_TRANSFER_HISTORY"===e.type?(t().tabs.query({url:"*://web.whatsapp.com/*"}).then(e=>{for(const a of e)a.id&&t().tabs.sendMessage(a.id,{type:"SHOW_TRANSFER_HISTORY_MODAL"}).catch(()=>{})}),s({success:!0}),!0):void 0}),(async()=>{try{const e=(await t().storage.local.get(C))[C];e&&e.enabled&&e.agentName&&await j(e.agentName,e.status||"online")}catch(e){}})();const K=e=>new Promise(t=>setTimeout(t,e));async function z(e){if(h.paused)return!0;try{const e=(await t().storage.local.get("wa_active_campaign")).wa_active_campaign;if(e&&!0===e.isPaused)return h.paused=!0,!0}catch(e){}return!1}async function Y(e){h.running=!0,h.paused=e.isPaused||!1,h.campaignId=e.id;const a=e.contactsWithData||[],s=e.messages||[];let n=e.sent||0,r=e.failed||0;const i=e.results||[],o=e.queueItems||[],c=new Set;o.forEach((e,t)=>{"sent"===e.status&&c.add(a[t]?.phone)});for(let d=e.currentIndex||0;d<a.length&&h.running;d++){let l=await z(e.id);for(;l&&h.running;)await K(500),l=await z(e.id);if(!h.running)break;const u=a[d];if(!u||!u.phone)continue;if(c.has(u.phone))continue;const m=e.minDelay||3,g=e.maxDelay||10,p=1e3*(Math.random()*(g-m)+m),f=500;let w=0;for(;w<p&&h.running;){const t=await z(e.id);for(;t&&h.running&&(await K(500),h.paused););if(!h.running)break;await K(Math.min(f,p-w)),w+=f}if(!h.running)break;const A=(await t().storage.local.get("wa_active_campaign")).wa_active_campaign;if(A&&!0===A.isPaused){for(h.paused=!0;h.paused&&h.running;){await K(500);const e=await t().storage.local.get("wa_active_campaign");if(!1===e.wa_active_campaign?.isPaused){h.paused=!1;break}}if(!h.running)break}o[d]&&(o[d].status="sending");try{const a=await t().tabs.query({url:"*://web.whatsapp.com/*"});if(0===a.length||!a[0].id){await K(2e3),d--;continue}let l;if(e.sendRandomMessage){l=[s[Math.floor(Math.random()*s.length)]]}else l=s;const p=a[0].id;let f=0,w=0,A=!1;if(!0===e.skipBulkMessage){try{const a=await t().tabs.sendMessage(p,{type:"PERFORM_BROADCAST_ACTIONS",contact:u.phone,contactName:u.name,contactData:u,groupActions:e.groupActions,addToGroupsEnabled:e.addToGroupsEnabled,removeFromGroupsEnabled:e.removeFromGroupsEnabled,groupsForAddAction:e.groupsForAddAction,groupsForRemoveAction:e.groupsForRemoveAction,customTabActions:e.customTabActions,addToTabsEnabled:e.addToTabsEnabled,removeFromTabsEnabled:e.removeFromTabsEnabled,tabsForAddAction:e.tabsForAddAction,tabsForRemoveAction:e.tabsForRemoveAction,labelsActions:e.labelsActions,addToLabelsEnabled:e.addToLabelsEnabled,removeFromLabelsEnabled:e.removeFromLabelsEnabled,labelsForAddAction:e.labelsForAddAction,labelsForRemoveAction:e.labelsForRemoveAction,kanbanBoardActions:e.kanbanBoardActions,addToKanbanEnabled:e.addToKanbanEnabled,removeFromKanbanEnabled:e.removeFromKanbanEnabled,kanbanForAddAction:e.kanbanForAddAction,kanbanForRemoveAction:e.kanbanForRemoveAction});c.add(u.phone),o[d]&&(o[d].status=a?.success?"sent":"failed",o[d].timestamp=Date.now(),a?.success||(o[d].error="Actions failed")),i.push({contact:u.phone,name:u.name||u.phone,success:!1!==a?.success,actionsOnly:!0,timestamp:Date.now()})}catch(e){r++,o[d]&&(o[d].status="failed",o[d].error=e.message),i.push({contact:u.phone,name:u.name||u.phone,success:!1,actionsOnly:!0,error:e.message,timestamp:Date.now()})}continue}for(let a=0;a<l.length;a++){const s=l[a];if(!h.running)break;let i=await z(e.id);for(;i&&h.running;)await K(500),i=await z(e.id);if(!h.running)break;const o=await t().tabs.sendMessage(p,{type:"SEND_BROADCAST_MESSAGE",contact:u.phone,contactName:u.name,contactData:u,message:s,enableLinkPreview:e.enableLinkPreview||!1,appendSignature:e.appendSignatureEnabled||!1,signature:e.userSignature||""});if(o&&!0===o.paused){for(h.paused=!0,A=!0;h.paused&&h.running;){await K(500);const e=await t().storage.local.get("wa_active_campaign");if(!1===e.wa_active_campaign?.isPaused){h.paused=!1;break}}if(h.running){a--;continue}break}if(o&&o.success?(n++,f++):(r++,w++),a<l.length-1&&h.running){const t=1e3*(Math.random()*(g-m)+m);let a=0;for(;a<t&&h.running;){if(await z(e.id))for(;h.paused&&h.running&&(await K(500),h.paused););if(!h.running)break;await K(Math.min(500,t-a)),a+=500}}}if((e.addToGroupsEnabled||e.removeFromGroupsEnabled||e.addToTabsEnabled||e.removeFromTabsEnabled||e.addToLabelsEnabled||e.removeFromLabelsEnabled||e.addToKanbanEnabled||e.removeFromKanbanEnabled)&&h.running)try{await t().tabs.sendMessage(p,{type:"PERFORM_BROADCAST_ACTIONS",contact:u.phone,contactName:u.name,contactData:u,groupActions:e.groupActions,addToGroupsEnabled:e.addToGroupsEnabled,removeFromGroupsEnabled:e.removeFromGroupsEnabled,groupsForAddAction:e.groupsForAddAction,groupsForRemoveAction:e.groupsForRemoveAction,customTabActions:e.customTabActions,addToTabsEnabled:e.addToTabsEnabled,removeFromTabsEnabled:e.removeFromTabsEnabled,tabsForAddAction:e.tabsForAddAction,tabsForRemoveAction:e.tabsForRemoveAction,labelsActions:e.labelsActions,addToLabelsEnabled:e.addToLabelsEnabled,removeFromLabelsEnabled:e.removeFromLabelsEnabled,labelsForAddAction:e.labelsForAddAction,labelsForRemoveAction:e.labelsForRemoveAction,kanbanBoardActions:e.kanbanBoardActions,addToKanbanEnabled:e.addToKanbanEnabled,removeFromKanbanEnabled:e.removeFromKanbanEnabled,kanbanForAddAction:e.kanbanForAddAction,kanbanForRemoveAction:e.kanbanForRemoveAction})}catch(e){}(!A||f>0||w>0)&&(c.add(u.phone),o[d]&&(0===w&&f>0?(o[d].status="sent",o[d].timestamp=Date.now()):0===f&&w>0?(o[d].status="failed",o[d].error="All messages failed"):f>0&&w>0&&(o[d].status="sent",o[d].error=`${w} of ${l.length} failed`)),i.push({contact:u.phone,name:u.name||u.phone,success:f>0,messagesSent:f,messagesFailed:w,totalMessages:l.length,timestamp:Date.now()}))}catch(e){r++,o[d]&&(o[d].status="failed",o[d].error=e.message),i.push({contact:u.phone,name:u.name||u.phone,success:!1,error:e.message,timestamp:Date.now()})}try{const a="wa_active_campaign",s=(await t().storage.local.get(a))[a];s&&s.id===e.id&&(!0===s.isPaused&&(h.paused=!0),s.currentIndex=d+1,s.sent=n,s.failed=r,s.queueItems=o,s.results=i,s.lastUpdatedAt=Date.now(),s.status=h.paused?"paused":"running",await t().storage.local.set({[a]:s}))}catch(e){}for(;h.paused&&h.running;)await K(500);if(!h.running)break}h.running=!1;try{const o="wa_active_campaign",c=(await t().storage.local.get(o))[o];if(c&&c.id===e.id){c.status="completed",c.currentIndex=a.length,await t().storage.local.set({[o]:c});const d="wa_broadcast_history",l=(await t().storage.local.get(d))[d]||[];l.unshift({id:e.id,name:`Broadcast ${(new Date).toLocaleDateString()}`,contacts:a.length,messages:s.length,sentCount:n,failedCount:r,startedAt:e.startedAt,completedAt:Date.now(),status:"completed",results:i}),l.length>100&&l.splice(100),await t().storage.local.set({[d]:l})}}catch(e){}}t().runtime.onMessage.addListener((e,a,s)=>{
  try {
    if ("START_BROADCAST_LOOP" === e.type) {
      if (h.running) {
        t().storage.local.get("wa_active_campaign").then(t=>{
          const a=t.wa_active_campaign;
          if (a&&"completed"!==a.status&&"stopped"!==a.status) {
            s({success:!1,error:"Loop already running"});
          } else {
            h.running=!1;
            h.paused=!1;
            h.campaignId=null;
            try {
              Y(e.campaign);
              s({success:!0,message:"Loop started (stuck state reset)"});
            } catch(yErr) {
              s({success:!1,error:"Failed to initialize campaign loop: " + yErr.message});
            }
          }
        }).catch(e=>{
          s({success:!1,error:"Error checking campaign state: " + e.message});
        });
        return !0;
      } else {
        try {
          Y(e.campaign);
          s({success:!0,message:"Loop started"});
        } catch(yErr) {
          s({success:!1,error:"Failed to start campaign loop: " + yErr.message});
        }
        return !0;
      }
    } else if ("GET_BROADCAST_LOOP_STATUS" === e.type) {
      s({success:!0,status:{running:h.running,paused:h.paused,campaignId:h.campaignId}});
      return !0;
    }
  } catch (err) {
    s({success:!1,error:"Exception in background listener: " + err.message});
    return !0; // return true just in case we still want to keep port open if async
  }
});const Z="wa_crm_todos_sync",X={en:{taskReminder:"📋 *TASK REMINDER*",title:"Task",description:"Description",subtasks:"Subtasks",priority:"Priority",priorityHigh:"High",priorityMedium:"Medium",priorityLow:"Low",category:"Category",dueDate:"Due Date",linkedContacts:"Linked Contacts",notificationTitle:"Task Reminder"},es:{taskReminder:"📋 *RECORDATORIO DE TAREA*",title:"Tarea",description:"Descripción",subtasks:"Subtareas",priority:"Prioridad",priorityHigh:"Alta",priorityMedium:"Media",priorityLow:"Baja",category:"Categoría",dueDate:"Fecha de vencimiento",linkedContacts:"Contactos Vinculados",notificationTitle:"Recordatorio de Tarea"},zh:{taskReminder:"📋 *任务提醒*",title:"任务",description:"描述",subtasks:"子任务",priority:"优先级",priorityHigh:"高",priorityMedium:"中",priorityLow:"低",category:"类别",dueDate:"截止日期",linkedContacts:"关联联系人",notificationTitle:"任务提醒"},ar:{taskReminder:"📋 *تذكير بالمهمة*",title:"المهمة",description:"الوصف",subtasks:"المهام الفرعية",priority:"الأولوية",priorityHigh:"عالية",priorityMedium:"متوسطة",priorityLow:"منخفضة",category:"الفئة",dueDate:"تاريخ الاستحقاق",linkedContacts:"جهات الاتصال المرتبطة",notificationTitle:"تذكير بالمهمة"},pt:{taskReminder:"📋 *LEMBRETE DE TAREFA*",title:"Tarefa",description:"Descrição",subtasks:"Subtarefas",priority:"Prioridade",priorityHigh:"Alta",priorityMedium:"Média",priorityLow:"Baixa",category:"Categoria",dueDate:"Data de vencimento",linkedContacts:"Contatos Vinculados",notificationTitle:"Lembrete de Tarefa"},ru:{taskReminder:"📋 *НАПОМИНАНИЕ О ЗАДАЧЕ*",title:"Задача",description:"Описание",subtasks:"Подзадачи",priority:"Приоритет",priorityHigh:"Высокий",priorityMedium:"Средний",priorityLow:"Низкий",category:"Категория",dueDate:"Срок выполнения",linkedContacts:"Связанные контакты",notificationTitle:"Напоминание о задаче"},fr:{taskReminder:"📋 *RAPPEL DE TÂCHE*",title:"Tâche",description:"Description",subtasks:"Sous-tâches",priority:"Priorité",priorityHigh:"Haute",priorityMedium:"Moyenne",priorityLow:"Basse",category:"Catégorie",dueDate:"Date d'échéance",linkedContacts:"Contacts liés",notificationTitle:"Rappel de Tâche"},hi:{taskReminder:"📋 *कार्य अनुस्मारक*",title:"कार्य",description:"विवरण",subtasks:"उप-कार्य",priority:"प्राथमिकता",priorityHigh:"उच्च",priorityMedium:"मध्यम",priorityLow:"निम्न",category:"श्रेणी",dueDate:"नियत तारीख",linkedContacts:"जुड़े संपर्क",notificationTitle:"कार्य अनुस्मारक"},bn:{taskReminder:"📋 *কাজের অনুস্মারক*",title:"কাজ",description:"বিবরণ",subtasks:"উপ-কাজ",priority:"অগ্রাধিকার",priorityHigh:"উচ্চ",priorityMedium:"মাঝারি",priorityLow:"নিম্ন",category:"বিভাগ",dueDate:"নির্ধারিত তারিখ",linkedContacts:"সংযুক্ত পরিচিতি",notificationTitle:"কাজের অনুস্মারক"},ur:{taskReminder:"📋 *ٹاسک یاد دہانی*",title:"ٹاسک",description:"تفصیل",subtasks:"ذیلی ٹاسک",priority:"ترجیح",priorityHigh:"اعلی",priorityMedium:"درمیانی",priorityLow:"کم",category:"زمرہ",dueDate:"آخری تاریخ",linkedContacts:"منسلک رابطے",notificationTitle:"ٹاسک یاد دہانی"},ja:{taskReminder:"📋 *タスクリマインダー*",title:"タスク",description:"説明",subtasks:"サブタスク",priority:"優先度",priorityHigh:"高",priorityMedium:"中",priorityLow:"低",category:"カテゴリー",dueDate:"期限",linkedContacts:"関連連絡先",notificationTitle:"タスクリマインダー"},de:{taskReminder:"📋 *AUFGABENERINNERUNG*",title:"Aufgabe",description:"Beschreibung",subtasks:"Unteraufgaben",priority:"Priorität",priorityHigh:"Hoch",priorityMedium:"Mittel",priorityLow:"Niedrig",category:"Kategorie",dueDate:"Fälligkeitsdatum",linkedContacts:"Verknüpfte Kontakte",notificationTitle:"Aufgabenerinnerung"}};function Q(e,t){return(X[e]||X.en)[t]||X.en[t]||t}async function ee(){try{const e=(await t().storage.local.get(Z))[Z];if(!e||!e.todos||0===e.todos.length)return;const a=Date.now(),s=[],n=e.categories||[];for(const t of e.todos)if(!t.notified&&"completed"!==t.status&&"cancelled"!==t.status&&t.reminderDate&&t.reminderTime){const e=new Date(t.reminderDate),[r,i]=t.reminderTime.split(":").map(Number);if(new Date(e.getFullYear(),e.getMonth(),e.getDate(),r,i,0,0).getTime()<=a){const e=n.find(e=>e.id===t.categoryId);s.push({todo:t,category:e})}}for(const{todo:a,category:n}of s){let s=!1,r=!1;if(!0===a.browserNotification)try{const e=await t().storage.local.get("wa_language"),r=Q(e.wa_language||"pt","notificationTitle")||"Task Reminder",i=n?` [${n.name}]`:"",o="high"===a.priority?"🔴":"medium"===a.priority?"🟡":"🟢",c=a.description?`${a.title} - ${a.description.substring(0,80)}`:a.title,d=`todo_${Date.now()}`;await t().notifications.create(d,{type:"basic",iconUrl:t().runtime.getURL("icons/icon-128.png"),title:`${o} ${r}${i}`,message:c,priority:2}),s=!0;try{await A({type:"SHOW_TODO_TOAST",todo:a,category:n})}catch(e){}}catch(e){}if(a.whatsappNotification)try{const e=(await t().storage.local.get("wa_language")).wa_language||"pt",s="high"===a.priority?"priorityHigh":"medium"===a.priority?"priorityMedium":"priorityLow",i="high"===a.priority?"🔴":"medium"===a.priority?"🟡":"🟢",o=Q(e,s),c=Q(e,"taskReminder"),d=Q(e,"title"),l=Q(e,"description"),u=Q(e,"subtasks"),m=Q(e,"priority"),g=Q(e,"category"),p=Q(e,"dueDate"),h=Q(e,"linkedContacts");let f="";if(a.subtasks&&a.subtasks.length>0){f=`\n\n*${u}* (${a.subtasks.filter(e=>e.completed).length}/${a.subtasks.length})\n`,f+=a.subtasks.map(e=>`${e.completed?"✅":"⬜"} ${e.title}`).join("\n")}const w=[c,"━━━━━━━━━━━━━━━━━━","",`📝 *${d}:* ${a.title}`];if(a.description&&(w.push(""),w.push(`📄 *${l}:*`),w.push(a.description)),f&&w.push(f),w.push(""),w.push("━━━━━━━━━━━━━━━━━━"),w.push(`${i} *${m}:* ${o}`),n&&w.push(`🏷️ *${g}:* ${n.name}`),a.dueDate){const e=new Date(a.dueDate).toLocaleDateString(),t=a.dueTime?` ${a.dueTime}`:"";w.push(`📅 *${p}:* ${e}${t}`)}if(a.linkedContactIds&&a.linkedContactIds.length>0)try{const e=(await t().storage.local.get("wa_crm_data_sync")).wa_crm_data_sync;if(e&&e.contacts){const t=[];for(const s of a.linkedContactIds){const a=e.contacts[s];if(a&&a.profile){const e=a.profile.name||"",n=a.profile.phone||s.replace("@c.us","");t.push(`• ${e} (${n})`)}else{const e=s.replace("@c.us","");t.push(`• ${e}`)}}t.length>0&&(w.push(""),w.push(`👥 *${h}:*`),w.push(t.join("\n")))}}catch(e){}w.push(""),w.push("━━━━━━━━━━━━━━━━━━");const y=w.join("\n");await A({type:"TODO_SELF_MESSAGE",message:y,todoId:a.id}),r=!0}catch(e){}if(s||r){const t=e.todos.findIndex(e=>e.id===a.id);-1!==t&&(e.todos[t].notified=!0,e.todos[t].updatedAt=Date.now())}await te("reminder",a,n)}s.length>0&&await t().storage.local.set({[Z]:e}),await async function(e){try{const a=Date.now();let s=!1;for(const t of e.todos)if(t.isRecurring&&t.recurringInterval&&"completed"===t.status&&t.nextOccurrence&&t.nextOccurrence<=a){if(t.recurringEndDate&&t.recurringEndDate<a)continue;const n=t.dueDate?new Date(t.dueDate):new Date;let r;switch(t.recurringInterval){case"daily":r=new Date(n.getTime()+864e5);break;case"weekly":r=new Date(n.getTime()+6048e5);break;case"monthly":r=new Date(n),r.setMonth(r.getMonth()+1);break;case"yearly":r=new Date(n),r.setFullYear(r.getFullYear()+1);break;default:continue}const i={...t,id:`todo_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,status:"pending",notified:!1,completedAt:void 0,dueDate:r.getTime(),reminderDate:t.reminderDate?r.getTime():void 0,nextOccurrence:r.getTime(),recurringParentId:t.recurringParentId||t.id,createdAt:Date.now(),updatedAt:Date.now(),subtasks:t.subtasks.map(e=>({...e,id:`subtask_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,completed:!1}))};e.todos.push(i);const o=e.todos.findIndex(e=>e.id===t.id);-1!==o&&(e.todos[o].nextOccurrence=void 0),s=!0}s&&(e.version=(e.version||0)+1,await t().storage.local.set({[Z]:e}))}catch(e){}}(e)}catch(e){}}async function te(e,a,s){try{const n=(await t().storage.local.get("webhook_settings")).webhook_settings;if(!n)return;const r=n.todos;if(!r||!r.active||!r.url)return;const i={};(r.dataFields||[]).forEach(t=>{if(t.enabled)switch(t.id){case"event_details":i.event={type:"todos",action:e,timestamp:Date.now()};break;case"todo_title":i.title=a.title;break;case"todo_description":i.description=a.description||null;break;case"todo_due_date":i.dueDate=a.dueDate?new Date(a.dueDate).toISOString():null,i.dueTime=a.dueTime||null;break;case"todo_priority":i.priority=a.priority;break;case"todo_category":i.category=s?{id:s.id,name:s.name,color:s.color}:null;break;case"todo_status":i.status=a.status;break;case"todo_subtasks":i.subtasks=a.subtasks||[],i.subtasksProgress={total:a.subtasks?.length||0,completed:a.subtasks?.filter(e=>e.completed).length||0}}}),i.todo={id:a.id,title:a.title,status:a.status,priority:a.priority,isRecurring:a.isRecurring||!1,recurringInterval:a.recurringInterval||null};try{(await fetch(r.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})).ok&&(r.lastUploads=[{timestamp:Date.now(),status:"success"},...(r.lastUploads||[]).slice(0,29)],await t().storage.local.set({webhook_settings:n}))}catch(e){}}catch(e){}}setInterval(()=>{ee()},15e3),setTimeout(ee,5e3),t().notifications.onClicked.addListener(async e=>{if(e.startsWith("todo_")){const e=await t().tabs.query({url:["https://web.whatsapp.com/*","https://web.whatsapp.com/"]});e.length>0&&e[0].id?(await t().tabs.update(e[0].id,{active:!0}),e[0].windowId&&await t().windows.update(e[0].windowId,{focused:!0})):await t().tabs.create({url:"https://web.whatsapp.com/"})}}),t().runtime.onMessage.addListener((e,a,s)=>"TODO_SNOOZE"===e.type?((async()=>{try{const a=(await t().storage.local.get(Z))[Z];if(!a||!a.todos)return void s({success:!1,error:"Todo state not found"});const n=a.todos.findIndex(t=>t.id===e.todoId);if(-1===n)return void s({success:!1,error:"Todo not found"});const r=a.todos[n],i=e.snoozeMinutes||15,o=Date.now()+60*i*1e3,c=new Date(o);a.todos[n]={...r,reminderDate:o,reminderTime:`${String(c.getHours()).padStart(2,"0")}:${String(c.getMinutes()).padStart(2,"0")}`,notified:!1,updatedAt:Date.now()},a.version=(a.version||0)+1,await t().storage.local.set({[Z]:a});try{await A({type:"TODO_UPDATE_LOCAL",todoId:e.todoId,updates:{reminderDate:o,reminderTime:`${String(c.getHours()).padStart(2,"0")}:${String(c.getMinutes()).padStart(2,"0")}`,notified:!1}})}catch(e){}s({success:!0,nextReminder:o})}catch(e){s({success:!1,error:e.message})}})(),!0):"TODO_COMPLETE"===e.type||"TODO_MARK_DONE"===e.type?((async()=>{try{const a=(await t().storage.local.get(Z))[Z];if(!a||!a.todos)return void s({success:!1,error:"Todo state not found"});const n=a.todos.findIndex(t=>t.id===e.todoId);if(-1===n)return void s({success:!1,error:"Todo not found"});const r=a.todos[n],i=a.categories?.find(e=>e.id===r.categoryId);a.todos[n]={...r,status:"completed",completedAt:Date.now(),notified:!0,updatedAt:Date.now()},a.version=(a.version||0)+1,await t().storage.local.set({[Z]:a}),await te("completed",a.todos[n],i);try{const t=a.todos[n].completedAt;await A({type:"TODO_UPDATE_LOCAL",todoId:e.todoId,updates:{status:"completed",completedAt:t,notified:!0}})}catch(e){}s({success:!0})}catch(e){s({success:!1,error:e.message})}})(),!0):void 0),t().runtime.onMessage.addListener((e,a,s)=>{if("GET_FLUXO_MEDIA"===e.type)return(async()=>{try{const{nodeId:a,flowId:n}=e,r=`fluxo_media_${n}_${a}`,i=await t().storage.local.get(r);i[r]?s({success:!0,mediaData:i[r]}):s({success:!1,error:"Media not found"})}catch(e){s({success:!1,error:e.message})}})(),!0});const ae="wa_schedules";async function se(){try{const e=(await t().storage.local.get(ae))[ae]||[];if(!e.length)return;const a=Date.now();e.forEach((e,t)=>{});let s=!1;for(const n of e){if(!n.isActive)continue;if("count"===n.endType&&n.executionCount>=(n.endAfterCount||0)){n.isActive=!1,s=!0;continue}if("date"===n.endType&&n.endDate&&a>n.endDate){n.isActive=!1,s=!0;continue}let e=!1;if("once"===n.mode)n.scheduledAt&&n.scheduledAt<=a&&!n.lastExecutedAt&&(e=!0);else if("repeated"===n.mode&&n.nextExecutionAt&&n.nextExecutionAt<=a)if(!n.runAnytime&&n.runBetweenStart&&n.runBetweenEnd){const t=new Date,a=60*t.getHours()+t.getMinutes(),[s,r]=n.runBetweenStart.split(":").map(Number),[i,o]=n.runBetweenEnd.split(":").map(Number),c=60*s+r,d=60*i+o;e=c<=d?a>=c&&a<=d:a>=c||a<=d}else e=!0;if(e){const e=await t().tabs.query({url:["https://web.whatsapp.com/*","https://web.whatsapp.com/"]});if(e.length>0&&e[0].id)try{await t().tabs.sendMessage(e[0].id,{type:"EXECUTE_SCHEDULED_MESSAGE",schedule:n}),n.lastExecutedAt=a,n.executionCount=(n.executionCount||0)+1,"repeated"===n.mode?(n.nextExecutionAt=ne(n),"count"===n.endType&&n.endAfterCount&&n.executionCount>=n.endAfterCount&&(n.isActive=!1)):n.isActive=!1,s=!0}catch(e){}else n.autoSendIfMissed||n.mode}}s&&await t().storage.local.set({[ae]:e})}catch(e){}}function ne(e){const t=new Date,a=e.lastExecutedAt?new Date(e.lastExecutedAt):t;if(!e.repeatedType)return t.getTime();switch(e.repeatedType){case"minute":{const t=e.repeatInterval||1;return a.getTime()+60*t*1e3}case"hour":{const t=e.repeatInterval||1;return a.getTime()+60*t*60*1e3}case"daily":{const a=e.timeEntries||[];if(0===a.length)return t.getTime()+864e5;const s=[...a].sort((e,t)=>{const[a,s]=e.time.split(":").map(Number),[n,r]=t.time.split(":").map(Number);return 60*a+s-(60*n+r)});for(const e of s){const[a,s]=e.time.split(":").map(Number),n=new Date(t);if(n.setHours(a,s,0,0),n>t)return n.getTime()}const[n,r]=s[0].time.split(":").map(Number),i=new Date(t);return i.setDate(i.getDate()+1),i.setHours(n,r,0,0),i.getTime()}case"weekly":{const a=e.timeEntries||[];if(0===a.length)return t.getTime()+6048e5;const s={};for(const e of a){const t=e.day||1;s[t]||(s[t]=[]),s[t].push(e)}const n=t.getDay()||7;for(let e=0;e<7;e++){const a=(n-1+e)%7+1;if(s[a]){const n=s[a].sort((e,t)=>{const[a,s]=e.time.split(":").map(Number),[n,r]=t.time.split(":").map(Number);return 60*a+s-(60*n+r)});for(const a of n){const[s,n]=a.time.split(":").map(Number),r=new Date(t);if(r.setDate(r.getDate()+e),r.setHours(s,n,0,0),r>t)return r.getTime()}}}const r=Object.keys(s).map(Number),i=Math.min(...r),o=s[i][0],[c,d]=o.time.split(":").map(Number),l=(i-n+7)%7||7,u=new Date(t);return u.setDate(u.getDate()+l),u.setHours(c,d,0,0),u.getTime()}case"monthly":{const a=e.timeEntries||[];if(0===a.length)return t.getTime()+2592e6;const s={};for(const e of a){const t=e.date||1;s[t]||(s[t]=[]),s[t].push(e)}const n=t.getDate(),r=Object.keys(s).map(Number).sort((e,t)=>e-t);for(const e of r)if(e>=n){const a=s[e].sort((e,t)=>{const[a,s]=e.time.split(":").map(Number),[n,r]=t.time.split(":").map(Number);return 60*a+s-(60*n+r)});for(const s of a){const[a,n]=s.time.split(":").map(Number),r=new Date(t);if(r.setDate(e),r.setHours(a,n,0,0),r>t)return r.getTime()}}const i=r[0],o=s[i][0],[c,d]=o.time.split(":").map(Number),l=new Date(t);return l.setMonth(l.getMonth()+1),l.setDate(i),l.setHours(c,d,0,0),l.getTime()}case"yearly":{const a=e.timeEntries||[];if(0===a.length)return t.getTime()+31536e6;const s=a.map(e=>({...e,month:e.month||1,date:e.date||1})).sort((e,t)=>{if(e.month!==t.month)return e.month-t.month;if(e.date!==t.date)return e.date-t.date;const[a,s]=e.time.split(":").map(Number),[n,r]=t.time.split(":").map(Number);return 60*a+s-(60*n+r)});for(const e of s){const[a,s]=e.time.split(":").map(Number),n=new Date(t);if(n.setMonth(e.month-1),n.setDate(e.date),n.setHours(a,s,0,0),n>t)return n.getTime()}const n=s[0],[r,i]=n.time.split(":").map(Number),o=new Date(t);return o.setFullYear(o.getFullYear()+1),o.setMonth(n.month-1),o.setDate(n.date),o.setHours(r,i,0,0),o.getTime()}default:return t.getTime()+864e5}}setInterval(()=>{se()},3e4),setTimeout(se,15e3),t().runtime.onMessage.addListener((e,a,s)=>{if("KANBAN_GET_PROFILE_PICS"===e.type)return(async()=>{try{const a=await t().tabs.query({url:["https://web.whatsapp.com/*","https://web.whatsapp.com/"]});if(0===a.length||!a[0].id)return void s({error:"WhatsApp Web not open",profilePics:{}});const n=await t().tabs.sendMessage(a[0].id,{type:"GET_PROFILE_PICS_FOR_KANBAN",chatIds:e.chatIds});s(n)}catch(e){s({error:e.message||"Failed to get profile pics",profilePics:{}})}})(),!0});let re=!1;async function ie(){if(!re){re=!0;try{const e=(0,n.Tt)(),a=(0,n.fI)();if(!e||!a)return;const s=(await t().storage.local.get(["license","phoneNumber"])).license;if(!s?.signature)return;const i=await r(s.signature),o=`${e}/public/whatsapp-queue-api.php?action=get_pending&limit=5&admin_id=${a}`,c=await fetch(o,{method:"GET",headers:{"X-Signature-Hash":i,"X-Admin-Id":a}});if(!c.ok)return;const d=await c.json();if(!d.success||!d.messages||0===d.messages.length)return;const l=await t().tabs.query({url:"*://web.whatsapp.com/*"});if(!l||0===l.length)return;for(const s of d.messages)try{let n=s.to_number.replace(/[^0-9]/g,"");n.includes("@")||(n+="@c.us");const r=await t().tabs.sendMessage(l[0].id,{type:"WA_QUEUE_SEND_MESSAGE",chatId:n,message:s.message_text}),o=`${e}/public/whatsapp-queue-api.php`,c=new URLSearchParams;c.append("action","mark_sent"),c.append("message_id",s.id.toString()),c.append("status",r?.success?"sent":"failed"),r?.success||c.append("error_message",r?.error||"Send failed"),await fetch(o,{method:"POST",headers:{"X-Signature-Hash":i,"X-Admin-Id":a,"Content-Type":"application/x-www-form-urlencoded"},body:c.toString()}),await new Promise(e=>setTimeout(e,2e3))}catch(e){}}catch(e){e.message}finally{re=!1}}}setInterval(ie,3e4),setTimeout(ie,1e4);const oe=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;function ce(e){return e?e.replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/&apos;/gi,"'").replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(parseInt(t,10))).replace(/&#x([0-9a-fA-F]+);/g,(e,t)=>String.fromCharCode(parseInt(t,16))):""}t().runtime.onMessage.addListener((e,a,s)=>{if(e&&"object"==typeof e){if("GMAPS_OPEN_MAPS_TAB"===e.action)return t().tabs.create({url:"https://www.google.com/maps/"}).then(()=>s({ok:!0})).catch(e=>s({ok:!1,error:String(e)})),!0;if("GMAPS_FETCH_EMAIL"===e.action){const t="string"==typeof e.url?e.url:"";return t?(async function(e){try{const t=new AbortController,a=setTimeout(()=>t.abort(),5e3),s=await fetch(e,{signal:t.signal,redirect:"follow",credentials:"omit",headers:{Accept:"text/html,*/*"}});if(clearTimeout(a),!s.ok)return null;const n=await s.text(),h=n.length>2e5?n.slice(0,2e5):n,r=h.match(oe);let email=null;if(r){const e=r[0].toLowerCase();/example\.|yourdomain|sentry|wixpress|cloudflare|sitelock|no-?reply/.test(e)||(email=e)}const insta=h.match(/(?:https?:)?\/\/(?:www\.)?instagram\.com\/([a-zA-Z0-9_\.-]+)/i);const instagram=insta?"https://www.instagram.com/"+insta[1]:null;return{email,instagram}}catch{return null}}(t).then(e=>s(e||{email:null,instagram:null})),!0):void s({email:null,instagram:null})}}}),t().runtime.onMessage.addListener((e,t,a)=>{if(!e||"SCRAPE_URL"!==e.type)return;const s="string"==typeof e.url?e.url.trim():"";return s?((async()=>{try{const e=await fetch(s,{method:"GET",credentials:"omit",headers:{Accept:"text/html,application/xhtml+xml"}});if(!e.ok)return void a({success:!1,error:`HTTP ${e.status} ${e.statusText}`});const t=e.headers.get("content-type")||"",n=await e.text();let r="",i="";if(/text\/html|application\/xhtml/i.test(t)||/<html|<body|<title/i.test(n)){const e=function(e){if(!e)return{title:"",text:""};const t=e.match(/<title[^>]*>([\s\S]*?)<\/title>/i),a=t?ce(t[1]).trim():"";let s=e;return s=s.replace(/<script[\s\S]*?<\/script>/gi," "),s=s.replace(/<style[\s\S]*?<\/style>/gi," "),s=s.replace(/<noscript[\s\S]*?<\/noscript>/gi," "),s=s.replace(/<nav[\s\S]*?<\/nav>/gi," "),s=s.replace(/<footer[\s\S]*?<\/footer>/gi," "),s=s.replace(/<header[\s\S]*?<\/header>/gi," "),s=s.replace(/<aside[\s\S]*?<\/aside>/gi," "),s=s.replace(/<svg[\s\S]*?<\/svg>/gi," "),s=s.replace(/<form[\s\S]*?<\/form>/gi," "),s=s.replace(/<!--[\s\S]*?-->/g," "),s=s.replace(/<\/(p|div|li|h[1-6]|tr|br)\s*>/gi,"\n"),s=s.replace(/<br\s*\/?>/gi,"\n"),s=s.replace(/<[^>]+>/g," "),s=ce(s),s=s.replace(/\r/g,""),s=s.replace(/[ \t]+/g," "),s=s.replace(/ *\n */g,"\n"),s=s.replace(/\n{3,}/g,"\n\n"),s=s.trim(),{title:a,text:s}}(n);r=e.title||s,i=e.text}else r=s,i=(n||"").trim();if(!i)return void a({success:!1,error:"No readable text found on the page"});a({success:!0,data:{title:r,text:i}})}catch(e){a({success:!1,error:e?.message||"Scrape failed"})}})(),!0):(a({success:!1,error:"URL is required"}),!0)})})()})();
