(function(){class r{playbooks=[];platformUrl="";apiKey="";isInitialized=!1;watchedSelectors=new Set;observer=null;constructor(){this.init()}async init(){try{const o=await chrome.storage.local.get(["platformUrl","apiKey"]);if(!o.platformUrl||!o.apiKey){console.log("[Playbooks] Not configured yet");return}this.platformUrl=o.platformUrl,this.apiKey=o.apiKey,await this.loadPlaybooks(),this.watchUrlChanges(),this.checkCurrentPage(),this.isInitialized=!0,console.log("[Playbooks] Initialized with",this.playbooks.length,"playbooks")}catch(o){console.error("[Playbooks] Init error:",o)}}async loadPlaybooks(){try{const o=await fetch(`${this.platformUrl}/wp-json/memory/v1/playbooks?include_public=true`,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!o.ok)throw new Error(`Failed to load playbooks: ${o.statusText}`);const e=await o.json();this.playbooks=e.playbooks||[],console.log("[Playbooks] Loaded",this.playbooks.length,"playbooks")}catch(o){console.error("[Playbooks] Load error:",o),this.playbooks=[]}}watchUrlChanges(){let o=location.href;new MutationObserver(()=>{const t=location.href;t!==o&&(o=t,console.log("[Playbooks] URL changed to:",t),this.checkCurrentPage())}).observe(document.body,{childList:!0,subtree:!0}),window.addEventListener("popstate",()=>{console.log("[Playbooks] Popstate event"),setTimeout(()=>this.checkCurrentPage(),100)})}async checkCurrentPage(){const o=location.href,e=this.playbooks.filter(t=>t.is_active&&this.matchesUrlPattern(o,t.url_pattern));if(e.length===0){console.log("[Playbooks] No matching playbooks for:",o);return}console.log("[Playbooks] Found",e.length,"matching playbook(s)");for(const t of e)t.dom_selector?this.watchForSelector(t):await this.executePlaybook(t)}matchesUrlPattern(o,e){if(!e)return!0;const t=e.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${t}$`,"i").test(o)}watchForSelector(o){const e=o.dom_selector;if(document.querySelector(e)){console.log("[Playbooks] Element found immediately:",e),this.executePlaybook(o);return}if(this.watchedSelectors.has(e))return;this.watchedSelectors.add(e),console.log("[Playbooks] Watching for selector:",e);const s=new MutationObserver(()=>{document.querySelector(e)&&(console.log("[Playbooks] Element appeared:",e),s.disconnect(),this.watchedSelectors.delete(e),this.executePlaybook(o))});s.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>{s.disconnect(),this.watchedSelectors.delete(e),console.log("[Playbooks] Timeout waiting for selector:",e)},1e4)}async executePlaybook(o){console.log("[Playbooks] Executing:",o.name);try{const e=await this.buildContext(o),t=await fetch(`${this.platformUrl}/wp-json/memory/v1/playbooks/run`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({playbook_id:o.id,context:e})});if(!t.ok)throw new Error(`Playbook execution failed: ${t.statusText}`);const s=await t.json();s.success?(console.log("[Playbooks] Success:",o.name,s),this.showNotification(`Playbook "${o.name}" completed successfully`,"success")):(console.error("[Playbooks] Execution errors:",s.errors),this.showNotification(`Playbook "${o.name}" failed: ${s.errors[0]?.error||"Unknown error"}`,"error"))}catch(e){console.error("[Playbooks] Execution error:",e),this.showNotification(`Playbook "${o.name}" error: ${e}`,"error")}}async buildContext(o){const e={url:location.href,scraped_data:{}};for(const t of o.steps)if(t.type==="scrape"&&t.selector){const s=this.scrapeElement(t.selector);s&&(e.scraped_data[t.selector]=s)}return e}scrapeElement(o){try{const e=document.querySelector(o);if(!e)return console.warn("[Playbooks] Element not found:",o),null;let t="";return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?t=e.value:e instanceof HTMLSelectElement?t=e.options[e.selectedIndex]?.text||"":t=e.textContent||"",t.trim()}catch(e){return console.error("[Playbooks] Scrape error:",e),null}}showNotification(o,e){const t=document.createElement("div");t.style.cssText=`
      position: fixed;
      top: 20px;
      right: 20px;
      background: ${e==="success"?"#10b981":"#ef4444"};
      color: white;
      padding: 12px 20px;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      z-index: 10000;
      font-family: system-ui, -apple-system, sans-serif;
      font-size: 14px;
      max-width: 300px;
      animation: slideIn 0.3s ease-out;
    `,t.textContent=o;const s=document.createElement("style");s.textContent=`
      @keyframes slideIn {
        from {
          transform: translateX(400px);
          opacity: 0;
        }
        to {
          transform: translateX(0);
          opacity: 1;
        }
      }
    `,document.head.appendChild(s),document.body.appendChild(t),setTimeout(()=>{t.style.animation="slideIn 0.3s ease-in reverse",setTimeout(()=>t.remove(),300)},5e3)}async reload(){await this.loadPlaybooks(),this.checkCurrentPage()}}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{new r}):new r;window.__playbookRunner=r;
})()
