import{M as G,D as _e}from"./api-D2MZ7O5A.js";import{S as Ae}from"./messages-CjQo1qp0.js";import{S as s}from"./storage-pXeRtiJs.js";import{c as qe,C as R,S as g,a as ie}from"./util_positioning-Cx352_Ay.js";import{s as Ne,b as Re,d as je,e as Ke,a as fe,g as he,c as $e}from"./mem0_proxy-DKi2ici5.js";Ne();async function Ue(){try{const t=await $e();chrome.runtime.sendMessage({action:Ae.OPEN_DASHBOARD,url:t})}catch(t){console.warn("Unable to open Memory Platform dashboard",t)}}let ne=!1,Te,H=!1,P=[];const M=new Set;let T=null,U=null,ge="",ye=null;const Oe=qe({fetch:async function(t,e){if(!await Re())return[];const o=await je([s.SIMILARITY_THRESHOLD,s.TOP_K]),i=typeof o[s.SIMILARITY_THRESHOLD]=="number"?o[s.SIMILARITY_THRESHOLD]:.1,l=typeof o[s.TOP_K]=="number"?o[s.TOP_K]:10;return(await Ke(t,{limit:l,signal:e?.signal})).filter(c=>typeof c.relevance!="number"?!0:c.relevance>=i)},onSuccess:function(t,e){if(!H)return;const n=(e||[]).map(o=>({id:String(o.id),text:o.memory,categories:o.categories||[]}));se(n,!1,ye)},onError:function(){H&&se([],!1,ye)},minLength:3,debounceMs:800,cacheTTL:6e4,abortPrevious:!1});function se(t,e=!1,n=null){H&&T&&document.body.removeChild(T),H=!0;let o=0;const i=447;let l=400,r=3,c=0,u=0;if(U)c=U.top,u=U.left;else if(n==="mem0-icon-button"){const a=document.querySelector("#mem0-icon-button");if(a){const d=a.getBoundingClientRect(),f=d.top,x=window.innerHeight;u=d.left-i+d.width,u=Math.max(u,10),f>=l+10?c=d.top-l-10:(c=d.bottom+10,d.bottom>x/2&&(l=300,r=2))}else p()}else if(n==="sync-button"){const a=document.querySelector("#sync-button");if(a){const d=a.getBoundingClientRect(),f=window.innerHeight;u=d.left,c=d.bottom+10,d.bottom>f/2&&(l=300,r=2),u=Math.min(u,window.innerWidth-i-10)}else p()}else p();function p(){const a=document.querySelector("#prompt-textarea")||document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea");if(!a){console.error("Input element not found");return}const d=a.getBoundingClientRect(),f=window.innerHeight,x=f-d.bottom;u=Math.max(d.right-20-i,10),x>=l?(c=d.bottom+10,d.bottom>f/2&&(l=300,r=2)):c=d.top-l-10}const m=document.createElement("div");m.style.cssText=`
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: transparent;
    display: flex;
    z-index: 10000;
    pointer-events: auto;
  `,T=m,m.addEventListener("click",a=>{a.target===m&&de()});const h=document.createElement("div");h.style.cssText=`
    background-color: #1e293b;
    border-radius: 12px;
    width: ${i}px;
    height: ${l}px;
    display: flex;
    flex-direction: column;
    color: white;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    position: absolute;
    top: ${c}px;
    left: ${u}px;
    pointer-events: auto;
    border: 1px solid #27272A;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    overflow: hidden;
  `;const k=document.createElement("div");k.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;
  `;const Y=document.createElement("div");Y.style.cssText=`
    display: flex;
    flex-direction: row;
    align-items: center;
  `;const le=document.createElement("img");le.src=chrome.runtime.getURL("icons/icon48.png"),le.style.cssText=`
    width: 26px;
    height: 26px;
    border-radius: 50%;
    margin-right: 8px;
  `;const ce=document.createElement("div");ce.textContent="Cogniz Memory",ce.style.cssText=`
    font-size: 16px;
    font-weight: 600;
    color: white;
  `;const J=document.createElement("div");J.style.cssText=`
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 8px;
  `;const N=document.createElement("button");N.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;
  `,N.textContent="Add to Prompt";const Ee=document.createElement("span");Ee.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>
`,N.appendChild(Ee);const L=document.createElement("button");L.style.cssText=`
    background: none;
    border: none;
    cursor: pointer;
    padding: 8px;
    opacity: 0.6;
    transition: opacity 0.2s;
  `,L.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>`,L.addEventListener("click",()=>{T&&document.body.contains(T)&&(document.body.removeChild(T),H=!1,T=null),chrome.runtime.sendMessage({action:Ae.SIDEBAR_SETTINGS})}),L.addEventListener("mouseenter",()=>{L.style.opacity="1"}),L.addEventListener("mouseleave",()=>{L.style.opacity="0.6"});let V=!1;const X={x:0,y:0};k.addEventListener("mousedown",a=>{if(a.target?.closest("button"))return;V=!0,k.style.cursor="grabbing";const f=h.getBoundingClientRect();X.x=a.clientX-f.left,X.y=a.clientY-f.top,a.preventDefault()}),document.addEventListener("mousemove",a=>{if(!V)return;const d=a.clientX-X.x,f=a.clientY-X.y,x=window.innerWidth-i,w=window.innerHeight-l,E=Math.max(0,Math.min(d,x)),y=Math.max(0,Math.min(f,w));h.style.left=`${E}px`,h.style.top=`${y}px`,U={left:E,top:y},a.preventDefault()}),document.addEventListener("mouseup",()=>{V&&(V=!1,k.style.cursor="move")});const Z=document.createElement("div"),ve=l-130;Z.style.cssText=`
    display: flex;
    flex-direction: column;
    padding: 0 16px;
    gap: 12px;
    overflow: hidden;
    flex: 1;
    height: ${ve}px;
  `;const I=document.createElement("div");I.style.cssText=`
    font-size: 16px;
    font-weight: 600;
    color: #FFFFFF;
    margin-top: 16px;
    flex-shrink: 0;
  `,e?I.textContent="Loading Relevant Memories...":I.textContent=`${t.length} Relevant Memories`;const Be=ve-40,C=document.createElement("div");C.style.cssText=`
    display: flex;
    flex-direction: column;
    gap: 8px;
    overflow-y: auto;
    flex: 1;
    max-height: ${Be}px;
    padding-right: 8px;
    margin-right: -8px;
    scrollbar-width: none;
    -ms-overflow-style: none;
  `,C.style.cssText+="::-webkit-scrollbar { display: none; }";let j=null;function De(){C.innerHTML="";for(let a=0;a<r;a++){const d=document.createElement("div");d.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 f=document.createElement("div");f.style.cssText=`
        background-color: #383838;
        border-radius: 4px;
        height: 14px;
        width: 85%;
        margin-bottom: 8px;
      `;const x=document.createElement("div");x.style.cssText=`
        background-color: #383838;
        border-radius: 4px;
        height: 14px;
        width: 65%;
      `;const w=document.createElement("div");w.style.cssText=`
        display: flex;
        gap: 4px;
        margin-left: 10px;
      `;const E=document.createElement("div");E.style.cssText=`
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background-color: #383838;
      `;const y=document.createElement("div");y.style.cssText=`
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background-color: #383838;
      `,w.appendChild(E),w.appendChild(y);const S=document.createElement("div");S.style.cssText=`
        display: flex;
        flex-direction: column;
        flex-grow: 1;
      `,S.appendChild(f),S.appendChild(x),d.appendChild(S),d.appendChild(w),C.appendChild(d)}if(!document.getElementById("skeleton-animation")){const a=document.createElement("style");a.id="skeleton-animation",a.innerHTML=`
        @keyframes pulse {
          0% { opacity: 0.6; }
          50% { opacity: 0.8; }
          100% { opacity: 0.6; }
        }
      `,document.head.appendChild(a)}}function He(a,d,f,x,w){j&&j!==a&&j.dispatchEvent(new Event("collapse")),w.value=!0,d.style.webkitLineClamp="unset",d.style.height="auto",f.style.overflowY="auto",f.style.maxHeight="240px",f.style.scrollbarWidth="none",f.style.cssText+="::-webkit-scrollbar { display: none; }",a.style.backgroundColor="#1C1C1E",a.style.maxHeight="300px",a.style.overflow="hidden",x.style.display="flex",j=a,C.scrollTop=a.offsetTop-C.offsetTop}function we(a,d,f,x,w){w.value=!1,d.style.webkitLineClamp="2",d.style.height="42px",f.style.overflowY="visible",a.style.backgroundColor="#27272A",a.style.maxHeight="72px",a.style.overflow="hidden",x.style.display="none",j=null}function B(){if(C.innerHTML="",e){De();return}if(t.length===0){Ce(),Se(0,0);return}const a=Math.min(r,t.length),d=Math.ceil(t.length/a),f=Math.floor(o/a)+1;Se(f,d);for(let x=0;x<a;x++){const w=o+x;if(w>=t.length)break;const E=t[w];if(M.has(String(E.id)))continue;E.id||(E.id=`memory-${Date.now()}-${w}`);const y=document.createElement("div");y.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 S=document.createElement("div");S.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 */
      `,S.textContent=E.text||"";const Q=document.createElement("div");Q.style.cssText=`
        display: flex;
        gap: 4px;
        margin-left: 10px;
        flex-shrink: 0;
      `;const ee=document.createElement("button");ee.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;
      `,ee.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>`,ee.addEventListener("click",K=>{K.stopPropagation(),fe("memory_injection",{provider:"chatgpt",source:"COGNIZ_CHROME_EXTENSION",browser:he(),injected_all:!1,memory_id:E.id}),M.add(String(E.id)),P.push(String(E.text||"")),ke();const $=t.findIndex(ue=>ue.id===E.id);$!==-1&&(t.splice($,1),o>0&&o>=t.length&&(o=Math.max(0,o-r)),I.textContent=`${t.length} Relevant Memories`,B())});const te=document.createElement("button");te.style.cssText=`
        background: none;
        border: none;
        cursor: pointer;
        padding: 4px;
        color: #A1A1AA;
      `,te.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 D={value:!1},_=document.createElement("button");_.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;
      `,_.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 A=document.createElement("div");A.style.cssText=`
        display: flex;
        flex-direction: column;
        flex-grow: 1;
      `,A.appendChild(S),A.appendChild(_),y.addEventListener("collapse",()=>{we(y,S,A,_,D)}),te.addEventListener("click",K=>{K.stopPropagation(),D.value?we(y,S,A,_,D):He(y,S,A,_,D)}),_.addEventListener("click",K=>{K.stopPropagation();const $=t.findIndex(ue=>ue.id===E.id);$!==-1&&(t.splice($,1),o>0&&o>=t.length&&(o=Math.max(0,o-r)),I.textContent=`${t.length} Relevant Memories`,B())}),Q.appendChild(ee),Q.appendChild(te),y.appendChild(A),y.appendChild(Q),C.appendChild(y),y.addEventListener("mouseenter",()=>{y.style.backgroundColor=D.value?"#18181B":"#323232"}),y.addEventListener("mouseleave",()=>{y.style.backgroundColor=D.value?"#1C1C1E":"#27272A"})}C.children.length===0&&t.length>0&&(o>0?(o=Math.max(0,o-r),B()):Ce())}function Ce(){C.innerHTML="";const a=document.createElement("div");a.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 d=document.createElement("div");d.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>`,d.style.marginBottom="16px";const f=document.createElement("div");f.textContent="No relevant memories found",f.style.cssText=`
      color: #71717A;
      font-size: 14px;
      font-weight: 500;
    `,a.appendChild(d),a.appendChild(f),C.appendChild(a)}function Se(a,d){if(t.length===0||d===0){b.disabled=!0,b.style.opacity="0.5",b.style.cursor="not-allowed",v.disabled=!0,v.style.opacity="0.5",v.style.cursor="not-allowed";return}a<=1?(b.disabled=!0,b.style.opacity="0.5",b.style.cursor="not-allowed"):(b.disabled=!1,b.style.opacity="1",b.style.cursor="pointer"),a>=d?(v.disabled=!0,v.style.opacity="0.5",v.style.cursor="not-allowed"):(v.disabled=!1,v.style.opacity="1",v.style.cursor="pointer")}const W=document.createElement("div");W.style.cssText=`
    display: flex;
    justify-content: center;
    gap: 12px;
    padding: 10px;
    border-top: none;
    flex-shrink: 0;
  `;const b=document.createElement("button");b.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>`,b.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 v=document.createElement("button");v.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>`,v.style.cssText=b.style.cssText,b.addEventListener("click",()=>{o>=r&&(o=Math.max(0,o-r),B())}),v.addEventListener("click",()=>{o+r<t.length&&(o=o+r,B())}),[b,v].forEach(a=>{a.addEventListener("mouseenter",()=>{a.disabled||(a.style.backgroundColor="#323232")}),a.addEventListener("mouseleave",()=>{a.disabled||(a.style.backgroundColor="#27272A")})}),Y.appendChild(le),Y.appendChild(ce),J.appendChild(N),J.appendChild(L),k.appendChild(Y),k.appendChild(J),Z.appendChild(I),Z.appendChild(C),W.appendChild(b),W.appendChild(v),h.appendChild(k),h.appendChild(Z),h.appendChild(W),m.appendChild(h),document.body.appendChild(m),B();function de(){T&&document.body.contains(T)&&document.body.removeChild(T),T=null,H=!1,U=null}N.addEventListener("click",()=>{const a=t.filter(d=>!M.has(String(d.id))&&!d.removed).map(d=>(M.add(String(d.id)),String(d.text||"")));fe("memory_injection",{provider:"chatgpt",source:"COGNIZ_CHROME_EXTENSION",browser:he(),injected_all:!0,memory_count:a.length}),P.push(...a),P.length>0?(ke(),de()):M.size>0&&de();for(let d=t.length-1;d>=0;d--)M.has(String(t[d]?.id))&&t.splice(d,1)})}function ke(){const t=document.querySelector("#prompt-textarea")||document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea");if(t&&P.length>0){const e=Pe();let n='<div id="mem0-wrapper" contenteditable="false" style="background-color: rgb(220, 252, 231); padding: 8px; border-radius: 4px; margin-top: 8px; margin-bottom: 8px;">';n+=ie.memory_header_html_strong,P.forEach((o,i)=>{const l=(o||"").toString();n+=`<div data-mem0-idx="${i}" style="user-select: text;">- ${l}</div>`}),n+="</div>",t.tagName.toLowerCase()==="div"?t.innerHTML=`${e}<div><br></div>${n}`:t.value=`${e}
${n}`;try{const o=document.getElementById("mem0-wrapper");o&&(o.setAttribute("contenteditable","false"),o.style.userSelect="text")}catch{}t.dispatchEvent(new Event("input",{bubbles:!0}))}}function Pe(t){if(typeof t=="string")return t;const e=document.querySelector("#prompt-textarea")||document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea");if(!e)return"";let n=e?.value||e.textContent||e.innerHTML;t&&(!n||n.trim()==='<p data-placeholder="Ask anything" class="placeholder"><br class="ProseMirror-trailingBreak"></p>')&&(n=t),n=n.replace(/<div id="mem0-wrapper"[\s\S]*?<\/div>/g,"");try{const o=ie.memory_header_plain_regex,i=ie.memory_header_html_regex;n=n.replace(i,""),n=n.replace(o,"")}catch{}return n=n.replace(/<p><br class="ProseMirror-trailingBreak"><\/p><p>$/g,""),n=n.replace(/<p>[\s\S]*?<\/p>/g,""),n.trim()}function re(){const t=document.querySelector("#composer-submit-button");if(t&&!t.dataset.mem0Listener){t.dataset.mem0Listener="true",t.addEventListener("click",function(){Le(),setTimeout(()=>{P=[],M.clear()},100)});const e=document.querySelector("#prompt-textarea")||document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea");e&&!e.dataset.mem0KeyListener&&(e.dataset.mem0KeyListener="true",e.addEventListener("keydown",function(n){ge=e?.value||e.textContent||ge,n.key==="Enter"&&!n.shiftKey&&(Le(),setTimeout(()=>{P=[],M.clear()},100))}))}}async function Le(){const t=document.querySelector("#prompt-textarea")||document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea")||document.querySelector('textarea[data-virtualkeyboard="true"]');if(!t)return;let e=t.textContent||t?.value;if((!e||e.trim()==="")&&(e=ge),!(!e||e.trim()==="")&&(e=Pe(e),!(!e||e.trim()==="")))try{const n=await Re();if(!n){console.warn("Memory Platform not configured");return}if(!n.memoryEnabled)return;const o=e,i=`${n.baseUrl.replace(/\/+$/,"")}/wp-json/memory/v1/store`,l={content:o,project_id:n.projectId,project_name:n.projectName,category:n.defaultCategory||"chatgpt"};console.log("[chatgpt-content] Storing memory via WordPress plugin:",i);const r=await fetch(i,{method:"POST",headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json","X-Memory-Platform-Client":"browser-extension"},body:JSON.stringify(l)});if(!r.ok)throw new Error(`Storage failed: ${r.status}`);const c=await r.json();console.log("[chatgpt-content] Memory stored successfully:",c)}catch(n){console.error("[chatgpt-content] Error saving memory:",n)}}async function O(){if(!await be())return;const e=document.querySelector("#prompt-textarea")||document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea"),n=document.getElementById("mem0-icon-button");if(!e||!n){setTimeout(O,1e3);return}const o=()=>{const l=e.textContent||e.value||"";n.setAttribute("data-has-text",l.trim()?"1":"0")};new MutationObserver(o).observe(e,{childList:!0,characterData:!0,subtree:!0}),e.addEventListener("input",o),e.addEventListener("keyup",o),e.addEventListener("focus",o),o()}async function q(t=null){if(!await be())return;const n=await new Promise(r=>{chrome.storage.sync.get([s.API_KEY,s.USER_ID_CAMEL,s.ACCESS_TOKEN],function(c){r(c)})});if(!n[s.API_KEY]&&!n[s.ACCESS_TOKEN]){Xe();return}const o=document.querySelector("#mem0-icon-button");let i=Ie();if(!i||i.trim()===""){o&&ze(o,"Please enter some text first");return}try{const r=ie.memory_header_plain_regex;i=i.replace(r,"").trim()}catch{}const l=i.indexOf("</p>");if(l!==-1&&(i=i.slice(0,l+4)),!ne){ne=!0,se([],!0,t);try{const r=await new Promise(h=>{chrome.storage.sync.get([s.API_KEY,s.USER_ID_CAMEL,s.ACCESS_TOKEN,s.SELECTED_ORG,s.SELECTED_PROJECT,s.USER_ID,s.SIMILARITY_THRESHOLD,s.TOP_K],function(k){h(k)})}),c=r[s.API_KEY],u=r[s.ACCESS_TOKEN];if(!c&&!u){ne=!1;return}fe("modal_clicked",{provider:"chatgpt",source:"COGNIZ_CHROME_EXTENSION",browser:he()}),Fe(2).push({role:G.User,content:i});const m={};r[s.SELECTED_ORG]&&(m.org_id=r[s.SELECTED_ORG]),r[s.SELECTED_PROJECT]&&(m.project_id=r[s.SELECTED_PROJECT]),ye=t,Oe.runImmediate(i)}catch(r){throw console.error("Error:",r),se([],!1,t),r}finally{ne=!1}}}function ze(t,e){let n=t||document.getElementById("mem0-icon-button");if(!n)return;let o=n.shadowRoot||n;const i=o.querySelector(".mem0-button-popup");i&&i.remove();const l=document.querySelector(".mem0-button-popover");l&&(l.style.opacity="0",l.style.display="none");const r=document.createElement("div");r.className="mem0-button-popup",r.style.cssText=`
    position: absolute;
    top: -40px;
    left: 50%;
    transform: translateX(-50%);
    background-color: #1e293b;
    border: 1px solid #27272A;
    color: white;
    padding: 8px 12px;
    border-radius: 6px;
    font-size: 12px;
    white-space: nowrap;
    z-index: 10001;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  `,r.textContent=e;const c=document.createElement("div");c.style.cssText=`
    position: absolute;
    bottom: -5px;
    left: 50%;
    transform: translateX(-50%) rotate(45deg);
    width: 10px;
    height: 10px;
    background-color: #1e293b;
    border-right: 1px solid #27272A;
    border-bottom: 1px solid #27272A;
  `,r.appendChild(c),o.appendChild(r),setTimeout(function(){r.isConnected&&r.remove()},3e3)}(function(){if(!(!R||!R.mountOnEditorFocus)){try{document.getElementById("mem0-icon-button")||R.resolveCachedAnchor({learnKey:location.host+":"+location.pathname},null,1440*60*1e3).then(function(t){if(!t||!t.el)return;let e=R.createShadowRootHost("mem0-root"),n=e.host,o=e.shadow;n.id="mem0-icon-button";let i=R.applyPlacement({container:n,anchor:t.el,placement:t.placement||{strategy:"inline",where:"beforeend",inlineAlign:"end"}}),l=document.createElement("style");l.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 r=document.createElement("button");r.className="mem0-btn";let c=document.createElement("img");c.src=chrome.runtime.getURL("icons/icon48.png");let u=document.createElement("div");u.className="dot",r.appendChild(c),o.append(l,r,u);try{let m=t.el&&(t.el.querySelector('button[aria-label="Dictate button"]')||t.el.querySelector('button[aria-label*="mic" i]')||t.el.querySelector('button[aria-label*="voice" i]'));if(m&&t.el){let h=m;for(;h&&h.parentElement!==t.el;)h=h.parentElement;h&&h.parentElement===t.el&&t.el.insertBefore(n,h)}}catch{}r.addEventListener("click",function(){q("mem0-icon-button")}),typeof O=="function"&&setTimeout(O,0);const p=new MutationObserver(function(){if(!document.contains(t.el)||!document.contains(n)){try{i()}catch{}try{p.disconnect()}catch{}}});p.observe(document.documentElement,{childList:!0,subtree:!0})}).catch(function(){})}catch{}R.mountOnEditorFocus({existingHostSelector:"#mem0-icon-button",editorSelector:typeof g<"u"&&g.chatgpt&&g.chatgpt.editorSelector?g.chatgpt.editorSelector:'textarea, [contenteditable="true"], input[type="text"]',deriveAnchor:typeof g<"u"&&g.chatgpt&&typeof g.chatgpt.deriveAnchor=="function"?g.chatgpt.deriveAnchor:function(t){return t.closest("form")||t.parentElement},placement:typeof g<"u"&&g.chatgpt&&g.chatgpt.placement?g.chatgpt.placement:{strategy:"inline",where:"beforeend",inlineAlign:"end"},render:function(t,e,n){e.id="mem0-icon-button";let o=document.createElement("style");o.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 i=document.createElement("button");i.className="mem0-btn";let l=document.createElement("img");l.src=chrome.runtime.getURL("icons/icon48.png");let r=document.createElement("div");r.className="dot",i.appendChild(l),t.append(o,i,r);try{let c=typeof g<"u"&&g.chatgpt?g.chatgpt:null,u=null;if(c&&Array.isArray(c.adjacentTargets))for(let p=0;p<c.adjacentTargets.length;p++){let m=c.adjacentTargets[p];if(m&&(u=n&&n.querySelector(m),u))break}if(u&&n){let p=u;for(;p&&p.parentElement!==n;)p=p.parentElement;p&&p.parentElement===n&&n.insertBefore(e,p),e.style.marginRight="",e.style.marginLeft=""}else e.style.marginLeft="4px"}catch{}i.addEventListener("click",function(){q("mem0-icon-button")}),typeof O=="function"&&setTimeout(O,0)},fallback:function(){let t=typeof g<"u"&&g.chatgpt?g.chatgpt:null;R.mountResilient({anchors:[{find:function(){let e=t&&t.editorSelector||'textarea, [contenteditable="true"], input[type="text"]',n=document.querySelector(e);if(!n)return null;try{return t&&typeof t.deriveAnchor=="function"?t.deriveAnchor(n):n.closest("form")||n.parentElement}catch{return n.closest("form")||n.parentElement}}}],placement:t&&t.placement||{strategy:"inline",where:"beforeend",inlineAlign:"end"},enableFloatingFallback:!0,render:function(e,n,o){n.id="mem0-icon-button";let i=document.createElement("style");i.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 r=document.createElement("img");r.src=chrome.runtime.getURL("icons/icon48.png");let c=document.createElement("div");c.className="dot",l.appendChild(r),e.append(i,l,c),l.addEventListener("click",function(){q("mem0-icon-button")});try{let u=typeof g<"u"&&g.chatgpt?g.chatgpt:null,p=null;if(u&&Array.isArray(u.adjacentTargets))for(let m=0;m<u.adjacentTargets.length;m++){let h=u.adjacentTargets[m];if(h&&(p=o&&o.querySelector(h),p))break}else p=o&&(o.querySelector('button[aria-label="Dictate button"]')||o.querySelector('button[aria-label*="mic" i]')||o.querySelector('button[aria-label*="voice" i]'));if(p&&o){let m=p;for(;m&&m.parentElement!==o;)m=m.parentElement;m&&m.parentElement===o&&o.insertBefore(n,m),n.style.marginRight="",n.style.marginLeft=""}else n.style.marginLeft="4px"}catch{}typeof O=="function"&&setTimeout(O,0)}})},persistCache:!0,cacheTtlMs:1440*60*1e3})}})();function Fe(t){const e=document.querySelector(".flex.flex-col.text-sm.md\\:pb-9");if(!e)return[];const n=Array.from(e.children).reverse(),o=[];for(const i of n){if(o.length>=t)break;const l=i.querySelector('[data-message-author-role="user"]'),r=i.querySelector('[data-message-author-role="assistant"]');if(l){const c=l.querySelector(".whitespace-pre-wrap")?.textContent?.trim()||"";o.unshift({role:G.User,content:c})}else if(r){const c=r.querySelector(".markdown")?.textContent?.trim()||"";o.unshift({role:G.Assistant,content:c})}}return o}function Ie(){const t=document.querySelector("#prompt-textarea")||document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea");return t&&(t.textContent||t?.value)||""}let oe=null;function pe(){const t=document.querySelector("#prompt-textarea")||document.querySelector('div[contenteditable="true"]')||document.querySelector("textarea");t&&(t.dataset.mem0BackgroundHooked||(t.dataset.mem0BackgroundHooked="true",oe||(oe=function(){const e=Ie()||"";console.log("Background search for:",e),Oe.setText(e)}),t.addEventListener("input",oe),t.addEventListener("keyup",oe)))}function xe(){const t=document.querySelector("div.mt-5.flex.justify-end");if(t){let e=document.querySelector("#sync-button");if(!e){e=document.createElement("button"),e.id="sync-button",e.className="btn relative btn-neutral mr-2",e.style.color="rgb(213, 213, 213)",e.style.backgroundColor="transparent",e.innerHTML='<div id="sync-button-content" class="flex items-center justify-center font-semibold">Sync Memory</div>',e.style.border="1px solid rgb(213, 213, 213)",e.style.fontSize="12px",e.style.fontWeight="500",e.style.marginRight="8px";const o=document.createElement("img");o.src=chrome.runtime.getURL("icons/icon48.png"),o.style.width="16px",o.style.height="16px",o.style.marginRight="8px",e.prepend(o),e.addEventListener("click",Ge),e.addEventListener("mouseenter",()=>{e.disabled||(e.style.filter="opacity(0.7)")}),e.addEventListener("mouseleave",()=>{e.disabled||(e.style.filter="opacity(1)")})}t.contains(e)||t.insertBefore(e,t.firstChild),(()=>{e.disabled=!1,e.disabled?(e.style.opacity="0.5",e.style.pointerEvents="none"):(e.style.opacity="1",e.style.pointerEvents="auto")})()}else{const e=document.querySelector("#sync-button");e&&e.parentNode&&e.parentNode.removeChild(e)}}function Ge(){be().then(t=>{if(!t){const o=document.querySelector("#sync-button");o&&F(o,"Memory is disabled");return}const e=document.querySelector("table.w-full.border-separate.border-spacing-0"),n=document.querySelector("#sync-button");if(e&&n){const o=e.querySelectorAll("tbody tr"),i=[];z(!0);let l=0;const r=o.length;o.forEach(c=>{const u=c.querySelectorAll("td");if(u.length>=1&&u[0]){const p=u[0].querySelector("div.whitespace-pre-wrap")?.textContent?.trim()||"",m={role:G.User,content:`Remember this about me: ${p}`};i.push(m),Je(m,!1).then(()=>{l++,l===r&&(F(n,`${l} memories synced`),z(!1))}).catch(()=>{l===r&&(F(n,`${l}/${r} memories synced`),z(!1))})}}),Ye(i).then(()=>{n&&F(n,`${i.length} memories synced`),z(!1),q("sync-button")}).catch(c=>{console.error("Error syncing memories:",c),n&&F(n,"Error syncing memories"),z(!1),q("sync-button")})}else console.error("Table or Sync button not found")})}function Ye(t){return new Promise((e,n)=>{chrome.storage.sync.get([s.API_KEY,s.USER_ID_CAMEL,s.ACCESS_TOKEN,s.SELECTED_ORG,s.SELECTED_PROJECT,s.USER_ID],function(o){if(o[s.API_KEY]||o[s.ACCESS_TOKEN]){const i=o[s.ACCESS_TOKEN]?`Bearer ${o[s.ACCESS_TOKEN]}`:`Token ${o[s.API_KEY]}`,l=o[s.USER_ID_CAMEL]||o[s.USER_ID]||_e,r={};o[s.SELECTED_ORG]&&(r.org_id=o[s.SELECTED_ORG]),o[s.SELECTED_PROJECT]&&(r.project_id=o[s.SELECTED_PROJECT]),fetch("https://api.mem0.ai/v1/memories/",{method:"POST",headers:{"Content-Type":"application/json",Authorization:i},body:JSON.stringify({messages:t,user_id:l,infer:!0,metadata:{provider:"ChatGPT"},source:"COGNIZ_CHROME_EXTENSION",...r})}).then(c=>{c.ok?e():n(`Failed to add memories: ${c.status}`)}).catch(c=>n(`Error sending memories to Mem0: ${c}`))}else n("API Key/Access Token not set")})})}function z(t){const e=document.querySelector("#sync-button"),n=document.querySelector("#sync-button-content");e&&(t?(e.disabled=!0,e.style.cursor="wait",document.body.style.cursor="wait",e.style.opacity="0.7",n&&(n.textContent="Syncing...")):(e.disabled=!1,e.style.cursor="pointer",e.style.opacity="1",document.body.style.cursor="default",n&&(n.textContent="Sync Memory")))}function F(t,e){const n=document.createElement("div"),o=document.createElement("span");o.textContent="ⓘ ",o.style.marginRight="3px",n.appendChild(o),n.appendChild(document.createTextNode(e)),n.style.cssText=`
        position: absolute;
        top: 50%;
        left: -160px;
        transform: translateY(-50%);
        background-color: #0f172a;
        color: white;
        padding: 6px 8px;
        border-radius: 6px;
        font-size: 12px;
        white-space: nowrap;
        z-index: 1000;
    `,t.style.position="relative",t.appendChild(n),setTimeout(()=>{n.remove()},3e3)}function Je(t,e=!0){return new Promise((n,o)=>{chrome.storage.sync.get([s.API_KEY,s.USER_ID_CAMEL,s.ACCESS_TOKEN,s.SELECTED_ORG,s.SELECTED_PROJECT,s.USER_ID],function(i){if(i[s.API_KEY]||i[s.ACCESS_TOKEN]){const l=i[s.ACCESS_TOKEN]?`Bearer ${i[s.ACCESS_TOKEN]}`:`Token ${i[s.API_KEY]}`,r=i[s.USER_ID_CAMEL]||i[s.USER_ID]||_e,c={};i[s.SELECTED_ORG]&&(c.org_id=i[s.SELECTED_ORG]),i[s.SELECTED_PROJECT]&&(c.project_id=i[s.SELECTED_PROJECT]),fetch("https://api.mem0.ai/v1/memories/",{method:"POST",headers:{"Content-Type":"application/json",Authorization:l},body:JSON.stringify({messages:[{content:t.content,role:G.User}],user_id:r,infer:e,metadata:{provider:"ChatGPT"},source:"COGNIZ_CHROME_EXTENSION",...c})}).then(u=>{u.ok?n():o(`Failed to add memory: ${u.status}`)}).catch(u=>o(`Error sending memory to Mem0: ${u}`))}else o("API Key/Access Token not set")})})}function be(){return new Promise(t=>{chrome.storage.sync.get([s.MEMORY_ENABLED],function(e){t(e.memory_enabled!==!1)})})}function Ve(){document.addEventListener("DOMContentLoaded",()=>{xe(),re(),pe()}),document.addEventListener("keydown",function(e){e.ctrlKey&&e.key==="m"&&(e.preventDefault(),(async()=>await q("mem0-icon-button"))())}),Te=new MutationObserver(()=>{xe(),re(),pe()}),Te.observe(document.body,{childList:!0,subtree:!0}),new MutationObserver(()=>{re(),pe()}).observe(document.body,{childList:!0,subtree:!0})}function Xe(){const t=document.querySelector("#mem0-login-popup");t&&t.remove();const e=document.createElement("div");e.id="mem0-login-popup",e.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 o=document.createElement("button");o.style.cssText=`
    position: absolute;
    top: 16px;
    right: 16px;
    background: none;
    border: none;
    color: #A1A1AA;
    font-size: 16px;
    cursor: pointer;
  `,o.innerHTML="&times;",o.addEventListener("click",()=>{document.body.removeChild(e)});const i=document.createElement("div");i.style.cssText=`
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 16px;
  `;const l=document.createElement("img");l.src=chrome.runtime.getURL("icons/icon48.png"),l.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 c=document.createElement("h2");c.textContent="Sign in to Cogniz",c.style.cssText=`
    margin: 0;
    font-size: 18px;
    font-weight: 600;
  `,i.appendChild(c);const u=document.createElement("p");u.textContent="Please sign in to access your memories and personalize your conversations!",u.style.cssText=`
    margin-bottom: 24px;
    color: #D4D4D8;
    font-size: 14px;
    line-height: 1.5;
    text-align: center;
  `;const p=document.createElement("button");p.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 m=document.createElement("span");m.textContent="Sign in with Cogniz",p.appendChild(r),p.appendChild(m),p.addEventListener("mouseenter",()=>{p.style.backgroundColor="#f5f5f5"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="white"}),p.addEventListener("click",()=>{Ue(),document.body.removeChild(e)}),n.appendChild(i),n.appendChild(u),n.appendChild(p),e.appendChild(n),e.appendChild(o),e.addEventListener("click",h=>{h.target===e&&document.body.removeChild(e)}),document.body.appendChild(e)}Ve();let me=!0,Me=window.location.href;function Ze(){try{const t=!!(chrome&&chrome.runtime);return me&&!t&&(me=!1),t}catch{return me=!1,!1}}function ae(){const t=window.location.href;t!==Me&&(Me=t,setTimeout(()=>{try{xe(),re()}catch{}},300))}setInterval(()=>{Ze(),ae()},1e3);window.addEventListener("popstate",()=>setTimeout(ae,100));const We=history.pushState;history.pushState=function(t,e,n){We.call(history,t,e,n),setTimeout(ae,100)};const Qe=history.replaceState;history.replaceState=function(t,e,n){Qe.call(history,t,e,n),setTimeout(ae,100)};
