import{M as U}from"./api-D2MZ7O5A.js";import{S as Ke}from"./messages-CjQo1qp0.js";import{S as h}from"./storage-pXeRtiJs.js";import{c as Ze,C as _,S as g,a as me}from"./util_positioning-Cx352_Ay.js";import{s as Je,a as Te,g as Le,b as Ie,c as Qe,d as et,e as tt}from"./mem0_proxy-D5oyS3vJ.js";Je();async function nt(){try{const e=await Qe();chrome.runtime.sendMessage({action:Ke.OPEN_DASHBOARD,url:e})}catch(e){console.warn("Unable to open Memory Platform dashboard",e)}}let v=[],R=!1,z=!1,Q=!0,P="",se=0,_e=null;const ve=Ze({fetch:async function(e,t){if(!await Ie())return[];const i=await et([h.SIMILARITY_THRESHOLD,h.TOP_K]),c=typeof i[h.SIMILARITY_THRESHOLD]=="number"?i[h.SIMILARITY_THRESHOLD]:.1,o=typeof i[h.TOP_K]=="number"?i[h.TOP_K]:10,r=(function(){try{const l=me.memory_header_plain_regex;return String(e).replace(l,"").trim()}catch{return e}})();return(await tt(r,{limit:o,signal:t?.signal})).filter(l=>typeof l.relevance!="number"?!0:l.relevance>=c)},onSuccess:function(e,t){if(!R)return;const n=(t||[]).map((i,c)=>({id:String(i.id||`memory-${Date.now()}-${c}`),text:i.memory,categories:i.categories||[]}));Ae(n,!1,_e)},onError:function(){R&&Ae([],!1,_e)},minLength:3,debounceMs:800,cacheTTL:6e4,abortPrevious:!1});let $=[];const Pe=12;function J(e,t){if(!t||!t.trim())return;const n=t.trim();if($.length>0){const c=$[$.length-1];if(c&&c.role===e&&c.content===n)return}const i={role:e,content:n,timestamp:Date.now()};$.push(i),$.length>Pe&&$.splice(0,$.length-Pe)}function Fe(e=!0){if($.length===0)return[];let t=[...$];return!e&&t.length>0&&(t=t.slice(0,-1)),t.slice(-6).map(i=>({role:i.role,content:i.content}))}function Xe(){const e=document.querySelector(".flex-1.flex.flex-col.gap-3.px-4.max-w-3xl.mx-auto.w-full");if(!e)return;Array.from(e.children).forEach(n=>{const i=n.querySelector(".font-user-message"),c=n.querySelector(".font-claude-message");if(i){const o=(i.textContent||"").trim();o&&J(U.User,o)}else if(c){const o=(c.textContent||"").trim();o&&J(U.Assistant,o)}})}const j=new Set;let C=null,X=null,re=null;async function qe(){return new Promise(e=>{if(!chrome||!chrome.storage||!chrome.storage.sync){console.log("⚠️ Chrome extension context invalid, defaulting to enabled"),e(!0);return}try{chrome.storage.sync.get(h.MEMORY_ENABLED,function(t){try{if(chrome.runtime&&chrome.runtime.lastError){console.log("⚠️ Chrome storage error, defaulting to enabled:",chrome.runtime.lastError),e(!0);return}console.log("🧠 Memory enabled from storage:",t.memory_enabled),e(t.memory_enabled)}catch{}})}catch(t){console.log("⚠️ Exception getting memory state, defaulting to enabled:",t),e(!0)}})}function ot(){const e=document.querySelector("#mem0-button");if(e){const n=e.closest("div");n?n.remove():e.remove()}const t=document.querySelector("#mem0-tooltip");t&&t.remove()}function Me(e,t="top"){const n=document.createElement("div");n.className="mem0-popup";let i="";return t==="top"?i=`
      bottom: 100%;
      left: 50%;
      transform: translateX(-40%);
      margin-bottom: 11px;
    `:t==="right"&&(i=`
      top: 50%;
      left: 100%;
      transform: translateY(-50%);
      margin-left: 11px;
    `),n.style.cssText=`
  display: none;
  position: absolute;
  background-color: #21201C;
  color: white;
  padding: 6px 8px;
  border-radius: 6px;
  font-size: 12px;
  z-index: 10000;
  white-space: nowrap;
  box-shadow: 0 2px 5px rgba(0,0,0,0.2);
  ${i}
      `,e.appendChild(n),n}const $e=document.querySelector('button[aria-label="Send Message"]'),je=document.querySelector('button[aria-label="Send message"]'),xe=document.querySelector('button[aria-label="Capture screenshot"]'),Y=document.querySelector("#input-tools-menu-trigger"),ke=document.querySelector("#mem0-button")||document.getElementById("mem0-icon-button")||document.querySelector('[id*="mem0"], .mem0-btn');if(Y&&!ke){const e=document.createElement("div");e.style.position="relative",e.style.display="inline-block";const t=document.createElement("button");t.id="mem0-button",t.className=Y.className,t.style.marginLeft="0px",t.setAttribute("aria-label","Add memories to your prompt");const n=document.createElement("img");n.src=chrome.runtime.getURL("icons/icon48.png"),n.style.width="16px",n.style.height="16px",n.style.borderRadius="50%";const i=Me(e,"top");t.appendChild(n),t.addEventListener("click",()=>{if(Q){const s=document.querySelector("#mem0-tooltip");s&&(s.style.display="none"),ae(i)}});const c=document.createElement("div");if(c.id="mem0-notification-dot",c.style.cssText=`
    position: absolute;
    top: -3px;
    right: -3px;
    width: 10px;
    height: 10px;
    background-color: rgb(128, 221, 162);
    border-radius: 50%;
    border: 2px solid #1C1C1E;
    display: none;
    z-index: 1001;
    pointer-events: none;
  `,t.appendChild(c),!document.getElementById("notification-dot-animation")){const s=document.createElement("style");s.id="notification-dot-animation",s.innerHTML=`
      @keyframes popIn {
        0% { transform: scale(0); }
        50% { transform: scale(1.2); }
        100% { transform: scale(1); }
      }
      
      #mem0-notification-dot.active {
        display: block !important;
        animation: popIn 0.3s ease-out forwards;
      }
    `,document.head.appendChild(s)}e.appendChild(t);const o=document.createElement("div");o.id="mem0-tooltip",o.textContent="Add memories to your prompt",o.style.cssText=`
              display: none;
              position: fixed;
              background-color: black;
              color: white;
              padding: 3px 7px;
              border-radius: 6px;
              font-size: 12px;
              z-index: 10000;
              pointer-events: none;
              white-space: nowrap;
              transform: translateX(-50%);
          `,document.body.appendChild(o),t.addEventListener("mouseenter",()=>{const s=document.querySelector('.mem0-popup[style*="display: block"]');s&&s!==i&&(s.style.display="none");const l=t.getBoundingClientRect(),a=l.left+l.width/2;o.style.display="block";const p=o.offsetHeight||24;o.style.left=`${a}px`,o.style.top=`${l.top-p-10}px`}),t.addEventListener("mouseleave",()=>{o.style.display="none"});const r=Y.closest(".relative.flex-1.flex.items-center.gap-2")||Y.closest(".relative.flex-1")||Y.parentNode?.parentNode?.parentNode?.parentNode?.parentNode;if(r){const s=r.querySelector(".flex.flex-row.items-center.gap-2.min-w-0"),l=Y.closest("div > div > div > div")?.parentNode?.parentNode;s&&l?r.insertBefore(e,s):r.appendChild(e)}else Y.parentNode?.insertBefore(e,Y.nextSibling);ee()}else if(window.location.href.includes("claude.ai/new")&&xe&&!ke){const e=document.createElement("div");e.style.position="relative",e.style.display="inline-block";const t=document.createElement("button");t.id="mem0-button",t.className=xe.className,t.style.marginLeft="0px",t.setAttribute("aria-label","Add memories to your prompt");const n=document.createElement("img");n.src=chrome.runtime.getURL("icons/icon48.png"),n.style.width="16px",n.style.height="16px",n.style.borderRadius="50%";const i=Me(e,"right");t.appendChild(n),t.addEventListener("click",()=>{if(Q){const r=document.querySelector("#mem0-tooltip");r&&(r.style.display="none"),ae(i)}});const c=document.createElement("div");c.id="mem0-notification-dot",c.style.cssText=`
        position: absolute;
        top: -3px;
        right: -3px;
        width: 10px;
        height: 10px;
        background-color: rgb(128, 221, 162);
        border-radius: 50%;
        border: 2px solid #1C1C1E;
        display: none;
        z-index: 1001;
        pointer-events: none;
      `,t.appendChild(c),e.appendChild(t);const o=document.createElement("div");o.id="mem0-tooltip",o.textContent="Add memories to your prompt",o.style.cssText=`
              display: none;
              position: fixed;
              background-color: black;
              color: white;
              padding: 3px 7px;
              border-radius: 6px;
              font-size: 12px;
              z-index: 10000;
              pointer-events: none;
              white-space: nowrap;
              transform: translateX(-50%);
          `,document.body.appendChild(o),t.addEventListener("mouseenter",()=>{const r=document.querySelector('.mem0-popup[style*="display: block"]');r&&r!==i&&(r.style.display="none");const s=t.getBoundingClientRect(),l=s.left+s.width/2;o.style.display="block";const a=o.offsetHeight||24;o.style.left=`${l}px`,o.style.top=`${s.top-a-10}px`}),t.addEventListener("mouseleave",()=>{o.style.display="none"}),xe.parentNode?.insertBefore(e,xe.nextSibling),ee()}else if(($e||je)&&!ke){const e=$e||je;if(e){const t=e.parentNode;if(t){const n=document.createElement("div");n.style.position="relative",n.style.display="inline-block",n.style.marginRight="12px";const i=document.createElement("button");i.id="mem0-button",i.style.cssText=`
        display: flex;
        align-items: center;
        justify-content: center;
        width: 32px;
        height: 32px;
        padding: 0;
        background: transparent;
        border: none;
        cursor: pointer;
        border-radius: 8px;
        position: relative;
        transition: background-color 0.3s ease;
      `,i.setAttribute("aria-label","Add memories to your prompt");const c=document.createElement("img");c.src=chrome.runtime.getURL("icons/icon48.png"),c.style.width="20px",c.style.height="20px",c.style.borderRadius="50%";const o=document.createElement("div");o.id="mem0-notification-dot",o.style.cssText=`
        position: absolute;
        top: 0px;
        right: 0px;
        width: 10px;
        height: 10px;
        background-color: rgb(128, 221, 162);
        border-radius: 50%;
        border: 2px solid #1C1C1E;
        display: none;
        z-index: 1001;
        pointer-events: none;
      `;const r=Me(n,"top");i.appendChild(c),i.appendChild(o),i.addEventListener("click",()=>{if(Q){const l=document.querySelector("#mem0-tooltip");l&&(l.style.display="none"),ae(r)}});const s=document.createElement("div");s.id="mem0-tooltip",s.textContent="Add memories to your prompt",s.style.cssText=`
                  display: none;
                  position: fixed;
                  background-color: black;
                  color: white;
                  padding: 3px 7px;
                  border-radius: 6px;
                  font-size: 12px;
                  z-index: 10000;
                  pointer-events: none;
                  white-space: nowrap;
                  transform: translateX(-50%);
              `,document.body.appendChild(s),i.addEventListener("mouseenter",()=>{const l=document.querySelector('.mem0-popup[style*="display: block"]');l&&l!==r&&(l.style.display="none");const a=i.getBoundingClientRect(),p=a.left+a.width/2;s.style.display="block";const u=s.offsetHeight||24;s.style.left=`${p}px`,s.style.top=`${a.top-u-10}px`}),i.addEventListener("mouseleave",()=>{i.style.backgroundColor="transparent",r.style.display="none"}),r.textContent="Add memories to your prompt",n.appendChild(i),t.querySelector('button[aria-label="Send message"]')?t.insertBefore(n,t.querySelector('button[aria-label="Send message"]')):t.insertBefore(n,e),ee()}}}const D=document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea")||document.querySelector('p[data-placeholder="How can I help you today?"]')||document.querySelector('p[data-placeholder="Reply to Claude..."]');if(D&&!D.dataset.mem0KeyListener&&(D.dataset.mem0KeyListener="true",D.addEventListener("keydown",function(e){const t=e;if(t.key==="Enter"&&!t.shiftKey&&!t.ctrlKey&&!t.metaKey&&D.tagName.toLowerCase()!=="textarea"){const n=B();n&&n.trim()!==""&&(P=n),se=Date.now(),G(P),setTimeout(()=>{v=[],j.clear()},100)}}),!D.dataset.mem0CacheListener)){D.dataset.mem0CacheListener="true";const e=()=>{const t=B();t&&t.trim()!==""&&(P=t)};D.addEventListener("input",e,!0),D.addEventListener("compositionend",e,!0)}ee();function Ae(e,t=!1,n=null){if(console.log("🎯 createMemoryModal called",{memoryItems:e,isLoading:t,sourceButtonId:n,memoryModalShown:R}),R){console.log("🗂️ Closing existing modal");try{typeof re=="function"&&re()}catch{}if(X&&X.isConnected)try{X.remove()}catch{}C&&document.body.contains(C)&&document.body.removeChild(C)}R=!0,console.log("✅ Modal state set to shown");let i=0;const c=447;let o=400,r=3;function s(){if(n){const m=document.getElementById(n);if(m)return m}const d=document.querySelector("#mem0-icon-button");return d||document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea")||document.querySelector('p[data-placeholder="How can I help you today?"]')||document.querySelector('p[data-placeholder="Reply to Claude..."]')}const l=s();let a="bottom";if(l){const d=l.getBoundingClientRect(),m=window.innerHeight;d.top>=o+10?(a="top",r=3):(a="bottom",d.bottom>m/2&&(o=300,r=2))}const p=document.createElement("div");p.style.cssText=`
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: transparent;
    display: flex;
    z-index: 10000;
    pointer-events: auto;
  `,C=p,p.addEventListener("click",d=>{d.target===p&&Oe()});const u=document.createElement("div");u.style.cssText=`
    background-color: #1e293b;
    border-radius: 12px;
    width: ${c}px;
    height: ${o}px;
    display: flex;
    flex-direction: column;
    color: white;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    pointer-events: auto;
    border: 1px solid #334155;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    overflow: hidden;
  `;let w=()=>{};if(_&&l){let d=typeof g<"u"&&g.claude?g.claude:null,m=d&&d.placement||{strategy:"dock",container:"form",side:a==="top"?"top":"bottom",align:"start",gap:8};w=_.applyPlacement({container:u,anchor:l,placement:m})}else document.body.appendChild(u),Object.assign(u.style,{position:"fixed",left:"50%",top:"20%",transform:"translateX(-50%)",zIndex:"2147483647"});X=u,re=w;const x=document.createElement("div");x.style.cssText=`
    display: flex;
    align-items: center;
    padding: 10px 16px;
    justify-content: space-between;
    background-color: #334155;
    flex-shrink: 0;
    cursor: move;
    user-select: none;
  `;let f=!1,b={x:0,y:0};x.addEventListener("mousedown",d=>{if(d.target===x||d.target===V||d.target===H||d.target===S){f=!0;const m=u.getBoundingClientRect();b.x=d.clientX-m.left,b.y=d.clientY-m.top,u.style.position="fixed",u.style.left=m.left+"px",u.style.top=m.top+"px",u.style.transform="none",u.style.zIndex="2147483647",d.preventDefault()}}),document.addEventListener("mousemove",d=>{if(f&&u){const m=d.clientX-b.x,y=d.clientY-b.y,q=window.innerWidth-u.offsetWidth,L=window.innerHeight-u.offsetHeight;u.style.left=Math.max(0,Math.min(m,q))+"px",u.style.top=Math.max(0,Math.min(y,L))+"px"}}),document.addEventListener("mouseup",()=>{f=!1});const S=document.createElement("div");S.style.cssText=`
    display: flex;
    flex-direction: row;
    align-items: center;
  `;const H=document.createElement("img");H.src=chrome.runtime.getURL("icons/icon48.png"),H.style.cssText=`
    width: 26px;
    height: 26px;
    border-radius: 50%;
    margin-right: 10px;
  `;const V=document.createElement("div");V.textContent="Cogniz Memory",V.style.cssText=`
    font-size: 16px;
    font-weight: 600;
    color: white;
  `;const K=document.createElement("div");K.style.cssText=`
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 8px;
  `;const E=document.createElement("button");E.style.cssText=`
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 5px 16px;
    gap: 8px;
    background-color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 12px;
    font-weight: 600;
    color: black;
  `,E.textContent="Add to Prompt";const te=document.createElement("span");te.innerHTML=`<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
    <path d="M5 12h14M12 5l7 7-7 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  </svg>`,E.appendChild(te);const O=document.createElement("button");O.style.cssText=`
    background: none;
    border: none;
    cursor: pointer;
    padding: 8px;
    opacity: 0.6;
    transition: opacity 0.2s;
  `,O.innerHTML=`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#FFFFFF" xmlns="http://www.w3.org/2000/svg">
    <path d="M12 15a3 3 0 100-6 3 3 0 000 6z" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
    <path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-2 2 2 2 0 01-2-2v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83 0 2 2 0 010-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 01-2-2 2 2 0 012-2h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 010-2.83 2 2 0 012.83 0l.06.06a1.65 1.65 0 001.82.33H9a1.65 1.65 0 001-1.51V3a2 2 0 012-2 2 2 0 012 2v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 0 2 2 0 010 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9a1.65 1.65 0 001.51 1H21a2 2 0 012 2 2 2 0 01-2 2h-.09a1.65 1.65 0 00-1.51 1z" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  </svg>`,O.addEventListener("click",()=>{C&&document.body.contains(C)&&(document.body.removeChild(C),R=!1,C=null),chrome.runtime.sendMessage({action:Ke.SIDEBAR_SETTINGS})}),O.addEventListener("mouseenter",()=>{O.style.opacity="1"}),O.addEventListener("mouseleave",()=>{O.style.opacity="0.6"});const ce=document.createElement("div"),Re=o-130;ce.style.cssText=`
    display: flex;
    flex-direction: column;
    padding: 0 16px;
    gap: 12px;
    overflow: hidden;
    flex: 1;
    height: ${Re}px;
  `;const F=document.createElement("div");F.style.cssText=`
    font-size: 16px;
    font-weight: 600;
    color: #FFFFFF;
    margin-top: 16px;
    flex-shrink: 0;
  `,t?F.textContent="Loading Relevant Memories...":e.length===0?F.textContent="No Relevant Memories":F.textContent=`${e.length} Relevant Memories`;const Ve=Re-40,I=document.createElement("div");I.style.cssText=`
    display: flex;
    flex-direction: column;
    gap: 8px;
    overflow-y: auto;
    flex: 1;
    max-height: ${Ve}px;
    padding-right: 8px;
    margin-right: -8px;
    scrollbar-width: none;
    -ms-overflow-style: none;
  `,I.style.cssText+="::-webkit-scrollbar { display: none; }";let de=null;function Ne(){I.innerHTML="";for(let d=0;d<r;d++){const m=document.createElement("div");m.style.cssText=`
        display: flex;
        flex-direction: row;
        align-items: flex-start;
        justify-content: space-between;
        padding: 12px;
        background-color: #1e293b;
        border-radius: 8px;
        height: 72px;
        flex-shrink: 0;
        animation: pulse 1.5s infinite ease-in-out;
      `;const y=document.createElement("div");y.style.cssText=`
        background-color: #383838;
        border-radius: 4px;
        height: 14px;
        width: 85%;
        margin-bottom: 8px;
      `;const q=document.createElement("div");q.style.cssText=`
        background-color: #383838;
        border-radius: 4px;
        height: 14px;
        width: 65%;
      `;const L=document.createElement("div");L.style.cssText=`
        display: flex;
        gap: 4px;
        margin-left: 10px;
      `;const A=document.createElement("div");A.style.cssText=`
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background-color: #383838;
      `;const k=document.createElement("div");k.style.cssText=`
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background-color: #383838;
      `,L.appendChild(A),L.appendChild(k);const N=document.createElement("div");N.style.cssText=`
        display: flex;
        flex-direction: column;
        flex-grow: 1;
      `,N.appendChild(y),N.appendChild(q),m.appendChild(N),m.appendChild(L),I.appendChild(m)}if(!document.getElementById("skeleton-animation")){const d=document.createElement("style");d.id="skeleton-animation",d.innerHTML=`
        @keyframes pulse {
          0% { opacity: 0.6; }
          50% { opacity: 0.8; }
          100% { opacity: 0.6; }
        }
      `,document.head.appendChild(d)}}function We(d,m,y,q,L){de&&de!==d&&de.dispatchEvent(new Event("collapse")),L.value=!0,m.style.webkitLineClamp="unset",m.style.height="auto",y.style.overflowY="auto",y.style.maxHeight="240px",y.style.scrollbarWidth="none",y.style.msOverflowStyle="none",y.style.cssText+="::-webkit-scrollbar { display: none; }",d.style.backgroundColor="#1C1C1E",d.style.maxHeight="300px",d.style.overflow="hidden",q.style.display="flex",de=d,I.scrollTop=d.offsetTop-I.offsetTop}function Be(d,m,y,q,L){L.value=!1,m.style.webkitLineClamp="2",m.style.height="42px",y.style.overflowY="visible",d.style.backgroundColor="#27272A",d.style.maxHeight="72px",d.style.overflow="hidden",q.style.display="none",de=null}function ne(){if(I.innerHTML="",t){Ne();return}if(e.length===0){Ee(),Ce(0,0);return}E&&(E.disabled=!1,E.style.opacity="1",E.style.cursor="pointer");const d=Math.min(r,e.length),m=Math.ceil(e.length/d),y=Math.floor(i/d)+1;Ce(y,m);for(let q=0;q<d;q++){const L=i+q;if(L>=e.length)break;const A=e[L];if(!A||j.has(String(A.id)))continue;A.id||(A.id=`memory-${Date.now()}-${L}`);const k=document.createElement("div");k.style.cssText=`
        display: flex;
        flex-direction: row;
        align-items: flex-start;
        justify-content: space-between;
        padding: 12px;
        background-color: #1e293b;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.2s ease;
        min-height: 72px;
        max-height: 72px;
        overflow: hidden;
        flex-shrink: 0;
      `;const N=document.createElement("div");N.style.cssText=`
        font-size: 14px;
        line-height: 1.5;
        color: #D4D4D8;
        flex-grow: 1;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        transition: all 0.2s ease;
        height: 42px; /* Height for 2 lines of text */
      `,N.textContent=A.text||"";const he=document.createElement("div");he.style.cssText=`
        display: flex;
        gap: 4px;
        margin-left: 10px;
        flex-shrink: 0;
      `;const ge=document.createElement("button");ge.style.cssText=`
        border: none;
        cursor: pointer;
        padding: 4px;
        background:rgb(66, 66, 69);
        color:rgb(199, 199, 201);
        border-radius: 100%;
        transition: all 0.2s ease;
      `,ge.innerHTML=`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>`,ge.addEventListener("click",ue=>{ue.stopPropagation(),Te("memory_injection",{provider:"claude",source:"COGNIZ_CHROME_EXTENSION",browser:Le(),injected_all:!1,memory_id:A.id}),j.add(String(A.id)),v.push(String(A.text||"")),De();const pe=e.findIndex(Se=>Se.id===A.id);pe!==-1&&(e.splice(pe,1),i>0&&i>=e.length&&(i=Math.max(0,i-r)),F.textContent=`${e.length} Relevant Memories`,ne())});const ye=document.createElement("button");ye.style.cssText=`
        background: none;
        border: none;
        cursor: pointer;
        padding: 4px;
        color: #A1A1AA;
      `,ye.innerHTML=`<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
        <circle cx="12" cy="12" r="2"/>
        <circle cx="12" cy="5" r="2"/>
        <circle cx="12" cy="19" r="2"/>
      </svg>`;const oe={value:!1},W=document.createElement("button");W.style.cssText=`
        display: none;
        align-items: center;
        gap: 6px;
        background:rgb(66, 66, 69);
        color:rgb(199, 199, 201);
        border-radius: 8px;
        padding: 2px 4px;
        border: none;
        cursor: pointer;
        font-size: 13px;
        margin-top: 12px;
        width: fit-content;
      `,W.innerHTML=`
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        Remove
      `;const Z=document.createElement("div");Z.style.cssText=`
        display: flex;
        flex-direction: column;
        flex-grow: 1;
      `,Z.appendChild(N),Z.appendChild(W),k.addEventListener("collapse",()=>{Be(k,N,Z,W,oe)}),ye.addEventListener("click",ue=>{ue.stopPropagation(),oe.value?Be(k,N,Z,W,oe):We(k,N,Z,W,oe)}),W.addEventListener("click",ue=>{ue.stopPropagation();const pe=e.findIndex(Se=>Se.id===A.id);pe!==-1&&(e.splice(pe,1),i>0&&i>=e.length&&(i=Math.max(0,i-r)),F.textContent=`${e.length} Relevant Memories`,ne())}),he.appendChild(ge),he.appendChild(ye),k.appendChild(Z),k.appendChild(he),I.appendChild(k),k.addEventListener("mouseenter",()=>{k.style.backgroundColor=oe.value?"#18181B":"#323232"}),k.addEventListener("mouseleave",()=>{k.style.backgroundColor=oe.value?"#1C1C1E":"#27272A"})}I.children.length===0&&e.length>0&&(i>0?(i=Math.max(0,i-r),ne()):(Ce(0,0),Ee()))}function Ee(){I.innerHTML="",F.textContent="No Relevant Memories";const d=document.createElement("div");d.style.cssText=`
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 32px 16px;
      text-align: center;
      flex: 1;
      min-height: 200px;
    `;const m=document.createElement("div");m.innerHTML=`<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#71717A" xmlns="http://www.w3.org/2000/svg">
      <path d="M9 3H5a2 2 0 00-2 2v4m6-6h10a2 2 0 012 2v10a2 2 0 01-2 2h-4M3 21h4a2 2 0 002-2v-4m-6 6V9m18 12a9 9 0 11-18 0 9 9 0 0118 0z" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>`,m.style.marginBottom="16px";const y=document.createElement("div");y.textContent="No relevant memories found",y.style.cssText=`
      color: #71717A;
      font-size: 14px;
      font-weight: 500;
    `,d.appendChild(m),d.appendChild(y),I.appendChild(d),E&&(E.disabled=!0,E.style.opacity="0.5",E.style.cursor="not-allowed")}function Ce(d,m){if(e.length===0||m===0){M.disabled=!0,M.style.opacity="0.5",M.style.cursor="not-allowed",T.disabled=!0,T.style.opacity="0.5",T.style.cursor="not-allowed";return}d<=1?(M.disabled=!0,M.style.opacity="0.5",M.style.cursor="not-allowed"):(M.disabled=!1,M.style.opacity="1",M.style.cursor="pointer"),d>=m?(T.disabled=!0,T.style.opacity="0.5",T.style.cursor="not-allowed"):(T.disabled=!1,T.style.opacity="1",T.style.cursor="pointer")}const fe=document.createElement("div");fe.style.cssText=`
    display: flex;
    justify-content: center;
    gap: 12px;
    padding: 10px;
    border-top: none;
    flex-shrink: 0;
  `;const M=document.createElement("button");M.innerHTML=`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M15 19l-7-7 7-7" stroke="#A1A1AA" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  </svg>`,M.style.cssText=`
    background: #27272A;
    border: none;
    border-radius: 50%;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: background-color 0.2s;
  `;const T=document.createElement("button");T.innerHTML=`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M9 5l7 7-7 7" stroke="#A1A1AA" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  </svg>`,T.style.cssText=M.style.cssText,M.addEventListener("click",()=>{i>=r&&(i=Math.max(0,i-r),ne())}),T.addEventListener("click",()=>{i+r<e.length&&(i=i+r,ne())}),[M,T].forEach(d=>{d.addEventListener("mouseenter",()=>{d.disabled||(d.style.backgroundColor="#323232")}),d.addEventListener("mouseleave",()=>{d.disabled||(d.style.backgroundColor="#27272A")})}),S.appendChild(H),S.appendChild(V),K.appendChild(E),K.appendChild(O),x.appendChild(S),x.appendChild(K),ce.appendChild(F),ce.appendChild(I),fe.appendChild(M),fe.appendChild(T),u.appendChild(x),u.appendChild(ce),u.appendChild(fe),document.body.appendChild(p),t?Ne():e.length===0?Ee():ne();function Oe(){console.log("🚪 Closing modal");try{typeof w=="function"&&w()}catch{}try{typeof re=="function"&&re()}catch{}if(X&&X.isConnected)try{X.remove()}catch{}C&&document.body.contains(C)&&document.body.removeChild(C),p&&document.body.contains(p)&&document.body.removeChild(p),C=null,X=null,re=null,R=!1,z=!1}E.addEventListener("click",()=>{const d=e.filter(m=>!j.has(String(m.id))&&!m.removed).map(m=>(j.add(String(m.id)),String(m.text||"")));Te("memory_injection",{provider:"claude",source:"COGNIZ_CHROME_EXTENSION",browser:Le(),injected_all:!0,memory_count:d.length}),d.length>0&&(v=[...v,...d],De()),Oe();for(let m=e.length-1;m>=0;m--)j.has(String(e[m]?.id))&&e.splice(m,1)})}function De(){let e=document.querySelector('div[contenteditable="true"].ProseMirror');if(e||(e=document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea")||document.querySelector('p[data-placeholder="How can I help you today?"]')||document.querySelector('p[data-placeholder="Reply to Claude..."]')),e&&v.length>0){const t=me.memory_header_text;if(e.classList.contains("ProseMirror")){if(Array.from(e.querySelectorAll("p strong")).some(o=>(o.textContent||"").includes("Here is some of my memories"))){const o=Array.from(e.querySelectorAll("p"));let r=-1;const s=[];for(let l=0;l<o.length;l++){const a=o[l]?.querySelector("strong");if(a&&(a.textContent||"").includes("Here is some of my memories")){r=l;break}}if(r>=0){for(let u=r+1;u<o.length;u++){const w=o[u];if(!w)continue;const x=(w.textContent||"").trim();x.startsWith("-")&&s.push(x.substring(1).trim())}const l=Array.from(o).slice(0,r+1).map(u=>u.outerHTML).join(""),a=[...s];v.forEach(u=>{a.includes(u)||a.push(u)});const p=a.map(u=>`<p>- ${u}</p>`).join("");e.innerHTML=l+p}}else{const o=le(void 0);let r=`<p><strong>${t}</strong></p>`;r+=v.map(s=>`<p>- ${s}</p>`).join(""),!o||o.trim()===""||e.querySelectorAll("p").length===1&&e.querySelector("p.is-empty")!==null?e.innerHTML=r:e.innerHTML=`${o}<p><br></p>${r}`}const i=new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText"});e.dispatchEvent(i);const c=new Event("change",{bubbles:!0});e.dispatchEvent(c)}else if(e.tagName.toLowerCase()==="div"){if(e.innerHTML.includes(t)){const n=e.innerHTML.split(t);if(n.length>1){const i=n[0],c=n[1],o=document.createElement("div");o.innerHTML=c||"";const r=[];Array.from(o.querySelectorAll("p")).forEach(a=>{const p=(a.textContent||"").trim();p.startsWith("-")&&r.push(p.substring(1).trim())});const s=[...r];v.forEach(a=>{s.includes(a)||s.push(a)});let l=i+`<p><strong>${t}</strong></p>`;s.forEach(a=>{l+=`<p>- ${a}</p>`}),e.innerHTML=l}}else{const n=le(void 0);let i=`<p><strong>${t}</strong></p>`;v.forEach(c=>{i+=`<p>- ${c}</p>`}),e.innerHTML=`${n}${n?"<p><br></p>":""}${i}`}e.dispatchEvent(new Event("input",{bubbles:!0}))}else if(e.tagName.toLowerCase()==="p"&&(e.getAttribute("data-placeholder")==="How can I help you today?"||e.getAttribute("data-placeholder")==="Reply to Claude...")){if((e.textContent||"").includes(t)){const n=(e.textContent||"").split(t);if(n.length>1){const i=n[0],c=n[1],o=[];(c||"").split(`
