import{S as ie}from"./messages-CjQo1qp0.js";import{S as m}from"./storage-pXeRtiJs.js";import{s as lt,a as De,g as ct,b as F,e as dt,c as je,f as Fe,h as Pe,i as pt,j as mt,k as ut,l as gt,m as bt,n as ht,o as xt,p as yt,u as ft,q as vt,r as Ue,t as wt}from"./mem0_proxy-D5oyS3vJ.js";const kt="modulepreload",Et=function(X){return"/"+X},Ge={},zt=function(_,ne,ae){let se=Promise.resolve();if(ne&&ne.length>0){let Ce=function(q){return Promise.all(q.map(Q=>Promise.resolve(Q).then(j=>({status:"fulfilled",value:j}),j=>({status:"rejected",reason:j}))))};document.getElementsByTagName("link");const U=document.querySelector("meta[property=csp-nonce]"),T=U?.nonce||U?.getAttribute("nonce");se=Ce(ne.map(q=>{if(q=Et(q),q in Ge)return;Ge[q]=!0;const Q=q.endsWith(".css"),j=Q?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${q}"]${j}`))return;const y=document.createElement("link");if(y.rel=Q?"stylesheet":kt,Q||(y.as="script"),y.crossOrigin="",y.href=q,T&&y.setAttribute("nonce",T),document.head.appendChild(y),Q)return new Promise((Le,fe)=>{y.addEventListener("load",Le),y.addEventListener("error",()=>fe(new Error(`Unable to preload CSS for ${q}`)))})}))}function le(U){const T=new Event("vite:preloadError",{cancelable:!0});if(T.payload=U,window.dispatchEvent(T),!T.defaultPrevented)throw U}return se.then(U=>{for(const T of U||[])T.status==="rejected"&&le(T.reason);return _().catch(le)})};lt();(function(){let X=!1,_=[];function ne(){chrome.runtime.onMessage.addListener(t=>{t.action===ie.TOGGLE_SIDEBAR&&chrome.storage.sync.get([m.API_KEY,m.PLATFORM_URL],function(i){i[m.API_KEY]&&i[m.PLATFORM_URL]?ae():chrome.runtime.sendMessage({action:ie.OPEN_POPUP})}),t.action===ie.SIDEBAR_SETTINGS&&chrome.storage.sync.get([m.API_KEY,m.PLATFORM_URL],function(i){i[m.API_KEY]&&i[m.PLATFORM_URL]&&(ae(),setTimeout(()=>{document.querySelector('.tab-button[data-tab="settings"]')?.click()},200))})})}function ae(){typeof De=="function"&&De("extension_browser_icon_clicked",{browser:ct(),source:"COGNIZ_CHROME_EXTENSION",tab_url:window.location.href});const t=document.getElementById("mem0-sidebar");t?(X=!X,t.style.right=X?"0px":"-600px",X?(document.addEventListener("click",le),document.addEventListener("keydown",se),j()):(document.removeEventListener("click",le),document.removeEventListener("keydown",se))):(U(),X=!0,document.addEventListener("click",le),document.addEventListener("keydown",se))}function se(t){t.key==="Escape"&&(document.querySelector(".search-memory")?Le():ae())}function le(t){const i=document.getElementById("mem0-sidebar");i&&!i.contains(t.target)&&!t.target?.closest?.(".mem0-toggle-btn")&&ae()}function U(){if(document.getElementById("mem0-sidebar"))return;const t=document.createElement("div");t.id="mem0-sidebar";const i=document.createElement("div");i.className="fixed-header",i.innerHTML=`
        <div class="header">
          <div class="logo-container">
            <img src=${chrome.runtime.getURL("icons/icon48.png")} class="openmemory-icon" alt="Cogniz Memory Logo">
            <span class="openmemory-logo">Cogniz Memory</span>
          </div>
          <div class="header-buttons">
            <button id="closeBtn" class="close-button" title="Close">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M18 6L6 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </button>
          </div>
        </div>
      `;const a=document.createElement("div");a.className="input-container",a.innerHTML=`
      <input
        type="text"
        id="memorySearch"
        class="search-input"
        placeholder="Search memories..."
      />
      <button id="addMemoryBtn" class="add-memory-button" title="Add New Memory">
        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <line x1="12" y1="5" x2="12" y2="19"/>
          <line x1="5" y1="12" x2="19" y2="12"/>
        </svg>
      </button>
    `,i.appendChild(a);const s=document.createElement("div");s.className="project-switcher",s.innerHTML=`
      <label for="projectSelect" class="project-label">Project:</label>
      <select id="projectSelect" class="project-dropdown">
        <option value="">Loading projects...</option>
      </select>
    `,i.appendChild(s);const n=document.createElement("div");n.className="filter-row",n.innerHTML=`
      <div class="category-filter">
        <label for="categoryFilter" class="category-label">Category:</label>
        <select id="categoryFilter" class="category-dropdown">
          <option value="">All Categories</option>
        </select>
      </div>
      <div class="action-buttons">
        <button id="optimizePromptBtn" class="action-button optimize-button" title="Optimize Prompt with Memories" style="background: linear-gradient(135deg, #38bdf8 0%, #0ea5e9 100%); color: #0f172a;">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M12 2L2 7l10 5 10-5-10-5z"/>
            <path d="M2 17l10 5 10-5"/>
            <path d="M2 12l10 5 10-5"/>
          </svg>
        </button>
        <button id="refreshMemoriesBtn" class="action-button refresh-button" title="Refresh Memories">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.2"/>
          </svg>
        </button>
        <button id="exportMemoriesBtn" class="action-button export-button" title="Export Memories">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
            <polyline points="7 10 12 15 17 10"/>
            <line x1="12" y1="15" x2="12" y2="3"/>
          </svg>
        </button>
      </div>
    `,i.appendChild(n);const c=document.createElement("div");c.className="tabs-container",c.innerHTML=`
      <div class="tabs">
        <button class="tab-button" data-tab="analytics">Analytics</button>
        <button class="tab-button active" data-tab="memories">Memories</button>
        <button class="tab-button" data-tab="playbooks">Playbooks</button>
        <button class="tab-button" data-tab="graph">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="5" cy="5" r="3"/>
            <circle cx="19" cy="5" r="3"/>
            <circle cx="12" cy="19" r="3"/>
            <line x1="7" y1="6" x2="10" y2="17"/>
            <line x1="14" y1="17" x2="17" y2="6"/>
            <line x1="8" y1="5" x2="16" y2="5"/>
          </svg>
          Graph
        </button>
        <button class="tab-button" data-tab="settings">Settings</button>
      </div>
    `,i.appendChild(c),t.appendChild(i);const u=document.createElement("div");u.className="content";const p=document.createElement("div");p.className="total-memories",p.innerHTML=`
      <div class="total-memories-content">
        <div>
          <p class="total-memories-label">Total Memories</p>
          <h3 class="memory-count loading">Loading...</h3>
        </div>
        <button id="openDashboardBtn" class="dashboard-button">
          Open Dashboard
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="external-link-icon">
            <path d="M7 17L17 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M7 7H17V17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </button>
      </div>
    `;const b=document.createElement("div");b.className="tab-content",b.id="analytics-tab",b.innerHTML=`
      <div class="analytics-section">
        <h2 class="section-title">Memory Statistics</h2>
        <div class="stat-grid">
          <div class="stat-card">
            <div class="stat-label">Total Memories</div>
            <div class="stat-value" id="analyticsMemoryCount">0</div>
          </div>
          <div class="stat-card">
            <div class="stat-label">Current Project</div>
            <div class="stat-value" id="analyticsProjectName">Not Set</div>
          </div>
        </div>
      </div>
    `;const E=document.createElement("div");E.className="tab-content active",E.id="memories-tab",E.appendChild(p);const w=document.createElement("div");w.className="section",w.innerHTML=`
      <h2 class="section-title">Recent Memories</h2>
      <div class="memory-cards">
        <div class="memory-loader">
          <div class="loader"></div>
        </div>
      </div>
    `,E.appendChild(w);const k=document.createElement("div");k.className="tab-content",k.id="settings-tab";const N=document.createElement("div");N.className="section",N.innerHTML=`
      <div class="section-header">
        <h2 class="section-title">Memory Suggestions</h2>
        <label class="switch">
          <input type="checkbox" id="mem0Toggle">
          <span class="slider"></span>
        </label>
      </div>
      <p class="section-description">Get relevant memories suggested while interacting with AI Agents</p>
    `,k.appendChild(N);const z=document.createElement("div");z.className="section",z.innerHTML=`
      <div class="section-header">
        <h2 class="section-title">Track searches</h2>
        <label class="switch">
          <input type="checkbox" id="trackSearchesToggle">
          <span class="slider"></span>
        </label>
      </div>
      <p class="section-description">Save searches and typed URLs as memories</p>
    `,k.appendChild(z);const $=document.createElement("div");$.className="section",$.innerHTML=`
      <div class="section-header">
        <h2 class="section-title">User ID</h2>
        <button id="userDashboardBtn" class="link-button" title="Open Users Dashboard">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-external-link-icon lucide-external-link">
            <path d="M15 3h6v6"/>
            <path d="M10 14 21 3"/>
            <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>
          </svg>
        </button>
      </div>
      <input type="text" id="userIdInput" class="settings-input" placeholder="Enter your user ID" value="chrome-extension-user">
    `,k.appendChild($);const L=document.createElement("div");L.className="section",L.innerHTML=`
      <div class="section-header">
        <h2 class="section-title">Project</h2>
      </div>
      <p class="section-description">Enter the Memory Platform project slug that should receive captured memories.</p>
      <input type="text" id="projectInput" class="settings-input" placeholder="project-slug" list="memoryProjects" />
      <datalist id="memoryProjects"></datalist>
    `,k.appendChild(L);const G=document.createElement("div");G.className="section",G.innerHTML=`
      <div class="section-header">
        <h2 class="section-title">Enable Auto-Inject</h2>
        <label class="switch">
          <input type="checkbox" id="autoInjectToggle" checked>
          <span class="slider"></span>
        </label>
      </div>
      <p class="section-description">Automatically inject relevant memories into conversations</p>
    `;const R=document.createElement("div");R.className="section",R.innerHTML=`
      <div class="section-header">
        <h2 class="section-title">Threshold</h2>
        <span class="threshold-value">0.3</span>
      </div>
      <p class="section-description">Set the minimum similarity score for memory suggestions</p>
      <div class="slider-container">
        <input type="range" id="thresholdSlider" class="threshold-slider" min="0" max="1" step="0.1" value="0.3">
        <div class="slider-labels">
          <span>0</span>
          <span>0.5</span>
          <span>1</span>
        </div>
      </div>
    `,k.appendChild(R);const S=document.createElement("div");S.className="section",S.innerHTML=`
      <div class="section-header">
        <h2 class="section-title">Top K</h2>
      </div>
      <p class="section-description">Maximum number of memories to suggest</p>
      <input type="number" id="topKInput" class="settings-input" min="1" max="50" value="10">
    `,k.appendChild(S);const O=document.createElement("div");O.className="section",O.innerHTML=`
      <button id="saveSettingsBtn" class="save-button">
        <span class="save-text">Save Settings</span>
        <div class="save-loader" style="display: none;">
          <div class="mini-loader"></div>
        </div>
      </button>
      <div id="saveMessage" class="save-message" style="display: none;"></div>
    `,k.appendChild(O);const H=document.createElement("div");H.className="tab-content",H.id="playbooks-tab";const K=document.createElement("div");K.className="section coming-soon-section",K.innerHTML=`
      <div class="coming-soon-container">
        <div class="coming-soon-icon">
          <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
            <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>
            <line x1="8" y1="21" x2="16" y2="21"></line>
            <line x1="12" y1="17" x2="12" y2="21"></line>
            <circle cx="12" cy="10" r="3" fill="currentColor"></circle>
          </svg>
        </div>
        <h2 class="coming-soon-title">Playbooks - Coming Soon</h2>
        <p class="coming-soon-description">
          Automate your workflow with intelligent playbooks that trigger actions on specific websites.
          Perfect for repetitive tasks like responding to messages, filling forms, or organizing content.
        </p>
        <div class="coming-soon-features">
          <div class="feature-item">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10b981" stroke-width="2">
              <polyline points="20 6 9 17 4 12"></polyline>
            </svg>
            <span>Automated responses for LinkedIn, Twitter, and more</span>
          </div>
          <div class="feature-item">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10b981" stroke-width="2">
              <polyline points="20 6 9 17 4 12"></polyline>
            </svg>
            <span>Custom playbook creation with visual editor</span>
          </div>
          <div class="feature-item">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10b981" stroke-width="2">
              <polyline points="20 6 9 17 4 12"></polyline>
            </svg>
            <span>Trigger playbooks based on page context and content</span>
          </div>
          <div class="feature-item">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10b981" stroke-width="2">
              <polyline points="20 6 9 17 4 12"></polyline>
            </svg>
            <span>AI-powered suggestions using your memory context</span>
          </div>
        </div>
        <p class="coming-soon-eta">
          This feature is under active development and will be available in a future update.
        </p>
      </div>
    `,H.appendChild(K);const Y=document.createElement("div");Y.className="tab-content",Y.id="graph-tab";const te=document.createElement("div");te.className="section coming-soon-section",te.innerHTML=`
      <div class="coming-soon-container">
        <div class="coming-soon-icon">
          <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="5" cy="5" r="3"/>
            <circle cx="19" cy="5" r="3"/>
            <circle cx="12" cy="19" r="3"/>
            <line x1="7" y1="6" x2="10" y2="17"/>
            <line x1="14" y1="17" x2="17" y2="6"/>
            <line x1="8" y1="5" x2="16" y2="5"/>
          </svg>
        </div>
        <h2 class="coming-soon-title">Knowledge Graph - Coming Soon</h2>
        <p class="coming-soon-description">
          Visualize and explore your knowledge with an intelligent graph that automatically extracts
          entities, relationships, and insights from your saved memories.
        </p>
        <div class="coming-soon-features">
          <div class="feature-item">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10b981" stroke-width="2">
              <polyline points="20 6 9 17 4 12"></polyline>
            </svg>
            <span>Automatic entity extraction (people, companies, topics, locations)</span>
          </div>
          <div class="feature-item">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10b981" stroke-width="2">
              <polyline points="20 6 9 17 4 12"></polyline>
            </svg>
            <span>Visual relationship mapping between entities</span>
          </div>
          <div class="feature-item">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10b981" stroke-width="2">
              <polyline points="20 6 9 17 4 12"></polyline>
            </svg>
            <span>Retrieval packs for quick context loading</span>
          </div>
          <div class="feature-item">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10b981" stroke-width="2">
              <polyline points="20 6 9 17 4 12"></polyline>
            </svg>
            <span>Interactive graph visualization with zoom and filtering</span>
          </div>
          <div class="feature-item">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#10b981" stroke-width="2">
              <polyline points="20 6 9 17 4 12"></polyline>
            </svg>
            <span>Export and share your knowledge graph</span>
          </div>
        </div>
        <p class="coming-soon-eta">
          This feature is under active development and will be available in a future update.
        </p>
      </div>
    `,Y.appendChild(te),u.appendChild(b),u.appendChild(E),u.appendChild(H),u.appendChild(Y),u.appendChild(k),t.appendChild(u);const W=document.createElement("div");W.className="footer",W.innerHTML=`
      <div class="shortcut">Shortcut : ^ + M</div>
      <button id="logoutBtn" class="logout-button"><span>Logout</span></button>
    `,chrome.storage.sync.get([m.MEMORY_ENABLED,m.USER_ID,m.USER_ID_CAMEL,m.SELECTED_PROJECT,m.SELECTED_PROJECT_NAME,m.AUTO_INJECT_ENABLED,m.SIMILARITY_THRESHOLD,m.TOP_K,m.TRACK_SEARCHES],async function(P){const I=N.querySelector("#mem0Toggle");I&&(I.checked=P[m.MEMORY_ENABLED]!==!1);const C=z.querySelector("#trackSearchesToggle");C&&(C.checked=P[m.TRACK_SEARCHES]===!0);const Z=$.querySelector("#userIdInput");Z&&(Z.value=String(P[m.USER_ID]??""));const ve=G.querySelector("#autoInjectToggle");ve&&(ve.checked=P[m.AUTO_INJECT_ENABLED]!==!1);const we=R.querySelector("#thresholdSlider"),oe=R.querySelector(".threshold-value"),ke=P[m.SIMILARITY_THRESHOLD]!==void 0?Number(P[m.SIMILARITY_THRESHOLD]):.1;we&&(we.value=String(ke)),oe&&(oe.textContent=ke.toFixed(1));const Ee=S.querySelector("#topKInput"),ce=P[m.TOP_K]!==void 0?Number(P[m.TOP_K]):10;Ee&&(Ee.value=String(ce));const be=L.querySelector("#projectInput");be&&(be.value=String(P[m.SELECTED_PROJECT]??"")),await T(be)}),t.appendChild(W),document.body.appendChild(t),q(t,N,$,L,G,R,S,O,p,W,z),setTimeout(()=>{t.style.right="0"},0),t.addEventListener("click",P=>{P.stopPropagation()}),Ke(),T(L.querySelector("#projectInput")),Q(),j()}async function T(t){if(!t)return;const i=document.getElementById("memoryProjects");if(i){i.innerHTML="";try{const[a,s]=await Promise.all([Pe(),F()]),n=new Set,c=(p,b)=>{if(!p||n.has(p))return;n.add(p);const E=document.createElement("option");E.value=p,b&&b!==p&&(E.label=b),i.appendChild(E)};a.forEach(p=>c(p.id,p.name)),c(s?.projectId,s?.projectName||null),!t.value&&s?.projectId&&(t.value=s.projectId);const u=document.getElementById("analyticsProjectName");u&&s?.projectName&&(u.textContent=s.projectName)}catch(a){console.warn("Unable to populate project suggestions",a)}}}function Ce(t,i,a,s,n,c,u,p,b,E,w){t.disabled=!0,i.style.display="none",a.style.display="flex",s.style.display="none";const k=n.querySelector("#userIdInput"),N=u.querySelector("#mem0Toggle"),z=p.querySelector("#autoInjectToggle"),$=b.querySelector("#thresholdSlider"),L=E.querySelector("#topKInput"),G=w.querySelector("#trackSearchesToggle"),R=(k?.value||"").trim(),S=(c?.value||"").trim(),O=document.getElementById("memoryProjects");let H=S;if(S&&O&&typeof CSS<"u"){const I=O.querySelector(`option[value="${CSS.escape(S)}"]`);I?.label&&(H=I.label)}const K=!!N?.checked,Y=!!z?.checked,te=parseFloat($?.value||"0.3"),W=parseInt(L?.value||"10",10);if(!S){t.disabled=!1,i.style.display="inline",a.style.display="none",s.style.display="block",s.className="save-message error",s.textContent="Project ID is required.";return}const P={user_id:R||void 0,selected_project:S,selected_project_name:H||void 0,memory_enabled:K,auto_inject_enabled:Y,similarity_threshold:te,top_k:W,track_searches:!!G?.checked};chrome.storage.sync.set(P,async()=>{try{const C=(await Pe()).filter(Z=>Z.id!==S);C.unshift({id:S,name:H||S,lastUsed:Date.now()}),await wt(C.slice(0,25))}catch(I){console.warn("Unable to update project cache",I)}chrome.runtime.sendMessage({action:ie.TOGGLE_MEM0,enabled:K}),await T(c??null),j(),setTimeout(()=>{t.disabled=!1,i.style.display="inline",a.style.display="none",s.style.display="block",s.className="save-message success",s.textContent="Settings saved successfully!",setTimeout(()=>{s.style.display="none"},3e3)},300)})}function q(t,i,a,s,n,c,u,p,b,E,w){t.querySelector("#closeBtn")?.addEventListener("click",ae);const N=document.getElementById("memorySearch");console.log("[sidebar] Search input element found:",!!N),N?.addEventListener("input",function(){const e=this.value.toLowerCase();console.log("[sidebar] Search input changed, query:",e),fe(e)});const z=document.getElementById("addMemoryBtn");console.log("[sidebar] Add Memory button element found:",!!z),z?.addEventListener("click",()=>{console.log("[sidebar] Add Memory button clicked"),Xe()});const $=document.getElementById("categoryFilter");console.log("[sidebar] Category filter element found:",!!$),$?.addEventListener("change",function(){const e=this.value;console.log("[sidebar] Category filter changed:",e),We(e)});const L=document.getElementById("refreshMemoriesBtn");console.log("[sidebar] Refresh button element found:",!!L),L?.addEventListener("click",async()=>{console.log("[sidebar] Refresh button clicked");try{L.classList.add("spinning"),L.disabled=!0,y("Loading..."),await j(),console.log("[sidebar] Memories refreshed successfully")}catch(e){console.error("[sidebar] Error refreshing memories:",e),y("Error refreshing")}finally{L.classList.remove("spinning"),L.disabled=!1}});const G=document.getElementById("exportMemoriesBtn");console.log("[sidebar] Export button element found:",!!G),G?.addEventListener("click",()=>{console.log("[sidebar] Export button clicked"),Ze()});const R=document.getElementById("optimizePromptBtn");console.log("[sidebar] Optimizer button element found:",!!R),R?.addEventListener("click",()=>{console.log("[sidebar] Optimizer button clicked - opening floating panel"),te()});const S=document.getElementById("projectSelect");console.log("[sidebar] Project dropdown element found:",!!S),S?.addEventListener("change",async function(){const e=this.value,o=this.options[this.selectedIndex].text;console.log("[sidebar] Switching to project:",e,o);try{await pt({[m.SELECTED_PROJECT]:e,[m.SELECTED_PROJECT_NAME]:o}),y("Loading..."),await j();const r=document.getElementById("analyticsProjectName");r&&(r.textContent=o),console.log("[sidebar] Successfully switched to project:",e)}catch(r){console.error("[sidebar] Error switching project:",r),alert("Failed to switch project. Please try again.")}});const O=t.querySelectorAll(".tab-button"),H=t.querySelectorAll(".tab-content");O.forEach(e=>{e.addEventListener("click",function(){const o=this.getAttribute("data-tab");O.forEach(r=>r.classList.remove("active")),H.forEach(r=>r.classList.remove("active")),this.classList.add("active"),document.getElementById(`${o}-tab`)?.classList.add("active"),o==="playbooks"&&K(),o==="graph"&&Z()})});async function K(){const e=document.getElementById("playbooksList");if(e){e.innerHTML=`
        <div class="loading-state">
          <div class="mini-loader"></div>
          <p>Loading playbooks...</p>
        </div>
      `;try{const o=await F();if(!o.baseUrl||!o.apiKey){e.innerHTML='<p class="error-message">Please configure your platform settings first.</p>';return}const r=await fetch(`${o.baseUrl}/wp-json/memory/v1/playbooks?include_public=true`,{headers:{Authorization:`Bearer ${o.apiKey}`}});if(!r.ok)throw new Error(`Failed to load playbooks: ${r.statusText}`);const l=(await r.json()).playbooks||[];if(l.length===0){e.innerHTML=`
            <div class="empty-state">
              <p>No playbooks yet. Click "Install Defaults" to get started!</p>
            </div>
          `;return}e.innerHTML=l.map(g=>`
          <div class="playbook-card" data-playbook-id="${g.id}">
            <div class="playbook-header">
              <div class="playbook-info">
                <h3 class="playbook-name">${g.name}</h3>
                <p class="playbook-description">${g.description||""}</p>
              </div>
              <label class="switch">
                <input type="checkbox" class="playbook-toggle" data-playbook-id="${g.id}" ${g.is_active?"checked":""}>
                <span class="slider"></span>
              </label>
            </div>
            <div class="playbook-meta">
              <span class="playbook-url-pattern">${g.url_pattern||"All URLs"}</span>
              <span class="playbook-run-count">${g.run_count||0} runs</span>
            </div>
          </div>
        `).join(""),e.querySelectorAll(".playbook-toggle").forEach(g=>{g.addEventListener("change",async function(){const M=this.getAttribute("data-playbook-id"),he=this.checked;try{if(!(await fetch(`${o.baseUrl}/wp-json/memory/v1/playbooks/${M}`,{method:"PUT",headers:{Authorization:`Bearer ${o.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({is_active:he})})).ok)throw new Error("Failed to update playbook");window.__playbookRunner&&await window.__playbookRunner.reload()}catch(de){console.error("Error toggling playbook:",de),this.checked=!he,alert("Failed to toggle playbook. Please try again.")}})})}catch(o){console.error("Error loading playbooks:",o),e.innerHTML='<p class="error-message">Failed to load playbooks. Please try again.</p>'}}}const Y=document.getElementById("installDefaultPlaybooksBtn");Y?.addEventListener("click",async()=>{const e=Y,o=e.innerHTML;e.disabled=!0,e.innerHTML='<div class="mini-loader"></div> Installing...';try{const r=await F();if(!r.baseUrl||!r.apiKey){alert("Please configure your platform settings first.");return}const{defaultPlaybooks:d}=await zt(async()=>{const{defaultPlaybooks:l}=await import("./default-playbooks-CP1EpXcL.js");return{defaultPlaybooks:l}},[]);for(const l of d)(await fetch(`${r.baseUrl}/wp-json/memory/v1/playbooks`,{method:"POST",headers:{Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(l)})).ok||console.error("Failed to install playbook:",l.name);e.innerHTML="✓ Installed!",setTimeout(()=>{e.innerHTML=o,e.disabled=!1,K()},2e3)}catch(r){console.error("Error installing playbooks:",r),e.innerHTML=o,e.disabled=!1,alert("Failed to install default playbooks. Please try again.")}});function te(){const e=document.getElementById("mem0-optimizer-panel");if(e){e.classList.add("optimizer-panel-closing"),setTimeout(()=>e.remove(),300);return}const o=document.createElement("div");o.id="mem0-optimizer-panel",o.className="mem0-optimizer-panel",o.innerHTML=`
        <div class="optimizer-panel-content">
          <div class="optimizer-panel-header">
            <h2 class="optimizer-panel-title">✨ Prompt Optimizer</h2>
            <button class="optimizer-panel-close" title="Close Optimizer">&times;</button>
          </div>

          <div class="optimizer-panel-body">
            <div class="optimizer-subtitle">Build paste-ready prompts with your memory context</div>

            <!-- Step 1: Instruction -->
            <div class="optimizer-section">
              <label class="optimizer-label">1. Your Question or Task</label>
              <textarea
                id="optimizerInstruction"
                class="optimizer-textarea"
                rows="3"
                placeholder="Example: Write a function to validate email addresses using regex..."
              ></textarea>
            </div>

            <!-- Step 2: Search Memories -->
            <div class="optimizer-section">
              <label class="optimizer-label">
                2. Search Your Memories
                <span id="optimizerSelectedCount" class="optimizer-count">0 selected</span>
              </label>
              <div class="optimizer-search-row">
                <input
                  id="optimizerSearchQuery"
                  type="text"
                  class="optimizer-search-input"
                  placeholder="Search keywords..."
                />
                <button id="optimizerSearchBtn" class="optimizer-btn optimizer-btn-secondary">
                  🔍 Search
                </button>
              </div>
              <div id="optimizerResults" class="optimizer-results"></div>
            </div>

            <!-- Step 3: Settings -->
            <div class="optimizer-section">
              <label class="optimizer-label">3. Optimization Settings</label>
              <div class="optimizer-settings-grid">
                <div>
                  <label class="optimizer-small-label">Preset Template</label>
                  <select id="optimizerPreset" class="optimizer-select">
                    <option value="general">General (Balanced)</option>
                    <option value="research">Research (Citations)</option>
                    <option value="coding">Coding (Implementation)</option>
                    <option value="copywriting">Copywriting (Variants)</option>
                    <option value="data_analysis">Data Analysis (Tables)</option>
                  </select>
                </div>
                <div>
                  <label class="optimizer-small-label">Token Budget</label>
                  <input
                    id="optimizerTokenBudget"
                    type="number"
                    class="optimizer-input"
                    min="512"
                    max="8192"
                    step="256"
                    value="2048"
                  />
                </div>
              </div>
            </div>

            <!-- Generate Button -->
            <button id="optimizerGenerateBtn" class="optimizer-btn optimizer-btn-primary" disabled>
              ✨ Generate Optimized Prompt
            </button>

            <!-- Step 4: Output -->
            <div id="optimizerOutputSection" class="optimizer-section optimizer-hidden">
              <label class="optimizer-label">4. Optimized Prompt</label>

              <!-- Intent Analysis (collapsible) -->
              <div id="optimizerIntentSection" class="optimizer-intent-section optimizer-hidden">
                <button id="optimizerIntentToggle" class="optimizer-intent-toggle">
                  ▶ Intent Analysis
                </button>
                <div id="optimizerIntentContent" class="optimizer-intent-content optimizer-hidden">
                  <div id="optimizerIntentData"></div>
                </div>
              </div>

              <div id="optimizerOutput" class="optimizer-output"></div>

              <div class="optimizer-button-row">
                <button id="optimizerCopyBtn" class="optimizer-btn optimizer-btn-success">
                  📋 Copy to Clipboard
                </button>
                <button id="optimizerResetBtn" class="optimizer-btn optimizer-btn-secondary">
                  🔄 Start Over
                </button>
              </div>
            </div>

            <!-- Status Message -->
            <div id="optimizerStatus" class="optimizer-status"></div>
          </div>
        </div>
      `,document.body.appendChild(o),o.querySelector(".optimizer-panel-close")?.addEventListener("click",()=>{o.classList.add("optimizer-panel-closing"),setTimeout(()=>o.remove(),300)}),o.addEventListener("click",d=>{d.target===o&&(o.classList.add("optimizer-panel-closing"),setTimeout(()=>o.remove(),300))}),W(o)}function W(e){const o=new Map;function r(x,v=3e3){const f=e.querySelector("#optimizerStatus");f&&(f.textContent=x,f.style.display=x?"block":"none",x&&v>0&&setTimeout(()=>{f.textContent===x&&(f.textContent="",f.style.display="none")},v))}function d(){const x=e.querySelector("#optimizerSelectedCount"),v=e.querySelector("#optimizerGenerateBtn"),f=e.querySelector("#optimizerInstruction");x&&(x.textContent=`${o.size} selected`);const A=f&&f.value.trim().length>0,pe=o.size>0;v&&(v.disabled=!(A&&pe))}const l=e.querySelector("#optimizerSearchBtn");l?.addEventListener("click",async()=>{const x=e.querySelector("#optimizerSearchQuery"),v=e.querySelector("#optimizerResults");if(!x||!v)return;const f=x.value.trim();if(!f){r("Please enter a search term");return}r("Searching…",0),l.disabled=!0;try{const A=await F();if(!A){r("Please configure the extension first"),l.disabled=!1;return}const pe=`${A.baseUrl}/wp-json/memory/v1/search?project_id=${encodeURIComponent(A.projectId)}&query=${encodeURIComponent(f)}&limit=20`,me=await fetch(pe,{method:"GET",headers:{Authorization:`Bearer ${A.apiKey}`,"Content-Type":"application/json","X-Memory-Platform-Client":"browser-extension"}});if(!me.ok)throw new Error(`Search failed: ${me.status}`);const re=(await me.json()).results||[];if(!re||re.length===0){v.innerHTML='<p style="padding: 12px; color: #94a3b8; margin: 0;">No memories found. Try different keywords.</p>',r("No memories found"),l.disabled=!1;return}v.innerHTML="",re.forEach(ue=>{const ge=ue.memory_id,Be=ue.content.substring(0,150)+(ue.content.length>150?"…":""),ee=document.createElement("div");ee.className="optimizer-result-item";const B=document.createElement("input");B.type="checkbox",B.checked=o.has(ge),B.addEventListener("change",()=>{B.checked?o.set(ge,{content:ue.content,memory_id:ge}):o.delete(ge),d()});const ye=document.createElement("div");ye.className="optimizer-result-content",ye.textContent=Be,ee.appendChild(B),ee.appendChild(ye),v.appendChild(ee)}),r(`Found ${re.length} memories`)}catch(A){console.error("[optimizer] search error",A),r("Search failed"),v.innerHTML='<p style="padding: 12px; color: #ef4444; margin: 0;">Error during search.</p>'}finally{l.disabled=!1}});const h=e.querySelector("#optimizerGenerateBtn");h?.addEventListener("click",async()=>{const x=e.querySelector("#optimizerInstruction"),v=e.querySelector("#optimizerPreset"),f=e.querySelector("#optimizerTokenBudget"),A=e.querySelector("#optimizerOutputSection"),pe=e.querySelector("#optimizerOutput");if(!x||!pe||!A)return;const me=x.value.trim();if(!me){r("Please enter your question or task");return}if(o.size===0){r("Please select at least one memory");return}r("Generating optimized prompt…",0),h.disabled=!0;try{const V=await F();if(!V){r("Please configure the extension first");return}const re=[];for(const[Se]of o.entries())re.push(Se);const ue=v?v.value:"general",ge=f?parseInt(f.value):2048,Be=`${V.baseUrl}/wp-json/memory/v1/optimize`,ee=await fetch(Be,{method:"POST",headers:{Authorization:`Bearer ${V.apiKey}`,"Content-Type":"application/json","X-Memory-Platform-Client":"browser-extension"},body:JSON.stringify({instruction:me,project_id:V.projectId,memory_ids:re,preset:ue,token_budget:ge,model:"gpt-4o-mini"})});if(!ee.ok)throw new Error(`Optimization failed: ${ee.status}`);const B=await ee.json();if(!B||!B.optimized_prompt)throw new Error("No optimized prompt in response");if(pe.textContent=B.optimized_prompt,A.classList.remove("optimizer-hidden"),B.debug?.intent_analysis){const Se=e.querySelector("#optimizerIntentSection"),He=e.querySelector("#optimizerIntentData"),D=B.debug.intent_analysis;if(Se&&He){let J="";D.core_task&&(J+=`<div class="optimizer-intent-item"><strong>Core Task:</strong> ${D.core_task}</div>`),D.expanded_instruction&&(J+=`<div class="optimizer-intent-item"><strong>Expanded Instruction:</strong><br>${D.expanded_instruction}</div>`),D.implicit_requirements&&D.implicit_requirements.length>0&&(J+='<div class="optimizer-intent-item"><strong>Implicit Requirements:</strong><ul>',D.implicit_requirements.forEach(Te=>{J+=`<li>${Te}</li>`}),J+="</ul></div>"),D.ambiguities&&D.ambiguities.length>0&&(J+='<div class="optimizer-intent-item"><strong>Ambiguities Addressed:</strong><ul>',D.ambiguities.forEach(Te=>{J+=`<li>${Te}</li>`}),J+="</ul></div>"),He.innerHTML=J,Se.classList.remove("optimizer-hidden")}}const ye=B.debug?.used_ai?`AI (${B.debug.model||"GPT"})`:"Local",at=B.debug?.fact_count||o.size,st=B.debug?.intent_analysis?" • Intent cached ⚡":"";r(`Optimized with ${ye} • ${at} memories included${st}`)}catch(V){console.error("[optimizer] generation error",V),r(V instanceof Error?V.message:"Optimization failed")}finally{h.disabled=!1}}),e.querySelector("#optimizerCopyBtn")?.addEventListener("click",()=>{const x=e.querySelector("#optimizerOutput");if(!x)return;const v=x.textContent||"";navigator.clipboard.writeText(v).then(()=>{r("✅ Copied to clipboard!")}).catch(f=>{console.error("[optimizer] copy failed",f),r("Failed to copy")})}),e.querySelector("#optimizerResetBtn")?.addEventListener("click",()=>{o.clear();const x=e.querySelector("#optimizerInstruction"),v=e.querySelector("#optimizerSearchQuery"),f=e.querySelector("#optimizerResults"),A=e.querySelector("#optimizerOutputSection");x&&(x.value=""),v&&(v.value=""),f&&(f.innerHTML=""),A&&A.classList.add("optimizer-hidden"),d(),r("")}),e.querySelector("#optimizerInstruction")?.addEventListener("input",()=>{d()}),e.querySelector("#optimizerSearchQuery")?.addEventListener("keypress",x=>{x.key==="Enter"&&(x.preventDefault(),l?.click())});const xe=e.querySelector("#optimizerIntentToggle"),ze=e.querySelector("#optimizerIntentContent");xe?.addEventListener("click",()=>{ze&&(ze.classList.contains("optimizer-hidden")?(ze.classList.remove("optimizer-hidden"),xe.textContent="▼ Intent Analysis"):(ze.classList.add("optimizer-hidden"),xe.textContent="▶ Intent Analysis"))})}b.querySelector("#openDashboardBtn")?.addEventListener("click",Ve);let I=[],C=[];async function Z(){await ve(),await we(),await ce(),be()}async function ve(){try{const e=await mt(),o=document.getElementById("totalEntities"),r=document.getElementById("totalRelationships"),d=document.getElementById("totalPacks");o&&(o.textContent=String(e.total_entities)),r&&(r.textContent=String(e.total_relationships)),d&&(d.textContent=String(e.total_packs))}catch(e){console.error("[Graph] Failed to load stats:",e)}}async function we(){const e=document.getElementById("entitiesList"),o=document.getElementById("entityCount");if(e)try{if(I=await ut(void 0,100),o&&(o.textContent=String(I.length)),I.length===0){e.innerHTML=`
            <div class="empty-state">
              <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="10"/>
                <line x1="12" y1="8" x2="12" y2="12"/>
                <line x1="12" y1="16" x2="12.01" y2="16"/>
              </svg>
              <h3>No Entities Yet</h3>
              <p>Extract entities from your memories to build your knowledge graph</p>
              <button id="extractStartBtn" class="primary-button">Extract Entities</button>
            </div>
          `,tt();return}oe(I)}catch(r){console.error("[Graph] Failed to load entities:",r),e&&(e.innerHTML='<p class="error-message">Failed to load entities. Please try again.</p>')}}function oe(e){const o=document.getElementById("entitiesList");if(!o)return;const r={person:{icon:"👤",color:"#38bdf8"},company:{icon:"🏢",color:"#f59e0b"},topic:{icon:"📌",color:"#10b981"},location:{icon:"📍",color:"#ef4444"},product:{icon:"📦",color:"#8b5cf6"},concept:{icon:"💡",color:"#ec4899"}};o.innerHTML=e.map(l=>{const h=r[l.entity_type]||{icon:"📄",color:"#6b7280"};return`
          <div class="entity-item ${C.includes(l.id)?"selected":""}" data-entity-id="${l.id}">
            <div class="entity-icon" style="background: ${h.color};">${h.icon}</div>
            <div class="entity-content">
              <div class="entity-name">${l.entity_name}</div>
              <div class="entity-type">${l.entity_type}</div>
            </div>
            <div class="entity-badge">${l.mention_count}</div>
          </div>
        `}).join(""),o.querySelectorAll(".entity-item").forEach(l=>{l.addEventListener("click",function(){const h=parseInt(this.getAttribute("data-entity-id")||"0");h&&(ke(h),Ee(h))})})}function ke(e){const o=C.indexOf(e);o>-1?C.splice(o,1):C.push(e);const r=document.querySelector(`.entity-item[data-entity-id="${e}"]`);r&&(C.indexOf(e)>-1?r.classList.add("selected"):r.classList.remove("selected"));const d=document.getElementById("createPackBtn");d&&(d.disabled=C.length===0)}async function Ee(e){try{const o=await gt(e),r=document.createElement("div");r.className="modal",r.innerHTML=`
          <div class="modal-content">
            <div class="modal-header">
              <h2>${o.entity_name}</h2>
              <button class="modal-close">&times;</button>
            </div>
            <div class="modal-body">
              <div class="entity-detail-section">
                <h3>Type</h3>
                <p>${o.entity_type||o.type||"Unknown"}</p>
              </div>
              ${o.description?`
                <div class="entity-detail-section">
                  <h3>Description</h3>
                  <p>${o.description}</p>
                </div>
              `:""}
              <div class="entity-detail-section">
                <h3>Mentions</h3>
                <p>${o.mention_count||o.mentions||0} times</p>
              </div>
              ${o.memories&&o.memories.length>0?`
                <div class="entity-detail-section">
                  <h3>Related Memories (${o.memories.length})</h3>
                  ${o.memories.map(l=>`
                    <div class="memory-snippet">
                      <div class="memory-snippet-content">${l.context_snippet||l.content?.substring(0,150)||"No content"}...</div>
                      <div class="memory-snippet-meta">Relevance: ${l.relevance_score?(l.relevance_score*100).toFixed(0):"N/A"}%</div>
                    </div>
                  `).join("")}
                </div>
              `:'<div class="entity-detail-section"><p>No related memories yet.</p></div>'}
              ${o.relationships&&o.relationships.length>0?`
                <div class="entity-detail-section">
                  <h3>Relationships (${o.relationships.length})</h3>
                  ${o.relationships.map(l=>`
                    <div class="relationship-item">
                      ${l.entity_name} <span class="relationship-type">(${l.relationship_type})</span>
                    </div>
                  `).join("")}
                </div>
              `:""}
            </div>
          </div>
        `,document.body.appendChild(r),r.querySelector(".modal-close")?.addEventListener("click",()=>r.remove()),r.addEventListener("click",l=>{l.target===r&&r.remove()})}catch(o){console.error("[Graph] Failed to load entity details:",o),alert("Failed to load entity details. Please try again.")}}async function ce(){const e=document.getElementById("packsList");if(e)try{const o=await bt();if(o.length===0){e.innerHTML='<div class="empty-state-mini"><p>No packs created yet</p></div>';return}e.innerHTML=o.map(r=>`
          <div class="pack-card" data-pack-id="${r.id}">
            <div class="pack-header">
              <div class="pack-name">${r.pack_name}</div>
              <div class="pack-actions">
                <button class="pack-use-btn" data-pack-id="${r.id}" title="Use pack">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M5 12h14M12 5l7 7-7 7"/>
                  </svg>
                </button>
                <button class="pack-delete-btn" data-pack-id="${r.id}" title="Delete pack">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/>
                  </svg>
                </button>
              </div>
            </div>
            ${r.description?`<div class="pack-description">${r.description}</div>`:""}
            <div class="pack-meta">
              <span>${r.entity_count} entities</span>
              <span>${r.memory_count} memories</span>
              <span>${r.use_count} uses</span>
            </div>
          </div>
        `).join(""),it()}catch(o){console.error("[Graph] Failed to load packs:",o),e&&(e.innerHTML='<p class="error-message">Failed to load packs</p>')}}function be(){document.getElementById("refreshGraphBtn")?.addEventListener("click",async()=>{await Z()});const o=document.getElementById("entitySearch");let r;o?.addEventListener("input",function(){clearTimeout(r),r=setTimeout(async()=>{const g=this.value.trim();if(g.length===0)oe(I);else if(g.length>=2)try{const M=await ht(g);oe(M)}catch(M){console.error("[Graph] Search failed:",M)}},300)}),document.querySelectorAll('.entity-type-filters input[type="checkbox"]').forEach(g=>{g.addEventListener("change",()=>{et()})}),document.getElementById("extractEntitiesBtn")?.addEventListener("click",_e),document.getElementById("createPackBtn")?.addEventListener("click",ot)}function et(){const e=document.querySelectorAll('.entity-type-filters input[type="checkbox"]'),o=[];e.forEach(d=>{d.checked&&o.push(d.value)});const r=I.filter(d=>o.includes(d.entity_type));oe(r)}function tt(){document.getElementById("extractStartBtn")?.addEventListener("click",_e)}function _e(){if(!_||_.length===0){alert("No memories found. Switch to Memories tab and load some memories first.");return}const e=document.createElement("div");e.className="modal",e.innerHTML=`
        <div class="modal-content">
          <div class="modal-header">
            <h2>Extract Entities</h2>
            <button class="modal-close">&times;</button>
          </div>
          <div class="modal-body">
            <p>Select memories to extract entities from:</p>
            <div class="memory-select-list">
              ${_.slice(0,10).map((d,l)=>{const h=d.memory||"";return`
                  <label class="memory-select-item">
                    <input type="checkbox" value="${d.id||""}" ${l===0?"checked":""}>
                    <span>${h.substring(0,100)}...</span>
                  </label>
                `}).join("")}
            </div>
            <div class="provider-select">
              <label>LLM Provider:</label>
              <select id="extractProvider">
                <option value="openai">OpenAI (GPT-4o-mini)</option>
                <option value="claude">Claude (Haiku)</option>
                <option value="gemini">Gemini (1.5 Flash)</option>
              </select>
            </div>
            <button id="startExtractionBtn" class="primary-button">Start Extraction</button>
            <div id="extractionProgress" class="extraction-progress" style="display: none;">
              <div class="mini-loader"></div>
              <p id="extractionStatus">Extracting...</p>
            </div>
          </div>
        </div>
      `,document.body.appendChild(e),e.querySelector(".modal-close")?.addEventListener("click",()=>e.remove()),e.addEventListener("click",d=>{d.target===e&&e.remove()});const r=e.querySelector("#startExtractionBtn");r?.addEventListener("click",async()=>{const d=e.querySelectorAll(".memory-select-item input:checked");if(d.length===0){alert("Please select at least one memory");return}const l=e.querySelector("#extractProvider").value,h=e.querySelector("#extractionProgress"),g=e.querySelector("#extractionStatus");r.disabled=!0,h&&(h.style.display="block");let M=0;for(const he of Array.from(d)){const de=he.value;g&&(g.textContent=`Extracting from memory ${M+1} of ${d.length}...`);try{await xt(de,l),M++}catch(xe){console.error(`[Graph] Failed to extract from ${de}:`,xe)}}g&&(g.textContent=`Completed! Extracted entities from ${M} memories.`),setTimeout(()=>{e.remove(),Z()},2e3)})}function ot(){if(C.length===0){alert("Please select at least one entity");return}const e=document.createElement("div");e.className="modal",e.innerHTML=`
        <div class="modal-content">
          <div class="modal-header">
            <h2>Create Retrieval Pack</h2>
            <button class="modal-close">&times;</button>
          </div>
          <div class="modal-body">
            <div class="form-group">
              <label>Pack Name</label>
              <input type="text" id="packNameInput" class="input-field" placeholder="e.g., AI Research Pack">
            </div>
            <div class="form-group">
              <label>Description (optional)</label>
              <textarea id="packDescriptionInput" class="input-field" rows="3" placeholder="Describe what this pack contains..."></textarea>
            </div>
            <div class="form-group">
              <label>
                <input type="checkbox" id="packPublicCheckbox">
                Make this pack public
              </label>
            </div>
            <p class="info-text">Selected entities: ${C.length}</p>
            <button id="createPackSubmitBtn" class="primary-button">Create Pack</button>
          </div>
        </div>
      `,document.body.appendChild(e),e.querySelector(".modal-close")?.addEventListener("click",()=>e.remove()),e.addEventListener("click",d=>{d.target===e&&e.remove()});const r=e.querySelector("#createPackSubmitBtn");r?.addEventListener("click",async()=>{const d=e.querySelector("#packNameInput").value.trim();if(!d){alert("Please enter a pack name");return}const l=e.querySelector("#packDescriptionInput").value.trim(),h=e.querySelector("#packPublicCheckbox").checked;r.disabled=!0,r.textContent="Creating...";try{await yt(d,C,l,h),e.remove(),C=[],await ce(),alert(`Pack "${d}" created successfully!`)}catch(g){console.error("[Graph] Failed to create pack:",g),alert("Failed to create pack. Please try again."),r.disabled=!1,r.textContent="Create Pack"}})}function rt(e,o,r){const d=document.querySelector(".pack-loaded-notification");d&&d.remove();const l=document.createElement("div");l.className="pack-loaded-notification",l.innerHTML=`
        <div class="notification-content">
          <div class="notification-icon">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
              <polyline points="22 4 12 14.01 9 11.01"></polyline>
            </svg>
          </div>
          <div class="notification-text">
            <div class="notification-title">Pack Loaded Successfully!</div>
            <div class="notification-details">
              <strong>${e}</strong> is now active
              <br>
              <span class="notification-stats">
                📦 ${o} entities &nbsp;|&nbsp; 💾 ${r} memories loaded
              </span>
            </div>
            <div class="notification-info">
              These entities and memories are now available in your context for AI assistants to reference.
            </div>
          </div>
          <button class="notification-close" title="Close">×</button>
        </div>
      `,document.body.appendChild(l),l.querySelector(".notification-close")?.addEventListener("click",()=>{l.classList.add("notification-hiding"),setTimeout(()=>l.remove(),300)}),setTimeout(()=>{l.classList.add("notification-hiding"),setTimeout(()=>l.remove(),300)},8e3),requestAnimationFrame(()=>{l.classList.add("notification-visible")})}function it(){document.querySelectorAll(".pack-use-btn").forEach(r=>{r.addEventListener("click",async function(){const d=parseInt(this.getAttribute("data-pack-id")||"0");if(!d)return;const h=this.closest(".pack-card")?.querySelector(".pack-name")?.textContent||"Pack";this.disabled=!0;const g=this.innerHTML;this.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="spinning">
            <path d="M21 12a9 9 0 11-6.219-8.56"/>
          </svg>`;try{const M=await ft(d);rt(h,M.entities.length,M.memories.length),await ce()}catch(M){console.error("[Graph] Failed to use pack:",M),alert("Failed to use pack. Please try again.")}finally{this.disabled=!1,this.innerHTML=g}})}),document.querySelectorAll(".pack-delete-btn").forEach(r=>{r.addEventListener("click",async function(){const d=parseInt(this.getAttribute("data-pack-id")||"0");if(d&&confirm("Are you sure you want to delete this pack?")){this.disabled=!0;try{await vt(d),await ce()}catch(l){console.error("[Graph] Failed to delete pack:",l),alert("Failed to delete pack. Please try again."),this.disabled=!1}}})})}E.querySelector("#logoutBtn")?.addEventListener("click",Ye);const qe=s.querySelector("#projectInput");T(qe),a.querySelector("#userDashboardBtn")?.addEventListener("click",async()=>{try{const e=await je();chrome.runtime.sendMessage({action:ie.OPEN_DASHBOARD,url:e})}catch(e){console.warn("Unable to open Memory Platform dashboard",e)}});const nt=c.querySelector("#thresholdSlider"),Ne=c.querySelector(".threshold-value");nt?.addEventListener("input",function(){Ne&&(Ne.textContent=parseFloat(this.value).toFixed(1))}),u.querySelector("#topKInput")?.addEventListener("input",function(){const e=parseInt(this.value,10);e<1?this.value=String(1):e>50&&(this.value=String(50))});const Me=p.querySelector("#saveSettingsBtn"),Re=p.querySelector(".save-text"),$e=p.querySelector(".save-loader"),Oe=p.querySelector("#saveMessage");Me?.addEventListener("click",()=>{!Me||!Re||!$e||!Oe||Ce(Me,Re,$e,Oe,a,qe,i,n,c,u,w)})}async function Q(){console.log("[sidebar] populateProjectDropdown called");const t=document.getElementById("projectSelect");if(console.log("[sidebar] Dropdown element:",t),!t){console.log("[sidebar] Project dropdown not found - element missing from DOM");return}try{console.log("[sidebar] Fetching projects and config...");const[i,a]=await Promise.all([Pe(),F()]);if(console.log("[sidebar] Populating project dropdown. Projects:",i,"Count:",i.length,"Current:",a?.projectId),t.innerHTML="",a?.projectId){const n=document.createElement("option");n.value=a.projectId,n.textContent=a.projectName||a.projectId,n.selected=!0,t.appendChild(n),console.log("[sidebar] Added current project:",a.projectId)}let s=0;i.forEach(n=>{if(console.log("[sidebar] Processing project:",n.id,n.name,"Current:",a?.projectId),n.id!==a?.projectId){const c=document.createElement("option");c.value=n.id,c.textContent=n.name||n.id,t.appendChild(c),s++,console.log("[sidebar] Added project to dropdown:",n.id)}}),console.log("[sidebar] Populated project dropdown with",t.options.length,"total projects (",s,"additional)")}catch(i){console.error("[sidebar] Error populating projects:",i),t.innerHTML='<option value="">Error loading projects</option>'}}async function j(){try{console.log("[sidebar] fetchMemoriesAndCount called");const t=await F();if(console.log("[sidebar] Platform config:",t),!t){console.log("[sidebar] No config found, showing configure message"),y("Configure"),Ae("Open the popup and configure your Memory Platform details.");return}console.log('[sidebar] Calling searchMemories with query="all", limit=20, projectId=',t.projectId);const i=await dt("all",{limit:20});console.log("[sidebar] searchMemories returned:",i),console.log("[sidebar] Number of results:",i.length);const a=i.map(s=>({id:String(s.id??""),memory:s.memory,categories:s.categories,relevance:s.relevance}));console.log("[sidebar] Mapped memories:",a),_=a,y(a.length),Ie(a),Qe(a)}catch(t){console.error("[sidebar] Error fetching memories:",t),y("Error"),Ae("Unable to load memories from the Memory Platform.")}}function y(t){const i=document.querySelector(".memory-count");i&&(i.classList.remove("loading"),i.textContent=typeof t=="number"?new Intl.NumberFormat().format(t)+" Memories":t);const a=document.getElementById("analyticsMemoryCount");a&&(a.textContent=typeof t=="number"?String(t):t)}function Le(){const i=document.querySelector(".input-container")?.querySelector(".search-memory"),a=document.getElementById("searchBtn");i&&(i.remove(),a?.classList.remove("active"),fe(""))}function fe(t){console.log("[sidebar] filterMemories called with query:",t);const i=document.querySelectorAll(".memory-card");console.log("[sidebar] Found .memory-card elements:",i.length);const a=document.querySelectorAll(".memory-item");console.log("[sidebar] Found .memory-item elements:",a.length),i.forEach(n=>{(n.textContent?.toLowerCase()||"").includes(t)?n.style.display="":n.style.display="none"}),a.forEach(n=>{(n.querySelector(".memory-text")?.textContent?.toLowerCase()||"").includes(t)?n.style.display="flex":n.style.display="none"});const s=document.getElementById("mem0-sidebar");s&&(s.style.width="400px")}function Ke(){const t=document.createElement("style");t.textContent=`
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
        
        :root {
          --bg-dark: #0f172a;
          --bg-card: #1e293b;
          --bg-button: #334155;
          --bg-button-hover: #475569;
          --text-white: #f8fafc;
          --text-gray: #94a3b8;
          --purple: #667eea;
          --border-color: #334155;
          --tag-bg: #334155;
          --scrollbar-bg: #1e293b;
          --scrollbar-thumb: #475569;
          --success-color: #10b981;
        }
        
        #mem0-sidebar {
          font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
          position: fixed; 
          top: 60px;
          right: 50px;
          width: 400px;
          height: auto;
          max-height: 85vh;
          background: var(--bg-dark);
          border: 1px solid var(--border-color);
          border-radius: 12px;
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          padding: 0px;
          color: var(--text-white);
          z-index: 2147483647;
          transition: right 0.3s ease-in-out;
          overflow: hidden;
          box-shadow: 0px 4px 20px rgba(0, 0, 0, 0.5);
        }
        
        .fixed-header {
          box-sizing: border-box;
          width: 100%;
          background: var(--bg-dark);
          border-bottom: 1px solid var(--border-color);
        }
        
        .tabs-container {
          padding: 0 16px;
          background: var(--bg-dark);
          border-bottom: 1px solid var(--border-color);
        }
        
        .tabs {
          display: flex;
          gap: 0;
        }
        
        .tab-button {
          flex: 1;
          padding: 12px 16px;
          background: none;
          border: none;
          color: var(--text-gray);
          font-size: 14px;
          font-weight: 500;
          cursor: pointer;
          transition: color 0.2s ease;
          position: relative;
          border-bottom: 2px solid transparent;
        }
        
        .tab-button.active {
          color: var(--text-white);
          border-bottom-color: var(--purple);
        }
        
        .tab-button:hover {
          color: var(--text-white);
        }
        
        .tab-content {
          display: none;
          flex-direction: column;
          gap: 24px;
        }
        
        .tab-content.active {
          display: flex;
        }
        
        .header {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
          padding: 16px;
          width: 100%;
          height: 62px;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border-radius: 12px 12px 0 0;
        }
        
        .logo-container {
          display: flex;
          flex-direction: row;
          align-items: center;
          padding: 0px;
          gap: 8px;
          height: 24px;
        }
        
        .openmemory-icon {
          width: 24px;
          height: 24px;
        }
        
        .openmemory-logo {
          height: 24px;
          font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          font-style: normal;
          font-weight: 600;
          font-size: 20px;
          line-height: 24px;
          letter-spacing: -0.03em;
          color: var(--text-white);
        }
        
        .header-buttons {
          display: flex;
          flex-direction: row;
          align-items: center;
          padding: 0px;
          gap: 16px;
          height: 30px;
        }
        
        .close-button {
          background: none;
          border: none;
          width: 24px;
          height: 24px;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          color: var(--text-gray);
          font-size: 20px;
          transition: color 0.2s ease;
        }
        
        .close-button:hover {
          color: var(--text-white);
        }
        
        /* Custom scrollbar styles */
        .content {
          padding: 16px;
          display: flex;
          flex-direction: column;
          gap: 24px;
          overflow-y: auto;
          max-height: calc(85vh - 62px - 49px - 60px); /* Subtract header, tab bar, and footer heights */
          
          /* Firefox */
          scrollbar-width: thin;
          scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-bg);
        }
        
        /* WebKit browsers (Chrome, Safari, Edge) */
        .content::-webkit-scrollbar {
          width: 4px;
        }
        
        .content::-webkit-scrollbar-track {
          background: var(--scrollbar-bg);
        }
        
        .content::-webkit-scrollbar-thumb {
          background-color: var(--scrollbar-thumb);
          border-radius: 4px;
          border: none;
        }
        
        .total-memories {
          background-color: var(--bg-card);
          border-radius: 8px;
          padding: 16px;
        }
        
        .total-memories-content {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
        
        .total-memories-label {
          color: var(--text-gray);
          font-size: 14px;
          margin-bottom: 4px;
        }
        
        .memory-count {
          font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          font-style: normal;
          font-weight: 500;
          font-size: 18px;
          line-height: 140%;
          letter-spacing: -0.03em;
          color: var(--text-white);
        }
        
        .memory-count.loading {
          color: var(--text-gray);
          font-size: 16px;
        }
        
        .dashboard-button {
          display: flex;
          flex-direction: row;
          align-items: center;
          padding: 4px 8px;
          gap: 4px;
          background: var(--bg-button);
          background-opacity: 0.5;
          border-radius: 8px;
          border: none;
          cursor: pointer;
          transition: all 0.2s ease;
          color: var(--text-white);
          font-size: 14px;
        }
        
        .dashboard-button:hover {
          background: var(--bg-button-hover);
        }
        
        .external-link-icon {
          width: 14px;
          height: 14px;
        }
        
        .section {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }
        
        .section-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
        }
        
        .section-title {
          font-size: 18px;
          font-weight: 500;
          color: var(--text-white);
        }
        
        .section-description {
          font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          font-style: normal;
          font-weight: 400;
          font-size: 14px;
          line-height: 140%;
          letter-spacing: -0.03em;
          color: var(--text-gray);
        }

        .analytics-section {
          padding: 16px;
        }

        .stat-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 12px;
          margin-top: 16px;
        }

        .stat-card {
          background: var(--bg-card);
          border: 1px solid var(--border-color);
          border-radius: 8px;
          padding: 16px;
          text-align: center;
        }

        .stat-label {
          font-size: 12px;
          color: var(--text-gray);
          margin-bottom: 8px;
          font-weight: 500;
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }

        .stat-value {
          font-size: 24px;
          color: var(--purple);
          font-weight: 700;
        }

        .switch {
          position: relative;
          display: inline-block;
          width: 44px;
          height: 22px;
        }
        
        .switch input {
          opacity: 0;
          width: 0;
          height: 0;
        }
        
        .slider {
          position: absolute;
          cursor: pointer;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: var(--bg-card);
          transition: .4s;
          border-radius: 34px;
        }
        
        .slider:before {
          position: absolute;
          content: "";
          height: 18px;
          width: 18px;
          left: 3px;
          bottom: 2px;
          background-color: white;
          transition: .4s;
          border-radius: 50%;
        }
        
        input:checked + .slider {
          background-color: var(--purple);
        }
        
        input:focus + .slider {
          box-shadow: 0 0 1px var(--purple);
        }
        
        input:checked + .slider:before {
          transform: translateX(20px);
        }

        /* Playbooks Styles */
        .playbooks-list {
          display: flex;
          flex-direction: column;
          gap: 12px;
        }

        .playbook-card {
          background-color: var(--bg-card);
          border-radius: 8px;
          padding: 16px;
          display: flex;
          flex-direction: column;
          gap: 12px;
          transition: all 0.2s ease;
        }

        .playbook-card:hover {
          background-color: rgba(108, 99, 255, 0.05);
        }

        .playbook-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          gap: 12px;
        }

        .playbook-info {
          flex: 1;
        }

        .playbook-name {
          font-size: 16px;
          font-weight: 500;
          color: var(--text-white);
          margin: 0 0 4px 0;
        }

        .playbook-description {
          font-size: 13px;
          color: var(--text-gray);
          margin: 0;
          line-height: 1.4;
        }

        .playbook-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 12px;
          color: var(--text-gray);
        }

        .playbook-url-pattern {
          font-family: 'Courier New', monospace;
          background-color: rgba(108, 99, 255, 0.1);
          padding: 2px 8px;
          border-radius: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          max-width: 300px;
        }

        .playbook-run-count {
          color: var(--purple);
        }

        .action-button {
          display: flex;
          align-items: center;
          gap: 6px;
          padding: 8px 16px;
          background-color: var(--purple);
          color: white;
          border: none;
          border-radius: 6px;
          font-size: 14px;
          font-weight: 500;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .action-button:hover {
          background-color: #5b54cc;
          transform: translateY(-1px);
        }

        .action-button:disabled {
          background-color: var(--bg-card);
          cursor: not-allowed;
          transform: none;
        }

        .action-button svg {
          width: 16px;
          height: 16px;
        }

        .loading-state {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          gap: 12px;
          padding: 40px 20px;
          color: var(--text-gray);
        }

        .empty-state {
          padding: 40px 20px;
          text-align: center;
          color: var(--text-gray);
        }

        .error-message {
          color: #ef4444;
          padding: 20px;
          text-align: center;
        }

        .memory-cards {
          display: flex;
          flex-direction: column;
          gap: 12px;
        }
        
        .memory-card {
          background-color: var(--bg-card);
          border-radius: 8px;
          padding: 12px;
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
        }
        
        .memory-content {
          flex: 1;
          padding-right: 8px;
        }
        
        .memory-text {
          color: var(--text-gray);
          font-size: 14px;
          margin: 0 0 8px 0;
        }
        
        .memory-categories {
          display: flex;
          flex-wrap: wrap;
          gap: 4px;
          margin-top: 4px;
        }
        
        .memory-category {
          background-color: var(--tag-bg);
          color: var(--text-white);
          font-size: 12px;
          padding: 2px 8px;
          border-radius: 4px;
        }
        
        .memory-actions {
          display: flex;
          gap: 4px;
          flex-shrink: 0;
        }
        
        .memory-action-button {
          background: none;
          border: none;
          color: var(--text-gray);
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: color 0.2s;
          width: 24px;
          height: 24px;
          border-radius: 4px;
        }
        
        .memory-action-button:hover {
          color: var(--text-white);
          background-color: var(--bg-button);
        }

        .memory-action-button.copied {
          color: var(--success-color);
        }

        .memory-action-button.edit-button:hover {
          color: #3b82f6;
          background-color: rgba(59, 130, 246, 0.1);
        }

        .memory-action-button.delete-button:hover {
          color: #ef4444;
          background-color: rgba(239, 68, 68, 0.1);
        }

        /* Modal Styles */
        .mem0-modal {
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.7);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 10000;
        }

        .mem0-modal-content {
          background: var(--bg-dark);
          border-radius: 12px;
          width: 90%;
          max-width: 500px;
          box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
        }

        .mem0-modal-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20px;
          border-bottom: 1px solid var(--border-color);
        }

        .mem0-modal-header h3 {
          margin: 0;
          color: var(--text-white);
          font-size: 18px;
        }

        .mem0-modal-close {
          background: none;
          border: none;
          color: var(--text-gray);
          font-size: 28px;
          cursor: pointer;
          padding: 0;
          width: 32px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 4px;
        }

        .mem0-modal-close:hover {
          color: var(--text-white);
          background-color: var(--bg-button);
        }

        .mem0-modal-body {
          padding: 20px;
        }

        .mem0-modal-body label {
          display: block;
          color: var(--text-white);
          margin-bottom: 8px;
          font-size: 14px;
          font-weight: 500;
        }

        .mem0-modal-body textarea,
        .mem0-modal-body input {
          width: 100%;
          padding: 10px;
          background: var(--bg-card);
          border: 1px solid var(--border-color);
          border-radius: 6px;
          color: var(--text-white);
          font-size: 14px;
          font-family: inherit;
          margin-bottom: 16px;
          box-sizing: border-box;
        }

        .mem0-modal-body textarea:focus,
        .mem0-modal-body input:focus {
          outline: none;
          border-color: var(--purple);
        }

        .mem0-modal-body textarea {
          resize: vertical;
          min-height: 100px;
        }

        .mem0-modal-footer {
          padding: 20px;
          border-top: 1px solid var(--border-color);
          display: flex;
          justify-content: flex-end;
          gap: 10px;
        }

        .mem0-modal-button {
          padding: 10px 20px;
          border-radius: 6px;
          border: none;
          cursor: pointer;
          font-size: 14px;
          font-weight: 500;
          transition: all 0.2s;
        }

        .mem0-modal-button.cancel {
          background: var(--bg-button);
          color: var(--text-white);
        }

        .mem0-modal-button.cancel:hover {
          background: var(--bg-card);
        }

        .mem0-modal-button.save {
          background: var(--purple);
          color: white;
        }

        .mem0-modal-button.save:hover {
          background: var(--purple-hover);
        }

        .mem0-modal-button:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .memory-loader {
          display: flex;
          justify-content: center;
          align-items: center;
          padding: 20px 0;
        }
        
        .no-memories, .memory-error {
          color: var(--text-gray);
          text-align: center;
          font-style: italic;
          padding: 20px 0;
        }
        
        .footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16px;
          border-top: 1px solid var(--border-color);
        }
        
        .shortcut {
          padding: 6px 12px;
          background-color: var(--bg-card);
          color: var(--text-gray);
          border-radius: 8px;
          font-size: 14px;
        }
        
        .logout-button {
          display: flex;
          flex-direction: row;
          align-items: center;
          padding: 6px 16px;
          background: var(--bg-button);
          border-radius: 8px;
          border: none;
          cursor: pointer;
          transition: all 0.2s ease;
          color: var(--text-white);
          font-size: 14px;
        }
        
        .logout-button:hover {
          background: var(--bg-button-hover);
        }
        
        .loader {
          border: 2px solid var(--bg-button);
          border-top: 2px solid var(--purple);
          border-radius: 50%;
          width: 20px;
          height: 20px;
          animation: spin 1s linear infinite;
          margin: 0 auto;
        }
        
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
        
        .input-container {
          width: 100%;
          padding: 12px 16px;
          box-sizing: border-box;
          display: flex;
          gap: 8px;
          align-items: center;
        }

        .search-input {
          flex: 1;
          padding: 10px 16px;
          background: var(--bg-card);
          border: 1px solid var(--border-color);
          border-radius: 8px;
          color: var(--text-white);
          font-size: 14px;
          outline: none;
          transition: border-color 0.2s;
        }

        .search-input:focus {
          border-color: var(--purple);
        }

        .search-input::placeholder {
          color: var(--text-gray);
        }

        .add-memory-button {
          padding: 10px;
          background: var(--purple);
          border: none;
          border-radius: 8px;
          color: white;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: background 0.2s;
        }

        .add-memory-button:hover {
          background: var(--purple-hover);
        }

        .add-memory-button svg {
          display: block;
        }

        .project-switcher {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 12px 16px;
          background: var(--bg-card);
          border-radius: 8px;
          margin-bottom: 8px;
        }

        .project-label {
          font-size: 14px;
          font-weight: 600;
          color: var(--text-white);
          min-width: 60px;
        }

        .project-dropdown {
          flex: 1;
          padding: 8px 12px;
          background: var(--bg-dark);
          border: 1px solid var(--border-color);
          border-radius: 6px;
          color: var(--text-white);
          font-size: 14px;
          cursor: pointer;
          outline: none;
          transition: border-color 0.2s;
        }

        .project-dropdown:hover {
          border-color: var(--purple);
        }

        .project-dropdown:focus {
          border-color: var(--purple);
          box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .project-dropdown option {
          background: var(--bg-card);
          color: var(--text-white);
          padding: 8px;
        }

        .filter-row {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 12px 16px;
          background: var(--bg-card);
          border-radius: 8px;
          margin-bottom: 8px;
        }

        .category-filter {
          flex: 1;
          display: flex;
          align-items: center;
          gap: 12px;
        }

        .category-label {
          font-size: 14px;
          font-weight: 600;
          color: var(--text-white);
          min-width: 70px;
        }

        .category-dropdown {
          flex: 1;
          padding: 8px 12px;
          background: var(--bg-dark);
          border: 1px solid var(--border-color);
          border-radius: 6px;
          color: var(--text-white);
          font-size: 14px;
          cursor: pointer;
          outline: none;
          transition: border-color 0.2s;
        }

        .category-dropdown:hover {
          border-color: var(--purple);
        }

        .category-dropdown:focus {
          border-color: var(--purple);
          box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .action-buttons {
          display: flex;
          gap: 8px;
          align-items: center;
        }

        .action-button {
          padding: 8px;
          background: var(--purple);
          border: none;
          border-radius: 6px;
          color: white;
          cursor: pointer;
          font-size: 14px;
          font-weight: 500;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          transition: background 0.2s;
          white-space: nowrap;
        }

        .action-button:hover {
          background: var(--purple-hover);
        }

        .action-button svg {
          display: block;
        }

        .export-button {
          padding: 8px 16px;
        }

        .refresh-button {
          width: 40px;
          height: 40px;
        }

        .refresh-button.spinning svg {
          animation: spin 1s linear infinite;
        }

        @keyframes spin {
          from { transform: rotate(0deg); }
          to { transform: rotate(360deg); }
        }

        .search-memory {
          width: 100%;
          box-sizing: border-box;
          margin-top: 16px;
        }
        
        .settings-input, .settings-select {
          width: 100%;
          padding: 12px 16px;
          background: var(--bg-card);
          border: 1px solid var(--border-color);
          border-radius: 8px;
          color: var(--text-white);
          font-size: 14px;
          font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          transition: border-color 0.2s ease, background-color 0.2s ease;
          box-sizing: border-box;
        }
        
        .settings-input:focus, .settings-select:focus {
          outline: none;
          border-color: var(--purple);
          background: var(--bg-button);
        }
        
        .settings-input::placeholder {
          color: var(--text-gray);
        }
        
        .settings-select option {
          background: var(--bg-card);
          color: var(--text-white);
        }
        
        .settings-select:hover {
          border-color: var(--text-gray);
        }
        
        .link-button {
          background: none;
          border: none;
          color: var(--text-gray);
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 24px;
          height: 24px;
          border-radius: 4px;
          transition: all 0.2s ease;
        }
        
        .link-button:hover {
          color: var(--text-white);
          background: var(--bg-button);
        }
        
        .save-button {
          width: 100%;
          padding: 12px 24px;
          background: var(--purple);
          border: none;
          border-radius: 8px;
          color: var(--text-white);
          font-size: 14px;
          font-weight: 500;
          cursor: pointer;
          transition: background-color 0.2s ease;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        .save-button:hover:not(:disabled) {
          background: #6d4ed6;
        }
        
        .save-button:disabled {
          background: var(--bg-button);
          cursor: not-allowed;
        }
        
        .save-loader {
          display: none;
          align-items: center;
          justify-content: center;
        }
        
        .mini-loader {
          border: 2px solid var(--bg-button);
          border-top: 2px solid var(--text-white);
          border-radius: 50%;
          width: 16px;
          height: 16px;
          animation: spin 1s linear infinite;
        }
        
        .save-message {
          margin-top: 8px;
          padding: 8px 12px;
          border-radius: 6px;
          font-size: 13px;
          text-align: center;
        }
        
        .save-message.success {
          background: rgba(34, 197, 94, 0.1);
          color: var(--success-color);
          border: 1px solid rgba(34, 197, 94, 0.3);
        }
        
        .save-message.error {
          background: rgba(239, 68, 68, 0.1);
          color: #f87171;
          border: 1px solid rgba(239, 68, 68, 0.3);
        }
        
        .threshold-value {
          color: var(--purple);
          font-weight: 600;
          font-size: 14px;
        }
        
        .slider-container {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }
        
        .threshold-slider {
          width: 100%;
          height: 6px;
          background: var(--bg-card);
          border-radius: 3px;
          outline: none;
          appearance: none;
          -webkit-appearance: none;
          cursor: pointer;
        }
        
        .threshold-slider::-webkit-slider-thumb {
          appearance: none;
          width: 20px;
          height: 20px;
          border-radius: 50%;
          background: var(--purple);
          cursor: pointer;
          border: 2px solid var(--bg-dark);
          box-shadow: 0 0 0 1px var(--purple);
        }
        
        .threshold-slider::-moz-range-thumb {
          width: 20px;
          height: 20px;
          border-radius: 50%;
          background: var(--purple);
          cursor: pointer;
          border: 2px solid var(--bg-dark);
          box-shadow: 0 0 0 1px var(--purple);
        }
        
        .threshold-slider::-webkit-slider-track {
          width: 100%;
          height: 6px;
          background: var(--bg-card);
          border-radius: 3px;
        }
        
        .threshold-slider::-moz-range-track {
          width: 100%;
          height: 6px;
          background: var(--bg-card);
          border-radius: 3px;
          border: none;
        }
        
        .threshold-slider:focus {
          outline: none;
        }
        
        .threshold-slider:focus::-webkit-slider-thumb {
          box-shadow: 0 0 0 2px var(--purple);
        }
        
        .threshold-slider:focus::-moz-range-thumb {
          box-shadow: 0 0 0 2px var(--purple);
        }
        
        .slider-labels {
          display: flex;
          justify-content: space-between;
          font-size: 12px;
          color: var(--text-gray);
          margin-top: 4px;
        }
        
        .settings-input[type="number"] {
          -moz-appearance: textfield;
        }
        
        .settings-input[type="number"]::-webkit-outer-spin-button,
        .settings-input[type="number"]::-webkit-inner-spin-button {
          -webkit-appearance: none;
          margin: 0;
        }

        /* ========================================
           OPTIMIZER TAB STYLES
           ======================================== */

        .optimizer-container {
          display: flex;
          flex-direction: column;
          gap: 20px;
        }

        .optimizer-header {
          margin-bottom: 8px;
        }

        .optimizer-subtitle {
          font-size: 14px;
          color: var(--text-gray);
          margin: 0;
        }

        .optimizer-section {
          background: var(--bg-card);
          border-radius: 8px;
          padding: 16px;
          border: 1px solid #334155;
        }

        .optimizer-label {
          display: block;
          font-size: 14px;
          font-weight: 600;
          color: var(--text-white);
          margin-bottom: 8px;
          text-transform: uppercase;
          letter-spacing: 0.05em;
        }

        .optimizer-small-label {
          display: block;
          font-size: 12px;
          font-weight: 500;
          color: var(--text-gray);
          margin-bottom: 6px;
        }

        .optimizer-count {
          float: right;
          font-size: 13px;
          color: #10b981;
          font-weight: 600;
          text-transform: none;
          letter-spacing: normal;
        }

        .optimizer-textarea {
          width: 100%;
          min-height: 80px;
          padding: 12px;
          background: var(--bg-dark);
          border: 1px solid #334155;
          border-radius: 6px;
          color: var(--text-white);
          font-family: inherit;
          font-size: 14px;
          line-height: 1.5;
          resize: vertical;
          transition: border-color 0.2s ease, box-shadow 0.2s ease;
        }

        .optimizer-textarea:focus {
          outline: none;
          border-color: #38bdf8;
          box-shadow: 0 0 0 2px rgba(56, 189, 248, 0.2);
        }

        .optimizer-textarea::placeholder {
          color: #64748b;
        }

        .optimizer-search-row {
          display: flex;
          gap: 8px;
          margin-bottom: 12px;
        }

        .optimizer-search-input {
          flex: 1;
          padding: 10px 12px;
          background: var(--bg-dark);
          border: 1px solid #334155;
          border-radius: 6px;
          color: var(--text-white);
          font-family: inherit;
          font-size: 14px;
          transition: border-color 0.2s ease, box-shadow 0.2s ease;
        }

        .optimizer-search-input:focus {
          outline: none;
          border-color: #38bdf8;
          box-shadow: 0 0 0 2px rgba(56, 189, 248, 0.2);
        }

        .optimizer-search-input::placeholder {
          color: #64748b;
        }

        .optimizer-input {
          width: 100%;
          padding: 10px 12px;
          background: var(--bg-dark);
          border: 1px solid #334155;
          border-radius: 6px;
          color: var(--text-white);
          font-family: inherit;
          font-size: 14px;
          transition: border-color 0.2s ease, box-shadow 0.2s ease;
        }

        .optimizer-input:focus {
          outline: none;
          border-color: #38bdf8;
          box-shadow: 0 0 0 2px rgba(56, 189, 248, 0.2);
        }

        .optimizer-select {
          width: 100%;
          padding: 10px 12px;
          background: var(--bg-dark);
          border: 1px solid #334155;
          border-radius: 6px;
          color: var(--text-white);
          font-family: inherit;
          font-size: 14px;
          cursor: pointer;
          transition: border-color 0.2s ease, box-shadow 0.2s ease;
        }

        .optimizer-select:focus {
          outline: none;
          border-color: #38bdf8;
          box-shadow: 0 0 0 2px rgba(56, 189, 248, 0.2);
        }

        .optimizer-settings-grid {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 12px;
        }

        .optimizer-btn {
          width: 100%;
          padding: 12px 20px;
          border: none;
          border-radius: 6px;
          font-weight: 600;
          font-size: 14px;
          cursor: pointer;
          transition: all 0.2s ease;
          font-family: inherit;
        }

        .optimizer-btn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .optimizer-btn-primary {
          background: linear-gradient(135deg, #38bdf8 0%, #0ea5e9 100%);
          color: var(--bg-dark);
        }

        .optimizer-btn-primary:hover:not(:disabled) {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(56, 189, 248, 0.4);
        }

        .optimizer-btn-secondary {
          background: var(--bg-button);
          color: var(--text-white);
          border: 1px solid #475569;
        }

        .optimizer-btn-secondary:hover:not(:disabled) {
          background: var(--bg-button-hover);
        }

        .optimizer-btn-success {
          background: #10b981;
          color: white;
        }

        .optimizer-btn-success:hover:not(:disabled) {
          background: #059669;
        }

        .optimizer-results {
          max-height: 300px;
          overflow-y: auto;
          margin-top: 8px;

          /* Firefox */
          scrollbar-width: thin;
          scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-bg);
        }

        .optimizer-results::-webkit-scrollbar {
          width: 4px;
        }

        .optimizer-results::-webkit-scrollbar-track {
          background: var(--scrollbar-bg);
        }

        .optimizer-results::-webkit-scrollbar-thumb {
          background-color: var(--scrollbar-thumb);
          border-radius: 4px;
        }

        .optimizer-result-item {
          display: flex;
          gap: 12px;
          align-items: flex-start;
          padding: 12px;
          margin-bottom: 8px;
          background: var(--bg-dark);
          border: 1px solid #334155;
          border-radius: 6px;
          transition: background 0.2s ease, border-color 0.2s ease;
        }

        .optimizer-result-item:hover {
          background: var(--bg-card);
          border-color: #475569;
        }

        .optimizer-result-item input[type="checkbox"] {
          margin-top: 4px;
          width: 18px;
          height: 18px;
          cursor: pointer;
          accent-color: #38bdf8;
        }

        .optimizer-result-content {
          flex: 1;
          font-size: 13px;
          line-height: 1.5;
          color: var(--text-gray);
        }

        .optimizer-output {
          padding: 16px;
          background: var(--bg-dark);
          border: 1px solid #334155;
          border-radius: 6px;
          font-family: 'Courier New', monospace;
          font-size: 13px;
          line-height: 1.6;
          white-space: pre-wrap;
          word-wrap: break-word;
          max-height: 400px;
          overflow-y: auto;
          color: var(--text-white);
          margin-bottom: 12px;

          /* Firefox */
          scrollbar-width: thin;
          scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-bg);
        }

        .optimizer-output::-webkit-scrollbar {
          width: 4px;
        }

        .optimizer-output::-webkit-scrollbar-track {
          background: var(--scrollbar-bg);
        }

        .optimizer-output::-webkit-scrollbar-thumb {
          background-color: var(--scrollbar-thumb);
          border-radius: 4px;
        }

        .optimizer-button-row {
          display: flex;
          gap: 10px;
        }

        .optimizer-button-row button {
          flex: 1;
        }

        .optimizer-status {
          min-height: 24px;
          padding: 8px 12px;
          font-size: 13px;
          text-align: center;
          color: #facc15;
          background: var(--bg-card);
          border-radius: 6px;
          border: 1px solid #334155;
          margin-top: 12px;
          display: none;
        }

        .optimizer-hidden {
          display: none;
        }

        /* ========================================
           FLOATING OPTIMIZER PANEL
           ======================================== */

        .mem0-optimizer-panel {
          position: fixed;
          top: 0;
          right: 420px; /* Sidebar width (400px) + 20px gap */
          width: 520px;
          height: 100vh;
          background: rgba(15, 23, 42, 0.98);
          backdrop-filter: blur(10px);
          border-left: 1px solid #334155;
          box-shadow: -4px 0 24px rgba(0, 0, 0, 0.4);
          z-index: 999998; /* Below sidebar (999999) but above page */
          animation: slideInFromRight 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          overflow: hidden;
        }

        .mem0-optimizer-panel.optimizer-panel-closing {
          animation: slideOutToRight 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        @keyframes slideInFromRight {
          from {
            transform: translateX(100%);
            opacity: 0;
          }
          to {
            transform: translateX(0);
            opacity: 1;
          }
        }

        @keyframes slideOutToRight {
          from {
            transform: translateX(0);
            opacity: 1;
          }
          to {
            transform: translateX(100%);
            opacity: 0;
          }
        }

        .optimizer-panel-content {
          display: flex;
          flex-direction: column;
          height: 100%;
          overflow: hidden;
        }

        .optimizer-panel-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20px 24px;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border-bottom: 1px solid #334155;
          flex-shrink: 0;
        }

        .optimizer-panel-title {
          margin: 0;
          font-size: 20px;
          font-weight: 600;
          color: white;
          letter-spacing: -0.02em;
        }

        .optimizer-panel-close {
          background: none;
          border: none;
          color: white;
          font-size: 32px;
          line-height: 1;
          cursor: pointer;
          width: 36px;
          height: 36px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 6px;
          transition: background 0.2s ease;
          padding: 0;
        }

        .optimizer-panel-close:hover {
          background: rgba(255, 255, 255, 0.15);
        }

        .optimizer-panel-body {
          flex: 1;
          overflow-y: auto;
          padding: 24px;
          scrollbar-width: thin;
          scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-bg);
        }

        .optimizer-panel-body::-webkit-scrollbar {
          width: 6px;
        }

        .optimizer-panel-body::-webkit-scrollbar-track {
          background: var(--scrollbar-bg);
        }

        .optimizer-panel-body::-webkit-scrollbar-thumb {
          background-color: var(--scrollbar-thumb);
          border-radius: 3px;
        }

        .optimizer-subtitle {
          font-size: 14px;
          color: var(--text-gray);
          margin-bottom: 24px;
        }

        /* Intent Analysis Section */
        .optimizer-intent-section {
          margin-bottom: 16px;
          background: rgba(102, 126, 234, 0.1);
          border: 1px solid rgba(102, 126, 234, 0.3);
          border-radius: 6px;
          overflow: hidden;
        }

        .optimizer-intent-toggle {
          width: 100%;
          background: none;
          border: none;
          color: var(--text-white);
          font-size: 14px;
          font-weight: 600;
          padding: 12px 16px;
          text-align: left;
          cursor: pointer;
          transition: background 0.2s ease;
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .optimizer-intent-toggle:hover {
          background: rgba(102, 126, 234, 0.15);
        }

        .optimizer-intent-content {
          padding: 0 16px 16px 16px;
        }

        .optimizer-intent-item {
          margin-bottom: 12px;
          font-size: 13px;
          line-height: 1.6;
          color: var(--text-gray);
        }

        .optimizer-intent-item strong {
          color: var(--text-white);
          display: block;
          margin-bottom: 4px;
        }

        .optimizer-intent-item ul {
          margin: 8px 0 0 20px;
          padding: 0;
        }

        .optimizer-intent-item li {
          margin-bottom: 4px;
        }

        /* Graph Tab Styles */
        .graph-stats {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 12px;
          margin-top: 16px;
        }

        .stat-card-mini {
          background: var(--bg-button);
          border-radius: 8px;
          padding: 12px;
          text-align: center;
        }

        .stat-card-mini .stat-label {
          font-size: 11px;
          color: var(--text-gray);
          text-transform: uppercase;
          letter-spacing: 0.5px;
          margin-bottom: 6px;
        }

        .stat-card-mini .stat-value {
          font-size: 20px;
          font-weight: 700;
          color: var(--text-white);
        }

        .entity-search-section {
          margin-bottom: 16px;
        }

        .search-container {
          display: flex;
          gap: 8px;
          margin-bottom: 12px;
        }

        .extract-btn {
          background: linear-gradient(135deg, #10b981 0%, #059669 100%);
          color: white;
          white-space: nowrap;
        }

        .extract-btn:hover {
          background: linear-gradient(135deg, #059669 0%, #047857 100%);
        }

        .entity-type-filters {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
        }

        .filter-checkbox {
          display: flex;
          align-items: center;
          cursor: pointer;
          user-select: none;
        }

        .filter-checkbox input[type="checkbox"] {
          margin-right: 6px;
        }

        .filter-label {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: 12px;
          color: var(--text-gray);
        }

        .entity-icon {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 20px;
          height: 20px;
          border-radius: 4px;
          font-size: 12px;
        }

        .entities-list {
          max-height: 400px;
          overflow-y: auto;
        }

        .entity-item {
          background: var(--bg-button);
          border-radius: 8px;
          padding: 12px;
          margin-bottom: 8px;
          cursor: pointer;
          transition: all 0.2s ease;
          display: flex;
          align-items: center;
          gap: 12px;
        }

        .entity-item:hover {
          background: var(--bg-button-hover);
          transform: translateY(-1px);
        }

        .entity-item-icon {
          width: 32px;
          height: 32px;
          border-radius: 6px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
          flex-shrink: 0;
        }

        .entity-item-content {
          flex: 1;
          min-width: 0;
        }

        .entity-item-name {
          font-weight: 600;
          color: var(--text-white);
          font-size: 14px;
          margin-bottom: 2px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .entity-item-type {
          font-size: 11px;
          color: var(--text-gray);
          text-transform: capitalize;
        }

        .entity-item-badge {
          background: rgba(102, 126, 234, 0.2);
          color: #667eea;
          padding: 4px 8px;
          border-radius: 12px;
          font-size: 11px;
          font-weight: 600;
          flex-shrink: 0;
        }

        .packs-list {
          max-height: 200px;
          overflow-y: auto;
        }

        .pack-item {
          background: var(--bg-button);
          border-radius: 8px;
          padding: 12px;
          margin-bottom: 8px;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .pack-info {
          flex: 1;
          min-width: 0;
        }

        .pack-name {
          font-weight: 600;
          color: var(--text-white);
          font-size: 13px;
          margin-bottom: 4px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .pack-meta {
          font-size: 11px;
          color: var(--text-gray);
        }

        .pack-actions {
          display: flex;
          gap: 6px;
        }

        .pack-use-btn, .pack-delete-btn {
          background: var(--bg-button-hover);
          border: none;
          color: var(--text-white);
          padding: 6px 12px;
          border-radius: 6px;
          font-size: 12px;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .pack-use-btn:hover {
          background: #667eea;
        }

        .pack-delete-btn:hover {
          background: #ef4444;
        }

        .action-button-small {
          background: var(--bg-button);
          border: none;
          color: var(--text-white);
          padding: 6px 12px;
          border-radius: 6px;
          font-size: 12px;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .action-button-small:hover:not(:disabled) {
          background: var(--bg-button-hover);
        }

        .action-button-small:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .primary-button {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border: none;
          color: white;
          padding: 10px 20px;
          border-radius: 8px;
          font-size: 14px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .primary-button:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .empty-state, .empty-state-mini {
          text-align: center;
          padding: 32px 16px;
          color: var(--text-gray);
        }

        .empty-state svg {
          margin-bottom: 16px;
          opacity: 0.5;
        }

        .empty-state h3 {
          font-size: 16px;
          margin-bottom: 8px;
          color: var(--text-white);
        }

        .empty-state p {
          font-size: 13px;
          margin-bottom: 16px;
        }

        .empty-state-mini {
          padding: 16px;
          font-size: 13px;
        }

        .subsection-title {
          font-size: 14px;
          font-weight: 600;
          color: var(--text-white);
          margin-bottom: 12px;
        }

        .loading-state {
          text-align: center;
          padding: 32px;
          color: var(--text-gray);
        }

        .mini-loader {
          border: 2px solid rgba(102, 126, 234, 0.2);
          border-top-color: #667eea;
          border-radius: 50%;
          width: 24px;
          height: 24px;
          animation: spin 0.8s linear infinite;
          margin: 0 auto 12px;
        }

        @keyframes spin {
          to { transform: rotate(360deg); }
        }

        /* Graph Tab Additional Styles */
        .entity-item.selected {
          background: rgba(102, 126, 234, 0.2);
          border-left: 3px solid var(--purple);
        }

        /* Modal Styles */
        .modal {
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: rgba(0, 0, 0, 0.7);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 100000;
          backdrop-filter: blur(4px);
        }

        .modal-content {
          background: var(--bg-card);
          border-radius: 12px;
          width: 90%;
          max-width: 600px;
          max-height: 80vh;
          overflow-y: auto;
          box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
        }

        .modal-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20px 24px;
          border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .modal-header h2 {
          margin: 0;
          font-size: 20px;
          font-weight: 600;
          color: var(--text-white);
        }

        .modal-close {
          background: none;
          border: none;
          color: var(--text-gray);
          font-size: 28px;
          cursor: pointer;
          padding: 0;
          width: 32px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 6px;
          transition: all 0.2s ease;
        }

        .modal-close:hover {
          background: var(--bg-button);
          color: var(--text-white);
        }

        .modal-body {
          padding: 24px;
        }

        .entity-detail-section {
          margin-bottom: 20px;
        }

        .entity-detail-section h3 {
          font-size: 14px;
          font-weight: 600;
          color: var(--text-gray);
          margin: 0 0 8px 0;
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }

        .entity-detail-section p {
          margin: 0;
          color: var(--text-white);
          line-height: 1.6;
        }

        .memory-snippet {
          background: var(--bg-button);
          border-radius: 8px;
          padding: 12px;
          margin-bottom: 8px;
        }

        .memory-snippet-content {
          color: var(--text-white);
          font-size: 13px;
          line-height: 1.5;
          margin-bottom: 8px;
        }

        .memory-snippet-meta {
          font-size: 11px;
          color: var(--text-gray);
        }

        .relationship-item {
          background: var(--bg-button);
          border-radius: 6px;
          padding: 8px 12px;
          margin-bottom: 6px;
          color: var(--text-white);
          font-size: 13px;
        }

        .relationship-type {
          color: var(--text-gray);
          font-size: 12px;
        }

        .memory-select-list {
          max-height: 300px;
          overflow-y: auto;
          border: 1px solid rgba(255, 255, 255, 0.1);
          border-radius: 8px;
          margin-bottom: 16px;
        }

        .memory-select-item {
          display: flex;
          align-items: start;
          padding: 12px;
          border-bottom: 1px solid rgba(255, 255, 255, 0.05);
          cursor: pointer;
          transition: background 0.2s ease;
        }

        .memory-select-item:hover {
          background: var(--bg-button);
        }

        .memory-select-item:last-child {
          border-bottom: none;
        }

        .memory-select-item input[type="checkbox"] {
          margin-right: 12px;
          margin-top: 2px;
          cursor: pointer;
        }

        .memory-select-item span {
          flex: 1;
          color: var(--text-white);
          font-size: 13px;
          line-height: 1.5;
        }

        .provider-select {
          margin-bottom: 16px;
        }

        .provider-select label {
          display: block;
          font-size: 13px;
          color: var(--text-gray);
          margin-bottom: 6px;
        }

        .provider-select select {
          width: 100%;
          padding: 10px 12px;
          background: var(--bg-button);
          border: 1px solid rgba(255, 255, 255, 0.1);
          border-radius: 6px;
          color: var(--text-white);
          font-size: 14px;
          cursor: pointer;
        }

        .extraction-progress {
          margin-top: 16px;
          padding: 16px;
          background: var(--bg-button);
          border-radius: 8px;
          text-align: center;
        }

        .extraction-progress p {
          margin: 12px 0 0 0;
          color: var(--text-gray);
          font-size: 13px;
        }

        .form-group {
          margin-bottom: 16px;
        }

        .form-group label {
          display: block;
          font-size: 13px;
          color: var(--text-gray);
          margin-bottom: 6px;
          font-weight: 500;
        }

        .input-field {
          width: 100%;
          padding: 10px 12px;
          background: var(--bg-button);
          border: 1px solid rgba(255, 255, 255, 0.1);
          border-radius: 6px;
          color: var(--text-white);
          font-size: 14px;
          font-family: inherit;
          transition: border-color 0.2s ease;
        }

        .input-field:focus {
          outline: none;
          border-color: var(--purple);
        }

        .input-field::placeholder {
          color: var(--text-gray);
          opacity: 0.5;
        }

        textarea.input-field {
          resize: vertical;
          min-height: 80px;
        }

        .info-text {
          font-size: 12px;
          color: var(--text-gray);
          margin-bottom: 16px;
        }

        .primary-button {
          width: 100%;
          padding: 12px 24px;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
          border: none;
          border-radius: 8px;
          font-size: 14px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .primary-button:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .primary-button:disabled {
          opacity: 0.5;
          cursor: not-allowed;
          transform: none;
        }

        /* Pack Loaded Notification Styles */
        .pack-loaded-notification {
          position: fixed;
          top: 20px;
          right: 20px;
          max-width: 400px;
          background: linear-gradient(135deg, var(--purple) 0%, #667eea 100%);
          color: white;
          border-radius: 12px;
          box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
          z-index: 999999;
          transform: translateX(450px);
          opacity: 0;
          transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
        }

        .pack-loaded-notification.notification-visible {
          transform: translateX(0);
          opacity: 1;
        }

        .pack-loaded-notification.notification-hiding {
          transform: translateX(450px);
          opacity: 0;
        }

        .notification-content {
          display: flex;
          align-items: start;
          gap: 12px;
          padding: 16px;
          position: relative;
        }

        .notification-icon {
          flex-shrink: 0;
          width: 24px;
          height: 24px;
          color: white;
          margin-top: 2px;
        }

        .notification-icon svg {
          width: 24px;
          height: 24px;
          stroke-width: 2.5;
        }

        .notification-text {
          flex: 1;
        }

        .notification-title {
          font-size: 16px;
          font-weight: 700;
          margin-bottom: 6px;
          color: white;
        }

        .notification-details {
          font-size: 14px;
          line-height: 1.5;
          margin-bottom: 8px;
          color: rgba(255, 255, 255, 0.95);
        }

        .notification-stats {
          font-size: 13px;
          color: rgba(255, 255, 255, 0.85);
          font-weight: 500;
        }

        .notification-info {
          font-size: 12px;
          line-height: 1.4;
          color: rgba(255, 255, 255, 0.75);
          font-style: italic;
        }

        .notification-close {
          position: absolute;
          top: 8px;
          right: 8px;
          background: rgba(255, 255, 255, 0.2);
          border: none;
          color: white;
          width: 24px;
          height: 24px;
          border-radius: 50%;
          font-size: 18px;
          line-height: 1;
          cursor: pointer;
          transition: all 0.2s ease;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .notification-close:hover {
          background: rgba(255, 255, 255, 0.3);
          transform: scale(1.1);
        }

        /* Spinning animation for loading button */
        @keyframes spin {
          from { transform: rotate(0deg); }
          to { transform: rotate(360deg); }
        }

        .spinning {
          animation: spin 1s linear infinite;
        }

        /* Coming Soon Section Styles */
        .coming-soon-section {
          padding: 32px 16px;
        }

        .coming-soon-container {
          text-align: center;
          max-width: 100%;
          margin: 0 auto;
        }

        .coming-soon-icon {
          color: var(--purple);
          margin-bottom: 24px;
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .coming-soon-icon svg {
          filter: drop-shadow(0 4px 8px rgba(102, 126, 234, 0.3));
        }

        .coming-soon-title {
          font-size: 24px;
          font-weight: 700;
          color: var(--text-white);
          margin-bottom: 16px;
          letter-spacing: -0.02em;
        }

        .coming-soon-description {
          font-size: 15px;
          line-height: 1.6;
          color: var(--text-gray);
          margin-bottom: 32px;
          max-width: 90%;
          margin-left: auto;
          margin-right: auto;
        }

        .coming-soon-features {
          display: flex;
          flex-direction: column;
          gap: 16px;
          margin-bottom: 32px;
          text-align: left;
        }

        .feature-item {
          display: flex;
          align-items: flex-start;
          gap: 12px;
          padding: 12px;
          background: rgba(102, 126, 234, 0.05);
          border-radius: 8px;
          border-left: 3px solid var(--purple);
          transition: all 0.2s ease;
        }

        .feature-item:hover {
          background: rgba(102, 126, 234, 0.1);
          transform: translateX(4px);
        }

        .feature-item svg {
          flex-shrink: 0;
          margin-top: 2px;
        }

        .feature-item span {
          font-size: 14px;
          line-height: 1.5;
          color: var(--text-white);
        }

        .coming-soon-eta {
          font-size: 13px;
          color: var(--text-gray);
          font-style: italic;
          padding: 16px;
          background: rgba(148, 163, 184, 0.1);
          border-radius: 8px;
          border: 1px dashed var(--border-color);
        }
    `,document.head.appendChild(t)}function Ye(){chrome.storage.sync.remove([m.API_KEY,m.USER_ID,m.SELECTED_PROJECT,m.SELECTED_PROJECT_NAME,m.DEFAULT_CATEGORY,m.MEMORY_ENABLED,m.KNOWN_PROJECTS],()=>{const t=document.getElementById("mem0-sidebar");t&&(t.style.right="-500px")})}async function Ve(){try{const t=await je();chrome.runtime.sendMessage({action:ie.OPEN_DASHBOARD,url:t})}catch(t){console.warn("Unable to open Memory Platform dashboard",t)}}function Ie(t){const i=document.querySelector(".memory-cards");if(i){if(i.innerHTML="",!t||t.length===0){i.innerHTML='<p class="no-memories">No memories found</p>';return}t.forEach(a=>{const s=a.memory||"",n=s.length>120?s.substring(0,120)+"...":s,c=a.categories||[],u=c.length>0?`<div class="memory-categories">${c.map(b=>`<span class="memory-category">${b}</span>`).join("")}</div>`:"",p=document.createElement("div");p.className="memory-card",p.setAttribute("data-memory-id",a.id||""),p.innerHTML=`
        <div class="memory-content">
          <p class="memory-text">${n}</p>
          ${u}
        </div>
        <div class="memory-actions">
          <button class="memory-action-button copy-button" title="Copy Memory" data-content="${encodeURIComponent(s)}">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-copy"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>
          </button>
          <button class="memory-action-button view-button" title="View Memory" data-id="${a.id||""}">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-eye"><path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"/><circle cx="12" cy="12" r="3"/></svg>
          </button>
          <button class="memory-action-button edit-button" title="Edit Memory" data-id="${a.id||""}" data-content="${encodeURIComponent(s)}" data-categories="${encodeURIComponent(JSON.stringify(c))}">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-edit">
              <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
              <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
            </svg>
          </button>
          <button class="memory-action-button delete-button" title="Delete Memory" data-id="${a.id||""}">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-trash-2">
              <path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/>
              <line x1="10" x2="10" y1="11" y2="17"/>
              <line x1="14" x2="14" y1="11" y2="17"/>
            </svg>
          </button>
        </div>
      `,i.appendChild(p)}),document.querySelectorAll(".copy-button").forEach(a=>{a.addEventListener("click",function(s){s.stopPropagation();const n=decodeURIComponent(this.getAttribute("data-content")||"");navigator.clipboard.writeText(n).then(()=>{const c=this.getAttribute("title")||"";this.setAttribute("title","Copied!"),this.classList.add("copied"),setTimeout(()=>{this.setAttribute("title",c),this.classList.remove("copied")},2e3)}).catch(c=>{console.error("Failed to copy: ",c)})})}),document.querySelectorAll(".view-button").forEach(a=>{a.addEventListener("click",async function(s){s.stopPropagation();const n=this.getAttribute("data-id");if(n)try{const c=await je(`/dashboard?memory_id=${encodeURIComponent(n)}`);chrome.runtime.sendMessage({action:ie.OPEN_DASHBOARD,url:c})}catch(c){console.warn("Unable to open memory detail",c)}})}),document.querySelectorAll(".delete-button").forEach(a=>{a.addEventListener("click",async function(s){s.stopPropagation();const n=this.getAttribute("data-id");if(!n){console.log("[sidebar] Delete button clicked but no memory ID found");return}if(!confirm("Delete this memory? This action cannot be undone.")){console.log("[sidebar] Delete cancelled by user");return}console.log("[sidebar] Deleting memory:",n);try{const c=await F();if(!c){alert("Unable to get platform configuration. Please check your settings.");return}await Fe(n,c.projectId),console.log("[sidebar] Successfully deleted memory:",n),y("Loading..."),await j(),console.log("[sidebar] Memories reloaded after deletion")}catch(c){console.error("[sidebar] Error deleting memory:",c),alert("Failed to delete memory. Please try again.")}})}),document.querySelectorAll(".edit-button").forEach(a=>{a.addEventListener("click",async function(s){s.stopPropagation();const n=this.getAttribute("data-id"),c=this.getAttribute("data-content"),u=this.getAttribute("data-categories");if(!n||!c){console.log("[sidebar] Edit button clicked but missing data");return}const p=decodeURIComponent(c),b=u?JSON.parse(decodeURIComponent(u)):[];console.log("[sidebar] Opening edit modal for memory:",n),Je(n,p,b)})})}}function Je(t,i,a){const s=document.getElementById("mem0-edit-modal");s&&s.remove();const n=document.createElement("div");n.id="mem0-edit-modal",n.className="mem0-modal",n.innerHTML=`
      <div class="mem0-modal-content">
        <div class="mem0-modal-header">
          <h3>Edit Memory</h3>
          <button class="mem0-modal-close">&times;</button>
        </div>
        <div class="mem0-modal-body">
          <label for="edit-memory-text">Memory Text:</label>
          <textarea id="edit-memory-text" rows="6">${i}</textarea>
          <label for="edit-memory-category">Category (optional):</label>
          <input type="text" id="edit-memory-category" value="${a[0]||""}" placeholder="general, work, personal, etc.">
        </div>
        <div class="mem0-modal-footer">
          <button class="mem0-modal-button cancel">Cancel</button>
          <button class="mem0-modal-button save">Save Changes</button>
        </div>
      </div>
    `,document.body.appendChild(n);const c=n.querySelector(".mem0-modal-close"),u=n.querySelector(".cancel"),p=n.querySelector(".save"),b=n.querySelector("#edit-memory-text"),E=n.querySelector("#edit-memory-category"),w=()=>n.remove();c.addEventListener("click",w),u.addEventListener("click",w),n.addEventListener("click",k=>{k.target===n&&w()}),p.addEventListener("click",async()=>{const k=b.value.trim(),N=E.value.trim();if(!k){alert("Memory text cannot be empty");return}console.log("[sidebar] Saving edited memory:",t),p.disabled=!0,p.textContent="Saving...";try{const z=await F();if(!z){alert("Platform not configured");return}await Fe(t,z.projectId),console.log("[sidebar] Deleted old memory:",t),await Ue(k,{category:N||void 0,projectId:z.projectId,projectName:z.projectName}),console.log("[sidebar] Created new memory with updated content"),y("Loading..."),await j(),w(),console.log("[sidebar] Memory edited successfully")}catch(z){console.error("[sidebar] Error editing memory:",z),alert("Failed to edit memory. Please try again."),p.disabled=!1,p.textContent="Save Changes"}})}function Xe(){const t=document.getElementById("mem0-add-modal");t&&t.remove();const i=document.createElement("div");i.id="mem0-add-modal",i.className="mem0-modal",i.innerHTML=`
      <div class="mem0-modal-content">
        <div class="mem0-modal-header">
          <h3>Add New Memory</h3>
          <button class="mem0-modal-close">&times;</button>
        </div>
        <div class="mem0-modal-body">
          <label for="add-memory-text">Memory Text:</label>
          <textarea id="add-memory-text" rows="6" placeholder="Enter memory text..."></textarea>
          <label for="add-memory-category">Category (optional):</label>
          <input type="text" id="add-memory-category" placeholder="general, work, personal, etc.">
        </div>
        <div class="mem0-modal-footer">
          <button class="mem0-modal-button cancel">Cancel</button>
          <button class="mem0-modal-button save">Add Memory</button>
        </div>
      </div>
    `,document.body.appendChild(i);const a=i.querySelector(".mem0-modal-close"),s=i.querySelector(".cancel"),n=i.querySelector(".save"),c=i.querySelector("#add-memory-text"),u=i.querySelector("#add-memory-category"),p=()=>i.remove();a.addEventListener("click",p),s.addEventListener("click",p),i.addEventListener("click",b=>{b.target===i&&p()}),n.addEventListener("click",async()=>{const b=c.value.trim(),E=u.value.trim();if(!b){alert("Memory text cannot be empty");return}console.log("[sidebar] Adding new memory"),n.disabled=!0,n.textContent="Adding...";try{const w=await F();if(!w){alert("Platform not configured");return}await Ue(b,{category:E||void 0,projectId:w.projectId,projectName:w.projectName}),console.log("[sidebar] Created new memory"),y("Loading..."),await j(),p(),console.log("[sidebar] Memory added successfully")}catch(w){console.error("[sidebar] Error adding memory:",w),alert("Failed to add memory. Please try again."),n.disabled=!1,n.textContent="Add Memory"}})}function Qe(t){const i=document.getElementById("categoryFilter");if(!i){console.log("[sidebar] Category filter element not found");return}const a=new Set;t.forEach(c=>{c.categories&&Array.isArray(c.categories)&&c.categories.forEach(u=>a.add(u))});const s=Array.from(a).sort();console.log("[sidebar] Found categories:",s);const n=i.value;i.innerHTML='<option value="">All Categories</option>',s.forEach(c=>{const u=document.createElement("option");u.value=c,u.textContent=c,i.appendChild(u)}),n&&s.includes(n)&&(i.value=n),console.log("[sidebar] Populated category filter with",s.length,"categories")}function We(t){if(console.log("[sidebar] Filtering by category:",t),!t){Ie(_),y(_.length);return}const i=_.filter(a=>a.categories&&a.categories.includes(t));console.log("[sidebar] Filtered memories:",i.length,"of",_.length),Ie(i),y(i.length)}function Ze(){if(console.log("[sidebar] Exporting",_.length,"memories"),_.length===0){alert("No memories to export");return}try{const t=JSON.stringify(_,null,2),i=new Blob([t],{type:"application/json"}),a=URL.createObjectURL(i),s=document.createElement("a");s.href=a,s.download=`memories-export-${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(a),console.log("[sidebar] Memories exported successfully")}catch(t){console.error("[sidebar] Error exporting memories:",t),alert("Failed to export memories. Please try again.")}}function Ae(t="Error loading memories"){const i=document.querySelector(".memory-cards");i&&(i.innerHTML=`<p class="memory-error">${t}</p>`)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ne):ne()})();
