Files
wp-agentic-writer/assets/js/dist/sidebar.js
Dwindi Ramadhana 690991c526 refactor: Cleanup git state - commit all staged changes
Major refactoring cleanup:
- Add new controller architecture (class-controller-*.php)
- Add new settings-v2 UI (views/settings-v2/)
- Add new CSS architecture (agentic-sidebar.css, tokens)
- Add esbuild build pipeline (scripts/build.js, package.json)
- Add composer dependencies (vendor/)
- Add frontend src directory (assets/js/src/index.jsx)
- Add documentation files
- Remove old/obsolete files (class-settings.php, old CSS)

This commits all pending changes from previous refactoring efforts.
2026-06-17 05:27:58 +07:00

63 lines
166 KiB
JavaScript

(()=>{(function(s){let{registerPlugin:cr}=s.plugins,{PluginSidebarMoreMenuItem:lr}=s.editPost,{PluginSidebar:dr}=s.editPost,{Panel:ur,TextareaControl:es,TextControl:yn,CheckboxControl:zt,Button:me}=s.components,{dispatch:ie,select:V}=s.data,{RawHTML:gr}=s.element,kn=typeof wpAgenticWriter!="undefined"&&wpAgenticWriter.debug,K={log:(...C)=>{kn&&console.log("[WPAW]",...C)},error:(...C)=>console.error("[WPAW]",...C),info:(...C)=>{kn&&console.info("[WPAW]",...C)},warn:(...C)=>{kn&&console.warn("[WPAW]",...C)}},ts=s.element.createElement("img",{src:wpAgenticWriter.pluginUrl+"/assets/img/icon.svg",alt:"WP Agentic Writer",style:{width:"20px",height:"20px"}}),fr=({postId:C})=>{let ae=typeof wpAgenticWriter!="undefined"?wpAgenticWriter.settings:{},fe=(e,t="The AI request failed.")=>{let n=typeof e=="string"?e:(e==null?void 0:e.message)||t,r=String(n||t).replace(/^API error:\s*/i,"").trim(),o=r.toLowerCase(),a=(i,c,l,d)=>({title:i,detail:c,actionUrl:l||"",actionLabel:d||""});if(o.includes("no allowed providers are available")||o.includes("allowed providers")&&o.includes("selected model")){let i=ae!=null&&ae.openrouter_provider_slug&&ae.openrouter_provider_slug!=="auto"?` Pinned: ${ae.openrouter_provider_slug}.`:"";return a("Model unavailable from current provider",`The pinned provider routing doesn't support this model.${i} Change provider routing or select a compatible model.`,(ae==null?void 0:ae.settings_url)||"","Open Settings")}return r.includes("429")||o.includes("rate limit")?a("Rate limit exceeded","The AI provider is throttling requests. Wait a moment and try again."):r.includes("cURL error 28")||o.includes("operation timed out")||o.includes("timed out after")?a("Request timed out","The model took too long to respond. Try a faster model, reduce content length, or check your provider routing.",(ae==null?void 0:ae.settings_url)||"","Open Settings"):r.startsWith("HTTP 401")||o.includes("unauthorized")?a("API key rejected","The provider rejected your API key. Check your key in settings.",(ae==null?void 0:ae.settings_url)||"","Open Settings"):r.startsWith("HTTP 402")||o.includes("insufficient credits")?a("Insufficient credits","Your provider account has no remaining credits or quota."):o.includes("api key is not configured")||o.includes("no_api_key")?a("API key not configured","Add your OpenRouter API key in plugin settings to start using AI features.",(ae==null?void 0:ae.settings_url)||"","Configure API Key"):a(r||t,"")},[Le,et]=React.useState("chat"),[J,u]=React.useState([]),[tt,pe]=React.useState(""),[U,M]=React.useState(!1),[z,nt]=React.useState(""),[ft,ns]=React.useState([]),[mt,Ge]=React.useState(!1),[Ce,xe]=React.useState("chat"),qt=React.useRef(Math.random().toString(36).substring(2,10)+Date.now().toString(36)),[Kt,bn]=React.useState({locked:!1,lockedByOther:!1,holderTabId:""}),pt=React.useRef(null),wn=React.useMemo(()=>({article_length:"medium",language:"auto",tone:"",audience:"",experience_level:"general",include_images:!0,web_search:!!ae.web_search_enabled,default_mode:"chat",seo_focus_keyword:"",focus_keyword:"",seo_secondary_keywords:"",seo_meta_description:"",seo_enabled:!0}),[ae.web_search_enabled]),[I,Jt]=React.useState(wn),[Xt,ss]=React.useState(!1),[vn,rs]=React.useState(!1),[Sn,os]=React.useState(""),Gt=React.useRef(!1),_n=React.useRef(""),We=React.useRef(null),[te,he]=React.useState({session:0,today:0,monthlyUsed:0}),[Vt,as]=React.useState(ae.monthly_budget||600),[be,is]=React.useState(null),we=e=>{if(!e)return;e.session_id&&nt(e.session_id);let t=e.provider_metadata||e,n=t.provider||t.selected_provider||t.provider;n&&is({provider:n,model:t.model,fallbackUsed:t.fallback_used||t.fallbackUsed,warnings:t.warnings||[]})},[xt,cs]=React.useState(!1),[Oe,ls]=React.useState(!1),[At,Cn]=React.useState([]),Qt=React.useRef([]),ht=React.useRef([]),st=React.useRef([]),hr=25,[Yt,xn]=React.useState({isOpen:!1,blockCount:0,dontAskAgain:!1}),An=React.useRef(null),ds=React.useRef(!1),[Be,yr]=React.useState(null),[Ve,us]=React.useState(!1),[rt,gs]=React.useState(!1),[fs,Nn]=React.useState(""),[Zt,Nt]=React.useState(!1),[Te,In]=React.useState([]),[Ae,yt]=React.useState(0),[de,Ne]=React.useState([]),[en,ms]=React.useState("auto"),[kr,br]=React.useState("generation"),[Rn,ps]=React.useState(null),[It,Rt]=React.useState(null),[tn,Bn]=React.useState([]),Tn=React.useRef(null),Q=React.useRef(null),$n=React.useRef(null),nn=React.useRef({}),Qe=React.useRef(null),He=React.useRef({}),kt=React.useRef({}),En=React.useRef(null),Bt=React.useRef(null),Mn=React.useRef(null),ue=React.useRef(!1),Tt=React.useRef(null),$t=React.useRef(null),sn=React.useRef({type:"idle",status:"idle",label:""}),[Uo,ot]=React.useState(!1),[$e,wr]=React.useState({type:"idle",status:"idle",label:""}),[Ue,hs]=React.useState({status:"idle",current_section_index:0,sections_written:[],last_updated:null,plan_id:"",resume_token:""}),[vr,ys]=React.useState(!1),[Et,Sr]=React.useState({title:"",blockCount:0,selectedBlockLabel:"None selected",selectedBlockPreview:""}),[rn,_r]=React.useState(()=>{try{return window.localStorage.getItem("wpaw_agent_workspace_collapsed")==="1"}catch{return!1}}),Cr=()=>{_r(e=>{let t=!e;try{window.localStorage.setItem("wpaw_agent_workspace_collapsed",t?"1":"0")}catch{}return t})},[Mt,at]=React.useState(!1),[zo,ks]=React.useState(""),[it,bt]=React.useState([]),[Pn,on]=React.useState(0),[Pt,Lt]=React.useState(!1),[qo,xr]=React.useState(""),[ct,an]=React.useState([]),[Ln,Wn]=React.useState(0),[bs,On]=React.useState(!1),ye=React.useRef(null),ve=React.useRef(null),[ws,vs]=React.useState([]),[Ee,lt]=React.useState(""),[Ko,Ss]=React.useState(!1),[Jo,Ar]=React.useState(""),Ie=React.useRef(null),wt=React.useRef(""),De=React.useRef(!1),[dt,Ye]=React.useState(!0),[Dn,Nr]=React.useState(""),[Fn,_s]=React.useState("chat"),[qe,Cs]=React.useState([]),xs=10,[vt,As]=React.useState({restored:!1,summary:"",memories:[],preferences:[],systemMessage:""}),Ns=React.useRef(!1);React.useEffect(()=>{Ce==="writing"&&!U&&xe("chat")},[Ce,U]),React.useEffect(()=>{C&&(ss(!0),fetch(`${wpAgenticWriter.apiUrl}/post-config/${C}`,{headers:{"X-WP-Nonce":wpAgenticWriter.nonce}}).then(e=>e.ok?e.json():Promise.reject(e)).then(e=>{let t={...wn,...e};t.default_mode="chat",Jt(t),_n.current=JSON.stringify(t),Gt.current=!0}).catch(()=>{Gt.current=!0}).finally(()=>{ss(!1)}))},[C,wn]);let Is=React.useCallback(async e=>{if(C){rs(!0),os("");try{let t=await fetch(`${wpAgenticWriter.apiUrl}/post-config/${C}`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({postConfig:e})});if(!t.ok){let r=await t.json();throw new Error(r.message||"Failed to save post configuration")}let n=await t.json();_n.current=JSON.stringify(n),Jt(r=>{let o={...r,...n};return JSON.stringify(r)===JSON.stringify(o)?r:o})}catch(t){os(t.message||"Failed to save post configuration")}finally{rs(!1)}}},[C]);React.useEffect(()=>{if(!(!Gt.current||Xt||JSON.stringify(I)===_n.current))return We.current&&clearTimeout(We.current),We.current=setTimeout(()=>{Is(I)},600),()=>{We.current&&clearTimeout(We.current)}},[I,Xt,Is]),React.useEffect(()=>{!ae.cost_tracking_enabled||!C||fetch(`${wpAgenticWriter.apiUrl}/cost-tracking/${C}`,{headers:{"X-WP-Nonce":wpAgenticWriter.nonce}}).then(e=>e.json()).then(e=>{var t,n,r,o;e&&typeof e.session=="number"&&he({session:e.session,today:((n=(t=e.today)==null?void 0:t.total)==null?void 0:n.cost)||0,monthlyUsed:((r=e.monthly)==null?void 0:r.used)||0}),(o=e==null?void 0:e.monthly)!=null&&o.budget&&as(e.monthly.budget)}).catch(()=>{})},[C]);let jn=(e={})=>({status:e.status||"idle",current_section_index:Number(e.current_section_index||0),sections_written:Array.isArray(e.sections_written)?e.sections_written:[],last_updated:e.last_updated||null,plan_id:e.plan_id||"",resume_token:e.resume_token||""}),Rs=React.useCallback(async e=>{if(!C)return;let t=jn(e);try{if(!(await fetch(`${wpAgenticWriter.apiUrl}/writing-state/${C}`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify(t)})).ok)throw new Error("Failed to save writing state")}catch(n){K.warn("Writing state save failed:",n)}},[C]),Fe=React.useCallback(e=>{hs(t=>{let n=jn({...t,...e});return Rs(n),n})},[Rs]);React.useEffect(()=>{if(!C)return;let e=!1;return ys(!0),fetch(`${wpAgenticWriter.apiUrl}/writing-state/${C}`,{headers:{"X-WP-Nonce":wpAgenticWriter.nonce}}).then(t=>t.ok?t.json():Promise.reject(t)).then(t=>{e||hs(jn(t))}).catch(t=>{K.warn("Writing state load failed:",t)}).finally(()=>{e||ys(!1)}),()=>{e=!0}},[C]);let Hn=React.useRef(null),Un=React.useRef(null);React.useEffect(()=>{Hn.current&&Hn.current.scrollIntoView({behavior:"smooth"})},[J]);let Ir=/^(I'll|Writing|Now|Creating|Adding|Let me|I'll write|Saya|Saya akan|Sedang menulis|Sedang membuat|Menulis tentang|Membuat tentang|Thinking|Analyzing|Reviewing|Refining|Checking|Updating|Planning|Searching|Querying|Generated|Drafting|Reading|Context|Processing)/i,Bs=new Set(["active","starting","refining","checking","waiting","planning","plan_complete","writing","writing_section"]),Rr=new Set(["writing","writing_section"]),Y=e=>{for(let t=e.length-1;t>=0;t--)if(e[t].type==="timeline"&&Bs.has(e[t].status))return t;return-1},oe=e=>e.map(t=>t.type==="timeline"&&Bs.has(t.status)?{...t,status:"inactive"}:t),cn=e=>{u(t=>{let n=[...t],r=Y(n);return r===-1?n.push({role:"system",type:"timeline",status:"active",message:e,timestamp:new Date}):n[r]={...n[r],message:e},n})},zn=(e,t,n={})=>{let{deactivate:r=!0,extra:o={}}=n;u(a=>[...r?oe(a):a,{role:"system",type:"timeline",status:e,message:t,timestamp:new Date,...o}])},qn=e=>{let t={type:(e==null?void 0:e.type)||"idle",status:(e==null?void 0:e.status)||"idle",label:(e==null?void 0:e.label)||""};sn.current=t,wr(t)},Me=(e,t)=>{ue.current=!1;let n=new AbortController;return Tt.current=n,$t.current=null,ot(!1),qn({type:e,status:"running",label:t}),n},ke=(e="")=>{let t=sn.current||{};e&&t.type&&t.type!==e||(Tt.current=null,$t.current=null,qn({type:"idle",status:"idle",label:""}))},Br=()=>{let e=sn.current||{};qn({type:e.type||"unknown",status:"stopping",label:e.label||"operation"}),u(t=>{let n=[...t],r=Y(n);return r!==-1&&(n[r]={...n[r],status:"stopping",message:`Stopping ${e.label||"operation"}...`,timestamp:new Date}),n})},Se=e=>(e==null?void 0:e.name)==="AbortError"||/aborted|abort/i.test(String((e==null?void 0:e.message)||"")),Ke=e=>($t.current=e,e),Tr=React.useCallback(e=>ds.current?Promise.resolve(!0):new Promise(t=>{An.current=t,xn({isOpen:!0,blockCount:Number(e)||0,dontAskAgain:!1})}),[]),Ts=React.useCallback(e=>{let t=An.current;An.current=null,xn(n=>({...n,isOpen:!1})),t&&t(!!e)},[]),$r=(e="AI Operation")=>{let n=V("core/block-editor").getBlocks().map(r=>s.blocks.serialize(r)).join(`
`);return{label:e,timestamp:new Date,blocks:n}},Kn=(e="AI Operation")=>{let t=$r(e);Cs(n=>{let r=[...n,t];return r.length>xs?r.slice(-xs):r})},$s=()=>{if(qe.length===0)return;let e=qe[qe.length-1],{resetBlocks:t}=ie("core/block-editor");try{let n=s.blocks.parse(e.blocks);t(n),Cs(r=>r.slice(0,-1)),u(r=>[...r,{role:"system",type:"timeline",status:"complete",message:`Undid: ${e.label}`,timestamp:new Date}])}catch(n){K.error("Failed to undo AI operation:",n),u(r=>[...r,{role:"system",type:"error",content:"Failed to undo operation: "+n.message}])}};React.useEffect(()=>{let e=Y(J),t=e!==-1?J[e]:null,n=!!(U&&t&&Rr.has(t.status));n&&!xt?(ie("core/editor").lockPostSaving("wpaw-writing"),document.body.classList.add("wpaw-editor-locked"),cs(!0)):!n&&xt&&(ie("core/editor").unlockPostSaving("wpaw-writing"),document.body.classList.remove("wpaw-editor-locked"),cs(!1))},[J,U,xt]),React.useEffect(()=>{Oe?(ie("core/editor").lockPostSaving("wpaw-refining"),document.body.classList.add("wpaw-refining-locked")):(ie("core/editor").unlockPostSaving("wpaw-refining"),document.body.classList.remove("wpaw-refining-locked"))},[Oe]),React.useEffect(()=>{let e=ie("core/block-editor");if(!(!e||typeof e.setBlockEditingMode!="function")){if(Oe){let t=V("core/block-editor").getBlocks(),n=[],r=o=>{o.forEach(a=>{a!=null&&a.clientId&&(n.push(a.clientId),Array.isArray(a.innerBlocks)&&a.innerBlocks.length>0&&r(a.innerBlocks))})};r(t),st.current=n,n.forEach(o=>e.setBlockEditingMode(o,"disabled"))}else st.current.length>0&&(st.current.forEach(t=>e.setBlockEditingMode(t,"default")),st.current=[]);return()=>{st.current.length>0&&(st.current.forEach(t=>e.setBlockEditingMode(t,"default")),st.current=[])}}},[Oe,J]),React.useEffect(()=>((Qt.current||[]).forEach(t=>{let n=document.querySelector(`[data-block="${t}"]`);n&&n.classList.remove("wpaw-block-refining")}),Oe&&Array.isArray(At)?(At.forEach(t=>{let n=document.querySelector(`[data-block="${t}"]`);n&&n.classList.add("wpaw-block-refining")}),Qt.current=[...At]):Qt.current=[],()=>{(Qt.current||[]).forEach(n=>{let r=document.querySelector(`[data-block="${n}"]`);r&&r.classList.remove("wpaw-block-refining")})}),[Oe,At,J]),React.useEffect(()=>{if(!Oe)return;let e=r=>!r||!(r instanceof Element)||r.closest(".wpaw-sidebar, .wpaw-command-area, .wpaw-messages")?!1:!!r.closest(".interface-interface-skeleton__content, .editor-styles-wrapper, .block-editor-writing-flow"),t=r=>{if(!e(r.target)||r.metaKey||r.ctrlKey||r.altKey)return;let o=new Set(["Enter","Backspace","Delete","Tab"]);(typeof r.key=="string"&&r.key.length===1||o.has(r.key))&&(r.preventDefault(),r.stopPropagation())},n=r=>{e(r.target)&&(r.preventDefault(),r.stopPropagation())};return document.addEventListener("keydown",t,!0),document.addEventListener("paste",n,!0),document.addEventListener("drop",n,!0),document.addEventListener("cut",n,!0),()=>{document.removeEventListener("keydown",t,!0),document.removeEventListener("paste",n,!0),document.removeEventListener("drop",n,!0),document.removeEventListener("cut",n,!0)}},[Oe]),React.useEffect(()=>{if(Oe){let e=Array.from(document.querySelectorAll('.editor-styles-wrapper [contenteditable="true"]'));ht.current=e.map(t=>({node:t,prev:t.getAttribute("contenteditable")})),ht.current.forEach(({node:t})=>{t.setAttribute("contenteditable","false")})}else(ht.current||[]).forEach(({node:e,prev:t})=>{e&&(t===null?e.removeAttribute("contenteditable"):e.setAttribute("contenteditable",t))}),ht.current=[];return()=>{(ht.current||[]).forEach(({node:e,prev:t})=>{e&&(t===null?e.removeAttribute("contenteditable"):e.setAttribute("contenteditable",t))}),ht.current=[]}},[Oe,J]);let Es=e=>e==null?"":typeof e=="string"||typeof e=="number"?String(e):"",ge=(e,t)=>{Jt(n=>({...n,[e]:t}))},Er=(e={})=>{let t={...I};if(e.config_language){let n=e.config_language;n==="__custom__"&&e.config_language_custom&&(n=e.config_language_custom.toLowerCase().trim()),n&&n!=="__skipped__"&&(t.language=n)}if(e.config_all)try{let n=JSON.parse(e.config_all);n.web_search!==void 0&&(t.web_search=n.web_search),n.seo!==void 0&&(t.seo_enabled=n.seo),n.focus_keyword&&(t.focus_keyword=n.focus_keyword,t.seo_focus_keyword=n.focus_keyword),n.secondary_keywords&&(t.seo_secondary_keywords=n.secondary_keywords)}catch(n){K.error("Failed to merge config answers:",n)}return t},Je=e=>{lt(e),ge("focus_keyword",e),ge("seo_focus_keyword",e),Ss(!1),Ar("")},Xo=e=>{let t=e.target.value;t==="__custom__"?Ss(!0):Je(t)},Jn=e=>{if(!e||typeof e!="string")return[];let t=[],n=e.match(/(?:fokus|focus)\s+keyword\s+suggestion[s]?\s*:\s*([\s\S]*?)(?=\n\n|Pilih|$)/i);if(n){let o=n[1].match(/[-*]\s*["']?([^"'\n]+)["']?/g);o&&o.forEach(a=>{let i=a.replace(/^[-*]\s*["']?/,"").replace(/["']?$/,"").trim();i.length>2&&i.length<60&&t.push(i)})}if(t.length===0){let r=e.match(/(?:fokus|focus)\s+keyword\s+suggestion[s]?\s*:\s*["']?([^"'\n]+)["']?/i);if(r&&!r[1].includes("-")&&!r[1].includes("*")){let o=r[1].trim();o.length>2&&o.length<60&&t.push(o)}}return t},Go=e=>{let t=Jn(e);return t.length>0?t[0]:null},Mr=e=>{e&&vs(t=>t.includes(e)?t:[...t,e].slice(-5))},Ms=e=>{!e||!Array.isArray(e)||e.forEach(t=>Mr(t))};React.useEffect(()=>{I.focus_keyword&&!Ee?lt(I.focus_keyword):I.seo_focus_keyword&&!Ee&&lt(I.seo_focus_keyword)},[I.focus_keyword,I.seo_focus_keyword]),React.useEffect(()=>{(J.length>0||Q.current)&&Ye(!1)},[J.length]);let Ps=()=>{if(Dn.trim()){let e=Dn.trim();Je(e)}xe(Fn),Ye(!1),setTimeout(()=>{ye.current&&ye.current.focus()},100)},Ls=async()=>{if(Ve||!C)return;let e=Me("seo_audit","SEO audit");us(!0);try{let t=await fetch(`${wpAgenticWriter.apiUrl}/seo-audit/${C}`,{headers:{"X-WP-Nonce":wpAgenticWriter.nonce},signal:e.signal}),n=await t.json();if(!t.ok)throw new Error(n.message||"Failed to run SEO audit");yr(n),u(r=>{let o=[...r],a=Y(o);return a!==-1&&(o[a]={...o[a],status:"complete",message:"SEO audit complete.",completedAt:new Date}),o})}catch(t){if(Se(t)){u(n=>{let r=[...n],o=Y(r);return o!==-1&&(r[o]={...r[o],status:"stopped",message:"SEO audit stopped."}),r});return}K.error("SEO Audit error:",t),u(n=>[...n,{role:"assistant",content:`SEO Audit error: ${t.message}`,type:"error"}]),u(n=>{let r=[...n],o=Y(r);return o!==-1&&(r[o]={...r[o],status:"error",message:"SEO audit failed."}),r})}finally{us(!1),ke("seo_audit")}},Pr=e=>{let t=Ee||I.focus_keyword||I.seo_focus_keyword||"",n=I.language&&I.language!=="auto"?`Use ${I.language}.`:"Use the same language as the article.",r=(e==null?void 0:e.name)||"SEO audit issue",o=(e==null?void 0:e.message)||"",a=t?`Focus keyword: "${t}".`:"If a focus keyword is missing, ask the user to set one first.",i=String(r).toLowerCase();return i.includes("keyword in intro")?`Fix this SEO audit issue in the article introduction: ${o}. ${a} Add the focus keyword naturally in the first paragraph without sounding forced. ${n}`:i.includes("keyword density")?`Fix this SEO audit issue across the article: ${o}. ${a} Improve keyword usage naturally, avoid stuffing, and keep the writing human and useful. ${n}`:i.includes("ai-ish")?`Fix this audit issue across the article: ${o}. Make the writing more natural, specific, and human. Reduce generic AI-style phrasing while preserving meaning, structure, and facts. ${n}`:i.includes("content length")?`Fix this SEO audit issue: ${o}. Expand the article with useful, non-fluffy details, examples, and reader guidance. ${a} ${n}`:i.includes("subheadings")?`Fix this readability issue: ${o}. Improve the article structure with useful H2/H3 subheadings while preserving the article's intent. ${a} ${n}`:`Fix this SEO audit issue: ${r}: ${o}. ${a} Keep the result natural, useful, and aligned with the article intent. ${n}`},Ws=e=>`${(e==null?void 0:e.name)||""}:${(e==null?void 0:e.message)||""}`,Os=e=>{let t=Number((Be==null?void 0:Be.ai_ish_pattern_count)||0);if(t>0)return t;let n=String((e==null?void 0:e.message)||"").match(/(\d+)\s+pattern/i);return n?Number(n[1]):0},ze=(e,t,n=`${t}s`)=>{let r=Number(e||0);return`${r} ${r===1?t:n}`},ln=e=>{let t=Number((e==null?void 0:e.patternCount)||0);return t>0?ze(t,"pattern occurrence"):"audit pattern occurrences"},Lr=(e,t,n)=>({source:"seo_audit",issueName:(e==null?void 0:e.name)||"SEO audit issue",auditMessage:(e==null?void 0:e.message)||"",patternCount:Os(e),candidateBlockCount:Array.isArray(t)?t.length:0,refineableBlockCount:Array.isArray(n)?n.length:0}),Wr=async e=>{if(U||Ve||!e)return;let t=String(e.name||"").toLowerCase(),n=Ee||I.focus_keyword||I.seo_focus_keyword||"",r=Ws(e);if(Nn(r),t.includes("focus keyword")&&!n){u(o=>[...o,{role:"system",type:"error",content:"Set a focus keyword first, then run the audit again."}]),et("config"),Nn("");return}et("chat"),Ye(!1);try{if(t.includes("meta description")){u(c=>[...c,{role:"user",content:`Fix SEO audit: ${e.message}`}]),u(c=>[...oe(c),{role:"system",type:"timeline",status:"refining",message:"Generating SEO meta description...",timestamp:new Date}]),await Xn();return}if(t.includes("keyword in title")){let c=n?`include the focus keyword "${n}" naturally in the title, keep it compelling, and match the article language`:"make the title more SEO-friendly and aligned with the article";await Js(`@title ${c}`,["@title"]);return}let o=jt();if(!o.length){u(c=>[...c,{role:"system",type:"error",content:"No article blocks found to fix yet. Generate or insert content first, then run the audit again."}]);return}let a=Pr(e),i=t.includes("ai-ish")?Yn(a,o):o;if(t.includes("ai-ish")&&i.length===0){let c=Os(e);u(l=>[...l,{role:"assistant",content:c>0?`Audit found ${ze(c,"pattern occurrence")}, but I could not safely map those occurrences to editor blocks. I did not send the whole article to refinement.`:"I rechecked the editor blocks and did not find AI-ish pattern matches, so I did not send the whole article to refinement."}]);return}await gt(a,i.map(c=>c.clientId),{useDiffPlan:!1,auditContext:t.includes("ai-ish")?Lr(e,i,o):null})}finally{Nn("")}},Xn=async()=>{if(rt)return;let e=Me("meta","meta description");gs(!0);try{let t=await fetch(`${wpAgenticWriter.apiUrl}/generate-meta`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({postId:C,sessionId:z,focusKeyword:I.seo_focus_keyword,chatHistory:J.filter(r=>r.role!=="system")}),signal:e.signal});if(!t.ok){let r=await t.json();throw new Error(r.message||"Failed to generate meta description")}let n=await t.json();if(we(n),n.meta_description)ge("seo_meta_description",n.meta_description),u(r=>[...r,{role:"assistant",content:"\u2705 Meta description generated successfully",type:"success"}]),u(r=>{let o=[...r],a=Y(o);return a!==-1&&(o[a]={...o[a],status:"complete",message:"Meta description generated.",completedAt:new Date}),o});else throw new Error("No meta description returned from API")}catch(t){if(Se(t)){u(n=>{let r=[...n],o=Y(r);return o!==-1&&(r[o]={...r[o],status:"stopped",message:"Meta description generation stopped."}),r});return}K.error("Error generating meta description:",t),u(n=>[...n,{role:"system",content:`\u274C Failed to generate meta description: ${t.message}`,type:"error"}]),u(n=>{let r=[...n],o=Y(r);return o!==-1&&(r[o]={...r[o],status:"error",message:"Meta description failed."}),r})}finally{gs(!1),ke("meta")}},Pe=e=>{var n,r,o,a;let t=Es(((n=e.attributes)==null?void 0:n.content)||((r=e.attributes)==null?void 0:r.value)||((o=e.attributes)==null?void 0:o.caption)||((a=e.attributes)==null?void 0:a.title)||"");if(t)return t;if(s.blocks&&typeof s.blocks.getBlockContent=="function"){let i=s.blocks.getBlockContent(e);if(i){let c=document.createElement("div");return c.innerHTML=i,Es(c.textContent)}}return""},Or=e=>{if(!e)return"";let n=V("core/block-editor").getBlocks().find(r=>r.clientId===e);return n?Pe(n):""},Ds=React.useCallback(()=>{let e=V("core/editor"),t=V("core/block-editor"),n=t!=null&&t.getBlocks?t.getBlocks():[],r=t!=null&&t.getSelectedBlockClientId?t.getSelectedBlockClientId():"",o=r&&(t!=null&&t.getBlock)?t.getBlock(r):null,a=e!=null&&e.getEditedPostAttribute&&e.getEditedPostAttribute("title")||"",i=o!=null&&o.name?o.name.replace("core/",""):"",c=o?Pe(o):"";return{title:a||"Untitled draft",blockCount:n.filter(l=>Pe(l)||Array.isArray(l.innerBlocks)&&l.innerBlocks.length>0).length,selectedBlockLabel:o?`${i||"block"} ${r.slice(0,6)}`:"None selected",selectedBlockPreview:c?c.slice(0,90):""}},[]);React.useEffect(()=>{var n;let e=()=>{let r=Ds();Sr(o=>JSON.stringify(o)===JSON.stringify(r)?o:r)};e();let t=(n=s.data)!=null&&n.subscribe?s.data.subscribe(e):null;return()=>{typeof t=="function"&&t()}},[Ds]),React.useEffect(()=>{if(Un.current){let e=Un.current;e.scrollTop=e.scrollHeight}},[J,U]),React.useEffect(()=>{let e=t=>{if(U)return t.preventDefault(),t.returnValue="",""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[U]),React.useEffect(()=>{Yr()},[C]),React.useEffect(()=>{if(C)try{let e=window.localStorage.getItem(`wpawSessionId_${C}`);e&&nt(e)}catch{}},[C]),React.useEffect(()=>{if(!(!C||!z))try{window.localStorage.setItem(`wpawSessionId_${C}`,z)}catch{}},[C,z]);let St=React.useCallback(e=>Array.isArray(e)?e.slice(-300).map(r=>{let o={};return o.role=typeof(r==null?void 0:r.role)=="string"?r.role:"assistant",typeof(r==null?void 0:r.content)=="string"&&(o.content=r.content),typeof(r==null?void 0:r.type)=="string"&&(o.type=r.type),typeof(r==null?void 0:r.status)=="string"&&(o.status=r.status),r!=null&&r.timestamp&&(o.timestamp=r.timestamp),Array.isArray(r==null?void 0:r.sections)&&(o.sections=r.sections),r!=null&&r.meta&&typeof r.meta=="object"&&(o.meta=r.meta),r!=null&&r.plan&&typeof r.plan=="object"&&(o.plan=r.plan),o}):[],[]),Fs=React.useCallback(e=>{var n,r;if(!Array.isArray(e)||e.length===0){Q.current=null,xe("chat");return}let t=null;for(let o=e.length-1;o>=0;o-=1)if(((n=e[o])==null?void 0:n.type)==="plan"&&((r=e[o])!=null&&r.plan)){t=Gn(e[o].plan);break}Q.current=t,xe(t?"planning":"chat"),Ye(!1)},[]),js=React.useCallback(async(e=null,t=!1,n=null)=>{var c,l;let r=e||z;if(!r)return;let o=n||(Re&&Re.current?Re.current:J);if(!Array.isArray(o)||o.length===0)return;let a=t?o:St(o),i=JSON.stringify(a);if(i!==wt.current)try{if(!(await fetch(`${wpAgenticWriter.apiUrl}/conversations/${r}/messages`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({messages:a})})).ok)throw new Error("Failed to persist session messages");wt.current=i}catch(d){(l=(c=window.console)==null?void 0:c.warn)==null||l.call(c,"WP Agentic Writer: failed to persist session messages.",d)}},[St,z]),Re=React.useRef(J);React.useEffect(()=>{Re.current=J},[J]),React.useEffect(()=>{let e=()=>{if(Ie.current&&clearTimeout(Ie.current),!z||De.current)return;let t=Re&&Re.current?Re.current:J;if(!Array.isArray(t)||t.length===0)return;let n=St(t);if(JSON.stringify(n)!==wt.current)try{let o=new XMLHttpRequest;o.open("POST",`${wpAgenticWriter.apiUrl}/conversations/${z}/messages`,!1),o.setRequestHeader("Content-Type","application/json"),o.setRequestHeader("X-WP-Nonce",wpAgenticWriter.nonce),o.send(JSON.stringify({messages:n}))}catch{}};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[z,St]);let Wt=React.useCallback(async e=>{var t;if(!e)return!1;try{let n=await fetch(`${wpAgenticWriter.apiUrl}/conversations/${e}/lock`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({tab_id:qt.current})});if(!n.ok)return!1;let r=await n.json();return r.locked?(bn({locked:!0,lockedByOther:!1,holderTabId:""}),!0):(bn({locked:!1,lockedByOther:!0,holderTabId:((t=r.holder)==null?void 0:t.tab_id)||""}),!1)}catch{return!0}},[]),Hs=React.useCallback(async e=>{if(e)try{await fetch(`${wpAgenticWriter.apiUrl}/conversations/${e}/lock`,{method:"DELETE",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({tab_id:qt.current}),keepalive:!0})}catch{}},[]),Ot=React.useCallback(e=>{pt.current&&clearInterval(pt.current),pt.current=setInterval(()=>{Wt(e)},3e4)},[Wt]),dn=React.useCallback(()=>{pt.current&&(clearInterval(pt.current),pt.current=null)},[]);React.useEffect(()=>{let e=()=>{if(z){dn();try{let t=new XMLHttpRequest;t.open("DELETE",`${wpAgenticWriter.apiUrl}/conversations/${z}/lock`,!1),t.setRequestHeader("Content-Type","application/json"),t.setRequestHeader("X-WP-Nonce",wpAgenticWriter.nonce),t.send(JSON.stringify({tab_id:qt.current}))}catch{}}};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[z,dn]);let Dr=React.useCallback(async()=>{if(z)try{let e=await fetch(`${wpAgenticWriter.apiUrl}/conversations/${z}/lock`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({tab_id:qt.current,force:!0})});e.ok&&(await e.json()).locked&&(bn({locked:!0,lockedByOther:!1,holderTabId:""}),Ot(z))}catch{}},[z,Ot]);React.useEffect(()=>{if(!z||De.current||Kt.lockedByOther)return;let e=Re&&Re.current?Re.current:J;if(!(!Array.isArray(e)||e.length===0))return Ie.current&&clearTimeout(Ie.current),Ie.current=setTimeout(()=>{if(De.current)return;let t=Re&&Re.current?Re.current:[];t.length!==0&&js(z,!1,t)},3e3),()=>{Ie.current&&clearTimeout(Ie.current)}},[z,J,js]),React.useEffect(()=>{(async()=>{if(!(J.length>0||De.current))try{let t={"X-WP-Nonce":wpAgenticWriter.nonce},n=[],r="",o=await un();if(!C)return;if(o.length>0&&o.length>0){let a=o[0],i=(()=>{try{return window.localStorage.getItem(`wpawSessionId_${C}`)||""}catch{return""}})();if(i){let c=o.find(l=>(l==null?void 0:l.session_id)===i);c&&(a=c)}r=(a==null?void 0:a.session_id)||"",Array.isArray(a==null?void 0:a.messages)&&a.messages.length>0&&(n=a.messages)}if(r&&n.length===0)try{let a=await fetch(`${wpAgenticWriter.apiUrl}/conversations/${r}`,{method:"GET",headers:t});if(a.ok){let i=await a.json();i&&Array.isArray(i.messages)&&i.messages.length>0&&(n=i.messages)}}catch{}if(C&&!r){let a=await fetch(`${wpAgenticWriter.apiUrl}/conversation/${C}`,{method:"GET",headers:t});if(a.ok){let i=await a.json();i!=null&&i.session_id&&(r=i.session_id),i&&Array.isArray(i.messages)&&i.messages.length>0&&(n=i.messages)}}if(C&&n.length===0&&!r){let a=await fetch(`${wpAgenticWriter.apiUrl}/chat-history/${C}`,{method:"GET",headers:t});if(a.ok){let i=await a.json();i&&Array.isArray(i.messages)&&i.messages.length>0&&(n=i.messages)}}n.length>0&&(De.current=!0,wt.current=JSON.stringify(St(n)),Fs(n),u(n),setTimeout(()=>{De.current=!1},0)),r&&(nt(r),Wt(r).then(a=>{a&&Ot(r)}))}catch{}})()},[C]),React.useEffect(()=>{!C||Ns.current||(Ns.current=!0,fetch(`${wpAgenticWriter.apiUrl}/memanto/restore?post_id=${C}`,{headers:{"X-WP-Nonce":wpAgenticWriter.nonce}}).then(e=>e.ok?e.json():Promise.reject(e)).then(e=>{e!=null&&e.restored&&(K.info("MEMANTO: Session restored",e),As({restored:!0,summary:e.summary||"",memories:e.memories||[],preferences:e.preferences||[],systemMessage:e.system_message||""}))}).catch(()=>{}))},[C]),React.useEffect(()=>{var e;!C||!vt.restored||!((e=vt.preferences)!=null&&e.length)||!Gt.current||Jt(t=>{let n=!1,r={...t};for(let o of vt.preferences){let a=o.content||"",i=a.match(/tone\s*=\s*([^,\n]+)/i),c=a.match(/audience\s*=\s*([^,\n]+)/i),l=a.match(/(?:article_)?length\s*=\s*([^,\n]+)/i),d=a.match(/language\s*=\s*([^,\n]+)/i);i&&!t.tone&&i[1].trim().toLowerCase()!=="default"&&(r.tone=i[1].trim(),n=!0),c&&!t.audience&&c[1].trim().toLowerCase()!=="general"&&(r.audience=c[1].trim(),n=!0),l&&t.article_length==="medium"&&l[1].trim().toLowerCase()!=="medium"&&(r.article_length=l[1].trim(),n=!0),d&&t.language==="auto"&&d[1].trim().toLowerCase()!=="auto"&&(r.language=d[1].trim(),n=!0)}return n?r:t})},[C,vt.restored,Xt]);let un=async()=>{let e={"X-WP-Nonce":wpAgenticWriter.nonce},t=[],n=[],r=async l=>{let d=await fetch(`${wpAgenticWriter.apiUrl}/conversations?status=${l}&limit=50`,{method:"GET",headers:e});if(!d.ok)return[];let g=await d.json();return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]},o=l=>l.filter(d=>Number((d==null?void 0:d.post_id)||0)===0);if(C){let l=await fetch(`${wpAgenticWriter.apiUrl}/conversations/post/${C}`,{method:"GET",headers:e});if(l.ok){let d=await l.json();t=Array.isArray(d==null?void 0:d.sessions)?d.sessions:[]}if(t.length===0){let[d,g]=await Promise.all([r("active"),r("completed")]);n=o([...d,...g])}}else{let[l,d]=await Promise.all([r("active"),r("completed")]);n=[...l,...d]}let a=[...t,...n],i=[],c=new Set;return a.forEach(l=>{var h;let d=(l==null?void 0:l.session_id)||"";!d||c.has(d)||Number((h=l==null?void 0:l.message_count)!=null?h:Array.isArray(l==null?void 0:l.messages)?l.messages.length:0)<=0||(c.add(d),i.push(l))}),ns(i),i},Us=async e=>{if(!e)return;let t={"X-WP-Nonce":wpAgenticWriter.nonce};Ge(!0);try{z&&z!==e&&(dn(),Hs(z));let n=await fetch(`${wpAgenticWriter.apiUrl}/conversations/${e}`,{method:"GET",headers:t});if(!n.ok)throw new Error("Failed to load session");let r=await n.json();Ie.current&&(clearTimeout(Ie.current),Ie.current=null),De.current=!0,nt(e);let o=Array.isArray(r==null?void 0:r.messages)?r.messages:[];if(o.length===0&&(r!=null&&r.post_id)&&Number(r.post_id)>0){K.warn("Session has 0 messages, attempting post-based recovery:",e);try{let c=await fetch(`${wpAgenticWriter.apiUrl}/conversation/${r.post_id}`,{method:"GET",headers:t});if(c.ok){let l=await c.json();Array.isArray(l==null?void 0:l.messages)&&l.messages.length>0&&o.push(...l.messages)}}catch{}}wt.current=JSON.stringify(St(o)),Fs(o),u(o),Ye(!1);let a=Number((r==null?void 0:r.post_id)||0);C&&C>0&&a===0&&fetch(`${wpAgenticWriter.apiUrl}/conversations/${e}/link-post`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({postId:C})}).catch(()=>{}),await Wt(e)&&Ot(e),setTimeout(()=>{De.current=!1},0)}catch{De.current=!1,u(r=>[...r,{role:"system",type:"error",content:"Error: Failed to load selected session."}])}finally{Ge(!1)}},Dt=e=>Ir.test(e)?"timeline":e.length>=6||/[\s.!?]/.test(e)?"assistant":null,gn=e=>e?e.replace(/[\u2010-\u2015\u2212]/g,"-").replace(/[.,;:!?)]*$/g,"").toLowerCase():"",zs=e=>{let t=[],n=/@([^\s]+)/g,r;for(;r=n.exec(e);){let o=gn(r[1]);o&&t.push("@"+o)}return t},qs=e=>e?e.replace(/@[\w-]+/g,"").replace(/\s{2,}/g," ").trim():"",Ks=e=>Array.isArray(e)&&e.some(t=>gn(String(t).replace("@",""))==="title"),Js=async(e,t,n={})=>{let{skipUserMessage:r=!1}=n,o=qs(e||"");if(!o)return u(i=>[...i,{role:"system",type:"error",content:"Please add title instruction after @title. Example: @title tulis ulang, gunakan focus keyword di awal."}]),!1;r||u(i=>[...i,{role:"user",content:e}]);let a=Me("title","title refinement");M(!0),u(i=>[...oe(i),{role:"system",type:"timeline",status:"refining",message:"Refining title...",timestamp:new Date}]);try{let i=await fetch(`${wpAgenticWriter.apiUrl}/refine-title`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({postId:C,sessionId:z,instruction:o}),signal:a.signal}),c=await i.json();if(!i.ok)throw new Error((c==null?void 0:c.message)||"Failed to refine title");return c!=null&&c.title&&ie("core/editor").editPost({title:c.title}),c!=null&&c.cost&&he({...te,session:te.session+Number(c.cost||0)}),we(c),u(l=>{let d=[...l],g=Y(d);return g!==-1&&(d[g]={...d[g],status:"complete",message:"Title refined successfully.",completedAt:new Date}),d.push({role:"assistant",content:`Updated title: ${c.title||""}`}),d}),!0}catch(i){return timeout&&clearTimeout(timeout),Se(i)?(u(c=>{let l=[...c],d=Y(l);return d!==-1&&(l[d]={...l[d],status:"stopped",message:"Title refinement stopped."}),l}),!1):(u(c=>[...c,{role:"system",type:"error",content:"Error: "+(i.message||"Failed to refine title")}]),!1)}finally{M(!1),ke("title")}},Fr=e=>{let t=[{mode:"add_below",regex:/^\s*(?:\/)?add below\b[:\-]?\s*/i},{mode:"add_above",regex:/^\s*(?:\/)?add above\b[:\-]?\s*/i},{mode:"append_code",regex:/^\s*(?:\/)?append code block\b[:\-]?\s*/i},{mode:"append_code",regex:/^\s*(?:\/)?append code\b[:\-]?\s*/i},{mode:"append_code",regex:/^\s*(?:\/)?add code block\b[:\-]?\s*/i}];for(let n of t)if(n.regex.test(e))return{mode:n.mode,message:e.replace(n.regex,"").trim()};return null},jr=e=>{let t=[{id:"add-below",label:"add below",sublabel:"Insert a new paragraph below the target block",insertText:"add below @"},{id:"add-above",label:"add above",sublabel:"Insert a new paragraph above the target block",insertText:"add above @"},{id:"append-code-block",label:"append code block",sublabel:"Insert a code block below the target block",insertText:"append code block @"},{id:"reformat",label:"reformat",sublabel:"Convert markdown-like text into blocks",insertText:"reformat @"}];if(!e)return t;let n=e.toLowerCase();return t.filter(r=>r.label.includes(n))},Hr=e=>{let t=V("core/block-editor").getBlockIndex?V("core/block-editor").getBlockIndex(e):-1;return t!==-1?t:V("core/block-editor").getBlocks().findIndex(r=>r.clientId===e)},Ur=e=>{if(e.length>0){let r=Ut(e);if(r.length>0)return r[0]}let t=V("core/block-editor").getSelectedBlockClientId();if(t)return t;let n=V("core/block-editor").getBlocks();return n.length>0?n[n.length-1].clientId:null},zr=async(e,t,n,r)=>{let o=Ur(n),a=o?V("core/block-editor").getBlock(o):null,c=((a==null?void 0:a.name)==="core/list-item"?yo(o):null)||o;if(!c){u(b=>[...b,{role:"system",type:"error",content:"No target block found. Select a block or mention one with @paragraph-1."}]),M(!1);return}let l=Hr(c),d=l===-1?void 0:l+(e==="add_above"?0:1),{insertBlocks:g}=ie("core/block-editor"),h=e==="append_code"?"core/code":"core/paragraph",v=s.blocks.createBlock(h,e==="append_code"?{content:"",language:"text"}:{content:""});g(v,d);let y=qs(t);if((a==null?void 0:a.name)==="core/list-item"){let b=Pe(a);b&&(y=y?`${y}
Add a short description for: "${b}".`:`Add a short description for: "${b}".`)}let _=vo(n,o);if(!_.length){let b=bo(c);b&&_.push(`Heading: ${b}`),wo(c,2).forEach((S,x)=>{_.push(`Paragraph ${x+1}: ${S}`)})}_.length&&(y=`${y}
Context snippets:
${_.map(b=>`- ${b}`).join(`
`)}`),y=`${y}
Return only JSON: {"content":"...","blockType":"${h}"} with no extra text.`,e==="append_code"&&(y+=' Put the code in "content" only, no backticks.'),pe(""),u(b=>[...b,{role:"user",content:r}]),await gt(y,[v.clientId],{skipUserMessage:!0,useDiffPlan:!1})},qr=async(e,t={})=>{var l,d,g,h,v,y,_,B;let{resume:n=!1,suggestKeywords:r=Ce==="planning"}=t,o={...e,postConfig:I,chatHistory:ut()};Tn.current=o;let a=Ce==="planning"?"planning":"generation",i=Me(a,a==="planning"?"outline generation":"article generation");M(!0),n||Kn("Article Generation");let c=null;try{let b=await fetch(wpAgenticWriter.apiUrl+"/generate-plan",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({...o,resume:n}),signal:i.signal});if(!b.ok){let $=await b.json();u(q=>[...q,{role:"system",type:"error",content:fe($,"Failed to generate article"),canRetry:!0,retryType:"generation"}]);return}let S=Ke(b.body.getReader()),x=new TextDecoder;for(c=setTimeout(()=>{U&&(K.error("Generation timeout - no response received"),u($=>[...$,{role:"system",type:"error",content:fe("cURL error 28: Operation timed out after 120000 milliseconds","Failed to generate article"),canRetry:!0,retryType:"generation"}]),M(!1),S.cancel())},12e4);;){if(ue.current||i.signal.aborted)throw await S.cancel().catch(()=>{}),new DOMException("Operation stopped by user","AbortError");let{done:$,value:q}=await S.read();if($)break;let L=x.decode(q,{stream:!0}).split(`
`);for(let w of L)if(w.startsWith("data: "))try{let f=JSON.parse(w.slice(6));if(f.type==="plan")he({...te,session:te.session+f.cost}),Ce==="planning"&&f.plan&&Ct(f.plan,{suggestKeywords:r});else if(f.type==="title_update")ie("core/editor").editPost({title:f.title});else if(f.type==="status"){if(f.status==="complete")continue;u(p=>{let m=[...p],k=Y(m);return k!==-1&&(m[k]={...m[k],status:f.status,message:f.message,icon:f.icon}),m})}else if(f.type==="conversational"||f.type==="conversational_stream"){let p=(f.content||"").replace(/~~~ARTICLE~+/g,"").replace(/~~~ARTICLE~~~[\r\n]*/g,"").trim();if(!p||pn(p))continue;let m=ve.current||Dt(p);if(!m)continue;ve.current=m,m==="timeline"?cn(p):f.type==="conversational"?u(k=>[...k,{role:"assistant",content:p}]):u(k=>{let N=[...k],Z=N.length-1;return N[Z]&&N[Z].role==="assistant"?N[Z]={...N[Z],content:p}:N.push({role:"assistant",content:p}),N})}else if(f.type==="block"){let{insertBlocks:p}=ie("core/block-editor"),m;if(f.block.blockName==="core/paragraph"){let k=((d=(l=f.block.innerHTML)==null?void 0:l.match(/<p>(.*?)<\/p>/))==null?void 0:d[1])||"";m=s.blocks.createBlock("core/paragraph",{content:k})}else if(f.block.blockName==="core/heading"){let k=((g=f.block.attrs)==null?void 0:g.level)||2,N=((v=(h=f.block.innerHTML)==null?void 0:h.match(/<h[1-6]>(.*?)<\/h[1-6]>/))==null?void 0:v[1])||"";m=s.blocks.createBlock("core/heading",{level:k,content:N})}else if(f.block.blockName==="core/list"){let k=(f.block.innerBlocks||[]).map(N=>{var _e,E;let Z=((E=(_e=N.innerHTML)==null?void 0:_e.match(/<li>(.*?)<\/li>/))==null?void 0:E[1])||"";return s.blocks.createBlock("core/list-item",{content:Z})});m=s.blocks.createBlock("core/list",{...f.block.attrs||{},ordered:((y=f.block.attrs)==null?void 0:y.ordered)||!1},k)}else if(f.block.blockName==="core/quote"){let k=((B=(_=f.block.innerHTML)==null?void 0:_.match(/<p>(.*?)<\/p>/))==null?void 0:B[1])||"";m=s.blocks.createBlock("core/quote",{value:k})}else f.block.blockName==="core/image"?m=s.blocks.createBlock("core/image",f.block.attrs||{}):f.block.blockName==="core/code"&&(m=s.blocks.createBlock("core/code",f.block.attrs||{}));m&&p(m)}else f.type==="complete"?(we(f),clearTimeout(c),he({...te,session:te.session+f.totalCost}),u(p=>{let m=[...p],k=Y(m);return k!==-1&&(m[k]={...m[k],status:"complete",message:Ce==="planning"?"Outline ready.":"Article generated successfully!",completedAt:new Date}),m})):f.type==="error"&&(clearTimeout(c),u(p=>[...p,{role:"system",type:"error",content:fe(f.message||"An error occurred during article generation","Failed to generate article"),canRetry:!0,retryType:"generation"}]))}catch(f){K.error("Failed to parse streaming data:",w,f)}}c&&clearTimeout(c)}catch(b){if(Se(b)){u(S=>{let x=[...S],$=Y(x);return $!==-1&&(x[$]={...x[$],status:"stopped",message:"Generation stopped."}),x});return}K.error("Article generation error:",b),u(S=>[...S,{role:"system",type:"error",content:fe(b,"Failed to generate article"),canRetry:!0,retryType:"generation"}])}finally{M(!1),ke(a)}},Kr=()=>{if(!Tn.current){u(e=>[...e,{role:"system",type:"error",content:"Cannot retry because the original generation request is no longer available. Please send the request again."}]);return}u(e=>[...oe(e),{role:"system",type:"timeline",status:"starting",message:"Resuming generation...",timestamp:new Date}]),qr(Tn.current,{resume:!0})},Jr=()=>{if(!$n.current){u(e=>[...e,{role:"system",type:"error",content:"Cannot retry because the original writing request is no longer available. Please start writing again."}]);return}Ft({retry:!0})},Xr=()=>{if(!Bt.current){u(e=>[...e,{role:"system",type:"error",content:"Cannot retry because the original refinement request is no longer available. Please send the refinement again."}]);return}u(e=>[...oe(e),{role:"system",type:"timeline",status:"starting",message:"Retrying refinement...",timestamp:new Date}]),gt(Bt.current.message,Bt.current.blocksOverride,Bt.current.options)},Gr=async()=>{if(!Mn.current){u(n=>[...n,{role:"system",type:"error",content:"Cannot retry because the original chat request is no longer available. Please send the message again."}]);return}let e=Mn.current.message;u(n=>n.filter(r=>!(r.type==="error"&&r.retryType==="chat"))),M(!0);let t=Me("chat","chat retry");try{let n=J.filter(v=>v.role==="user"||v.role==="assistant").map(v=>({role:v.role,content:v.content})),r=await fetch(wpAgenticWriter.apiUrl+"/chat",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({messages:[...n,{role:"user",content:e}],postId:C,sessionId:z,type:"chat",stream:!0,postConfig:I}),signal:t.signal});if(!r.ok){let v=await r.json();throw new Error(v.message||"Failed to chat")}let o=Ke(r.body.getReader()),a=new TextDecoder,i="",c="",l=null,d=Date.now(),g=!1,h=setInterval(()=>{Date.now()-d>3e4&&!g&&(g=!0,u(v=>[...v,{role:"system",type:"timeline",status:"active",message:"\u23F3 Still waiting for response \u2014 the model is processing...",timestamp:new Date}]))},1e4);try{for(;;){if(ue.current||t.signal.aborted)throw new DOMException("Chat retry stopped","AbortError");let{done:v,value:y}=await o.read();if(v)break;d=Date.now(),g=!1,i+=a.decode(y,{stream:!0});let _=i.split(`
`);i=_.pop()||"";for(let B of _)if(B.startsWith("data: "))try{let b=JSON.parse(B.slice(6));if(b.type==="error"){l=new Error(b.message||"Chat error");break}if(b.type==="conversational_stream"||b.type==="conversational")c=b.content,u(S=>{let x=S[S.length-1];return x&&x.role==="assistant"&&x.isStreaming?[...S.slice(0,-1),{...x,content:c}]:[...S,{role:"assistant",content:c,isStreaming:!0}]});else if(b.type==="complete"){if(we(b),u(S=>{let x=S[S.length-1];return x&&x.role==="assistant"?[...S.slice(0,-1),{...x,isStreaming:!1}]:S}),c){let S=Jn(c);S.length>0&&Ms(S)}}else b.type==="provider"&&b.fallback_used&&u(S=>[...S,{role:"system",type:"timeline",status:"active",message:`\u26A0\uFE0F ${b.selectedProvider||"Selected provider"} unavailable \u2014 using ${b.provider||"fallback"}`,timestamp:new Date}])}catch(b){K.error("Failed to parse retry streaming data:",B,b)}if(l)throw l}if(ue.current||t.signal.aborted)throw new DOMException("Chat retry stopped","AbortError")}finally{clearInterval(h)}}catch(n){if(Se(n)||ue.current||t.signal.aborted)u(r=>[...oe(r),{role:"system",type:"timeline",status:"stopped",message:"Chat retry stopped by user.",timestamp:new Date}]);else{let r=fe(n,"Failed to chat");u(o=>[...o,{role:"system",type:"error",content:r,canRetry:!0,retryType:"chat"}])}}finally{M(!1),ke("chat")}},_t=e=>{let t=e.blockType||"core/paragraph",n=e.content||"";if(t==="core/image"){let r=n.match(/^!\[(.*?)\]\(([^)\s]+)(?:\s+"[^"]*")?\)\s*$/),o=r?r[1]:"",a=r?r[2]:"";return s.blocks.createBlock("core/image",{id:0,url:a,alt:o,caption:"",sizeSlug:"large",linkDestination:"none"})}if(t==="core/heading")return s.blocks.createBlock("core/heading",{level:e.level||2,content:n});if(t==="core/list"){let o=n.split(`
`).map(a=>a.trim()).filter(Boolean).map(a=>s.blocks.createBlock("core/list-item",{content:a}));return s.blocks.createBlock("core/list",{ordered:e.ordered||!1,...e.start?{start:parseInt(e.start,10)}:{}},o)}return t==="core/code"?s.blocks.createBlock("core/code",{content:n,language:e.language||"text"}):t==="core/paragraph"&&n.includes("<")&&n.includes(">")?s.blocks.rawHandler({HTML:n}):s.blocks.createBlock(t,{content:n})},fn=e=>!e||!e.actions?[]:Array.isArray(e.actions)?e.actions:Object.values(e.actions),Vr=(e,t)=>{if(!e||!e.action)return{title:"Unknown action"};let n=e.blockType?` (${e.blockType.replace("core/","")})`:"",r=(e.content||"").replace(/\s+/g," ").trim(),o=r||"",a=Or(e.blockId),i=a||"",c=a?` "${a.substring(0,40)}${a.length>40?"...":""}"`:"",l=i||'"Target block not found"',d=e.blockId||null;switch(e.action){case"keep":return{title:"Keep"};case"delete":return{title:`Delete${c}`,blockId:d,viewInEditor:!0};case"replace":return{title:`Replace${c}${n}`,blockId:d,viewInEditor:!0};case"change_type":return{title:`Change type${c}${n}`,blockId:d,viewInEditor:!0};case"insert":return{title:`Insert new block${n}`,blockId:d,viewInEditor:!0};case"insert_before":return{title:`Insert before${c}${n}`,blockId:d,viewInEditor:!0};case"insert_after":return{title:`Insert after${c}${n}`,blockId:d,viewInEditor:!0};default:return{title:`Unknown action: ${e.action}`}}},Xs=e=>((e==null?void 0:e.heading)||(e==null?void 0:e.title)||"").toString().replace(/<[^>]+>/g,"").trim().toLowerCase(),Gs=(e,t)=>{if(!e||!t)return;let n=He.current[e]||[];n.includes(t)||(He.current[e]=[...n,t]),kt.current[t]=e},Qr=(e,t)=>{if(!e||!t)return;let n=He.current[e]||[];He.current[e]=n.filter(r=>r!==t),delete kt.current[t]},Yr=async()=>{if(C)try{let e=await fetch(`${wpAgenticWriter.apiUrl}/section-blocks/${C}`,{method:"GET",headers:{"X-WP-Nonce":wpAgenticWriter.nonce}});if(!e.ok)return;let t=await e.json();t&&t.sectionBlocks&&typeof t.sectionBlocks=="object"&&(He.current=t.sectionBlocks,kt.current={},Object.entries(t.sectionBlocks).forEach(([n,r])=>{Array.isArray(r)&&r.forEach(o=>{kt.current[o]=n})}))}catch{}},Vs=async e=>{if(!e||!C)return;let t=He.current[e]||[];try{await fetch(`${wpAgenticWriter.apiUrl}/section-blocks`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({postId:C,sessionId:z,sectionId:e,blockIds:t})})}catch{}},Gn=e=>{if(!e||!Array.isArray(e.sections))return e;let t=e.sections.map((n,r)=>{let o=(n==null?void 0:n.id)||`section-${r+1}`,a=(n==null?void 0:n.status)||"pending";return{...n,id:o,status:a}});return{...e,sections:t}},Zr=e=>{if(!e||!/(kode|coding|code|script|snippet|skrip)/i.test(e))return null;let r=V("core/block-editor").getBlocks().filter(i=>i.name==="core/code");if(r.length===0)return null;let o=new Set;if(r.forEach(i=>{let c=kt.current[i.clientId];c&&o.add(c)}),o.size===0)return null;let a=[];return o.forEach(i=>{(He.current[i]||[]).forEach(l=>{a.push(l)})}),[...new Set(a)]},eo=e=>{let t=Q.current;if(!t||!Array.isArray(t.sections)||!e)return null;let n=new Set(["dalam","poin","bagian","yang","dan","atau","untuk","dengan","ada","tidak","lebih","ini","itu","seperti","agar","akan","jadi","fokus","tulis","ulang","hapus","tambahkan","pembahasan","pada","berikan","gunakan","jelaskan","buat"]),r=e.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(i=>i.length>3&&!n.has(i));if(r.length===0)return null;let o=null,a=0;return t.sections.forEach(i=>{var d;let c=[i==null?void 0:i.heading,i==null?void 0:i.title,i==null?void 0:i.description,Array.isArray(i==null?void 0:i.content)&&i.content.length>0?(d=i.content[0])==null?void 0:d.content:""].filter(Boolean).join(" ").toLowerCase();if(!c)return;let l=0;r.forEach(g=>{c.includes(g)&&(l+=1)}),l>a&&(a=l,o=i)}),!o||a<2?null:o},Qs=(e,t)=>{e&&u(n=>{var o;let r=[...n];for(let a=r.length-1;a>=0;a--)if(r[a].type==="plan"&&((o=r[a].plan)!=null&&o.sections)){let i=r[a].plan.sections.map(l=>l.id===e?{...l,status:t}:l),c={...r[a].plan,sections:i};r[a]={...r[a],plan:c},Q.current=c;break}return r})},to=(e,t)=>{let n=V("core/block-editor").getBlocks();if(!e||!Array.isArray(e.sections)||!t)return n.length;let r=e.sections,o=r.findIndex(a=>a.id===t);if(o===-1)return n.length;for(let a=o+1;a<r.length;a++){let i=r[a];if(((i==null?void 0:i.status)||"pending")!=="done")continue;let l=Xs(i);if(!l)continue;let d=n.findIndex(g=>{var v;return g.name!=="core/heading"?!1:Xs({heading:(v=g.attributes)==null?void 0:v.content})===l});if(d!==-1)return d}return n.length},mn=()=>Ce!=="writing"||Q.current?!1:!(V("core/block-editor").getBlocks().length>0),no=async()=>{let e=J.filter(t=>t.role!=="system");if(e.length<4)return{summary:"",useFullHistory:!0,cost:0};try{let t=await fetch(wpAgenticWriter.apiUrl+"/summarize-context",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({chatHistory:e,postId:C,sessionId:z})});if(!t.ok)throw new Error("Summarization failed");let n=await t.json();return we(n),n.tokens_saved>0&&K.log(`Context optimized: ~${n.tokens_saved} tokens saved (~$${(n.tokens_saved*2e-7).toFixed(4)})`),{summary:n.summary||"",useFullHistory:n.use_full_history||!1,cost:n.cost||0,tokensSaved:n.tokens_saved||0}}catch(t){return K.error("Summarization error:",t),{summary:"",useFullHistory:!0,cost:0}}},so=async e=>{if(!e||e.trim().length===0)return{intent:"continue_chat",cost:0};try{let t=await fetch(wpAgenticWriter.apiUrl+"/detect-intent",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({lastMessage:e,hasPlan:!!Q.current,currentMode:Ce,postId:C,sessionId:z})});if(!t.ok){let r="Intent detection failed";try{let o=await t.json();r=(o==null?void 0:o.message)||r}catch{}throw new Error(r)}let n=await t.json();return we(n),{intent:n.intent||"continue_chat",cost:n.cost||0}}catch(t){return K.error("Intent detection error:",fe(t,"Intent detection failed")),{intent:"continue_chat",cost:0}}},Vo=async()=>{let e=await no();return e.useFullHistory?{type:"full",messages:J.filter(t=>t.role!=="system"),cost:0}:{type:"summary",summary:e.summary,cost:e.cost,tokensSaved:e.tokensSaved}},ro=async()=>{if(confirm("Clear all conversation history? This cannot be undone."))try{u([]),Q.current=null,await fetch(wpAgenticWriter.apiUrl+"/clear-context",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({postId:C})}),u([{role:"system",type:"info",content:"\u2705 Context cleared. Starting fresh conversation."}])}catch(e){K.error("Reset error:",e),u(t=>[...t,{role:"system",type:"error",content:"Failed to clear context. Please try again."}])}},Ct=(e,t={})=>{let{append:n=!1,suggestKeywords:r=Ce==="planning"}=t,o=Gn(e);Q.current=o,u(a=>{let i=[...a];if(!n){for(let c=i.length-1;c>=0;c--)if(i[c].type==="plan")return i[c]={...i[c],plan:o},i}return i.push({role:"assistant",type:"plan",plan:o}),i}),r&&o&&oo(o)},oo=async e=>{if(!(!e||!e.title||!e.sections))try{let t=await fetch(wpAgenticWriter.apiUrl+"/suggest-keywords",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({postId:C,sessionId:z,title:e.title,sections:e.sections})});if(!t.ok)throw new Error("Failed to suggest keywords");let n=await t.json();n.focus_keyword&&ge("seo_focus_keyword",n.focus_keyword),n.secondary_keywords&&Array.isArray(n.secondary_keywords)&&ge("seo_secondary_keywords",n.secondary_keywords.join(", ")),n.cost&&he({...te,session:te.session+n.cost}),we(n),u(r=>[...r,{role:"assistant",content:`\u{1F3AF} **SEO Keywords Suggested:**
**Focus Keyword:** ${n.focus_keyword}
**Secondary Keywords:** ${n.secondary_keywords.join(", ")}
${n.reasoning||""}
You can review and edit these in the Config panel before writing.`}])}catch(t){K.error("Keyword suggestion error:",t)}},ut=React.useCallback(()=>J.filter(e=>(e.role==="user"||e.role==="assistant")&&typeof e.content=="string"&&e.content.trim()).filter(e=>e.type!=="plan").map(e=>({role:e.role,content:e.content.trim().slice(0,2e3)})).slice(-10),[J]),ao=React.useCallback(()=>{for(let e=J.length-1;e>=0;e-=1){let t=J[e];if((t==null?void 0:t.role)==="user"&&typeof t.content=="string"&&t.content.trim())return t.content.trim()}return""},[J]),pn=e=>{if(Ce!=="planning")return!1;let t=String(e||"").toLowerCase();return t.includes("article generation complete")||t.includes("content has been added to your editor")||t.includes("article generated successfully")},Ys=(e=Q.current)=>{let t=Array.isArray(e==null?void 0:e.sections)?e.sections:[],n=t.filter(a=>a.status==="done").length,r=t.filter(a=>a.status==="in_progress").length,o=Math.max(0,t.length-n);return{total:t.length,done:n,inProgress:r,pending:o,label:t.length>0?`${n}/${t.length} written`:"No outline"}},je=(e=Q.current)=>{var t;return(e==null?void 0:e.id)||((t=e==null?void 0:e.meta)==null?void 0:t.id)||(e==null?void 0:e.title)||""},io=e=>{let t=String(e||"").toLowerCase(),n=/\b(?:out?line|plan|structure|kerangka|rencana)(?:\s*[- ]?\s*(?:nya|kan))?\b/i;return/@[a-z0-9-]/i.test(e)||Ks(zs(e))?"targeted_refinement":/\b(meta description|meta title|seo audit|seo score|keyword density|schema|faq)\b/i.test(t)?/\b(meta description|description)\b/i.test(t)?"generate_meta":"seo_audit":/\b(continue|resume|start writing|write article|write it|generate article|lanjut|tulis artikel|buat artikel)\b/i.test(t)?"write":n.test(t)?"outline":/\b(refine|rewrite|improve|polish|fix|ai-ish|aiish|slop|humanize|natural|tone|clarity|rapikan|perbaiki)\b/i.test(t)?"refine":"chat"},co=e=>{let t=io(e),n=Ys(),o=jt().length>0,a=!!(Q.current&&n.total>0);return t==="generate_meta"?{action:"generate_meta",mode:"seo",reason:"SEO meta request"}:t==="seo_audit"?{action:"seo_audit",mode:"seo",reason:"SEO analysis request"}:t==="targeted_refinement"?{action:"targeted_refinement",mode:"refinement",reason:"Block mention detected"}:t==="write"&&a&&n.pending>0?{action:"execute_plan",mode:"writing",reason:"Outline has pending sections"}:(t==="write"||t==="outline")&&!o?{action:"create_outline",mode:"planning",reason:"Fresh post needs outline first"}:t==="outline"?{action:a?"revise_outline":"create_outline",mode:"planning",reason:a?"Existing outline can be revised":"Outline requested"}:t==="refine"&&o?{action:"article_refinement",mode:"refinement",reason:"Content refinement requested"}:{action:"chat",mode:"chat",reason:"Conversation"}},Ft=async(e={})=>{var c,l,d,g,h,v,y,_,B;if(U)return;if(!Q.current){u(b=>[...b,{role:"system",type:"error",content:"No outline found yet. Ask the agent for an outline first, then it can continue into writing."}]),M(!1);return}let t=Q.current;if(V("core/block-editor").getBlocks().some(b=>{var S;return b.name!=="core/paragraph"||((S=b.attributes)==null?void 0:S.content)&&b.attributes.content.trim().length>0})&&!e.skipConfirm){let b=Array.isArray(t==null?void 0:t.sections)?t.sections.filter(x=>x.status!=="done").length:0;if(!window.confirm(`This will write ${b} sections into the editor. Existing content will be preserved below the new content.
Continue?`))return}if(xe("writing"),(Array.isArray(t==null?void 0:t.sections)?t.sections.filter(b=>b.status!=="done").length:null)===0){u(b=>[...oe(b),{role:"system",type:"timeline",status:"complete",message:"All outline items are already written.",timestamp:new Date}]),Fe({status:"completed",current_section_index:Array.isArray(t==null?void 0:t.sections)?t.sections.length:0,sections_written:Array.isArray(t==null?void 0:t.sections)?t.sections.map(b=>b.id||b.heading||"").filter(Boolean):[],plan_id:je(t),resume_token:""}),xe("chat");return}let{retry:a=!1}=e;$n.current={postId:C,sessionId:z,stream:!0,postConfig:I,detectedLanguage:en,chatHistory:J.filter(b=>b.role!=="system")},ue.current=!1,ot(!1);let i=Me("writing","writing");M(!0),Fe({status:"in_progress",current_section_index:0,sections_written:a?Ue.sections_written:[],plan_id:je(t),resume_token:""}),u(b=>[...oe(b),{role:"system",type:"timeline",status:"writing",message:a?"Retrying outline...":"Writing from outline...",timestamp:new Date}]),nn.current={},Qe.current=null;try{let b=await fetch(wpAgenticWriter.apiUrl+"/execute-article",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify($n.current),signal:i.signal});if(!b.ok){let G=await b.json();throw new Error(G.message||"Failed to execute outline")}let S=Ke(b.body.getReader()),x=new TextDecoder,$="",q=setTimeout(()=>{U&&(u(G=>[...G,{role:"system",type:"error",content:"Request timeout. The AI is taking too long to respond. Please try again."}]),Fe({status:"failed",plan_id:je(Q.current),resume_token:Qe.current||""}),M(!1),S.cancel())},12e4);for(;;){if(ue.current||i.signal.aborted){await S.cancel().catch(()=>{}),clearTimeout(q),ot(!0),M(!1);let f=Q.current,p=((c=f==null?void 0:f.sections)==null?void 0:c.filter(N=>N.status==="done").length)||0,m=((l=f==null?void 0:f.sections)==null?void 0:l.length)||0,k=m-p;Fe({status:"paused",current_section_index:p,sections_written:((d=f==null?void 0:f.sections)==null?void 0:d.filter(N=>N.status==="done").map(N=>N.id||N.heading||"").filter(Boolean))||[],plan_id:je(f),resume_token:Qe.current||""}),u(N=>[...oe(N),{role:"system",type:"timeline",status:"stopped",message:`\u23F8\uFE0F Execution stopped (${p}/${m} sections completed)`,timestamp:new Date},{role:"assistant",content:`**Execution Paused**
\u2705 Completed: ${p} section${p!==1?"s":""}
\u23F3 Pending: ${k} section${k!==1?"s":""}
Your generated content has been preserved in the editor.`,showResumeActions:!0,pendingCount:k}]);break}let{done:G,value:L}=await S.read();if(G)break;$+=x.decode(L,{stream:!0});let w=$.split(`
`);$=w.pop()||"";for(let f of w)if(f.startsWith("data: "))try{let p=JSON.parse(f.slice(6));if(p.type==="title_update")ie("core/editor").editPost({title:p.title});else if(p.type==="section_start"){Qe.current=p.sectionId||null;let m=to(Q.current,p.sectionId);p.sectionId&&(nn.current[p.sectionId]=m,He.current[p.sectionId]=He.current[p.sectionId]||[]),Qs(p.sectionId,"in_progress"),Fe({status:"in_progress",current_section_index:Number(p.index||0),plan_id:je(Q.current),resume_token:p.sectionId||""})}else if(p.type==="status"){if(p.status==="complete")continue;u(m=>{let k=[...m],N=Y(k);return N!==-1&&(k[N]={...k[N],status:p.status,message:p.message,icon:p.icon}),k})}else if(p.type==="block"){let{insertBlocks:m}=ie("core/block-editor"),k=Vn(p.block);if(k){let N=p.sectionId||Qe.current,Z=N?nn.current[N]:void 0;typeof Z=="number"?(m(k,Z),nn.current[N]=Z+1):m(k),N&&Gs(N,k.clientId)}}else if(p.type==="section_complete"){Qs(p.sectionId,"done"),Vs(p.sectionId);let m=Array.isArray((g=Q.current)==null?void 0:g.sections)?Q.current.sections.filter(k=>k.status==="done").map(k=>k.id||k.heading||"").filter(Boolean):[...new Set([...Ue.sections_written||[],p.sectionId].filter(Boolean))];if(Fe({status:"in_progress",current_section_index:m.length,sections_written:m,plan_id:je(Q.current),resume_token:""}),ue.current){await S.cancel().catch(()=>{}),clearTimeout(q),ot(!0),M(!1),Fe({status:"paused",current_section_index:m.length,sections_written:m,plan_id:je(Q.current),resume_token:p.sectionId||""}),u(k=>[...oe(k),{role:"system",type:"timeline",status:"stopped",message:"\u23F8\uFE0F Execution stopped by user",timestamp:new Date}]);break}}else if(p.type==="assistant_message")u(m=>[...m,{role:"assistant",content:p.message}]);else if(p.type==="complete")clearTimeout(q),p.totalCost&&he({...te,session:te.session+p.totalCost}),we(p),u(m=>{let k=[...m],N=Y(k);return N!==-1&&(k[N]={...k[N],status:"complete",message:"Article generated successfully!",completedAt:new Date}),k}),xe("chat"),Fe({status:"completed",current_section_index:Array.isArray((h=Q.current)==null?void 0:h.sections)?Q.current.sections.length:Ue.current_section_index,sections_written:Array.isArray((v=Q.current)==null?void 0:v.sections)?Q.current.sections.map(m=>m.id||m.heading||"").filter(Boolean):Ue.sections_written,plan_id:je(Q.current),resume_token:""}),M(!1);else if(p.type==="error")throw clearTimeout(q),new Error(p.message||"Failed to execute outline")}catch(p){K.error("Failed to parse streaming data:",f,p)}}clearTimeout(q),u(G=>G.some(w=>w.type==="timeline"&&w.status&&!["complete","inactive","stopped"].includes(w.status))?oe(G):G)}catch(b){if(Se(b)||ue.current){let S=Q.current,x=((y=S==null?void 0:S.sections)==null?void 0:y.filter(G=>G.status==="done").length)||0,$=((_=S==null?void 0:S.sections)==null?void 0:_.length)||0,q=$-x;Fe({status:"paused",current_section_index:x,sections_written:((B=S==null?void 0:S.sections)==null?void 0:B.filter(G=>G.status==="done").map(G=>G.id||G.heading||"").filter(Boolean))||[],plan_id:je(S),resume_token:Qe.current||""}),u(G=>[...oe(G),{role:"system",type:"timeline",status:"stopped",message:`Execution stopped (${x}/${$} sections completed)`,timestamp:new Date},{role:"assistant",content:`**Execution Paused**
Completed: ${x} section${x!==1?"s":""}
Pending: ${q} section${q!==1?"s":""}
Your generated content has been preserved in the editor.`,showResumeActions:!0,pendingCount:q}]);return}xe(Q.current?"planning":"chat"),Fe({status:"failed",plan_id:je(Q.current),resume_token:Qe.current||""}),u(S=>[...oe(S),{role:"system",type:"error",content:fe(b,"Failed to execute outline"),canRetry:!0,retryType:"execute"}])}finally{M(!1),ke("writing")}},lo=()=>{var e;!U&&!Ve&&!rt||(ue.current=!0,ot(!0),Br(),((e=sn.current)==null?void 0:e.type)==="writing"&&Fe({status:"paused",plan_id:je(Q.current),resume_token:Qe.current||""}),$t.current&&$t.current.cancel().catch(()=>{}),Tt.current&&!Tt.current.signal.aborted&&Tt.current.abort())},Qo=async()=>{if(!(U||!window.confirm("Start a new agent session for this post? The current session will stay available in Sessions.")))try{Ge(!0);let t=await fetch(wpAgenticWriter.apiUrl+"/conversations",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({post_id:C})});if(!t.ok)throw new Error("Failed to create a new conversation");let n=await t.json();n!=null&&n.session_id&&nt(n.session_id),await un(),u([]),Nt(!1),In([]),yt(0),Ne([]),ps(null),Rt(null),ve.current=null}catch(t){if(Se(t)||ue.current){u(n=>{let r=[...n],o=Y(r);return o!==-1&&(r[o]={...r[o],status:"stopped",message:"Refinement stopped by user."}),r}),u(n=>[...n,{role:"assistant",content:"Refinement stopped. Already-applied block changes remain in the editor and can be undone from the top bar."}]);return}u(n=>[...n,{role:"system",type:"error",content:"Error: Failed to start a new conversation."}])}finally{Ge(!1)}},Vn=e=>{if(!e||!e.blockName)return null;let t={...e.attrs||{}};if(e.blockName==="core/code"&&!t.content&&e.innerHTML){let n=e.innerHTML.match(/<code>([\s\S]*?)<\/code>/i);n&&n[1]&&(t.content=n[1].replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"'))}if(e.blockName==="core/table"&&e.innerHTML){let n=e.innerHTML.match(/<thead>([\s\S]*?)<\/thead>/i),r=e.innerHTML.match(/<tbody>([\s\S]*?)<\/tbody>/i);(n||r)&&(t.head=[],t.body=[],n&&(n[1].match(/<tr>([\s\S]*?)<\/tr>/gi)||[]).forEach(a=>{let i=[];(a.match(/<t[hd]>([\s\S]*?)<\/t[hd]>/gi)||[]).forEach(l=>{let d=l.replace(/<\/?t[hd]>/gi,"");i.push({content:d,tag:"th"})}),i.length>0&&t.head.push({cells:i})}),r&&(r[1].match(/<tr>([\s\S]*?)<\/tr>/gi)||[]).forEach(a=>{let i=[];(a.match(/<td>([\s\S]*?)<\/td>/gi)||[]).forEach(l=>{let d=l.replace(/<\/?td>/gi,"");i.push({content:d,tag:"td"})}),i.length>0&&t.body.push({cells:i})}))}if((e.blockName==="core/buttons"||e.blockName==="core/button")&&e.blockName==="core/button")return s.blocks.createBlock("core/buttons",{},[s.blocks.createBlock("core/button",t)]);if(e.innerBlocks&&e.innerBlocks.length>0){let n=e.innerBlocks.map(r=>Vn(r)).filter(Boolean);return s.blocks.createBlock(e.blockName,t,n)}return s.blocks.createBlock(e.blockName,t)},uo=async(e,t)=>{if(!U){if(!e||e.length===0){u(n=>[...n,{role:"system",type:"error",content:"No blocks found to reformat."}]);return}M(!0),u(n=>[...oe(n),{role:"system",type:"timeline",status:"refining",message:`Reformatting ${e.length} block(s)...`,timestamp:new Date}]);try{let n=await fetch(wpAgenticWriter.apiUrl+"/reformat-blocks",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({blocks:e,postId:C,sessionId:z})});if(!n.ok){let c=await n.json();throw new Error(c.message||"Failed to reformat blocks")}let r=await n.json();we(r);let o=r.results||[],{replaceBlocks:a}=ie("core/block-editor"),i=V("core/editor").getEditedPostAttribute("title")||"";o.forEach(c=>{let l=(c.blocks||[]).map(Vn).filter(Boolean);l.length>0&&a(c.clientId,l)}),u(c=>[...c,{role:"system",type:"timeline",status:"complete",message:`Reformatted ${o.length} block(s).`,timestamp:new Date,completedAt:new Date}]),r.recommended_title&&(u(c=>[...c,{role:"assistant",content:`Suggested title: ${r.recommended_title}`}]),(r.title_updated||!i)&&ie("core/editor").editPost({title:r.recommended_title}))}catch(n){u(r=>[...r,{role:"system",type:"error",content:"Error: "+(n.message||"Failed to reformat blocks")}])}finally{M(!1)}}},go=async e=>{if(U)return;let t=Q.current;if(!t){u(n=>[...n,{role:"system",type:"error",content:"No outline found to revise. Generate an outline first."}]);return}M(!0),u(n=>[...oe(n),{role:"system",type:"timeline",status:"planning",message:"Updating outline...",timestamp:new Date}]);try{let n=await fetch(wpAgenticWriter.apiUrl+"/revise-plan",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({instruction:e,plan:t,postId:C,sessionId:z,postConfig:I})});if(!n.ok){let o=await n.json();throw new Error(o.message||"Failed to revise outline")}let r=await n.json();r.plan&&Ct(r.plan,{append:!0}),r.cost&&he({...te,session:te.session+r.cost}),we(r),u(o=>{let a=[...o],i=Y(a);return i!==-1&&(a[i]={...a[i],status:"complete",message:"Outline updated.",completedAt:new Date}),a})}catch(n){u(r=>[...r,{role:"system",type:"error",content:"Error: "+(n.message||"Failed to revise outline")}])}finally{M(!1)}},fo=e=>{let t=fn(e);if(t.length===0){Rt(null);return}let{replaceBlocks:n,insertBlocks:r,removeBlocks:o,updateBlockAttributes:a}=ie("core/block-editor");tn.length>0&&(o(tn),Bn([])),Kn("Apply Edit Plan");let i=V("core/block-editor").getBlocks(),c=new Map(i.map((g,h)=>[g.clientId,h])),l={},d=new Set(i.map(g=>g.clientId));t.forEach(g=>{if(g.action!=="keep"&&!(g.blockId&&!d.has(g.blockId))){if(g.action==="delete"&&g.blockId){o(g.blockId);return}if(g.action==="change_type"&&g.blockId){let h=[].concat(_t(g));n(g.blockId,h);return}if(g.action==="replace"&&g.blockId){let h=[].concat(_t(g));n(g.blockId,h);return}if(g.action==="insert"||g.action==="insert_after"||g.action==="insert_before")if(g.blockId&&d.has(g.blockId)){let h=c.get(g.blockId),v=l[g.blockId]||{before:0,after:0},y;typeof h=="number"&&(g.action==="insert_before"?(y=h+v.before,v.before+=1):(y=h+v.before+1+v.after,v.after+=1)),l[g.blockId]=v;let _=[].concat(_t(g));r(_,y)}else{let h=[].concat(_t(g));r(h,i.length)}}}),Rt(null),u(g=>[...g,{role:"system",type:"timeline",status:"complete",message:"Changes applied."}])},mo=()=>{let{removeBlocks:e,updateBlockAttributes:t}=ie("core/block-editor"),n=V("core/block-editor").getBlocks();tn.length>0&&(e(tn),Bn([])),(It?fn(It):[]).forEach(o=>{if((o.action==="replace"||o.action==="delete")&&o.blockId){let a=n.find(i=>i.clientId===o.blockId);if(a&&a.attributes.className){let i=a.attributes.className.replace("wpaw-diff-removed","").trim();t(o.blockId,{className:i})}}}),Rt(null),u(o=>[...o,{role:"system",type:"timeline",status:"inactive",message:"Changes cancelled."}])},po=(e,t)=>{if(!e||e.length===0)return"";let n=[];return e.forEach(r=>{let o=t[r.id];o&&n.push(`- ${r.question||r.prompt||"Question"}: ${o}`)}),n.length===0?"":`
Clarification Answers:
${n.join(`
`)}`};React.useEffect(()=>{if(Zt&&Te.length>0&&Te[Ae]){let e=Te[Ae];if(e.type==="single_choice"&&e.options&&e.options.length>0&&!de[e.id]){let t={...de};t[e.id]=e.options[0].value,Ne(t)}}},[Ae,Te,Zt]);let Yo=e=>{var r;if(!e||e.length===0)return e;let t=[],n=null;for(let o of e){if(o.name==="core/heading"){let a=(((r=o.attributes)==null?void 0:r.content)||"").trim().toLowerCase();if(a===n){K.log("WP Agentic Writer: Removed duplicate heading:",o.attributes.content);continue}n=a}else n=null;t.push(o)}return t},jt=(e={})=>{let{textOnly:t=!1}=e,n=V("core/block-editor").getBlocks(),r=new Set(["core/paragraph","core/heading","core/list","core/quote","core/pullquote","core/code","core/preformatted","core/table"]);return n.filter(o=>{var c;if(!o.name||!o.name.startsWith("core/")||t&&!r.has(o.name))return!1;let a=((c=o.attributes)==null?void 0:c.content)||"",i=o.innerBlocks&&o.innerBlocks.length>0;return a.trim().length>0||i})},Zs=()=>{let e=V("core/block-editor").getBlocks(),t=[],n=0;return e.forEach(r=>{if(r.name!=="core/list")return;n+=1,(Array.isArray(r.innerBlocks)?r.innerBlocks:[]).forEach((a,i)=>{a.name==="core/list-item"&&t.push({block:a,parentId:r.clientId,listIndex:n,itemIndex:i})})}),t},ho=(e,t)=>Zs().find(r=>r.listIndex===e&&r.itemIndex===t),yo=e=>{let t=V("core/block-editor").getBlockParents;if(!t)return null;let n=t(e);for(let r of n){let o=V("core/block-editor").getBlock(r);if((o==null?void 0:o.name)==="core/list")return r}return null},ko=e=>{let t=e?V("core/block-editor").getBlock(e):null;if(!t)return"";let n=Pe(t);return n?n.trim():""},bo=e=>{let t=V("core/block-editor").getBlocks(),n=t.findIndex(r=>r.clientId===e);if(n===-1)return"";for(let r=n-1;r>=0;r-=1)if(t[r].name==="core/heading")return Pe(t[r])||"";return""},wo=(e,t=2)=>{let n=V("core/block-editor").getBlocks(),r=n.findIndex(a=>a.clientId===e);if(r===-1)return[];let o=[];for(let a=r-1;a>=0&&o.length<t;a-=1){if(n[a].name==="core/paragraph"){let i=Pe(n[a]);i&&o.push(i.trim())}if(n[a].name==="core/heading")break}return o.reverse()},vo=(e,t)=>{let n=Ut(e).filter(o=>o&&o!==t);return[...new Set(n)].map(o=>ko(o)).filter(o=>o)},So=e=>{if(!e||typeof e!="string")return[];let t=[],n=/"([^"]+)"|'([^']+)'/g,r;for(;(r=n.exec(e))!==null;){let o=(r[1]||r[2]||"").trim().toLowerCase();o&&o.length<=40&&t.push(o)}return[...new Set(t)]},Qn=()=>jt({textOnly:!0}),_o=e=>{let t=Qn(),n=So(e);if(!n.length)return t;let r=t.filter(o=>{let a=(Pe(o)||"").toLowerCase();return n.some(i=>a.includes(i))});return r.length>0?r:t},Ht=(e="")=>/\b(ai-ish|aiish|ai-style|ai style|slop|humanize|natural|robotic|generic|fluffy|formulaic|tone)\b/i.test(String(e)),er=e=>{let t=(Pe(e)||"").trim();if(!t)return[];let n=[];return[{label:"formulaic contrast phrase",pattern:/\b(bukan sekadar|not just)\b/i},{label:"template-like conclusion phrase",pattern:/\b(pada akhirnya|in conclusion|to summarize|in summary|kesimpulannya)\b/i},{label:"instructional/meta leakage",pattern:/\b(refined version|key refinements|changes made|rationale|could you please share)\b/i},{label:"dash-heavy sentence style",pattern:/\s[—–-]\s/u},{label:"generic AI phrase",pattern:/\b(delve|furthermore|moreover|crucial|paramount|landscape|testament|unlock|harness|leverage|seamless|robust)\b/i},{label:"generic marketing claim",pattern:/\b(in today's digital world|plays a vital role|it is important to note|when it comes to)\b/i}].forEach(o=>{o.pattern.test(t)&&n.push(o.label)}),e.name==="core/heading"&&/\b(introduction|conclusion|overview|benefits|key takeaways|final thoughts)\b/i.test(t)&&n.push("weak generic heading"),[...new Set(n)]},Yn=(e,t=Qn())=>{if(!Ht(e))return t;let n=t.map(r=>({block:r,findings:er(r)})).filter(r=>r.findings.length>0);return n.length>0?n.map(r=>r.block):[]},Co=(e,t)=>{let n=new Set(e);return t.filter((r,o)=>{if(n.has(r.clientId))return!0;let a=t[o+1],i=t[o-1];return(n.has(a==null?void 0:a.clientId)||n.has(i==null?void 0:i.clientId))&&r.name==="core/heading"})},xo=(e,t=[],n={})=>{let r=n.auditContext||null;if((r==null?void 0:r.source)==="seo_audit"){let h=Number(r.candidateBlockCount||t.length||0),v=ln(r),y=ze(h,"candidate block"),_=Number(r.refineableBlockCount||0)>h?` I am not sending the full article; I narrowed the scope from ${ze(r.refineableBlockCount,"refineable block")} to ${y}.`:"";return`Audit found ${v}. I mapped that audit signal to ${y} in the editor.${_} I will report changed blocks separately after verification.`}let o=/\b(introduction|conclusion|overview|benefits|key takeaways|final thoughts)\b/i,a=0,i=0,c=0;t.forEach(h=>{let y=(Pe({name:h.name,attributes:h.attributes||{},innerBlocks:h.innerBlocks||[]})||"").trim();y&&(h.name==="core/heading"&&(y.length<18||o.test(y))&&(i+=1),h.name==="core/paragraph"&&er(h).length>0&&(a+=1),y.split(/\s+/).length<14&&h.name!=="core/heading"&&(c+=1))});let l=[];a>0&&l.push(`${a} AI-ish paragraph${a===1?"":"s"}`),i>0&&l.push(`${i} weak heading${i===1?"":"s"}`),c>0&&l.push(`${c} thin block${c===1?"":"s"}`);let d=t.length===1?"1 block":`${t.length} blocks`,g=/\b(ai-ish|aiish|slop|humanize|natural)\b/i.test(e)?"tone and AI-slop cleanup":"the requested refinement";return l.length===0?`I inspected ${d}. I did not find obvious slop markers, so I will focus on ${g} while preserving structure.`:`I inspected ${d}. I found ${l.join(", ")}. I will focus the refinement on ${g} and keep the surrounding structure stable.`},Ut=e=>{let t=V("core/block-editor").getBlocks(),n=V("core/block-editor").getSelectedBlockClientId(),r=[],o=Zs();return e.forEach(a=>{let i=gn(a.replace("@","")),c=i.match(/^([a-z0-9-]+)-(\d+)$/i),l=i.match(/^(?:listitem|list-item|li)-(\d+)$/i),d=i.match(/^list-(\d+)\.list-item-(\d+)$/i);switch(i){case"this":n&&r.push(n);break;case"previous":if(n){let g=t.findIndex(h=>h.clientId===n);g>0&&r.push(t[g-1].clientId)}break;case"next":if(n){let g=t.findIndex(h=>h.clientId===n);g<t.length-1&&r.push(t[g+1].clientId)}break;case"all":Qn().forEach(g=>{r.push(g.clientId)});break;default:if(d){let g=parseInt(d[1],10),h=parseInt(d[2],10),v=ho(g,h);v&&r.push(v.block.clientId);break}if(l){let g=parseInt(l[1],10),h=g<=0?1:g,v=o[h-1];v&&r.push(v.block.clientId);break}if(c){let g="core/"+c[1],h=parseInt(c[2])-1,v=0;t.forEach(y=>{y.name===g&&(v===h&&r.push(y.clientId),v++)})}break}}),[...new Set(r)]},gt=async(e,t=null,n={})=>{let{skipUserMessage:r=!1,useDiffPlan:o=!0,auditContext:a=null}=n;Bt.current={message:e,blocksOverride:t,options:n},Kn("Block Refinement");let i=/@([a-z0-9-]+(?:-\d+)?|this|previous|next|all)/gi,l=[...e.matchAll(i)].map(w=>"@"+w[1]),d=t||Ut(l),g=l.some(w=>gn(w.replace("@",""))==="all"),h=d;if(g&&!t&&(h=(Ht(e)?Yn(e):_o(e)).map(f=>f.clientId),u(f=>[...f,{role:"system",type:"timeline",status:"inactive",message:`@all scope narrowed to ${h.length} likely block(s) based on the request.`,timestamp:new Date}])),h.length===0){u(w=>[...w,{role:"system",type:"error",content:"No valid blocks found to refine. Try @this, @previous, @next, @all, @paragraph-1, @listitem-3, or @list-3.list-item-0."}]),M(!1);return}if(g&&h.length>=hr&&!await Tr(h.length)){u(f=>[...f,{role:"system",type:"timeline",status:"inactive",message:`Cancelled @all refinement (${h.length} target blocks).`,timestamp:new Date}]),M(!1);return}let v=g?!1:o,y=g||Ht(e)&&h.length>1,_=w=>w?{clientId:w.clientId,name:w.name,attributes:w.attributes||{},innerBlocks:Array.isArray(w.innerBlocks)?w.innerBlocks.map(_).filter(Boolean):[]}:null,b=V("core/block-editor").getBlocks().map(_).filter(Boolean),S=h.map(w=>b.find(f=>f.clientId===w)).filter(Boolean),x=Co(h,b),$=xo(e,S,{auditContext:a}),q=(a==null?void 0:a.source)==="seo_audit",G=q?`${h.length} audit candidate block(s)`:`${h.length} block(s)`;r||u(w=>[...w,{role:"user",content:e}]),u(w=>[...oe(w),{role:"system",type:"timeline",status:"checking",message:q?"Reading editor and mapping audit findings to candidate blocks...":"Reading editor and inspecting target blocks...",timestamp:new Date},{role:"assistant",type:"agent_diagnosis",content:$},{role:"system",type:"timeline",status:"refining",message:q?`Processing ${G}; changed blocks will be verified after streaming...`:`Refining ${G}...`,timestamp:new Date}]),ls(!0),Cn(h);let L=Me("refinement","refinement");M(!0);try{let w=V("core/block-editor").getSelectedBlockClientId(),f=await fetch(wpAgenticWriter.apiUrl+"/refine-from-chat",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({topic:e,context:e,selectedBlockClientId:w,blocksToRefine:S,allBlocks:x,postId:C,sessionId:z,stream:!0,diffPlan:v,selectiveRefine:y,auditContext:q?a:null,postConfig:I,chatHistory:J.filter(ne=>ne.role!=="system")}),signal:L.signal});if(!f.ok){let ne=await f.json();throw new Error(ne.message||"Refinement failed")}ve.current=null;let p=Ke(f.body.getReader()),m=new TextDecoder,k="",N=0,Z=new Set,{replaceBlocks:_e}=ie("core/block-editor"),E=!1,se="";for(;;){if(ue.current||L.signal.aborted)throw await p.cancel().catch(()=>{}),new DOMException("Operation stopped by user","AbortError");let{done:ne,value:re}=await p.read();if(ne)break;k+=m.decode(re,{stream:!0});let H=k.split(`
`);k=H.pop()||"";for(let le of H){if(le.startsWith("data: "))try{let D=JSON.parse(le.slice(6));if(D.type==="error"){E=!0,se=D.message||"Refinement failed.";break}else if(D.type==="status")u(P=>{let A=[...P],O=Y(A);return O!==-1&&(A[O]={...A[O],message:D.message||A[O].message,timestamp:new Date}),A});else if(D.type==="edit_plan"){Rt(D.plan);let{insertBlocks:P,updateBlockAttributes:A}=ie("core/block-editor"),O=V("core/block-editor").getBlocks(),F=new Set(O.map(T=>T.clientId)),W=[],R=fn(D.plan),ee={};[...R].reverse().forEach(T=>{if(T.action==="replace"&&T.blockId&&F.has(T.blockId)){let j=O.find(X=>X.clientId===T.blockId);if(j){let X=j.attributes.className||"";X.includes("wpaw-diff-removed")||A(T.blockId,{className:(X?X+" ":"")+"wpaw-diff-removed"});let ce=[].concat(_t(T));ce.forEach(Ze=>{let ir=Ze.attributes.className||"";Ze.attributes.className=(ir?ir+" ":"")+"wpaw-diff-added",W.push(Ze.clientId)});let Xe=O.findIndex(Ze=>Ze.clientId===T.blockId);Xe!==-1&&P(ce,Xe+1)}}else if(T.action==="delete"&&T.blockId&&F.has(T.blockId)){let j=O.find(X=>X.clientId===T.blockId);if(j){let X=j.attributes.className||"";X.includes("wpaw-diff-removed")||A(T.blockId,{className:(X?X+" ":"")+"wpaw-diff-removed"})}}else if(T.action==="insert"||T.action==="insert_after"||T.action==="insert_before"){let j=[].concat(_t(T));if(j.forEach(X=>{let ce=X.attributes.className||"";X.attributes.className=(ce?ce+" ":"")+"wpaw-diff-added",W.push(X.clientId)}),T.blockId&&F.has(T.blockId)){let X=O.findIndex(ce=>ce.clientId===T.blockId);if(X!==-1){let ce=ee[T.blockId]||{before:0,after:0},Xe=X;T.action==="insert_before"?(Xe=X+ce.before,ce.before+=1):(Xe=X+ce.before+1+ce.after,ce.after+=1),ee[T.blockId]=ce,P(j,Xe)}}else P(j,O.length)}}),Bn(W),u(T=>[...T,{role:"system",type:"edit_plan",plan:D.plan}])}else if(D.type==="block"){let P=D.block;if(P.blockName&&P.attrs){let A;if(P.innerBlocks&&P.innerBlocks.length>0){let O=P.innerBlocks.map(F=>s.blocks.createBlock(F.blockName,F.attrs));A=s.blocks.createBlock(P.blockName,P.attrs,O)}else A=s.blocks.createBlock(P.blockName,P.attrs);if(A&&A.name){let O=kt.current[P.clientId];_e(P.clientId,A),Cn(F=>F.map(W=>W===P.clientId?A.clientId:W)),O&&(Qr(O,P.clientId),Gs(O,A.clientId),Z.add(O))}}N++}else D.type==="complete"&&(we(D),u(P=>{let A=[...P],O=Y(A);if(O!==-1){let F=Number(D.failed||0)>0?`, ${Number(D.failed)} failed`:"",W=ln(a),R=ze((a==null?void 0:a.candidateBlockCount)||h.length,"candidate block"),ee=ze(N,"changed block");A[O]={...A[O],status:D.aborted?"error":"complete",message:q?D.aborted?`Audit fix stopped early: ${W} -> ${R} inspected -> ${ee}${F}`:`Audit fix complete: ${W} -> ${R} inspected -> ${ee}${F}`:D.aborted?`Refinement stopped early: ${N} updated${F}`:`Refined ${N} block(s) successfully${F}`,timestamp:new Date}}return A}),u(P=>[...P,{role:"assistant",content:D.aborted?q?`Audit fix stopped early after provider errors.
- Audit signal: ${ln(a)}
- Candidate scope: ${ze((a==null?void 0:a.candidateBlockCount)||h.length,"candidate block")} inspected
- Editor changes: ${ze(N,"block")} changed${Number(D.failed||0)>0?`
- Failed attempts: ${Number(D.failed)}`:""}`:`\u26A0\uFE0F I stopped early after provider errors. Updated ${N} block(s)${Number(D.failed||0)>0?`, ${Number(D.failed)} failed`:""}.`:q?`Audit fix complete.
- Audit signal: ${ln(a)}
- Candidate scope: ${ze((a==null?void 0:a.candidateBlockCount)||h.length,"candidate block")} inspected
- Editor changes: ${ze(N,"block")} changed${Number(D.failed||0)>0?`
- Failed attempts: ${Number(D.failed)}`:""}
Verification: changed blocks were written back to the editor and can be undone from the top bar.`:`\u2705 Done! I've refined ${N} block(s) as requested${Number(D.failed||0)>0?`, with ${Number(D.failed)} failed attempts`:""}.
Verification: updated blocks were written back to the editor and can be undone from the top bar.`}]),D.totalCost&&he({...te,session:te.session+D.totalCost}),Z.forEach(P=>{Vs(P)}))}catch(D){K.error("Failed to parse streaming data:",le,D)}if(E)break}if(E)break}if(ue.current||L.signal.aborted)throw new DOMException("Operation stopped by user","AbortError");E&&(u(ne=>[...ne,{role:"system",type:"error",content:`Refinement stopped: ${se}`,canRetry:!0,retryType:"refine"}]),u(ne=>{let re=[...ne],H=Y(re);return H!==-1&&(re[H]={...re[H],status:"error",message:"Refinement stopped (edit plan failed)"}),re}))}catch(w){if(Se(w)||ue.current){u(f=>{let p=[...f],m=Y(p);return m!==-1&&(p[m]={...p[m],status:"stopped",message:"Refinement stopped by user."}),p}),u(f=>[...f,{role:"assistant",content:"Refinement stopped. Already-applied block changes remain in the editor and can be undone from the top bar."}]);return}u(f=>[...f,{role:"system",type:"error",content:"Error: "+w.message,canRetry:!0,retryType:"refine"}]),u(f=>{let p=[...f],m=Y(p);return m!==-1&&(p[m]={...p[m],status:"error",message:"Refinement failed"}),p})}finally{ls(!1),Cn([]),M(!1),ke("refinement")}},Ao=()=>Yt.isOpen?s.element.createElement("div",{className:"wpaw-refine-confirm-overlay",role:"dialog","aria-modal":"true","aria-label":"Confirm large @all refinement"},s.element.createElement("div",{className:"wpaw-refine-confirm-modal"},s.element.createElement("div",{className:"wpaw-refine-confirm-title"},"Confirm @all Refinement"),s.element.createElement("div",{className:"wpaw-refine-confirm-body"},`This will refine ${Yt.blockCount} text block(s) in batches of 5. This may take time and consume API credits.`),s.element.createElement(zt,{label:"Don\u2019t ask again for this session",checked:Yt.dontAskAgain,onChange:e=>{xn(t=>({...t,dontAskAgain:!!e}))}}),s.element.createElement("div",{className:"wpaw-refine-confirm-actions"},s.element.createElement(me,{isSecondary:!0,onClick:()=>Ts(!1)},"Cancel"),s.element.createElement(me,{isPrimary:!0,onClick:()=>{Yt.dontAskAgain&&(ds.current=!0),Ts(!0)}},"Continue")))):null,hn=e=>{let t=V("core/block-editor").getBlocks(),n=V("core/block-editor").getSelectedBlockClientId(),r=[];(!e||"this".includes(e.toLowerCase()))&&r.push({id:"this",label:"@this",sublabel:"Currently selected block",type:"special"}),(!e||"previous".includes(e.toLowerCase()))&&r.push({id:"previous",label:"@previous",sublabel:"Block before current selection",type:"special"}),(!e||"next".includes(e.toLowerCase()))&&r.push({id:"next",label:"@next",sublabel:"Block after current selection",type:"special"}),(!e||"all".includes(e.toLowerCase()))&&r.push({id:"all",label:"@all",sublabel:"All content blocks",type:"special"}),(!e||"title".includes(e.toLowerCase()))&&r.push({id:"title",label:"@title",sublabel:"Refine post title with instruction",type:"special"});let o={},a=e.toLowerCase(),i=0,c=0;return t.forEach(l=>{if(!l.name||!l.name.startsWith("core/"))return;let d=l.name.replace("core/","");o[d]=(o[d]||0)+1;let g=`@${d}-${o[d]}`,h=Pe(l),v=h.toLowerCase();if(!e||g.includes(a)||v.startsWith(a)){let y=h.length>40?h.substring(0,40)+"...":h;r.push({id:g,label:String(g),sublabel:y||String(d),type:"block",clientId:l.clientId})}l.name==="core/list"&&(c+=1,(Array.isArray(l.innerBlocks)?l.innerBlocks:[]).forEach((_,B)=>{if(_.name!=="core/list-item")return;i+=1;let b=`@listitem-${i}`,S=`@list-${c}.list-item-${B}`,x=Pe(_),$=x.toLowerCase();if(!e||b.includes(a)||S.includes(a)||$.startsWith(a)){let q=x.length>40?x.substring(0,40)+"...":x;r.push({id:b,label:String(S),sublabel:q?`List ${c}: ${q}`:`List ${c} item`,type:"list-item",clientId:_.clientId,parentClientId:l.clientId})}}))}),r};React.useEffect(()=>{let e=t=>{var r;let n=(r=t==null?void 0:t.detail)==null?void 0:r.token;n&&(et("chat"),pe(o=>`${o&&!/\s$/.test(o)?o+" ":o}${n}`),setTimeout(()=>{var i;let o=((i=ye.current)==null?void 0:i.textarea)||ye.current;o&&(o.focus(),o.selectionStart=o.selectionEnd=o.value.length);let a=hn("");bt(a),at(a.length>0)},0))};return window.addEventListener("wpaw:insert-mention",e),()=>window.removeEventListener("wpaw:insert-mention",e)},[hn]);let No=e=>{var i;pe(e);let t=((i=ye.current)==null?void 0:i.textarea)||ye.current,n=typeof(t==null?void 0:t.selectionStart)=="number"?t.selectionStart:e.length,r=e.substring(0,n),o=r.match(/@(\w*)$/),a=r.match(/\/([\w\s]*)$/);if(o){let c=o[1];ks(c);let l=hn(c);bt(l),at(l.length>0),on(0),Lt(!1),an([])}else if(a){let c=a[1];xr(c);let l=jr(c);an(l),Lt(l.length>0),Wn(0),at(!1),bt([])}else at(!1),bt([]),Lt(!1),an([])},Io=e=>{if(!Mt&&!Pt){e.keyCode===13&&(e.metaKey||e.ctrlKey)&&sr();return}Mt&&e.keyCode===40?(e.preventDefault(),on(t=>(t+1)%it.length)):Mt&&e.keyCode===38?(e.preventDefault(),on(t=>(t-1+it.length)%it.length)):Mt&&e.keyCode===13?(e.preventDefault(),it[Pn]&&tr(it[Pn])):Pt&&e.keyCode===40?(e.preventDefault(),Wn(t=>(t+1)%ct.length)):Pt&&e.keyCode===38?(e.preventDefault(),Wn(t=>(t-1+ct.length)%ct.length)):Pt&&e.keyCode===13?(e.preventDefault(),ct[Ln]&&nr(ct[Ln])):e.keyCode===27&&(e.preventDefault(),at(!1),Lt(!1))},tr=e=>{var d;let t=tt,n=((d=ye.current)==null?void 0:d.textarea)||ye.current,r=typeof(n==null?void 0:n.selectionStart)=="number"?n.selectionStart:t.length,a=t.substring(0,r).lastIndexOf("@"),i=t.substring(0,a),c=t.substring(r),l=i+e.label+" "+c;pe(l),at(!1),bt([]),setTimeout(()=>{ye.current&&ye.current.focus()},0)},nr=e=>{var d;let t=tt,n=((d=ye.current)==null?void 0:d.textarea)||ye.current,r=typeof(n==null?void 0:n.selectionStart)=="number"?n.selectionStart:t.length,a=t.substring(0,r).lastIndexOf("/"),i=t.substring(0,a),c=t.substring(r),l=i+e.insertText+c;if(pe(l),Lt(!1),an([]),e.insertText.endsWith("@")){let g=hn("");ks(""),bt(g),at(g.length>0),on(0)}setTimeout(()=>{ye.current&&ye.current.focus()},0)},sr=async()=>{var B,b,S,x,$,q,G,L,w,f,p,m,k,N,Z,_e;if(!tt.trim()||U)return;let e=tt.trim();if(On(!1),/^\s*(\/reset|\/clear)\s*$/i.test(e)){pe(""),await ro();return}let t=co(e),n=t.mode||Ce||"chat";if(["chat","planning","writing"].includes(n)&&n!==Ce&&xe(n),t.action==="execute_plan"){pe(""),u(E=>[...E,{role:"user",content:e}]),zn("checking","Checking outline and editor context..."),await Ft({skipConfirm:!0});return}if(t.action==="generate_meta"){pe(""),u(E=>[...E,{role:"user",content:e}]),zn("checking","Reading article and generating meta description..."),await Xn();return}if(t.action==="seo_audit"){pe(""),u(E=>[...E,{role:"user",content:e}]),zn("checking","Reading editor and running SEO audit..."),await Ls();return}let r=Fr(e),o=r?r.message:e,a=zs(o),i=a.length>0,c=Ks(a),l=jt(),d=n==="planning",g=n==="planning"?"Creating outline...":"Generating article...",h=/^\s*(?:\/)?reformat\b/i;if(r){M(!0),u(E=>[...oe(E),{role:"system",type:"timeline",status:"refining",message:"Preparing insertion...",timestamp:new Date}]),await zr(r.mode,o,a,e),M(!1);return}if(h.test(e)){pe(""),u(re=>[...re,{role:"user",content:e}]);let E=i?Ut(a):jt().map(re=>re.clientId),ne=V("core/block-editor").getBlocks().filter(re=>E.includes(re.clientId));await uo(ne,e);return}if(c){pe(""),await Js(e,a);return}if(n==="planning"&&!i&&Q.current){pe(""),u(E=>[...E,{role:"user",content:e}]),await go(e);return}if(n==="chat"&&!i){pe(""),u(se=>[...se,{role:"user",content:e}]);let E=Me("chat","chat response");M(!0),Mn.current={message:e};try{let se=J.filter(P=>P.role==="user"||P.role==="assistant").map(P=>({role:P.role,content:P.content})),ne=await fetch(wpAgenticWriter.apiUrl+"/chat",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({messages:[...se,{role:"user",content:e}],postId:C,sessionId:z,type:"chat",stream:!0,postConfig:I}),signal:E.signal});if(!ne.ok){let P=await ne.json();throw new Error(P.message||"Failed to chat")}let re=Ke(ne.body.getReader()),H=new TextDecoder,le="",D=null;for(ve.current=null;;){if(ue.current||E.signal.aborted)throw await re.cancel().catch(()=>{}),new DOMException("Operation stopped by user","AbortError");let{done:P,value:A}=await re.read();if(P)break;le+=H.decode(A,{stream:!0});let O=le.split(`
`);le=O.pop()||"";for(let F of O)if(F.startsWith("data: "))try{let W=JSON.parse(F.slice(6));if(W.type==="error"){D=new Error(W.message||"Failed to chat");break}if(W.type==="conversational"||W.type==="conversational_stream"){let R=(W.content||"").trim();if(!R)continue;let ee=ve.current||Dt(R);if(!ee)continue;ve.current=ee,W.type==="conversational"?u(T=>{let j=[...T],X=j.length-1,ce=j[X];return ce&&ce.role==="assistant"&&ce.content===R||j.push({role:"assistant",content:R}),j}):u(T=>{let j=[...T],X=j.length-1;return j[X]&&j[X].role==="assistant"?j[X]={...j[X],content:R}:j.push({role:"assistant",content:R}),j})}else W.type==="complete"&&(W.totalCost&&he({...te,session:te.session+W.totalCost}),we(W),u(R=>{let ee=R.filter(T=>T.role==="assistant").pop();if(ee&&ee.content){let T=Jn(ee.content);T.length>0&&Ms(T)}return R}))}catch(W){K.error("Failed to parse streaming data:",F,W)}if(D)throw D}try{let P=await so(e);P.cost>0&&he(A=>({...A,session:A.session+P.cost})),P.intent&&P.intent!=="continue_chat"&&u(A=>{let O=[...A],F=O.length-1;return O[F]&&O[F].role==="assistant"&&(O[F]={...O[F],detectedIntent:P.intent}),O})}catch(P){K.error("Intent detection failed:",fe(P,"Intent detection failed"))}}catch(se){if(Se(se))u(ne=>[...oe(ne),{role:"system",type:"timeline",status:"stopped",message:"Chat response stopped.",timestamp:new Date}]);else{let ne=fe(se,"Failed to chat");u(re=>[...re,{role:"system",type:"error",content:ne,canRetry:!0,retryType:"chat"}])}}M(!1),ke("chat");return}if(!i&&l.length>0&&t.action==="article_refinement"){let E=Zr(e),se=E?null:eo(e),ne=se?He.current[se.id]||[]:[];pe(""),u(H=>[...H,{role:"user",content:e}]),ne.length>0&&u(H=>[...H,{role:"assistant",content:`Targeting section: ${se.heading||se.title||"Selected section"} (${ne.length} block(s)).`}]),M(!0),u(H=>[...oe(H),{role:"system",type:"timeline",status:"checking",message:se?`Analyzing request (targeting: ${se.heading||se.title||"section"})...`:"Analyzing request...",timestamp:new Date}]);let re=Ht(e)?Yn(e,l).map(H=>H.clientId):l.map(H=>H.clientId);if(Ht(e)&&re.length===0&&!E&&ne.length===0){u(H=>[...oe(H),{role:"assistant",content:"I inspected the article and did not find blocks matching the AI-ish/slop detector, so I did not send the whole article to refinement."}]),M(!1);return}await gt(e,E&&E.length>0?E:ne.length>0?ne:re,{skipUserMessage:!0});return}if(!i){pe(""),u(H=>[...H,{role:"user",content:e}]);let E=n==="planning"?"planning":"generation",se=Me(E,n==="planning"?"outline generation":"article generation");M(!0),u(H=>[...oe(H),{role:"system",type:"timeline",status:"checking",message:"Analyzing request...",timestamp:new Date}]);let ne=en;try{let H=await fetch(wpAgenticWriter.apiUrl+"/check-clarity",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({topic:e,answers:[],postId:C,sessionId:z,mode:"generation",postConfig:I,chatHistory:ut()}),signal:se.signal});if(H.ok){let D=(await H.json()).result;if(D.detected_language&&(ne=D.detected_language,ms(D.detected_language)),!D.is_clear&&D.questions&&D.questions.length>0){In(D.questions),Nt(!0),yt(0),Ne([]),M(!1),u(P=>{let A=[...P],O=Y(A);return O!==-1&&(A[O]={...A[O],status:"waiting",message:"Waiting for clarification..."}),A}),ke(E);return}}}catch(H){if(Se(H)){u(le=>[...oe(le),{role:"system",type:"timeline",status:"stopped",message:"Generation stopped.",timestamp:new Date}]),M(!1),ke(E);return}K.warn("Clarity check failed, proceeding with generation:",H)}u(H=>{let le=[...H],D=Y(le);return D!==-1&&(le[D]={...le[D],status:"starting",message:g}),le});let re=null;try{let H=await fetch(wpAgenticWriter.apiUrl+"/generate-plan",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({topic:e,context:"",postId:C,sessionId:z,answers:[],autoExecute:n!=="planning",stream:!0,articleLength:I.article_length,detectedLanguage:ne,postConfig:I,chatHistory:ut()}),signal:se.signal});if(!H.ok){let P=await H.json();u(A=>[...A,{role:"system",type:"error",content:fe(P,"Failed to generate article"),canRetry:!0,retryType:"generation"}]),M(!1);return}ve.current=null;let le=Ke(H.body.getReader()),D=new TextDecoder;for(re=setTimeout(()=>{U&&(K.error("Generation timeout - no response received"),u(P=>[...P,{role:"system",type:"error",content:fe("cURL error 28: Operation timed out after 120000 milliseconds","Failed to generate article"),canRetry:!0,retryType:"generation"}]),M(!1),le.cancel())},12e4);;){if(ue.current||se.signal.aborted)throw await le.cancel().catch(()=>{}),new DOMException("Operation stopped by user","AbortError");let{done:P,value:A}=await le.read();if(P)break;let F=D.decode(A,{stream:!0}).split(`
`);for(let W of F){if(W.startsWith("data: "))try{let R=JSON.parse(W.slice(6));if(R.type==="plan")he({...te,session:te.session+R.cost}),d&&R.plan&&Ct(R.plan,{suggestKeywords:n==="planning"});else if(R.type==="title_update")ie("core/editor").editPost({title:R.title});else if(R.type==="status"){if(R.status==="complete")continue;u(ee=>{let T=[...ee],j=Y(T);return j!==-1&&(T[j]={...T[j],status:R.status,message:R.message,icon:R.icon}),T})}else if(R.type==="conversational"||R.type==="conversational_stream"){let ee=(R.content||"").replace(/~~~ARTICLE~+/g,"").replace(/~~~ARTICLE~~~[\r\n]*/g,"").trim();if(!ee||pn(ee))continue;let T=ve.current||Dt(ee);if(!T)continue;ve.current=T,T==="timeline"?cn(ee):R.type==="conversational"?u(j=>[...j,{role:"assistant",content:ee}]):u(j=>{let X=[...j],ce=X.length-1;return X[ce]&&X[ce].role==="assistant"?X[ce]={...X[ce],content:ee}:X.push({role:"assistant",content:ee}),X})}else if(R.type==="block"){let{insertBlocks:ee}=ie("core/block-editor"),T;if(R.block.blockName==="core/paragraph"){let j=((b=(B=R.block.innerHTML)==null?void 0:B.match(/<p>(.*?)<\/p>/))==null?void 0:b[1])||"";T=s.blocks.createBlock("core/paragraph",{content:j})}else if(R.block.blockName==="core/heading"){let j=((S=R.block.attrs)==null?void 0:S.level)||2,X=(($=(x=R.block.innerHTML)==null?void 0:x.match(/<h[1-6]>(.*?)<\/h[1-6]>/))==null?void 0:$[1])||"";T=s.blocks.createBlock("core/heading",{level:j,content:X})}else if(R.block.blockName==="core/list"){let j=(R.block.innerBlocks||[]).map(X=>{var Xe,Ze;let ce=((Ze=(Xe=X.innerHTML)==null?void 0:Xe.match(/<li>(.*?)<\/li>/))==null?void 0:Ze[1])||"";return s.blocks.createBlock("core/list-item",{content:ce})});T=s.blocks.createBlock("core/list",{...R.block.attrs||{},ordered:((q=R.block.attrs)==null?void 0:q.ordered)||!1},j)}else if(R.block.blockName==="core/quote"){let j=((L=(G=R.block.innerHTML)==null?void 0:G.match(/<p>(.*?)<\/p>/))==null?void 0:L[1])||"";T=s.blocks.createBlock("core/quote",{value:j})}else R.block.blockName==="core/image"&&(T=s.blocks.createBlock("core/image",R.block.attrs||{}));T&&ee(T)}else R.type==="complete"?(we(R),clearTimeout(re),he({...te,session:te.session+R.totalCost}),u(ee=>{let T=[...ee],j=Y(T);return j!==-1&&(T[j]={...T[j],status:"complete",message:n==="planning"?"Outline ready.":"Article generated successfully!"}),T}),M(!1)):R.type==="error"&&(clearTimeout(re),u(ee=>[...ee,{role:"system",type:"error",content:fe(R.message||"An error occurred during article generation","Failed to generate article"),canRetry:!0,retryType:"generation"}]),M(!1))}catch(R){K.error("Failed to parse streaming data:",W,R)}if(streamError)throw streamError}}clearTimeout(re)}catch(H){re&&clearTimeout(re),Se(H)?u(le=>[...oe(le),{role:"system",type:"timeline",status:"stopped",message:"Generation stopped.",timestamp:new Date}]):(K.error("Article generation error:",H),u(le=>[...le,{role:"system",type:"error",content:fe(H,"Failed to generate article"),canRetry:!0,retryType:"generation"}])),M(!1)}finally{ke(E)}return}let v=[];if(i&&(v=Ut(a)),i&&v.length===0){u(E=>[...E,{role:"system",type:"error",content:"No valid blocks found to refine. Select a block and use @this, or target an existing block like @paragraph-1."}]),M(!1);return}if(v.length>0){pe(""),await gt(e);return}if(l.length>0){if(e.includes("@")){u(E=>[...E,{role:"system",type:"error",content:"No valid blocks found to refine. Try @this, @previous, @next, @all, or @paragraph-1."}]),M(!1);return}pe(""),await gt(e,l.map(E=>E.clientId));return}pe(""),u(E=>[...E,{role:"user",content:e}]);let y=n==="planning"?"planning":"generation",_=Me(y,n==="planning"?"outline generation":"article generation");M(!0),u(E=>[...oe(E),{role:"system",type:"timeline",status:"starting",message:"Initializing...",timestamp:new Date}]);try{let E=await fetch(wpAgenticWriter.apiUrl+"/generate-plan",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({topic:e,context:"",postId:C,sessionId:z,answers:[],autoExecute:n!=="planning",stream:!0,articleLength:I.article_length,postConfig:I,chatHistory:ut()}),signal:_.signal});if(!E.ok){let re=await E.json();u(H=>[...H,{role:"system",type:"error",content:fe(re,"Failed to generate article"),canRetry:!0,retryType:"generation"}]),M(!1);return}let se=Ke(E.body.getReader()),ne=new TextDecoder;for(;;){if(ue.current||_.signal.aborted)throw await se.cancel().catch(()=>{}),new DOMException("Operation stopped by user","AbortError");let{done:re,value:H}=await se.read();if(re)break;let D=ne.decode(H,{stream:!0}).split(`
`);for(let P of D)if(P.startsWith("data: "))try{let A=JSON.parse(P.slice(6));if(A.type==="plan")he({...te,session:te.session+A.cost}),n==="planning"&&A.plan&&Ct(A.plan);else if(A.type==="title_update")ie("core/editor").editPost({title:A.title});else if(A.type==="status"){if(A.status==="complete")continue;u(O=>{let F=[...O],W=Y(F);return W!==-1&&(F[W]={...F[W],status:A.status,message:A.message,icon:A.icon}),F})}else if(A.type==="conversational"||A.type==="conversational_stream"){let O=(A.content||"").replace(/~~~ARTICLE~+/g,"").replace(/~~~ARTICLE~~~[\r\n]*/g,"").trim();if(!O||pn(O))continue;let F=ve.current||Dt(O);if(!F)continue;ve.current=F,F==="timeline"?cn(O):A.type==="conversational"?u(W=>[...W,{role:"assistant",content:O}]):u(W=>{let R=[...W],ee=R.length-1;return R[ee]&&R[ee].role==="assistant"?R[ee]={...R[ee],content:O}:R.push({role:"assistant",content:O}),R})}else if(A.type==="block"){let{insertBlocks:O}=ie("core/block-editor"),F;if(A.block.blockName==="core/paragraph"){let W=((f=(w=A.block.innerHTML)==null?void 0:w.match(/<p>(.*?)<\/p>/))==null?void 0:f[1])||"";F=s.blocks.createBlock("core/paragraph",{content:W})}else if(A.block.blockName==="core/heading"){let W=((p=A.block.attrs)==null?void 0:p.level)||2,R=((k=(m=A.block.innerHTML)==null?void 0:m.match(/<h[1-6]>(.*?)<\/h[1-6]>/))==null?void 0:k[1])||"";F=s.blocks.createBlock("core/heading",{level:W,content:R})}else if(A.block.blockName==="core/list"){let W=(A.block.innerBlocks||[]).map(R=>{var T,j;let ee=((j=(T=R.innerHTML)==null?void 0:T.match(/<li>(.*?)<\/li>/))==null?void 0:j[1])||"";return s.blocks.createBlock("core/list-item",{content:ee})});F=s.blocks.createBlock("core/list",{...A.block.attrs||{},ordered:((N=A.block.attrs)==null?void 0:N.ordered)||!1},W)}else if(A.block.blockName==="core/quote"){let W=((_e=(Z=A.block.innerHTML)==null?void 0:Z.match(/<p>(.*?)<\/p>/))==null?void 0:_e[1])||"";F=s.blocks.createBlock("core/quote",{value:W})}else if(A.block.blockName==="core/image")F=s.blocks.createBlock("core/image",A.block.attrs||{});else{let W=s.blocks.parse(A.block.innerHTML);F=W&&W.length>0?W[0]:null}F&&O(F)}else if(A.type==="complete")we(A),he({...te,session:te.session+A.totalCost}),u(O=>{let F=[...O],W=Y(F);return W!==-1&&(F[W]={...F[W],status:"complete",message:n==="planning"?"Outline ready.":"Article generation complete!"}),F}),n!=="planning"&&setTimeout(()=>{let F=V("core/block-editor").getBlocks().filter(W=>W.name==="core/image"&&W.attributes["data-agent-image-id"]);F.length>0&&window.dispatchEvent(new CustomEvent("wpaw:open-image-review-modal",{detail:{postId:C,sessionId:z,imageCount:F.length}}))},500);else if(A.type==="error")throw new Error(A.message)}catch(A){K.error("Failed to parse streaming data:",P,A)}}setTimeout(()=>{M(!1)},1500)}catch(E){Se(E)?u(se=>[...oe(se),{role:"system",type:"timeline",status:"stopped",message:"Generation stopped.",timestamp:new Date}]):u(se=>[...se,{role:"system",type:"error",content:"Error: "+E.message}]),M(!1)}finally{ke(y)}},rr=async()=>{var a,i,c,l,d,g,h,v;if(U)return;let e=Er(de);if(de.config_language){let y=de.config_language;y==="__custom__"&&de.config_language_custom&&(y=de.config_language_custom.toLowerCase().trim()),y&&y!=="__skipped__"&&ge("language",y)}if(de.config_all)try{let y=JSON.parse(de.config_all);y.web_search!==void 0&&ge("web_search",y.web_search),y.seo!==void 0&&ge("seo_enabled",y.seo),y.focus_keyword&&(ge("focus_keyword",y.focus_keyword),ge("seo_focus_keyword",y.focus_keyword)),y.secondary_keywords&&ge("seo_secondary_keywords",y.secondary_keywords)}catch(y){K.error("Failed to parse config answers:",y)}if(kr==="refinement"&&Rn){Nt(!1);let y=po(Te,de),_=`${Rn.message}${y}`,B=Rn.blocks||[];ps(null),br("generation"),await gt(_,B,{skipUserMessage:!0});return}let t=Ce||"chat",n=t==="planning"?"planning":"generation",r=Me(n,t==="planning"?"outline generation":"article generation");M(!0),Nt(!1),u(y=>[...oe(y),{role:"system",type:"timeline",status:"starting",message:t==="planning"?"Creating outline...":"Generating article...",timestamp:new Date}]);let o=null;try{let y=ao()||J.map(S=>typeof S.content=="string"?S.content:"").filter(Boolean).join(`
`),_=await fetch(wpAgenticWriter.apiUrl+"/generate-plan",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({topic:y,context:"",postId:C,sessionId:z,clarificationAnswers:de,autoExecute:t!=="planning",stream:!0,articleLength:e.article_length,detectedLanguage:en,postConfig:e,chatHistory:ut()}),signal:r.signal});if(!_.ok){let S=await _.json();u(x=>[...x,{role:"system",type:"error",content:fe(S,"Failed to generate plan"),canRetry:!0,retryType:"generation"}]),M(!1);return}ve.current=null;let B=Ke(_.body.getReader()),b=new TextDecoder;for(o=setTimeout(()=>{U&&(K.error("Generation timeout - no response received"),u(S=>[...S,{role:"system",type:"error",content:fe("cURL error 28: Operation timed out after 120000 milliseconds","Failed to generate plan"),canRetry:!0,retryType:"generation"}]),M(!1),B.cancel())},12e4);;){if(ue.current||r.signal.aborted)throw await B.cancel().catch(()=>{}),new DOMException("Operation stopped by user","AbortError");let{done:S,value:x}=await B.read();if(S)break;let q=b.decode(x,{stream:!0}).split(`
`);for(let G of q)if(G.startsWith("data: "))try{let L=JSON.parse(G.slice(6));if(L.type==="plan")he({...te,session:te.session+L.cost}),t==="planning"&&L.plan&&Ct(L.plan);else if(L.type==="title_update")ie("core/editor").editPost({title:L.title});else if(L.type==="status"){if(L.status==="complete")continue;u(w=>{let f=[...w],p=Y(f);return p!==-1&&(f[p]={...f[p],status:L.status,message:L.message,icon:L.icon}),f})}else if(L.type==="conversational"||L.type==="conversational_stream"){let w=(L.content||"").replace(/~~~ARTICLE~+/g,"").replace(/~~~ARTICLE~~~[\r\n]*/g,"").trim();if(!w||pn(w))continue;let f=ve.current||Dt(w);if(!f)continue;ve.current=f,f==="timeline"?cn(w):L.type==="conversational"?u(p=>[...p,{role:"assistant",content:w}]):u(p=>{let m=[...p],k=m.length-1;return m[k]&&m[k].role==="assistant"?m[k]={...m[k],content:w}:m.push({role:"assistant",content:w}),m})}else if(L.type==="block"){let{insertBlocks:w}=ie("core/block-editor"),f;if(L.block.blockName==="core/paragraph"){let p=((i=(a=L.block.innerHTML)==null?void 0:a.match(/<p>(.*?)<\/p>/))==null?void 0:i[1])||"";f=s.blocks.createBlock("core/paragraph",{content:p})}else if(L.block.blockName==="core/heading"){let p=((c=L.block.attrs)==null?void 0:c.level)||2,m=((d=(l=L.block.innerHTML)==null?void 0:l.match(/<h[1-6]>(.*?)<\/h[1-6]>/))==null?void 0:d[1])||"";f=s.blocks.createBlock("core/heading",{level:p,content:m})}else if(L.block.blockName==="core/list"){let p=(L.block.innerBlocks||[]).map(m=>{var N,Z;let k=((Z=(N=m.innerHTML)==null?void 0:N.match(/<li>(.*?)<\/li>/))==null?void 0:Z[1])||"";return s.blocks.createBlock("core/list-item",{content:k})});f=s.blocks.createBlock("core/list",{...L.block.attrs||{},ordered:((g=L.block.attrs)==null?void 0:g.ordered)||!1},p)}else if(L.block.blockName==="core/quote"){let p=((v=(h=L.block.innerHTML)==null?void 0:h.match(/<p>(.*?)<\/p>/))==null?void 0:v[1])||"";f=s.blocks.createBlock("core/quote",{value:p})}else L.block.blockName==="core/image"&&(f=s.blocks.createBlock("core/image",L.block.attrs||{}));f&&w(f)}else L.type==="complete"?(we(L),clearTimeout(o),he({...te,session:te.session+L.totalCost}),u(w=>{let f=[...w],p=Y(f);return p!==-1&&(f[p]={...f[p],status:"complete",message:t==="planning"?"Outline ready.":"Article generated successfully!"}),f}),M(!1)):L.type==="error"&&(clearTimeout(o),u(w=>[...w,{role:"system",type:"error",content:fe(L.message||"An error occurred during article generation","Failed to generate plan"),canRetry:!0,retryType:"generation"}]),M(!1))}catch(L){K.error("Failed to parse streaming data:",G,L)}clearTimeout(o)}}catch(y){o&&clearTimeout(o),Se(y)?u(_=>[...oe(_),{role:"system",type:"timeline",status:"stopped",message:"Generation stopped.",timestamp:new Date}]):(K.error("Article generation error:",y),u(_=>[..._,{role:"system",type:"error",content:fe(y,"Failed to generate article"),canRetry:!0,retryType:"generation"}])),M(!1)}finally{ke(n)}},Ro=()=>{if(!Zt||Te.length===0)return null;let e=Te[Ae],t=de[e.id]||"",n=()=>{let c=`${e.id}_custom`,l=de[c]||"",d=t==="__custom__";return s.element.createElement("div",{className:"wpaw-answer-options"},e.options.map((g,h)=>{let v=t===g.value;return s.element.createElement("label",{key:h},s.element.createElement("input",{type:"radio",name:e.id,checked:v,onChange:()=>{let y={...de};y[e.id]=g.value,Ne(y)}}),s.element.createElement("span",null,g.value))}),s.element.createElement("div",{className:"wpaw-custom-answer-wrapper",key:"custom"},s.element.createElement("label",null,s.element.createElement("input",{type:"radio",name:e.id,checked:d,onChange:()=>{let g={...de};g[e.id]="__custom__",Ne(g)}}),s.element.createElement("span",null,"Other (specify):")),d&&s.element.createElement("textarea",{className:"wpaw-custom-text-input",placeholder:"Type your answer here...",value:l,rows:3,onChange:g=>{let h={...de};h[c]=g.target.value,Ne(h)},autoFocus:!0,style:{resize:"vertical"}})))},r=()=>{let c=t?t.split(", "):[];return s.element.createElement("div",{className:"wpaw-answer-options"},e.options.map((l,d)=>{let g=c.includes(l.value);return s.element.createElement("label",{key:d},s.element.createElement("input",{type:"checkbox",checked:g,onChange:()=>{let h={...de},v=g?c.filter(y=>y!==l.value):[...c,l.value];h[e.id]=v.join(", "),Ne(h)}}),s.element.createElement("span",null,l.value))}))},o=()=>s.element.createElement("div",{className:"wpaw-answer-options"},s.element.createElement(es,{placeholder:e.placeholder||"Type your answer here...",value:t,onChange:c=>{let l={...de};l[e.id]=c,Ne(l)},rows:4,maxLength:e.max_length||500})),a=()=>{let c={};if(t)try{c=JSON.parse(t)}catch{c={}}let l=e.fields||[];if(l.forEach(d=>{c[d.id]===void 0&&d.default!==void 0&&(c[d.id]=d.default)}),!t&&Object.keys(c).length>0){let d={...de};d[e.id]=JSON.stringify(c),Ne(d)}return s.element.createElement("div",{className:"wpaw-config-form"},l.map((d,g)=>{let h=c[d.id]!==void 0?c[d.id]:d.default;return d.conditional&&!c[d.conditional]?null:s.element.createElement("div",{key:g,className:"wpaw-config-field"},d.type==="toggle"?s.element.createElement(React.Fragment,null,s.element.createElement("label",{className:"wpaw-config-label"},s.element.createElement("span",{className:"wpaw-config-label-text"},d.label),d.description&&s.element.createElement("span",{className:"wpaw-config-description"},d.description)),s.element.createElement("label",{className:"wpaw-config-toggle"},s.element.createElement("input",{type:"checkbox",checked:h||!1,onChange:y=>{let _={...c};_[d.id]=y.target.checked;let B={...de};B[e.id]=JSON.stringify(_),Ne(B)}}),s.element.createElement("span",{className:"wpaw-toggle-slider"}))):s.element.createElement(React.Fragment,null,s.element.createElement("label",{className:"wpaw-config-label"},s.element.createElement("span",{className:"wpaw-config-label-text"},d.label),d.description&&s.element.createElement("span",{className:"wpaw-config-description"},d.description)),s.element.createElement("input",{type:"text",className:"wpaw-config-text-input",placeholder:d.placeholder||"",value:h||"",maxLength:d.max_length||200,onChange:y=>{let _={...c};_[d.id]=y.target.value;let B={...de};B[e.id]=JSON.stringify(_),Ne(B)}})))}))},i;switch(e.type){case"single_choice":i=n();break;case"multiple_choice":i=r();break;case"open_text":i=o();break;case"config_form":i=a();break;default:i=n()}return s.element.createElement("div",{className:"wpaw-clarification-quiz dark-theme"},s.element.createElement("div",{className:"wpaw-quiz-header"},s.element.createElement("h3",null," Clarification Questions"),s.element.createElement("div",{className:"wpaw-progress-bar"},s.element.createElement("div",{className:"wpaw-progress-fill",style:{width:(Ae+1)/Te.length*100+"%"}})),s.element.createElement("span",null,`${Ae+1} of ${Te.length}`)),s.element.createElement("div",{className:"wpaw-question-card"},s.element.createElement("h4",null,e.question),i,s.element.createElement("div",{className:"wpaw-quiz-actions"},Ae>0&&s.element.createElement(me,{isSecondary:!0,onClick:()=>yt(Ae-1),disabled:U},"Previous"),s.element.createElement(me,{isSecondary:!0,onClick:()=>{let c={...de};c[e.id]="__skipped__",Ne(c),Ae===Te.length-1?rr():yt(Ae+1)},disabled:U},"Skip"),s.element.createElement(me,{isPrimary:!0,onClick:()=>{Ae===Te.length-1?rr():yt(Ae+1)},disabled:U||!t.trim()&&t!=="__custom__"},Ae===Te.length-1?"Finish":"Next"))))},Zo=async()=>{if(!(U||mt))try{Ge(!0);let e=await fetch(wpAgenticWriter.apiUrl+"/conversations",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({post_id:C||0})});if(!e.ok)throw new Error("Failed to create a new conversation");let t=await e.json();z&&(dn(),Hs(z)),Ie.current&&(clearTimeout(Ie.current),Ie.current=null),De.current=!0,t!=null&&t.session_id&&nt(t.session_id),wt.current=JSON.stringify([]),u([]),Q.current=null,xe("chat"),Ye(!1),vs([]),lt(""),is(null),As({restored:!1,summary:"",memories:[],preferences:[],systemMessage:""});let n=await un();t!=null&&t.session_id&&(ns(r=>r.some(o=>(o==null?void 0:o.session_id)===t.session_id)?r:[t,...r]),Wt(t.session_id).then(r=>{r&&Ot(t.session_id)})),setTimeout(()=>{De.current=!1,ye.current&&ye.current.focus()},50)}catch{u(t=>[...t,{role:"system",type:"error",content:"Error: Failed to start a new conversation."}])}finally{Ge(!1)}},Bo=async e=>{var t,n;if(!(!e||mt)&&window.confirm("Delete this session permanently?"))try{if(Ge(!0),!(await fetch(`${wpAgenticWriter.apiUrl}/conversations/${e}`,{method:"DELETE",headers:{"X-WP-Nonce":wpAgenticWriter.nonce}})).ok)throw new Error("Failed to delete session");let o=await un();if(z===e){let a=((t=o[0])==null?void 0:t.session_id)||"";nt(a),u(Array.isArray((n=o[0])==null?void 0:n.messages)?o[0].messages:[])}}catch{u(o=>[...o,{role:"system",type:"error",content:"Error: Failed to delete session."}])}finally{Ge(!1)}},or=(e,t)=>{if(e!=null&&e.title&&e.title.trim())return e.title.trim();let n=Array.isArray(e==null?void 0:e.messages)?e.messages.find(o=>(o==null?void 0:o.role)==="user"&&typeof(o==null?void 0:o.content)=="string"&&o.content.trim()):null;if(n!=null&&n.content)return n.content.trim().slice(0,56);let r=(e==null?void 0:e.updated_at)||(e==null?void 0:e.last_activity)||"";if(r){let o=new Date(r);if(!Number.isNaN(o.getTime()))return`Session ${t+1} - ${o.toLocaleDateString()}`}return`Session ${t+1}`},To=e=>{let t=String((e==null?void 0:e.status)||"active").toLowerCase();return t==="completed"?"Continuable":t==="archived"?"Archived":"Active"},ea=e=>{let t=Number((e==null?void 0:e.id)||0),n=String((e==null?void 0:e.session_id)||"-"),r=Number((e==null?void 0:e.post_id)||0),o=String((e==null?void 0:e.status)||"active"),a=String((e==null?void 0:e.post_status)||"").toLowerCase();return`id: ${t||"-"} | sid: ${n} | post_id: ${r} | post: ${r===0?"unassigned":a||"unknown"} | session: ${o}`},$o=()=>{let e=ft.length>0?ft[0]:null;return s.element.createElement("div",{className:"wpaw-welcome-screen"},s.element.createElement("div",{className:"wpaw-welcome-content"},s.element.createElement("span",{className:"wpaw-welcome-icon",dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"><path d="M12 5a3 3 0 1 0-5.997.125a4 4 0 0 0-2.526 5.77a4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M9 13a4.5 4.5 0 0 0 3-4M6.003 5.125A3 3 0 0 0 6.401 6.5m-2.924 4.396a4 4 0 0 1 .585-.396M6 18a4 4 0 0 1-1.967-.516M12 13h4m-4 5h6a2 2 0 0 1 2 2v1M12 8h8m-4 0V5a2 2 0 0 1 2-2"/><circle cx="16" cy="13" r=".5"/><circle cx="18" cy="3" r=".5"/><circle cx="20" cy="21" r=".5"/><circle cx="20" cy="8" r=".5"/></g></svg>'}}),s.element.createElement("h2",{className:"wpaw-welcome-title"},"Agentic Writer"),s.element.createElement("p",{className:"wpaw-welcome-subtitle"},"What are we writing today?"),e&&s.element.createElement("button",{className:"wpaw-welcome-pill",style:{width:"100%",marginBottom:"12px"},disabled:mt,onClick:()=>Us(e.session_id||"")},`\u21A9 Continue: ${or(e,0)}`),ft.length>1&&s.element.createElement("details",{style:{marginBottom:"12px",width:"100%"}},s.element.createElement("summary",{style:{fontSize:"12px",color:"#8b95a5",cursor:"pointer",marginBottom:"8px"}},`${ft.length-1} more session${ft.length>2?"s":""}`),s.element.createElement("div",{className:"wpaw-session-list"},ft.slice(1).map((t,n)=>{var r;return s.element.createElement("div",{key:t.session_id||n,className:"wpaw-welcome-pill",style:{width:"100%",marginBottom:"6px",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px"}},s.element.createElement("button",{type:"button",disabled:mt,className:"wpaw-session-open-btn",style:{flex:1,background:"transparent",border:"none",color:"inherit",textAlign:"left",cursor:mt?"wait":"pointer"},onClick:()=>Us(t.session_id||"")},s.element.createElement("div",null,or(t,n+1)),s.element.createElement("div",{style:{opacity:.7,fontSize:"11px"}},`${Number((r=t==null?void 0:t.message_count)!=null?r:Array.isArray(t==null?void 0:t.messages)?t.messages.length:0)} msgs \xB7 ${To(t)}`)),s.element.createElement("button",{type:"button",title:"Delete session",disabled:mt,style:{background:"transparent",border:"1px solid rgba(255,255,255,0.25)",color:"inherit",borderRadius:"6px",padding:"2px 6px",cursor:"pointer"},onClick:()=>Bo(t.session_id)},"\xD7"))}))),s.element.createElement("input",{type:"text",className:"wpaw-welcome-input",placeholder:"Focus keyword (optional)",value:Dn,onChange:t=>Nr(t.target.value),onKeyDown:t=>{t.key==="Enter"&&Ps()}}),s.element.createElement("div",{className:"wpaw-welcome-pills"},s.element.createElement("button",{className:"wpaw-welcome-pill"+(Fn==="chat"?" active":""),onClick:()=>_s("chat")},"Explore First"),s.element.createElement("button",{className:"wpaw-welcome-pill"+(Fn==="planning"?" active":""),onClick:()=>_s("planning")},"Start Outline")),s.element.createElement(me,{isPrimary:!0,onClick:Ps,className:"wpaw-welcome-start-btn"},"Start Writing")))},Eo=()=>s.element.createElement("div",{className:"wpaw-writing-empty-state"},s.element.createElement("div",{className:"wpaw-empty-state-content"},s.element.createElement("span",{className:"wpaw-empty-state-icon",dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" style="width: 60px; height: 60px;"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"><path d="M12 5a3 3 0 1 0-5.997.125a4 4 0 0 0-2.526 5.77a4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M9 13a4.5 4.5 0 0 0 3-4M6.003 5.125A3 3 0 0 0 6.401 6.5m-2.924 4.396a4 4 0 0 1 .585-.396M6 18a4 4 0 0 1-1.967-.516M12 13h4m-4 5h6a2 2 0 0 1 2 2v1M12 8h8m-4 0V5a2 2 0 0 1 2-2"/><circle cx="16" cy="13" r=".5"/><circle cx="18" cy="3" r=".5"/><circle cx="20" cy="21" r=".5"/><circle cx="20" cy="8" r=".5"/></g></svg>'}}),s.element.createElement("h3",null,"Create an Outline First"),s.element.createElement("p",null,"Before writing, the agent needs an outline to structure the article and keep costs predictable. Ask for the article topic and the agent will create one first."),s.element.createElement(me,{isPrimary:!0,onClick:()=>xe("planning"),className:"wpaw-empty-state-button"},s.element.createElement("div",{style:{display:"inline-flex",alignItems:"center",gap:"8px"}},s.element.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"0 0 24 24"},s.element.createElement("path",{fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1",d:"M16 5H3m13 7H3m8 7H3m12-1l2 2l4-4"})),"Create Outline")),s.element.createElement("p",{className:"wpaw-empty-state-hint",style:{marginTop:"16px",fontSize:"13px",color:"#a7aaad"}},"Tip: tell the agent what you want to publish, then approve or adjust the outline before writing."))),ta=()=>{let e=Ee&&Ee.length>0;return bs?s.element.createElement("div",{className:"wpaw-focus-keyword-bar wpaw-expanded"},s.element.createElement("div",{className:"wpaw-fk-header"},s.element.createElement("span",null,"\u{1F3AF} FOCUS KEYWORD"),s.element.createElement("button",{className:"wpaw-fk-collapse",onClick:()=>On(!1),title:"Collapse"},"\u2193")),s.element.createElement("div",{className:"wpaw-fk-main-input"},s.element.createElement("input",{type:"text",className:"wpaw-fk-custom-input",placeholder:e?"Edit focus keyword...":"Enter focus keyword...",value:Ee||"",onChange:t=>{let n=t.target.value;lt(n)},onBlur:t=>{t.target.value!==I.focus_keyword&&Je(t.target.value)},onKeyDown:t=>{t.key==="Enter"&&t.target.value.trim()&&(Je(t.target.value.trim()),t.target.blur())}})),ws.length>0&&s.element.createElement("div",{className:"wpaw-fk-suggestions"},s.element.createElement("div",{className:"wpaw-fk-suggestions-label"},"\u{1F4DD} AI Suggestions:"),ws.map((t,n)=>s.element.createElement("div",{key:n,className:"wpaw-fk-suggestion-item"+(t===Ee?" selected":""),onClick:()=>Je(t)},s.element.createElement("span",{className:"wpaw-fk-radio"},t===Ee?"\u25CF":"\u25CB"),s.element.createElement("span",{className:"wpaw-fk-suggestion-text"},t),s.element.createElement("span",{className:"wpaw-fk-suggestion-source"},`(#${n+1})`)))),s.element.createElement("div",{className:"wpaw-fk-stats"},s.element.createElement("span",null,`\u{1F4B0} $${(te.session||0).toFixed(4)}`),be&&s.element.createElement("span",{className:"wpaw-provider-info",title:be.warnings.length>0?be.warnings.join("; "):"AI provider used"},be.fallbackUsed?" \u26A0\uFE0F "+(be.provider||"fallback"):" \u{1F4E1} "+(be.provider||"AI")),s.element.createElement("span",{className:"wpaw-fk-divider"},"\u2502"),s.element.createElement("span",null,`\u{1F4CA} ~${J.filter(t=>t.role!=="system").length*500} tokens`))):s.element.createElement("div",{className:"wpaw-focus-keyword-bar wpaw-compact"},s.element.createElement("div",{className:"wpaw-fk-left"},s.element.createElement("span",{className:"wpaw-fk-icon"},"\u{1F3AF}"),s.element.createElement("input",{type:"text",className:"wpaw-fk-input",placeholder:"Enter focus keyword...",value:Ee||"",onChange:t=>{let n=t.target.value;lt(n),We.current&&clearTimeout(We.current),We.current=setTimeout(()=>{Je(n)},500)},onBlur:t=>{t.target.value!==I.focus_keyword&&Je(t.target.value)},disabled:U})),s.element.createElement("span",{className:"wpaw-fk-cost"},`$${(te.session||0).toFixed(4)}`,be&&s.element.createElement("span",{className:"wpaw-provider-badge",title:be.warnings.length>0?be.warnings.join("; "):"AI provider"},be.fallbackUsed?"\u26A0":"\u{1F4E1}")),s.element.createElement("button",{className:"wpaw-fk-expand",onClick:()=>On(!0),title:"Expand"},s.element.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24"},s.element.createElement("path",{fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"m7 15l5 5l5-5M7 9l5-5l5 5"}))))},Mo=()=>{let e=Ys(),t=J.filter(c=>c.role==="user"||c.role==="assistant").length,n=be!=null&&be.provider?`${be.provider}${be.model?` / ${be.model}`:""}`:"Provider not used yet",r=$e.status&&$e.status!=="idle"?$e.status:Ue.status||"idle",o=$e.status&&$e.status!=="idle"?`${$e.status==="stopping"?"Stopping":"Running"} ${$e.label||$e.type}`:vr?"Loading...":String(Ue.status||"idle").replace(/_/g," "),a=!U&&Q.current&&["in_progress","paused","failed"].includes(Ue.status),i=Et.selectedBlockPreview?`: ${Et.selectedBlockPreview}`:"";return s.element.createElement("div",{className:`wpaw-agent-workspace-card${rn?" is-collapsed":""}`},s.element.createElement("div",{className:"wpaw-agent-workspace-header"},s.element.createElement("div",{className:"wpaw-agent-workspace-heading"},s.element.createElement("div",{className:"wpaw-agent-workspace-kicker"},"Agent Workspace"),s.element.createElement("div",{className:"wpaw-agent-workspace-title"},Et.title||"Untitled draft")),s.element.createElement("div",{className:"wpaw-agent-workspace-actions"},s.element.createElement("span",{className:`wpaw-agent-workspace-status status-${r}`},o))),!rn&&s.element.createElement("div",{className:"wpaw-agent-context-grid"},s.element.createElement("div",{className:"wpaw-agent-context-item"},s.element.createElement("span",null,"Post blocks"),s.element.createElement("strong",null,String(Et.blockCount||0))),s.element.createElement("div",{className:"wpaw-agent-context-item"},s.element.createElement("span",null,"Outline"),s.element.createElement("strong",null,e.label)),s.element.createElement("div",{className:"wpaw-agent-context-item"},s.element.createElement("span",null,"Selected"),s.element.createElement("strong",null,`${Et.selectedBlockLabel}${i}`)),s.element.createElement("div",{className:"wpaw-agent-context-item"},s.element.createElement("span",null,"Focus keyword"),s.element.createElement("input",{type:"text",className:"wpaw-agent-keyword-input",placeholder:"Optional",value:Ee||"",onChange:c=>{let l=c.target.value;lt(l),We.current&&clearTimeout(We.current),We.current=setTimeout(()=>{Je(l)},500)},onBlur:c=>{c.target.value!==I.focus_keyword&&Je(c.target.value)},disabled:U})),s.element.createElement("div",{className:"wpaw-agent-context-item"},s.element.createElement("span",null,"Conversation"),s.element.createElement("strong",null,`${t} message${t===1?"":"s"}`)),s.element.createElement("div",{className:"wpaw-agent-context-item"},s.element.createElement("span",null,"Provider"),s.element.createElement("strong",null,n))),!rn&&a&&s.element.createElement("div",{className:"wpaw-agent-resume-card"},s.element.createElement("div",null,s.element.createElement("strong",null,Ue.status==="failed"?"Writing can be retried":"Writing can resume"),s.element.createElement("span",null,`Last saved section: ${Ue.current_section_index||0}`)),s.element.createElement(me,{isPrimary:!0,isSmall:!0,onClick:()=>Ft({retry:!0,skipConfirm:!0})},Ue.status==="failed"?"Retry":"Resume")))},Po=e=>{if(!e||e==="continue_chat")return null;let n={create_outline:{icon:"\u{1F4DD}",title:"Ready to create an outline?",description:"I'll generate a structured outline based on our conversation.",button:"Create Outline Now",onClick:async()=>{xe("planning");let r=Ee||I.focus_keyword||I.seo_focus_keyword,o=J.find(l=>l.role==="user"),a=r||(o?o.content.substring(0,100):"");pe(""),M(!0),u(l=>[...oe(l),{role:"system",type:"timeline",status:"checking",message:"Analyzing request...",timestamp:new Date}]);let i=en,c=Me("planning","outline generation");try{K.log("[WPAW] Calling clarity check with topic:",a);let l=await fetch(wpAgenticWriter.apiUrl+"/check-clarity",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({topic:a||"article outline",answers:[],postId:C,sessionId:z,mode:"generation",postConfig:I,chatHistory:ut()}),signal:c.signal});if(K.log("[WPAW] Clarity response status:",l.status),!l.ok){let h=await l.text();throw K.error("[WPAW] Clarity check failed:",h),new Error("Clarity check failed: "+h)}let d=await l.json();we(d);let g=d.result;if(K.log("[WPAW] Clarity result:",g),g.detected_language&&(i=g.detected_language,ms(g.detected_language)),g.questions&&g.questions.length>0){K.log("[WPAW] Showing quiz with",g.questions.length,"questions"),In(g.questions),Nt(!0),yt(0),Ne([]),M(!1),u(h=>{let v=[...h],y=Y(v);return y!==-1&&(v[y]={...v[y],status:"waiting",message:"Waiting for clarification..."}),v}),ke("planning");return}else K.warn("[WPAW] No questions returned from clarity check!")}catch(l){K.error("[WPAW] Clarity check error:",l),Se(l)||ue.current||c.signal.aborted?u(d=>[...oe(d),{role:"system",type:"timeline",status:"stopped",message:"Outline generation stopped by user.",timestamp:new Date}]):u(d=>[...d,{role:"system",type:"error",content:"Clarity check failed. Please try again.",canRetry:!0}]),M(!1),ke("planning");return}u(l=>{let d=[...l],g=Y(d);return g!==-1&&(d[g]={...d[g],status:"starting",message:"Creating outline..."}),d});try{let l=await fetch(wpAgenticWriter.apiUrl+"/generate-plan",{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":wpAgenticWriter.nonce},body:JSON.stringify({topic:a||"article outline",context:"",postId:C,sessionId:z,answers:[],autoExecute:!1,stream:!0,articleLength:I.article_length,detectedLanguage:i,postConfig:I,chatHistory:ut()}),signal:c.signal});if(!l.ok){let h=await l.json();u(v=>[...v,{role:"system",type:"error",content:fe(h,"Failed to generate outline"),canRetry:!0,retryType:"generation"}]),M(!1),ke("planning");return}ve.current=null;let d=Ke(l.body.getReader()),g=new TextDecoder;for(;;){if(ue.current||c.signal.aborted)throw new DOMException("Outline generation stopped","AbortError");let{done:h,value:v}=await d.read();if(h)break;let _=g.decode(v,{stream:!0}).split(`
`);for(let B of _)if(B.startsWith("data: "))try{let b=JSON.parse(B.slice(6));if(b.type==="plan")he(S=>({...S,session:S.session+(b.cost||0)})),b.plan&&Ct(b.plan,{suggestKeywords:!0});else if(b.type==="status"){if(b.status==="complete")continue;u(S=>{let x=[...S],$=Y(x);return $!==-1&&(x[$]={...x[$],status:b.status,message:b.message,icon:b.icon}),x})}}catch(b){K.error("Failed to parse streaming data:",b)}}if(ue.current||c.signal.aborted)throw new DOMException("Outline generation stopped","AbortError");M(!1),ke("planning")}catch(l){Se(l)||ue.current||c.signal.aborted?u(d=>[...oe(d),{role:"system",type:"timeline",status:"stopped",message:"Outline generation stopped by user.",timestamp:new Date}]):u(d=>[...d,{role:"system",type:"error",content:fe(l,"Failed to generate outline"),canRetry:!0,retryType:"generation"}]),M(!1),ke("planning")}}}}[e];return n?s.element.createElement("div",{className:"wpaw-contextual-action"},s.element.createElement("div",{className:"wpaw-action-icon"},n.icon),s.element.createElement("div",{className:"wpaw-action-content"},s.element.createElement("h4",null,n.title),s.element.createElement("p",null,n.description),s.element.createElement(me,{isPrimary:!0,onClick:n.onClick},n.button))):null},Lo=()=>{let e=l=>l==null?"":typeof l=="string"||typeof l=="number"?String(l):JSON.stringify(l),t=l=>String(l).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),n=l=>{let d=t(l);return d=d.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(g,h,v)=>`<a href="${t(v)}" target="_blank" rel="noopener noreferrer">${h}</a>`),d=d.replace(/`([^`]+)`/g,(g,h)=>`<code>${t(h)}</code>`),d=d.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),d=d.replace(/__([^_]+)__/g,"<strong>$1</strong>"),d=d.replace(/\*([^*]+)\*/g,"<em>$1</em>"),d=d.replace(/_([^_]+)_/g,"<em>$1</em>"),d},r=l=>{let d=e(l);if(!d)return"";if(window.markdownit&&window.DOMPurify){if(!En.current){let f=window.markdownit({html:!1,linkify:!0,breaks:!1});window.markdownitTaskLists&&f.use(window.markdownitTaskLists,{enabled:!0,label:!0,labelAfter:!0});let p=f.renderer.rules.link_open||function(m,k,N,Z,_e){return _e.renderToken(m,k,N)};f.renderer.rules.link_open=function(m,k,N,Z,_e){let E=m[k],se=E.attrIndex("target");se<0?E.attrPush(["target","_blank"]):E.attrs[se][1]="_blank";let ne=E.attrIndex("rel");return ne<0?E.attrPush(["rel","noopener noreferrer"]):E.attrs[ne][1]="noopener noreferrer",p(m,k,N,Z,_e)},En.current=f}let w=En.current.render(d);return window.DOMPurify.sanitize(w,{USE_PROFILES:{html:!0},ADD_TAGS:["input","label"],ADD_ATTR:["type","checked","disabled","class"]})}let g=[],v=d.replace(/```(\w+)?\n([\s\S]*?)```/g,(w,f,p)=>{let m=f?` class="language-${t(f)}"`:"",k=g.length;return g.push(`<pre><code${m}>${t(p)}</code></pre>`),`@@CODEBLOCK${k}@@`}).split(/\r?\n/),y="",_=[],B=null,b=!1,S=!1,x=()=>{_.length&&(y+=`<p>${n(_.join(" "))}</p>`,_=[])},$=()=>{if(B){let w=B.items.map(f=>{let p=f.details&&f.details.length>0?f.details.map(k=>`<p>${n(k)}</p>`).join(""):"",m=f.children&&f.children.length>0?`<ul>${f.children.map(k=>`<li>${n(k)}</li>`).join("")}</ul>`:"";return`<li>${n(f.content)}${p}${m}</li>`}).join("");y+=`<${B.type}>${w}</${B.type}>`,B=null}},q=(w,f)=>{w.items.push({content:f,children:[],details:[]}),S=!0},G=(w,f,p)=>{let m=w.items[w.items.length-1];m&&(p||m.details.length===0?m.details.push(f):m.details[m.details.length-1]+=` ${f}`,S=!1)},L=w=>/^\d+\.\s+/.test(w)?"ol":/^[-*+]\s+/.test(w)?"ul":null;for(let w=0;w<v.length;w++){let f=v[w].trim();if(f===""){let N=w+1;for(;N<v.length&&v[N].trim()==="";)N+=1;let Z=N<v.length?v[N].trim():"",_e=L(Z);if(B&&_e&&_e===B.type)continue;if(B&&B.type==="ol"&&Z&&!_e&&!Z.startsWith("@@CODEBLOCK")&&!/^(#{1,6})\s+/.test(Z)){b=!0,S=!1;continue}$(),x(),S=!1;continue}if(f.startsWith("@@CODEBLOCK")){$(),x(),y+=f,S=!1;continue}let p=f.match(/^(#{1,6})\s+(.*)$/);if(p){$(),x();let N=p[1].length;y+=`<h${N}>${n(p[2])}</h${N}>`,S=!1;continue}let m=f.match(/^[-*+]\s+(.*)$/),k=f.match(/^\d+\.\s+(.*)$/);if(m||k){x(),b=!1;let N=k?"ol":"ul",Z=(k?k[1]:m[1])||"";if(k&&(Z=Z.replace(/^\d+\.\s+/,"")),!k&&B&&B.type==="ol"&&B.items.length>0){B.items[B.items.length-1].children.push(Z);continue}(!B||B.type!==N)&&($(),B={type:N,items:[]}),q(B,Z);continue}if(B&&B.type==="ol"&&(S||b)){G(B,f,b),b=!1;continue}B&&$(),_.push(f),S=!1}return $(),x(),g.forEach((w,f)=>{y=y.replace(`@@CODEBLOCK${f}@@`,w)}),y},o=(l,d)=>d?s.element.createElement(gr,null,r(l)):e(l),a=Y(J),i=[],c=null;return J.forEach((l,d)=>{if(l.role==="user"){i.push({type:"user",message:l,key:`user-${d}`}),c=null;return}c||(c={type:"ai",items:[],key:`ai-${d}`},i.push(c)),c.items.push({message:l,index:d})}),i.map((l,d)=>{if(l.type==="user")return s.element.createElement("div",{key:l.key,className:"wpaw-message wpaw-message-user"},s.element.createElement("div",{className:"wpaw-message-content"},o(l.message.content,!1)));let g=d===i.length-1,h="Streaming...";for(let v=l.items.length-1;v>=0;v--){let y=l.items[v].message;if(y.type==="timeline"&&y.status){y.status==="checking"?h="Analyzing...":y.status==="planning"||y.status==="plan_complete"?h="Planning...":y.status==="writing"||y.status==="writing_section"?h="Writing...":y.status==="refining"?h="Refining...":h="Streaming...";break}}return s.element.createElement("div",{key:l.key,className:"wpaw-ai-response"},l.items.map((v,y)=>{var S;let _=v.message,B=v.index,b=y===l.items.length-1;if(_.type==="timeline"){let x=_.status==="complete"?"complete":_.status==="inactive"?"inactive":"active",$=U&&_.status==="refining",q=_.status==="complete"&&_.timestamp&&_.completedAt?((new Date(_.completedAt)-new Date(_.timestamp))/1e3).toFixed(1)+"s":null;return s.element.createElement("div",{key:`timeline-${B}`,className:"wpaw-ai-item wpaw-timeline-entry "+x+(B===a?" is-current":"")},s.element.createElement("div",{className:"wpaw-timeline-dot","aria-hidden":"true"}),s.element.createElement("div",{className:"wpaw-timeline-content"},s.element.createElement("div",{className:"wpaw-timeline-message"},e(_.message)),_.status==="complete"&&s.element.createElement("div",{className:"wpaw-timeline-complete-row",style:{display:"flex",justifyContent:"space-between",alignItems:"center"}},s.element.createElement("div",{className:"wpaw-timeline-complete"},"\u2713 Complete",q&&s.element.createElement("span",{className:"wpaw-timeline-elapsed"},` (${q})`)),qe.length>0&&g&&b&&(_.message.toLowerCase().includes("refine")||_.message.toLowerCase().includes("generated"))&&s.element.createElement("button",{className:"wpaw-inline-undo-btn",onClick:$s,disabled:U,title:`Undo: ${((S=qe[qe.length-1])==null?void 0:S.label)||"Last AI operation"}`,style:{background:"transparent",border:"none",color:"var(--aw-primary)",cursor:U?"not-allowed":"pointer",fontSize:"11px",fontFamily:"inherit",fontWeight:"500",display:"flex",alignItems:"center",gap:"4px",padding:"2px 6px",borderRadius:"4px"}},s.element.createElement("span",{dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13"/></svg>'}}),"Undo")),$&&s.element.createElement("div",{className:"wpaw-processing-indicator"},s.element.createElement("span",{className:"wpaw-dots-loader"}),s.element.createElement("span",null,"Processing updates\u2026")),!$&&U&&g&&b&&s.element.createElement("div",{className:"wpaw-typing-indicator","aria-label":"Agent is typing"},h,s.element.createElement("span",{className:"wpaw-typing-dots"},s.element.createElement("span",null),s.element.createElement("span",null),s.element.createElement("span",null)))))}if(_.type==="plan"){let x=Gn(_.plan),$=Array.isArray(x==null?void 0:x.sections)?x.sections:[],q=m=>{if(m.description)return m.description;if(Array.isArray(m.content)&&m.content.length>0){let k=m.content.find(N=>N&&N.content);return k?k.content:""}return""},G=$.filter(m=>m.status!=="done").length,L=G?`Write ${G} Pending`:"Write Article",w=[],f=I.language==="auto"?"Auto-detect":I.language.charAt(0).toUpperCase()+I.language.slice(1);w.push(`\u{1F30D} Language: ${f}`);let p={short:"Short (~800 words)",medium:"Medium (~1500 words)",long:"Long (~2500 words)"};if(w.push(`\u{1F4CF} Length: ${p[I.article_length]||"Medium"}`),I.audience&&w.push(`\u{1F465} Audience: ${I.audience}`),I.web_search&&w.push("\u{1F50D} Web Search: Enabled"),I.seo_enabled){let m=[];I.seo_focus_keyword&&m.push(`Focus: "${I.seo_focus_keyword}"`),I.seo_secondary_keywords&&m.push(`Secondary: "${I.seo_secondary_keywords}"`),w.push(`\u{1F4CA} SEO: Enabled${m.length?" ("+m.join(", ")+")":""}`)}return s.element.createElement("div",{key:`plan-${B}`,className:"wpaw-ai-item wpaw-plan-card"},s.element.createElement("div",{className:"wpaw-plan-title"},(x==null?void 0:x.title)||"Proposed Outline"),s.element.createElement("div",{className:"wpaw-plan-config-summary"},w.map((m,k)=>s.element.createElement("div",{key:k,className:"wpaw-config-summary-item"},m))),$.length>0&&s.element.createElement("ol",{className:"wpaw-plan-sections"},$.map((m,k)=>s.element.createElement("li",{key:`plan-section-${k}`,className:`wpaw-plan-section ${m.status||"pending"}`},s.element.createElement("div",{className:"wpaw-plan-section-row"},s.element.createElement("input",{className:"wpaw-plan-section-check",type:"checkbox",checked:m.status==="done",readOnly:!0,disabled:!0}),s.element.createElement("div",{className:"wpaw-plan-section-body"},s.element.createElement("div",{className:"wpaw-plan-section-title"},m.title||m.heading||`Section ${k+1}`),q(m)&&s.element.createElement("div",{className:"wpaw-plan-section-desc"},q(m))),s.element.createElement("div",{className:"wpaw-plan-section-status"},m.status==="done"?"Done":m.status==="in_progress"?"Writing":"Pending"))))),!$.length&&(x==null?void 0:x.summary)&&s.element.createElement("div",{className:"wpaw-plan-section-desc"},x.summary),s.element.createElement("div",{className:"wpaw-plan-actions"},s.element.createElement(me,{isPrimary:!0,onClick:Ft,disabled:U},L)))}if(_.type==="edit_plan"){let x=_.plan||It,$=!!It&&x===It,q=fn(x),G=V("core/block-editor").getBlocks(),L=new Set(G.map(k=>k.clientId)),w=q.filter(k=>!(k.action==="keep"||k.blockId&&!L.has(k.blockId))),f=w.length,p=(x==null?void 0:x.summary)||`Proposed changes: ${f}`,m=w.map((k,N)=>Vr(k,N));return s.element.createElement("div",{key:`plan-${B}`,className:"wpaw-ai-item wpaw-edit-plan"},s.element.createElement("div",{className:"wpaw-edit-plan-title"},"Proposed Changes"),s.element.createElement("div",{className:"wpaw-edit-plan-summary"},p),m.length>0&&s.element.createElement("div",{className:"wpaw-edit-plan-preview-label"},"Apply preview"),m.length>0&&s.element.createElement("ol",{className:"wpaw-edit-plan-list"},m.map((k,N)=>s.element.createElement("li",{key:`plan-action-${N}`,className:"wpaw-edit-plan-item"},s.element.createElement("div",{className:"wpaw-edit-plan-item-title",style:{marginBottom:"6px"}},k.title),k.viewInEditor&&s.element.createElement("button",{type:"button",className:"wpaw-edit-plan-item-target",disabled:!$,title:"Scroll to changes in editor",onClick:()=>{if(!$||!k.blockId)return;ie("core/block-editor").selectBlock(k.blockId);let Z=document.querySelector(`[data-block="${k.blockId}"]`);Z&&Z.scrollIntoView({behavior:"smooth",block:"center"})}},"View in Editor \u{1F441}\uFE0F")))),s.element.createElement("div",{className:"wpaw-edit-plan-actions"},s.element.createElement(me,{isPrimary:!0,onClick:()=>fo(x),disabled:!x||!$},`Apply (${f})`),s.element.createElement(me,{isSecondary:!0,onClick:mo,disabled:!$},"Cancel")))}if(_.type==="error"){let x=()=>{if(_.retryType==="execute"){Jr();return}if(_.retryType==="refine"){Xr();return}if(_.retryType==="chat"){Gr();return}Kr()},$=_.content,q=$&&typeof $=="object"&&$.title;return s.element.createElement("div",{key:`error-${B}`,className:"wpaw-ai-item wpaw-message wpaw-message-error"},q?s.element.createElement("div",null,s.element.createElement("div",{className:"wpaw-error-title"},"\u26A0 ",$.title),$.detail&&s.element.createElement("div",{className:"wpaw-error-detail"},$.detail),$.actionUrl&&s.element.createElement("a",{href:$.actionUrl,target:"_blank",rel:"noopener",style:{display:"inline-block",marginTop:"8px",fontSize:"12px",color:"#fca5a5",textDecoration:"underline"}},$.actionLabel||"Open Settings")):s.element.createElement("div",{className:"wpaw-message-content"},o($,!0)),_.canRetry&&s.element.createElement(me,{isSecondary:!0,onClick:x},"\u21BB Retry"))}return s.element.createElement("div",{key:`response-${B}`,className:"wpaw-ai-item wpaw-response"},s.element.createElement("div",{className:"wpaw-response-content"},o(_.content,!0)),U&&g&&b&&s.element.createElement("div",{className:"wpaw-typing-indicator","aria-label":"Agent is typing"},h,s.element.createElement("span",{className:"wpaw-typing-dots"},s.element.createElement("span",null),s.element.createElement("span",null),s.element.createElement("span",null))),_.detectedIntent&&Po(_.detectedIntent),_.showResumeActions&&s.element.createElement("div",{className:"wpaw-resume-actions"},s.element.createElement(me,{isPrimary:!0,onClick:()=>{ot(!1),Ft()},style:{marginRight:"8px"}},`Resume Writing (${_.pendingCount} pending)`),s.element.createElement(me,{isSecondary:!0,onClick:()=>{ot(!1),xe("planning")}},"Review Outline")))}))})},Wo=()=>{var t,n,r;let e=U||Xt||vn;return s.element.createElement("div",{className:"wpaw-tab-content wpaw-config-tab dark-theme"},s.element.createElement("div",{className:"wpaw-tab-header"},s.element.createElement("h3",null,"CONFIGURATION")),s.element.createElement("div",{className:"wpaw-config-section"},s.element.createElement("label",null,"AGENT WORKSPACE"),s.element.createElement("p",{className:"description"},"The command box now routes chat, outline, writing, refinement, and SEO requests automatically from the current editor context.")),s.element.createElement("div",{className:"wpaw-config-section"},s.element.createElement("label",null,"ARTICLE LENGTH"),s.element.createElement("select",{value:I.article_length,onChange:o=>ge("article_length",o.target.value),disabled:e,className:"wpaw-select"},s.element.createElement("option",{value:"short"},"Short (500-800 words)"),s.element.createElement("option",{value:"medium"},"Medium (800-1500 words)"),s.element.createElement("option",{value:"long"},"Long (1500-2500 words)"))),s.element.createElement("div",{className:"wpaw-config-section"},s.element.createElement("label",null,"Language"),s.element.createElement("select",{value:I.language,onChange:o=>ge("language",o.target.value),disabled:e,className:"wpaw-select"},(()=>{let o=ae.preferred_languages||["auto","English","Indonesian"],a=ae.custom_languages||[];return[...o,...a].map(c=>{let l=c.toLowerCase();return s.element.createElement("option",{key:l,value:l},c==="auto"?"Auto-detect":c)})})()),s.element.createElement("p",{className:"description"},"Overrides the detected language when writing or refining.")),s.element.createElement("div",{className:"wpaw-config-section"},s.element.createElement(yn,{label:"Tone",value:I.tone,onChange:o=>ge("tone",o),disabled:e,placeholder:"e.g., Friendly, persuasive, professional"}),s.element.createElement("p",{className:"description"},"Use this to consistently guide the writing tone.")),s.element.createElement("div",{className:"wpaw-config-section"},s.element.createElement("label",null,"Experience Level"),s.element.createElement("select",{value:I.experience_level,onChange:o=>ge("experience_level",o.target.value),disabled:e,className:"wpaw-select"},s.element.createElement("option",{value:"general"},"General audience"),s.element.createElement("option",{value:"beginner"},"Beginner"),s.element.createElement("option",{value:"intermediate"},"Intermediate"),s.element.createElement("option",{value:"advanced"},"Advanced"))),s.element.createElement("div",{className:"wpaw-config-section"},s.element.createElement(zt,{label:"Include image suggestions",checked:!!I.include_images,onChange:o=>ge("include_images",o),disabled:e}),s.element.createElement("p",{className:"description"},"When enabled, the agent will add image placeholders.")),s.element.createElement("div",{className:"wpaw-config-section"},s.element.createElement(zt,{label:"Enable web search for outlines",checked:!!I.web_search,onChange:o=>ge("web_search",o),disabled:e}),s.element.createElement("p",{className:"description"},"Uses web search when planning outlines.")),s.element.createElement("div",{className:"wpaw-config-divider"},s.element.createElement("span",null,"\u{1F50D} SEO OPTIMIZATION")),s.element.createElement("div",{className:"wpaw-config-section"},s.element.createElement(zt,{label:"Enable SEO optimization",checked:!!I.seo_enabled,onChange:o=>ge("seo_enabled",o),disabled:e}),s.element.createElement("p",{className:"description"},"Include SEO guidelines in AI prompts for keyword-optimized content.")),I.seo_enabled&&s.element.createElement("div",{className:"wpaw-config-section"},s.element.createElement(yn,{label:"Focus Keyword",value:I.seo_focus_keyword,onChange:o=>ge("seo_focus_keyword",o),disabled:e,placeholder:"e.g., wordpress seo plugin"}),s.element.createElement("p",{className:"description"},"Primary keyword to optimize content for. Will be included in title, headings, and body.")),I.seo_enabled&&s.element.createElement("div",{className:"wpaw-config-section"},s.element.createElement(yn,{label:"Secondary Keywords",value:I.seo_secondary_keywords,onChange:o=>ge("seo_secondary_keywords",o),disabled:e,placeholder:"e.g., content optimization, search ranking"}),s.element.createElement("p",{className:"description"},"Comma-separated related keywords to sprinkle throughout content.")),I.seo_enabled&&s.element.createElement("div",{className:"wpaw-config-section"},s.element.createElement(es,{label:"Meta Description",value:I.seo_meta_description,onChange:o=>ge("seo_meta_description",o),disabled:e,placeholder:"Enter meta description (120-160 chars recommended)",rows:3}),s.element.createElement("div",{className:"wpaw-meta-info"},s.element.createElement("span",{className:(((t=I.seo_meta_description)==null?void 0:t.length)||0)>=120&&(((n=I.seo_meta_description)==null?void 0:n.length)||0)<=160?"good":"warning"},`${((r=I.seo_meta_description)==null?void 0:r.length)||0}/160 chars`),s.element.createElement(me,{isSecondary:!0,isSmall:!0,onClick:()=>Xn(),disabled:e||rt},rt?s.element.createElement("span",{style:{display:"flex",alignItems:"center",gap:"5px"}},s.element.createElement("span",{className:"wpaw-spinning-icon",dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#fbbf24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2v4"/><path d="m16.2 7.8 2.9-2.9"/><path d="M18 12h4"/><path d="m16.2 16.2 2.9 2.9"/><path d="M12 18v4"/><path d="m4.9 19.1 2.9-2.9"/><path d="M2 12h4"/><path d="m4.9 4.9 2.9 2.9"/></svg>'}})," Generating..."):s.element.createElement("span",{style:{display:"flex",alignItems:"center",gap:"5px"}},s.element.createElement("span",{className:"wpaw-svg-wrapper",dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"><g fill="none" stroke="#fbbf24" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"><path d="M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594zM20 2v4m2-2h-4"/><circle cx="4" cy="20" r="2"/></g></svg>'}})," Generate")))),I.seo_enabled&&s.element.createElement("div",{className:"wpaw-config-section wpaw-seo-audit"},s.element.createElement("div",{className:"wpaw-seo-audit-header"},s.element.createElement("label",null,"SEO Audit"),s.element.createElement(me,{isSecondary:!0,isSmall:!0,onClick:()=>Ls(),disabled:e||Ve},Ve?s.element.createElement("span",{style:{display:"flex",alignItems:"center",gap:"5px"}},s.element.createElement("span",{className:"wpaw-spinning-icon",style:{display:"inline-flex",lineHeight:"0"},dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#4ade80" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2v4"/><path d="m16.2 7.8 2.9-2.9"/><path d="M18 12h4"/><path d="m16.2 16.2 2.9 2.9"/><path d="M12 18v4"/><path d="m4.9 19.1 2.9-2.9"/><path d="M2 12h4"/><path d="m4.9 4.9 2.9 2.9"/></svg>'}})," Analyzing..."):s.element.createElement("span",{style:{display:"flex",alignItems:"center",gap:"5px"}},s.element.createElement("span",{className:"wpaw-svg-wrapper",style:{display:"inline-flex",lineHeight:"0"},dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="none" stroke="#4ade80" stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M13 5h8m-8 7h8m-8 7h8M3 17l2 2l4-4M3 7l2 2l4-4"/></svg>'}})," Run Audit"))),Be&&s.element.createElement("div",{className:"wpaw-seo-audit-results"},s.element.createElement("div",{className:"wpaw-seo-score "+(Be.score>=70?"good":Be.score>=40?"warning":"poor")},s.element.createElement("span",{className:"score-value"},Be.score),s.element.createElement("span",{className:"score-label"},"/100")),s.element.createElement("div",{className:"wpaw-seo-stats"},s.element.createElement("div",{className:"wpaw-seo-stat"},s.element.createElement("span",{className:"stat-label"},"Words"),s.element.createElement("span",{className:"stat-value"},Be.word_count||0)),s.element.createElement("div",{className:"wpaw-seo-stat"},s.element.createElement("span",{className:"stat-label"},"Keyword Density"),s.element.createElement("span",{className:"stat-value"},`${(Be.keyword_density||0).toFixed(1)}%`))),Be.checks&&s.element.createElement("div",{className:"wpaw-seo-checks"},Be.checks.map((o,a)=>{let i=o.status==="good"||o.status==="ok",c=fs===Ws(o);return s.element.createElement("div",{key:a,className:"wpaw-seo-check "+(i?"passed":"failed")},s.element.createElement("span",{className:"check-icon"},i?"\u2713":"\u2717"),s.element.createElement("span",{className:"check-label"},o.message),!i&&s.element.createElement(me,{isSmall:!0,isSecondary:!0,className:"wpaw-seo-fix-button"+(c?" is-fixing":""),onClick:()=>Wr(o),disabled:U||Ve||rt||!!fs},c?"Fixing...":"Fix"))}))),!Be&&s.element.createElement("p",{className:"description"},'Click "Run Audit" to analyze your content for SEO optimization.')),(vn||Sn)&&s.element.createElement("div",{className:"wpaw-config-section"},vn&&s.element.createElement("p",{className:"description"},"Saving post configuration..."),Sn&&s.element.createElement("p",{className:"description"},Sn)),s.element.createElement("div",{className:"wpaw-config-section"},s.element.createElement("p",{className:"description"},"Configure global settings like API keys, models, and clarification quiz options in ",s.element.createElement("a",{href:ae.settings_url||"/wp-admin/options-general.php?page=wp-agentic-writer",target:"_blank"},"Settings \u2192 WP Agentic Writer"))))},Oo=()=>{var r,o;let e=U||Ve||rt;if($e.status==="stopping")return"stopping";if(!e)return"idle";let n=J.filter(a=>a.type==="timeline").pop();return $e.type==="refinement"?"refining":$e.type==="seo_audit"?"checking":(r=n==null?void 0:n.message)!=null&&r.toLowerCase().includes("writing")||(o=n==null?void 0:n.message)!=null&&o.toLowerCase().includes("generating")?"writing":"thinking"},Do=()=>{var n;let e=Oo(),t={idle:"Ready",thinking:"Thinking...",checking:"Checking...",refining:"Refining...",writing:"Writing...",stopping:"Stopping...",complete:"Done",error:"Error"};return s.element.createElement("div",{className:"wpaw-status-bar",role:"status","aria-live":"polite"},s.element.createElement("div",{className:"wpaw-status-indicator"},s.element.createElement("span",{className:"wpaw-status-dot "+e}),s.element.createElement("span",{className:"wpaw-status-label"},t[e])),vt.restored&&s.element.createElement("div",{className:"wpaw-memanto-badge",title:"Restored from memory: "+(vt.summary||"prior session context")},"\u{1F9E0} Restored"),s.element.createElement("div",{className:"wpaw-status-actions"},qe.length>0&&s.element.createElement("button",{className:"wpaw-status-icon-btn wpaw-undo-btn has-undo",title:`Undo: ${((n=qe[qe.length-1])==null?void 0:n.label)||"Last AI operation"}`,onClick:$s,disabled:U,dangerouslySetInnerHTML:{__html:'<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"><path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13"/></svg>'}}),s.element.createElement("button",{className:"wpaw-status-icon-btn"+(Le==="chat"&&dt?" is-active":""),dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M3 6h.01"/><path d="M3 12h.01"/><path d="M3 18h.01"/></svg>'},title:"Sessions",onClick:()=>{et("chat"),Ye(!0)},disabled:U}),J.length>0&&s.element.createElement("button",{className:"wpaw-status-icon-btn"+(Le==="chat"&&!dt?" is-active":""),dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 9a2 2 0 0 1-2 2H6l-4 4V4c0-1.1.9-2 2-2h8a2 2 0 0 1 2 2z"/><path d="M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"/></svg>'},title:"Chat",onClick:()=>{et("chat"),Ye(!1)},disabled:U}),J.length>0&&s.element.createElement("button",{className:"wpaw-status-icon-btn wpaw-workspace-toggle-btn",dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"><path d="M12 5a3 3 0 1 0-5.997.125a4 4 0 0 0-2.526 5.77a4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M9 13a4.5 4.5 0 0 0 3-4M6.003 5.125A3 3 0 0 0 6.401 6.5m-2.924 4.396a4 4 0 0 1 .585-.396M6 18a4 4 0 0 1-1.967-.516M12 13h4m-4 5h6a2 2 0 0 1 2 2v1M12 8h8m-4 0V5a2 2 0 0 1 2-2"/></svg>'},title:rn?"Show Agent Workspace":"Hide Agent Workspace",onClick:Cr}),s.element.createElement("button",{className:"wpaw-status-icon-btn"+(Le==="config"?" is-active":""),dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"><path d="M14 17H5M19 7h-9"/><circle cx="17" cy="17" r="3"/><circle cx="7" cy="7" r="3"/></g></svg>'},title:"Configuration",onClick:()=>et(Le==="config"?"chat":"config"),disabled:U}),s.element.createElement("button",{className:"wpaw-status-icon-btn"+(Le==="cost"?" is-active":""),dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"><path d="M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"/><path d="M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"/></g></svg>'},title:"Cost Tracking",onClick:()=>et(Le==="cost"?"chat":"cost"),disabled:U})))},Fo=()=>{let e=U||Ve||rt,t=$e.status==="stopping";return s.element.createElement("div",{className:"wpaw-tab-content wpaw-chat-tab dark-theme"},s.element.createElement("div",{className:`wpaw-chat-container ${Zt?"is-dimmed":""}`},xt&&s.element.createElement("div",{className:"wpaw-editor-lock-banner"},"Writing in progress \u2014 please wait until the article finishes."),Oe&&s.element.createElement("div",{className:"wpaw-refinement-lock-banner"},`Refining in progress \u2014 editing is temporarily locked. You can still scroll and review changes live (${At.length} target block(s)).`),Kt.lockedByOther&&s.element.createElement("div",{className:"wpaw-session-lock-banner"},s.element.createElement("span",null,"\u26A0\uFE0F This session is active in another tab. Changes here won\u2019t be saved."),s.element.createElement(me,{isSmall:!0,isSecondary:!0,className:"wpaw-session-lock-takeover",onClick:Dr},"Take Over")),wpAgenticWriter.health&&!wpAgenticWriter.health.ok&&wpAgenticWriter.health.issues.map((n,r)=>s.element.createElement("div",{key:`health-${r}`,className:"wpaw-health-notice"},"\u26A0\uFE0F ",n.message,n.actionUrl&&s.element.createElement("a",{href:n.actionUrl,target:"_blank",rel:"noopener",style:{marginLeft:"8px"}},n.actionLabel||"Fix"))),dt&&!xt&&$o(),!dt&&mn()&&Eo(),!dt&&!mn()&&Mo(),!dt&&!mn()&&s.element.createElement("div",{className:"wpaw-messages wpaw-activity-log"},s.element.createElement("div",{className:"wpaw-messages-inner",ref:Un},Lo(),s.element.createElement("div",{ref:Hn}))),!dt&&!mn()&&s.element.createElement("div",{className:"wpaw-command-area",style:{position:"relative"}},Ro(),s.element.createElement("div",{className:`wpaw-input-hint ${tt||U?"is-hidden":""}`},"Type ",s.element.createElement("kbd",null,"/")," for commands or ",s.element.createElement("kbd",null,"@")," to mention a block"),s.element.createElement("div",{className:"wpaw-command-input-wrapper"+(bs?" expanded":"")},s.element.createElement("span",{className:"wpaw-command-prefix"},">"),s.element.createElement("textarea",{ref:ye,className:"wpaw-input",value:tt,disabled:Kt.lockedByOther,onChange:n=>{let r=n.target.value;No(r);let o=ye.current;o&&(o.style.height="auto",o.style.height=Math.min(o.scrollHeight,250)+"px",o.style.overflowY=o.scrollHeight>250?"auto":"hidden")},onKeyDown:Io,rows:2,style:{minHeight:"60px",maxHeight:"250px",resize:"none",width:"100%",boxSizing:"border-box",padding:"10px 12px",fontFamily:"inherit",fontSize:"13px",lineHeight:"1.4",border:"1px solid var(--aw-outline-subtle)",borderRadius:"6px",background:"transparent",color:"inherit"},placeholder:"Ask the agent to write, continue, inspect, refine, or use @ to target blocks..."})),Mt&&it.length>0&&s.element.createElement("div",{className:"wpaw-mention-autocomplete",style:{position:"absolute",bottom:"100%",left:0,right:0,maxHeight:"200px",overflowY:"auto",background:"#1e1e1e",border:"1px solid #3c3c3c",zIndex:1e3}},it.map((n,r)=>{let o=r===Pn;return s.element.createElement("div",{key:n.id,className:"wpaw-mention-option"+(o?" selected":""),onClick:()=>tr(n),style:{padding:"8px 12px",cursor:"pointer",background:o?"#2c2c2c":"transparent",borderBottom:"1px solid #3c3c3c"}},s.element.createElement("strong",{style:{display:"block",color:"#fff",fontSize:"13px"}},n.label),s.element.createElement("span",{style:{display:"block",color:"#a7aaad",fontSize:"12px",marginTop:"2px"}},n.sublabel))})),Pt&&ct.length>0&&s.element.createElement("div",{className:"wpaw-mention-autocomplete",style:{position:"absolute",bottom:"100%",left:0,right:0,maxHeight:"200px",overflowY:"auto",background:"#1e1e1e",border:"1px solid #3c3c3c",zIndex:1e3}},ct.map((n,r)=>{let o=r===Ln;return s.element.createElement("div",{key:n.id,className:"wpaw-mention-option"+(o?" selected":""),onClick:()=>nr(n),style:{padding:"8px 12px",cursor:"pointer",background:o?"#2c2c2c":"transparent",borderBottom:"1px solid #3c3c3c"}},s.element.createElement("strong",{style:{display:"block",color:"#fff",fontSize:"13px"}},n.label),s.element.createElement("span",{style:{display:"block",color:"#a7aaad",fontSize:"12px",marginTop:"2px"}},n.sublabel))})),s.element.createElement("div",{className:"wpaw-command-actions"},s.element.createElement("div",{className:"wpaw-command-actions-group"},(()=>{let r=(ae.task_providers||{})[Ce]||"openrouter",o=r==="local_backend"||r==="codex",a=!!ae.brave_search_api_key,i=o&&!a,c=i?"Web Search unavailable \u2014 Brave API Key required for "+r.replace("_"," ")+". Configure in Settings > General.":o?"Web search via Brave Search API (free tier: 2,000 req/mo)":"Web search via OpenRouter (~$0.02/search)";return s.element.createElement("label",{className:"wpaw-web-search-toggle"+(i?" wpaw-search-blocked":""),title:c,onClick:i?l=>{l.preventDefault(),alert("Web Search for "+r.replace("_"," ")+` requires a Brave Search API Key.
Get a free key (2,000 requests/month) and configure it in:
WP Agentic Writer Settings \u2192 General \u2192 Brave Search API Key`)}:void 0},s.element.createElement("input",{type:"checkbox",checked:i?!1:I.web_search||!1,onChange:i?()=>{}:l=>{ge("web_search",l.target.checked)},disabled:U||i}),s.element.createElement("span",{className:"wpaw-web-search-icon",dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20a14.5 14.5 0 0 0 0-20M2 12h20"/></g></svg>'}}),s.element.createElement("span",{className:"wpaw-web-search-label"},i?"Search \u2715":"Search"))})()),s.element.createElement("div",{className:"wpaw-command-actions-group"},e&&s.element.createElement("button",{className:"wpaw-command-circle-btn wpaw-stop-circle-btn"+(t?" is-stopping":""),type:"button",onClick:lo,disabled:t,title:t?"Stopping...":"Stop current operation",dangerouslySetInnerHTML:{__html:t?'<svg class="wpaw-stop-spinner" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-width="2"><path d="M12 3a9 9 0 1 1-8.5 6"/><path d="M12 7v5l3 2"/></g></svg>':'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="currentColor" d="M11.945 5.75c-1.367 0-2.47 0-3.337.117c-.9.12-1.658.38-2.26.981c-.602.602-.86 1.36-.981 2.26c-.117.867-.117 1.97-.117 3.337v.11c0 1.367 0 2.47.117 3.337c.12.9.38 1.658.981 2.26c.602.602 1.36.86 2.26.982c.867.116 1.97.116 3.337.116h.11c1.367 0 2.47 0 3.337-.116c.9-.122 1.658-.38 2.26-.982s.86-1.36.982-2.26c.116-.867.116-1.97.116-3.337v-.11c0-1.367 0-2.47-.116-3.337c-.122-.9-.38-1.658-.982-2.26s-1.36-.86-2.26-.981c-.867-.117-1.97-.117-3.337-.117z"/></svg>'}}),!e&&s.element.createElement("button",{className:"wpaw-command-circle-btn wpaw-send-circle-btn",type:"button",onClick:sr,disabled:!tt.trim()||Kt.lockedByOther,title:"Send message",dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="currentColor" d="M19.5 2.001a3.5 3.5 0 0 1 3.03 5.249l-7.5 12.99a3.5 3.5 0 0 1-6.411-.842l-1.5-5.595l8.77-5.064a1 1 0 0 0-1-1.732L6.12 12.07L2.026 7.975A3.5 3.5 0 0 1 4.5 2z"/></svg>'}}))),s.element.createElement("div",{className:"wpaw-keyboard-hints","aria-hidden":"true"},s.element.createElement("span",{className:"wpaw-kbd"},s.element.createElement("kbd",null,/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"\u2318":"Ctrl"),"+",s.element.createElement("kbd",null,"\u21B5")," Send"),s.element.createElement("span",{className:"wpaw-kbd"},s.element.createElement("kbd",null,"@")," Blocks"),s.element.createElement("span",{className:"wpaw-kbd"},s.element.createElement("kbd",null,"/")," Commands")),Ao())))},[Zn,jo]=s.element.useState([]),ar=async()=>{var e,t,n,r;if(C)try{let a=await(await fetch(`${wpAgenticWriter.apiUrl}/cost-tracking/${C}`,{headers:{"X-WP-Nonce":wpAgenticWriter.nonce}})).json();a&&typeof a.session=="number"&&he({session:a.session,today:((t=(e=a.today)==null?void 0:e.total)==null?void 0:t.cost)||0,monthlyUsed:((n=a.monthly)==null?void 0:n.used)||0}),(r=a==null?void 0:a.monthly)!=null&&r.budget&&as(a.monthly.budget),a!=null&&a.history&&jo(a.history)}catch(o){K.error("Failed to refresh cost data:",o)}};React.useEffect(()=>{Le==="cost"&&ar()},[Le,C]);let Ho=()=>{let e=Vt>0?te.monthlyUsed/Vt*100:0,t=e>90?"danger":e>70?"warning":"ok",n=Math.max(0,Vt-te.monthlyUsed),r=Zn.reduce((a,i)=>{let c=i.action||"unknown",l=parseFloat(i.cost||0),d=parseInt(i.input_tokens||0)+parseInt(i.output_tokens||0);return a[c]||(a[c]={action:c,cost:0,tokens:0,count:0}),a[c].cost+=l,a[c].tokens+=d,a[c].count+=1,a},{}),o=Object.values(r).sort((a,i)=>i.cost-a.cost);return s.element.createElement("div",{className:"wpaw-tab-content wpaw-cost-tab dark-theme"},s.element.createElement("div",{className:"wpaw-tab-header"},s.element.createElement("h3",null,"OPENROUTER COST"),s.element.createElement("button",{className:"wpaw-refresh-btn",dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><g fill="none" stroke="#ffffff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"><path d="M21 12a9 9 0 0 0-9-9a9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5m-5 4a9 9 0 0 0 9 9a9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 16h5v5"/></g></svg>'},onClick:ar,title:"Refresh cost data"})),s.element.createElement("div",{className:"wpaw-cost-card"},s.element.createElement("div",{className:"wpaw-cost-stat"},s.element.createElement("label",null,"This Post"),s.element.createElement("div",{className:"wpaw-cost-value"},"$",te.session.toFixed(4))),s.element.createElement("div",{className:"wpaw-cost-stat"},s.element.createElement("label",null,"Month Used"),s.element.createElement("div",{className:"wpaw-cost-value"},"$",te.monthlyUsed.toFixed(4))),s.element.createElement("div",{className:"wpaw-cost-stat wpaw-cost-remaining"},s.element.createElement("label",null,"Remaining"),s.element.createElement("div",{className:"wpaw-cost-value "+t},"$",n.toFixed(2)))),s.element.createElement("div",{className:"wpaw-budget-section"},s.element.createElement("div",{className:"wpaw-budget-label"},s.element.createElement("span",null,"Budget: $",Vt.toFixed(2)),s.element.createElement("span",null,e.toFixed(1),"%")),s.element.createElement("div",{className:"wpaw-budget-bar"},s.element.createElement("div",{className:"wpaw-budget-fill "+t,style:{width:Math.min(e,100)+"%"}}))),e>80&&s.element.createElement("div",{className:"wpaw-budget-warning "+t},e>=100?"\u26A0\uFE0F Budget exceeded!":"\u26A0\uFE0F Approaching budget limit"),Zn.length>0&&s.element.createElement("div",{className:"wpaw-cost-history"},s.element.createElement("h4",null,"Cost By Action"),s.element.createElement("div",{className:"wpaw-cost-table-wrapper",style:{marginBottom:"24px"}},s.element.createElement("table",{className:"wpaw-cost-table"},s.element.createElement("thead",null,s.element.createElement("tr",null,s.element.createElement("th",null,"Action"),s.element.createElement("th",null,"Calls"),s.element.createElement("th",null,"Tokens"),s.element.createElement("th",null,"Cost(US$)"))),s.element.createElement("tbody",null,o.map((a,i)=>s.element.createElement("tr",{key:i},s.element.createElement("td",null,a.action),s.element.createElement("td",null,a.count),s.element.createElement("td",null,a.tokens.toLocaleString()),s.element.createElement("td",null,"$"+a.cost.toFixed(4))))))),s.element.createElement("h4",null,"OpenRouter Cost History"),s.element.createElement("div",{className:"wpaw-cost-table-wrapper"},s.element.createElement("table",{className:"wpaw-cost-table"},s.element.createElement("thead",null,s.element.createElement("tr",null,s.element.createElement("th",null,"Time"),s.element.createElement("th",null,"Action"),s.element.createElement("th",null,"Model"),s.element.createElement("th",null,"Tokens"),s.element.createElement("th",null,"Cost(US$)"))),s.element.createElement("tbody",null,Zn.map((a,i)=>{let c=parseInt(a.input_tokens||0)+parseInt(a.output_tokens||0),l=new Date(a.created_at).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}),d=a.model?a.model.split("/").pop().substring(0,20):"N/A";return s.element.createElement("tr",{key:i},s.element.createElement("td",null,l),s.element.createElement("td",null,a.action),s.element.createElement("td",{title:a.model},d),s.element.createElement("td",null,c.toLocaleString()),s.element.createElement("td",null,"$"+parseFloat(a.cost).toFixed(4)))}))))),s.element.createElement("div",{className:"wpaw-cost-footer"},s.element.createElement("a",{href:ae.settings_url||"/wp-admin/options-general.php?page=wp-agentic-writer",target:"_blank",className:"wpaw-cost-settings-link"},s.element.createElement("span",{dangerouslySetInnerHTML:{__html:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" style="margin-bottom: -7px;"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1"><path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0a2.34 2.34 0 0 0 3.319 1.915a2.34 2.34 0 0 1 2.33 4.033a2.34 2.34 0 0 0 0 3.831a2.34 2.34 0 0 1-2.33 4.033a2.34 2.34 0 0 0-3.319 1.915a2.34 2.34 0 0 1-4.659 0a2.34 2.34 0 0 0-3.32-1.915a2.34 2.34 0 0 1-2.33-4.033a2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"/><circle cx="12" cy="12" r="3"/></g></svg> Manage Budget Settings'}}))))};return s.element.createElement(s.element.Fragment,null,s.element.createElement(lr,{target:"wp-agentic-writer",icon:ts},"WP Agentic Writer"),s.element.createElement(dr,{name:"wp-agentic-writer",title:s.element.createElement("div",{style:{display:"flex",alignItems:"center",gap:"8px"}},s.element.createElement("img",{src:wpAgenticWriter.pluginUrl+"/assets/img/icon.svg",alt:"WP Agentic Writer",style:{width:"24px",height:"24px"}}),s.element.createElement("span",null,"WP Agentic Writer"))},s.element.createElement(ur,null,s.element.createElement("div",{className:"wpaw-tab-content-wrapper"},Do(),Le==="chat"&&Fo(),Le==="config"&&Wo(),Le==="cost"&&Ho()))))},mr=C=>({postId:C("core/editor").getCurrentPostId()}),pr=s.data.withSelect(mr)(fr);cr("wp-agentic-writer",{icon:ts,render:pr})})(window.wp);})();