`).forEach(a=>{const p=a.trim();p.startsWith("-")&&o.push(p.substring(1).trim())});const s=[...o];v.forEach(a=>{s.includes(a)||s.push(a)});const l=i+t+`

`+s.map(a=>`- ${a}`).join(`
`);e.textContent=l}}else{const n=le(void 0);e.textContent=`${n}${n?`

`:""}${t}

${v.map(i=>`- ${i}`).join(`
`)}`}e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("focus",{bubbles:!0})),e.dispatchEvent(new KeyboardEvent("keydown",{bubbles:!0})),e.dispatchEvent(new KeyboardEvent("keyup",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}else{if((e.value||"").includes(t)){const n=(e.value||"").split(t);if(n.length>1){const i=n[0],c=n[1],o=[];(c||"").split(`
`).forEach(a=>{const p=a.trim();p.startsWith("-")&&o.push(p.substring(1).trim())});const s=[...o];v.forEach(a=>{s.includes(a)||s.push(a)});const l=i+t+`

`+s.map(a=>`- ${a}`).join(`
`);e.value=l}}else{const n=le(void 0);e.value=`${n}${n?`

`:""}${t}

${v.map(i=>`- ${i}`).join(`
`)}`}e.dispatchEvent(new Event("input",{bubbles:!0}))}e.focus()}}function le(e){let t=document.querySelector('div[contenteditable="true"].ProseMirror');t||(t=document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea")||document.querySelector('p[data-placeholder="How can I help you today?"]')||document.querySelector('p[data-placeholder="Reply to Claude..."]'));let n="";if(typeof e=="string")n=e;else{if(!t)return"";t.classList.contains("ProseMirror")||t.tagName.toLowerCase()==="div"?n=t.innerHTML:t.tagName.toLowerCase()==="p"&&(t.getAttribute("data-placeholder")==="How can I help you today?"||t.getAttribute("data-placeholder")==="Reply to Claude...")?n=t.innerHTML||t.textContent||"":n=t.value||""}try{const i=me.memory_header_html_regex,c=me.memory_header_plain_regex;n=n.replace(i,""),n=n.replace(c,"")}catch{}return n=n.replace(/<p><br><\/p>$/g,""),n=n.replace(/<p class="is-empty"><br class="ProseMirror-trailingBreak"><\/p>$/g,""),n.trim()}async function ae(e,t=!1,n=null){if(console.log("🚀 handleMem0Modal called",{popup:e,clickSendButton:t,sourceButtonId:n,isProcessingMem0:z,memoryModalShown:R}),z){console.log("⏸️ Already processing, returning early");return}if(R){console.log("📱 Modal already shown, returning early");return}const i=await qe();if(console.log("🧠 Memory enabled state:",i),i===!1){console.log("❌ Memory disabled, not showing modal");return}z=!0;const c=document.querySelector("#mem0-tooltip");c&&(c.style.display="none");try{const o=await new Promise(f=>{chrome.storage.sync.get([h.API_KEY,h.USER_ID_CAMEL,h.ACCESS_TOKEN,h.SELECTED_ORG,h.SELECTED_PROJECT,h.USER_ID,h.SIMILARITY_THRESHOLD,h.TOP_K],function(b){f(b)})}),r=o.apiKey,s=o.userId||o.user_id||"chrome-extension-user",l=o.access_token;if(!r&&!l){z=!1,it();return}let a=B();if(console.log("📝 Input message:",a),!a||a.trim()===""){if(console.log("❌ No input message, showing popup"),e){const f=document.querySelector("#mem0-tooltip");f&&(f.style.display="none"),ze(e,"Please enter some text first")}z=!1;return}console.log("✅ All checks passed, creating memory modal"),Ae([],!0,n),a=le(void 0);const p=document.createElement("div");p.innerHTML=a,a=p.textContent||p.innerText||a,a=a.trim(),Te("modal_clicked",{provider:"claude",source:"COGNIZ_CHROME_EXTENSION",browser:Le()});const u=l?`Bearer ${l}`:`Token ${r}`,w=Fe(!1);if(w.push({role:U.User,content:a}),t){const f=document.querySelector('button[aria-label="Send Message"]')||document.querySelector('button[aria-label="Send message"]');f&&setTimeout(()=>{f.click()},100)}const x={};o.selected_org&&(x.org_id=o.selected_org),o.selected_project&&(x.project_id=o.selected_project),_e=n;try{const f=(function(){const b=document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea")||document.querySelector('p[data-placeholder="How can I help you today?"]')||document.querySelector('p[data-placeholder="Reply to Claude..."]');return b&&(b.textContent||b.value||"").trim()||a})();console.log("Claude modal search for:",f),console.log("Cache state:",ve.getState()),ve.runImmediate(f)}catch{ve.runImmediate(a)}(async()=>{try{const f=await Ie();if(!f||!f.memoryEnabled)return;const b=w.map((te,O)=>`${te.role?te.role.toUpperCase():`MESSAGE ${O+1}`}:
${te.content||""}`).join(`

`),S=["provider: Claude",`page_url: ${window.location.href}`,"source: COGNIZ_CHROME_EXTENSION"],H=b+`

---
Metadata
`+S.join(`
`),V=`${f.baseUrl.replace(/\/+$/,"")}/wp-json/memory/v1/store`,K={content:H,project_id:f.projectId,project_name:f.projectName,category:f.defaultCategory||"claude"};(await fetch(V,{method:"POST",headers:{Authorization:`Bearer ${f.apiKey}`,"Content-Type":"application/json","X-Memory-Platform-Client":"browser-extension"},body:JSON.stringify(K)})).ok&&console.log("[claude-content] Memory stored successfully via WordPress plugin")}catch(f){console.error("[claude-content] Error storing memory:",f)}})()}catch{e&&ze(e,"Failed to send message to Mem0")}finally{z=!1}}function ze(e,t){e&&(Array.from(document.querySelectorAll("#mem0-tooltip")).forEach(n=>{try{n.remove()}catch{}}),e.textContent=t,e.style.display="block",setTimeout(()=>{e.style.display="none"},2e3))}function B(){const e=document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea")||document.querySelector('p[data-placeholder="How can I help you today?"]')||document.querySelector('p[data-placeholder="Reply to Claude..."]');return e?e.tagName.toLowerCase()==="p"&&(e.getAttribute("data-placeholder")==="How can I help you today?"||e.getAttribute("data-placeholder")==="Reply to Claude...")?e.textContent||"":e.textContent||e?.value||null:null}let be=null;function Ye(){const e=document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea")||document.querySelector('p[data-placeholder="How can I help you today?"]')||document.querySelector('p[data-placeholder="Reply to Claude..."]');e&&(e.dataset.claudeBackgroundHooked||(e.dataset.claudeBackgroundHooked="true",be||(be=function(){let t=B()||"";try{const n=me.memory_header_plain_regex;t=t.replace(n,"").trim()}catch{}console.log("Claude background search triggered:",t),ve.setText(t)}),e.addEventListener("input",be),e.addEventListener("keyup",be)))}async function Ue(){Q=!!await qe(),Q===!1&&ot()}function rt(){console.log("🚀 initializeMem0Integration started"),Ue(),Ye();const e=B();e&&e.trim()&&(P=e);const t=()=>{[document.querySelector('button[aria-label="Send Message"]'),document.querySelector('button[aria-label="Send message"]')].filter(Boolean).forEach(r=>{r&&!r.dataset.mem0Listener&&(r.dataset.mem0Listener="true",r.addEventListener("pointerdown",function(){const s=B();s&&s.trim()!==""&&(P=s),se=Date.now()},!0),r.addEventListener("click",function(){G(P),setTimeout(()=>{v=[],j.clear()},100)},!0))})};t();const n=setInterval(()=>{t()},100);setTimeout(()=>{clearInterval(n)},5e3),document.__mem0FocusPrimed||(document.__mem0FocusPrimed=!0,document.addEventListener("focusin",o=>{const r=o.target;if(r&&r.closest&&r.closest('div[contenteditable="true"], textarea, p[data-placeholder="How can I help you today?"], p[data-placeholder="Reply to Claude..."]')){const l=B();l&&l.trim()&&(P=l)}},!0)),document.addEventListener("keydown",function(o){if(o.ctrlKey&&o.key==="m"){if(o.preventDefault(),console.log("⌨️ Ctrl+M pressed",{memoryEnabled:Q,memoryModalShown:R,isProcessingMem0:z}),R){console.log("🔄 Modal already shown, closing it"),C&&document.body.contains(C)&&document.body.removeChild(C),R=!1,C=null;return}if(Q&&!z){const r=document.querySelector(".mem0-popup");r?(async()=>await ae(r,!1))():(async()=>await ae(null,!1,"mem0-icon-button"))()}}}),console.log("🎯 Starting cache-first mount for Claude");function i(o,r){console.log("🎨 renderMem0Icon called",{shadow:o,host:r});let s=document.createElement("style");s.textContent=`
        :host { position: relative; }
        .mem0-btn { all: initial; cursor: pointer; display:inline-flex; align-items:center; justify-content:center; width:32px; height:32px; border-radius:50%; }
        .mem0-btn img { width:18px; height:18px; border-radius:50%; }
        .dot { position:absolute; top:-2px; right:-2px; width:8px; height:8px; background:#80DDA2; border-radius:50%; border:2px solid #1C1C1E; display:none; }
        :host([data-has-text="1"]) .dot { display:block; }
      `;let l=document.createElement("button");l.className="mem0-btn";let a=document.createElement("img");a.src=chrome.runtime.getURL("icons/icon48.png");let p=document.createElement("div");p.className="dot",l.appendChild(a),o.append(s,l,p),l.addEventListener("click",function(){console.log("🖱️ Mem0 button clicked!"),ae(null,!1,"mem0-icon-button")}),typeof ee=="function"&&setTimeout(ee,0)}try{console.log("🔍 Checking for existing button and COGNIZ_UI",{existingButton:!!document.getElementById("mem0-icon-button"),hasCognizUI:!!_}),!(document.getElementById("mem0-icon-button")||document.querySelector('[id*="mem0"]')||document.querySelector(".mem0-btn"))&&_?(console.log("🚀 Starting COGNIZ_UI.resolveCachedAnchor"),_.resolveCachedAnchor({learnKey:location.host+":"+location.pathname},null,1440*60*1e3).then(function(r){if(console.log("🎯 resolveCachedAnchor result:",r),!r||!r.el){console.log("❌ No anchor found, cannot create button");return}console.log("✅ Anchor found, creating button");let s=_.createShadowRootHost("mem0-root"),l=s.host,a=s.shadow;l.id="mem0-icon-button";let p=typeof g<"u"&&g.claude?g.claude:null,u=r.placement||p&&p.placement||{strategy:"dock",container:"form",side:"bottom",align:"start",gap:8};_.applyPlacement({container:l,anchor:r.el,placement:u}),i(a,l)}).catch(function(r){console.error("❌ Error in resolveCachedAnchor:",r)})):console.log("❌ Cannot create button:",{buttonExists:!!document.getElementById("mem0-icon-button"),hasCognizUI:!!_})}catch(o){console.error("❌ Error in cache-first mount:",o)}console.log("🎯 Checking focus-driven mount"),_&&_.mountOnEditorFocus&&!document.querySelector('[id*="mem0"], .mem0-btn')&&(console.log("🚀 Starting focus-driven mount"),_.mountOnEditorFocus({existingHostSelector:'#mem0-icon-button, [id*="mem0"], .mem0-btn',editorSelector:typeof g<"u"&&g.claude&&g.claude.editorSelector?g.claude.editorSelector:'div[contenteditable="true"], textarea, p[data-placeholder], [contenteditable="true"]',deriveAnchor:typeof g<"u"&&g.claude&&typeof g.claude.deriveAnchor=="function"?g.claude.deriveAnchor:function(o){return o.closest("form")||o.parentElement},placement:typeof g<"u"&&g.claude&&g.claude.placement?g.claude.placement:{strategy:"dock",container:"form",side:"bottom",align:"start",gap:8},render:function(o,r){return r.id="mem0-icon-button",i(o,r)},fallback:function(){try{let o=typeof g<"u"&&g.claude?g.claude:null;if(!o||!_||!_.mountResilient)return;_.mountResilient({anchors:o.fallbackAnchors||[],placement:o.placement,enableFloatingFallback:!0,render:function(r,s){return s.id="mem0-icon-button",i(r,s)}})}catch{}}})),document.__mem0EnterCapture||(document.__mem0EnterCapture=!0,document.addEventListener("keydown",o=>{if(o.key==="Enter"&&!o.shiftKey&&!o.ctrlKey&&!o.metaKey){const r=B();r&&r.trim()&&(P=r,se=Date.now())}},!0)),document.__mem0SubmitCapture||(document.__mem0SubmitCapture=!0,document.addEventListener("submit",()=>{const o=B();o&&o.trim()&&(P=o),se=Date.now(),G(P)},!0)),chrome.storage.onChanged.addListener((o,r)=>{r==="sync"&&o.memory_enabled&&Ue()});const c=()=>{const o=document.querySelector(".flex-1.flex.flex-col.gap-3.px-4.max-w-3xl.mx-auto.w-full");if(!o){setTimeout(c,1e3);return}if(o.__mem0Observed)return;o.__mem0Observed=!0;const r=new Set;new MutationObserver(l=>{for(let a=0;a<l.length;a++){const p=l[a];if(!p)continue;const u=p.addedNodes;for(let w=0;w<u.length;w++){const x=u[w];if(!x)continue;const f=x.nodeType===1?x:null;if(!f)continue;const b=f.matches?.(".font-user-message")?f:f.querySelector?.(".font-user-message");if(b){const S=(b.textContent||"").trim();if(S){const H=S.length+"_"+S.substring(0,50);if(r.has(H))return;if(r.add(H),r.size>10){const K=Array.from(r);r.clear(),K.slice(-5).forEach(E=>r.add(E))}Date.now()-se<500?setTimeout(()=>{r.has(H+"_processed")||(r.add(H+"_processed"),G(S))},200):(r.add(H+"_processed"),G(S)),se=Date.now();return}}}}}).observe(o,{childList:!0,subtree:!0})};c()}function it(){const e=document.querySelector("#mem0-login-popup");e&&e.remove();const t=document.createElement("div");t.id="mem0-login-popup",t.style.cssText=`
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10001;
  `;const n=document.createElement("div");n.style.cssText=`
    background-color: #1e293b;
    border-radius: 12px;
    width: 320px;
    padding: 24px;
    color: white;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  `;const i=document.createElement("button");i.style.cssText=`
    position: absolute;
    top: 16px;
    right: 16px;
    background: none;
    border: none;
    color: #A1A1AA;
    font-size: 16px;
    cursor: pointer;
  `,i.innerHTML="&times;",i.addEventListener("click",()=>{document.body.removeChild(t)});const c=document.createElement("div");c.style.cssText=`
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 16px;
  `;const o=document.createElement("img");o.src=chrome.runtime.getURL("icons/icon48.png"),o.style.cssText=`
    width: 24px;
    height: 24px;
    border-radius: 50%;
    margin-right: 12px;
  `;const r=document.createElement("img");r.src=chrome.runtime.getURL("icons/icon128.png"),r.style.cssText=`
    width: 24px;
    height: 24px;
    border-radius: 50%;
    margin-right: 12px;
  `;const s=document.createElement("h2");s.textContent="Sign in to Cogniz",s.style.cssText=`
    margin: 0;
    font-size: 18px;
    font-weight: 600;
  `,c.appendChild(s);const l=document.createElement("p");l.textContent="Please sign in to access your memories and personalize your conversations!",l.style.cssText=`
    margin-bottom: 24px;
    color: #D4D4D8;
    font-size: 14px;
    line-height: 1.5;
    text-align: center;
  `;const a=document.createElement("button");a.style.cssText=`
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    padding: 10px;
    background-color: white;
    color: black;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: background-color 0.2s;
  `;const p=document.createElement("span");p.textContent="Sign in with Cogniz",a.appendChild(r),a.appendChild(p),a.addEventListener("mouseenter",()=>{a.style.backgroundColor="#f5f5f5"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="white"}),a.addEventListener("click",()=>{nt(),document.body.removeChild(t)}),n.appendChild(c),n.appendChild(l),n.appendChild(a),t.appendChild(n),t.appendChild(i),t.addEventListener("click",u=>{u.target===t&&document.body.removeChild(t)}),document.body.appendChild(t)}async function G(e){if(!chrome||!chrome.storage)return;try{if(await qe()===!1)return}catch{return}let t=typeof e=="string"&&e.trim()!==""?e:"";if(!t){let n=document.querySelector('div[contenteditable="true"].ProseMirror');if(n||(n=document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea")||document.querySelector('p[data-placeholder="How can I help you today?"]')||document.querySelector('p[data-placeholder="Reply to Claude..."]')),!n)return;n.classList.contains("ProseMirror")||n.tagName.toLowerCase()==="div"||n.tagName.toLowerCase()==="p"?t=n.textContent||"":t=n.value||""}if(!(!t||t.trim()==="")&&((typeof e!="string"||!e.trim())&&(t=le(t)),!(!t||t.trim()==="")))try{if(!chrome||!chrome.storage||!chrome.storage.sync)return;chrome.storage.sync.get([h.API_KEY,h.USER_ID_CAMEL,h.ACCESS_TOKEN,h.MEMORY_ENABLED,h.SELECTED_ORG,h.SELECTED_PROJECT,h.USER_ID],function(n){try{if(chrome.runtime&&chrome.runtime.lastError)return}catch{}if(n.memory_enabled===!1||!n.apiKey&&!n.access_token)return;const i=n.access_token?`Bearer ${n.access_token}`:`Token ${n.apiKey}`,c=n.userId||n.user_id||"chrome-extension-user",o=Fe(!1);o.push({role:U.User,content:t});const r={};n.selected_org&&(r.org_id=n.selected_org),n.selected_project&&(r.project_id=n.selected_project),(async()=>{try{const s=await Ie();if(!s||!s.memoryEnabled)return;const l=o.map((f,b)=>`${f.role?f.role.toUpperCase():`MESSAGE ${b+1}`}:
${f.content||""}`).join(`

`),a=["provider: Claude",`page_url: ${window.location.href}`,"source: COGNIZ_CHROME_EXTENSION"],p=l+`

---
Metadata
`+a.join(`
`),u=`${s.baseUrl.replace(/\/+$/,"")}/wp-json/memory/v1/store`,w={content:p,project_id:s.projectId,project_name:s.projectName,category:s.defaultCategory||"claude"};(await fetch(u,{method:"POST",headers:{Authorization:`Bearer ${s.apiKey}`,"Content-Type":"application/json","X-Memory-Platform-Client":"browser-extension"},body:JSON.stringify(w)})).ok&&console.log("[claude-content] Background memory stored successfully via WordPress plugin")}catch(s){console.error("[claude-content] Error storing background memory:",s)}})()})}catch{}}function ee(){const e=document.querySelectorAll("#mem0-notification-dot");if(!e.length)return;let t=document.querySelector('div[contenteditable="true"].ProseMirror');if(t||(t=document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea")||document.querySelector('p[data-placeholder="How can I help you today?"]')||document.querySelector('p[data-placeholder="Reply to Claude..."]')),!t)return;const n=()=>{let c=!1;if(t.classList.contains("ProseMirror")){const o=t.querySelectorAll("p");c=(t.textContent||"").trim()!==""||o.length>1||o.length===1&&!o[0]?.classList?.contains("is-empty")}else t.tagName.toLowerCase()==="p"||t.tagName.toLowerCase()==="div"?c=(t.textContent||"").trim()!=="":c=(t.value||"").trim()!=="";e.forEach(o=>{c?(o.classList.add("active"),o.style.display="block"):(o.classList.remove("active"),o.style.display="none")})};new MutationObserver(n).observe(t,{childList:!0,characterData:!0,subtree:!0,attributes:!0,attributeFilter:["class"]}),t.addEventListener("input",n),t.addEventListener("keyup",n),t.addEventListener("focus",n),n(),setTimeout(n,500)}let He=!1;function Ge(){if(He)return;He=!0;function e(){const n=".flex-1.flex.flex-col.gap-3.px-4.max-w-3xl.mx-auto.w-full",i=new MutationObserver(o=>{o.forEach(r=>{r.addedNodes.forEach(s=>{if(s.nodeType===1){const l=s,a=l.querySelector(".font-user-message");if(a){const u=(a.textContent||"").trim();u&&(J(U.User,u),setTimeout(()=>{G(u),setTimeout(()=>{v=[],j.clear()},100)},50))}if(l.classList&&l.classList.contains("font-user-message")){const u=(l.textContent||"").trim();u&&(J(U.User,u),setTimeout(()=>{G(u),setTimeout(()=>{v=[],j.clear()},100)},50))}const p=l.querySelector(".font-claude-message");if(p){const u=(p.textContent||"").trim();u&&J(U.Assistant,u)}if(l.classList&&l.classList.contains("font-claude-message")){const u=(l.textContent||"").trim();u&&J(U.Assistant,u)}}})})}),c=document.querySelector(n);c?i.observe(c,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):setTimeout(e,1e3)}function t(){const n=['div[contenteditable="true"].ProseMirror','div[contenteditable="true"]',"textarea",'p[data-placeholder="How can I help you today?"]','p[data-placeholder="Reply to Claude..."]'];let i="",c;function o(){for(const r of n){const s=document.querySelector(r);if(s){c&&c.disconnect(),c=new MutationObserver(()=>{const l=B()||"";i.trim()&&!l.trim()&&(J(U.User,i),setTimeout(()=>{G(i),setTimeout(()=>{v=[],j.clear()},100)},50)),i=l}),c.observe(s,{childList:!0,subtree:!0,characterData:!0,attributes:!0}),s.addEventListener("input",()=>{i=B()||""});break}}}o(),setInterval(o,5e3)}e(),t()}let ie=window.location.href;function st(){return!!(chrome&&chrome.runtime)}function we(){const e=window.location.href;if(e!==ie){const t=ie.includes("/new")||ie.includes("/chat/new"),n=e.includes("/new")||e.includes("/chat/new"),i=ie.includes("/chat/")&&e.includes("/chat/")&&ie!==e;(n||i||t)&&($=[]),He=!1,ie=e,setTimeout(()=>{Xe(),Ye(),Ge(),ee()},500)}}setInterval(()=>{st(),we()},1e3);window.addEventListener("popstate",()=>{setTimeout(we,100)});const lt=history.pushState;history.pushState=function(e,t,n){lt.call(history,e,t,n),setTimeout(we,100)};const at=history.replaceState;history.replaceState=function(e,t,n){at.call(history,e,t,n),setTimeout(we,100)};Xe();Ge();console.log("🎯 Starting main initialization");rt();
