openwriter 0.40.0 → 0.40.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -205,7 +205,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),Qt=je,kt=et),wt===void
205
205
  Run: ${j.updateCommand}`,children:["v",j.latestVersion]})]}),l.jsxs("div",{className:"titlebar-right",children:[!g&&m&&l.jsx("button",{className:`titlebar-nav-btn${h?" titlebar-nav-btn--active":""}`,onClick:m,title:"Focus mode","aria-label":"Focus mode","aria-pressed":h,children:l.jsx(RT,{})}),!g&&d&&l.jsx("button",{className:`titlebar-nav-btn${f?" titlebar-nav-btn--active":""}`,onClick:d,title:"Toggle format toolbar","aria-label":"Toggle format toolbar","aria-pressed":f,children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M4 20h16"}),l.jsx("path",{d:"m6 16 6-12 6 12"}),l.jsx("path",{d:"M8 12h8"})]})}),!g&&l.jsx("button",{className:"titlebar-nav-btn",onClick:()=>v(x||"activity"),title:"Show right rail","aria-label":"Show right rail",children:l.jsx(a$,{})})]})]})}const wk="ow-update-dismissed";function c$(){const[t,e]=y.useState(null);if(y.useEffect(()=>{fetch("/api/update-info").then(r=>r.json()).then(r=>{if(!r.updateAvailable)return;let s="";try{s=localStorage.getItem(wk)||""}catch{}s!==r.updateAvailable&&e({currentVersion:r.currentVersion,latestVersion:r.updateAvailable,updateCommand:r.updateCommand||"npm update -g openwriter"})}).catch(()=>{})},[]),!t)return null;const n=()=>{try{localStorage.setItem(wk,t.latestVersion)}catch{}e(null)};return l.jsxs("div",{className:"editor-update-banner",role:"status","aria-live":"polite",children:[l.jsx("span",{className:"editor-update-dot","aria-hidden":"true"}),l.jsxs("span",{children:["OpenWriter ",l.jsxs("strong",{children:["v",t.latestVersion]})," is available"," ","(you're on v",t.currentVersion,") — update with"," ",l.jsx("code",{className:"editor-update-cmd",children:t.updateCommand})]}),l.jsx("button",{type:"button",className:"editor-update-dismiss",onClick:n,"aria-label":"Dismiss update notification",children:"×"})]})}function Wn(t,e){let n=null;return t.state.doc.descendants((r,s)=>{var i;return((i=r.attrs)==null?void 0:i.id)===e?(n={node:r,pos:s},!1):!0}),n}function nf(t,e){const n=[];return t.state.doc.descendants((r,s)=>{var i;return((i=r.attrs)==null?void 0:i.pendingGroupId)===e&&n.push({nodeId:r.attrs.id,pos:s,node:r}),!0}),n}function ua(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,"").slice(0,8):Math.random().toString(16).slice(2,10)}function Ld(t){return t?Array.isArray(t)?t.map(Ld).join(""):t.text?t.text:t.content&&Array.isArray(t.content)?t.content.map(e=>Ld(e)).join(""):"":""}const u$=new Set(["paragraph","heading","codeBlock","horizontalRule","table","image"]);function Dd(t,e){for(const n of t)n.type&&u$.has(n.type)?n.attrs={...n.attrs,pendingStatus:e}:n.content&&Dd(n.content,e)}function Qg(t,e,n,r){const s=Array.isArray(n)?n:[n],i=(r==null?void 0:r.autoAccept)===!0;if(e.nodeId&&!e.afterNodeId&&!e.beforeNodeId){const m=Wn(t,e.nodeId);if(!m)return{success:!1,error:`Node ${e.nodeId} not found`};const g=s.map((v,x)=>{var k;return{...v,attrs:{...v.attrs,id:((k=v.attrs)==null?void 0:k.id)||(x===0?e.nodeId:ua())}}});i||Dd(g,"insert");try{return t.chain().deleteRange({from:m.pos,to:m.pos+m.node.nodeSize}).insertContentAt(m.pos,g).run(),{success:!0,nodeId:e.nodeId}}catch(v){return{success:!1,error:`Failed to replace empty node: ${v}`}}}if(!e.afterNodeId&&!e.beforeNodeId)return{success:!1,error:"Insert requires afterNodeId, beforeNodeId, or nodeId"};const o=e.afterNodeId||e.beforeNodeId,c=!!e.afterNodeId,d=Wn(t,o);if(!d)return{success:!1,error:`Anchor node ${o} not found`};if(!i){const m=Ld(n),g=c?d.pos+d.node.nodeSize:0,v=c?d.pos+d.node.nodeSize+5e3:d.pos;let x=null;if(t.state.doc.nodesBetween(g,Math.min(v,t.state.doc.content.size),k=>{var w,S;return((w=k.attrs)==null?void 0:w.pendingStatus)==="insert"&&((S=k.attrs)!=null&&S.id)&&(k.textContent||"")===m?(x=k.attrs.id,!1):!0}),x)return{success:!0,nodeId:x}}const f=s.map(m=>{var g;return{...m,attrs:{...m.attrs,id:((g=m.attrs)==null?void 0:g.id)||ua()}}});i||Dd(f,"insert");const h=c?d.pos+d.node.nodeSize:d.pos;try{return t.chain().insertContentAt(h,f).run(),{success:!0,nodeId:f[0].attrs.id}}catch(m){return{success:!1,error:`Failed to insert content: ${m}`}}}function ub(t,e,n,r,s){var w,S,N,j,M,_;const i=Wn(t,e);if(!i)return{success:!1,error:`Node ${e} not found`};const{node:o,pos:c}=i,d=Array.isArray(n)?n:[n],f=(s==null?void 0:s.autoAccept)===!0,m=!((w=o.attrs)!=null&&w.pendingOriginalContent)?o.toJSON():o.attrs.pendingOriginalContent,v=((S=d[0])==null?void 0:S.type)==="listItem"&&((_=(M=(j=(N=d[0])==null?void 0:N.content)==null?void 0:j[0])==null?void 0:M.attrs)==null?void 0:_.pendingStatus)!=null?{...d[0],attrs:{...d[0].attrs,id:e}}:{...d[0],attrs:f?{...d[0].attrs,id:e}:{...d[0].attrs,id:e,pendingStatus:"rewrite",pendingOriginalContent:m,...r?{pendingSelectionFrom:r.selectionFrom,pendingSelectionTo:r.selectionTo,pendingOriginalFrom:r.originalFrom,pendingOriginalTo:r.originalTo}:{}}},x=d.slice(1).map(R=>{var L;return{...R,attrs:{...R.attrs,id:((L=R.attrs)==null?void 0:L.id)||ua()}}});f||Dd(x,"insert");const k=[v,...x];try{return t.chain().command(({tr:R})=>{const L=k.map($=>t.state.schema.nodeFromJSON($));return R.replaceWith(c,c+o.nodeSize,L),!0}).run(),{success:!0,nodeId:e}}catch(R){return{success:!1,error:`Failed to rewrite: ${R}`}}}function d$(t,e,n){if(e.length===0)return{success:!1,error:"Range rewrite requires original IDs"};if(!n||n.length===0)return{success:!1,error:"Range rewrite requires new content (received empty)"};if(n.map(m=>Ld(m)).join("").trim().length===0)return{success:!1,error:"Range rewrite content is empty (no text) — aborting"};const s=Wn(t,e[0]),i=Wn(t,e[e.length-1]);if(!s||!i)return{success:!1,error:"Could not find original nodes for range rewrite"};const o=[];for(const m of e){const g=Wn(t,m);g&&o.push(g.node.toJSON())}const c=s.pos,d=i.pos+i.node.nodeSize,f=ua()+ua(),h=n.map((m,g)=>{var v;return{...m,attrs:{...m.attrs,id:((v=m.attrs)==null?void 0:v.id)||ua(),pendingStatus:"rewrite",pendingGroupId:f,...g===0?{pendingOriginalContent:o}:{}}}});try{return t.chain().deleteRange({from:c,to:d}).insertContentAt(c,h).run(),{success:!0,nodeId:h[0].attrs.id}}catch(m){return{success:!1,error:`Failed to apply range rewrite: ${m}`}}}function OT(t,e,n){var c;const r=Wn(t,e);if(!r)return{success:!1,error:`Node ${e} not found`};const{node:s,pos:i}=r,o=(n==null?void 0:n.autoAccept)===!0;if(!o&&((c=s.attrs)==null?void 0:c.pendingStatus)==="delete")return{success:!0,nodeId:e};try{return o?t.chain().deleteRange({from:i,to:i+s.nodeSize}).run():t.chain().command(({tr:d})=>(d.setNodeMarkup(i,void 0,{...s.attrs,pendingStatus:"delete"}),!0)).run(),{success:!0,nodeId:e}}catch(d){return{success:!1,error:`Failed to ${o?"delete":"mark for deletion"}: ${d}`}}}function f$(t,e){const n=e.autoAccept?{autoAccept:!0}:void 0;if(e.operation==="rewrite"&&e.nodeId&&e.content){const r=ub(t,e.nodeId,e.content,null,n);return{success:r.success,error:r.error}}if(e.operation==="insert"&&e.content){let r=null;if(e.nodeId&&!e.afterNodeId?r={nodeId:e.nodeId}:e.afterNodeId&&(r={afterNodeId:e.afterNodeId}),!r)return{success:!1,error:"Insert requires afterNodeId or nodeId"};const s=Qg(t,r,e.content,n);return{success:s.success,error:s.error}}if(e.operation==="delete"&&e.nodeId){const r=OT(t,e.nodeId,n);return{success:r.success,error:r.error}}return{success:!1,error:`Invalid operation: ${e.operation}`}}function Rp(t,e){if(e.length===0)return;if(e.length===1){f$(t,e[0]);return}const n=t.state.schema;t.chain().command(({tr:r})=>{var s;for(const i of e)try{const o=i.autoAccept===!0;if(i.operation==="rewrite"&&i.nodeId&&i.content){const c=nl(r.doc,i.nodeId);if(!c){console.warn("[openwriter] rewrite skipped — node id not found in editor",{nodeId:i.nodeId});continue}const f=(Array.isArray(i.content)?i.content:[i.content]).map(h=>n.nodeFromJSON(h));r.replaceWith(c.pos,c.pos+c.node.nodeSize,f)}else if(i.operation==="insert"&&i.content){const d=(Array.isArray(i.content)?i.content:[i.content]).map(f=>n.nodeFromJSON(f));if(!o){const f=d.map(h=>h.textContent||"").join("");if(f&&i.afterNodeId){const h=nl(r.doc,i.afterNodeId);if(h){const m=h.pos+h.node.nodeSize,g=Math.min(m+5e3,r.doc.content.size);let v=!1;if(r.doc.nodesBetween(m,g,x=>{var k;return v?!1:((k=x.attrs)==null?void 0:k.pendingStatus)==="insert"&&(x.textContent||"")===f?(v=!0,!1):!0}),v)continue}}}if(i.nodeId&&!i.afterNodeId){const f=nl(r.doc,i.nodeId);if(!f){console.warn("[openwriter] insert (replace) skipped — node id not found in editor",{nodeId:i.nodeId});continue}r.replaceWith(f.pos,f.pos+f.node.nodeSize,d)}else if(i.afterNodeId){const f=nl(r.doc,i.afterNodeId);if(!f){console.warn("[openwriter] insert (after) skipped — anchor id not found in editor",{afterNodeId:i.afterNodeId});continue}const h=f.pos+f.node.nodeSize;r.insert(h,ke.fromArray(d))}}else if(i.operation==="delete"&&i.nodeId){const c=nl(r.doc,i.nodeId);if(!c){console.warn("[openwriter] delete skipped — node id not found in editor",{nodeId:i.nodeId});continue}if(o)r.delete(c.pos,c.pos+c.node.nodeSize);else{if(((s=c.node.attrs)==null?void 0:s.pendingStatus)==="delete")continue;r.setNodeMarkup(c.pos,void 0,{...c.node.attrs,pendingStatus:"delete"})}}}catch{continue}return!0}).run()}function nl(t,e){let n=null;return t.descendants((r,s)=>{var i;return((i=r.attrs)==null?void 0:i.id)===e?(n={node:r,pos:s},!1):!0}),n}function h$(t,e){if(!e||e.length===0||t.isDestroyed)return;const n=new Map(e.map(r=>[r.oldId,r.newId]));t.chain().command(({tr:r})=>{const s=[];r.doc.descendants((i,o)=>{var d;const c=(d=i.attrs)==null?void 0:d.id;c&&n.has(c)&&s.push({pos:o,attrs:{...i.attrs,id:n.get(c)}})});for(const{pos:i,attrs:o}of s)r.setNodeMarkup(i,void 0,o);return!0}).run()}function p$(t,e,n,r){const s=[];if(r==="delete"){for(const o of n)s.push(OT(t,o));return s}if(r==="insert"){const o=n[n.length-1];return o&&e.length>0&&s.push(Qg(t,{nodeId:o},e)),s}if(n.length>1){const o=d$(t,n,e);return s.push(o),s}const i=ub(t,n[0],e[0]);if(s.push(i),e.length>1){const o=e.slice(1);s.push(Qg(t,{afterNodeId:n[0]},o))}return s}const kk="[[START_SELECTION]]",Sk="[[END_SELECTION]]";function m$(t){if(!(t!=null&&t.content)||!Array.isArray(t.content))return 0;let e=0;for(const n of t.content)n.type==="text"&&typeof n.text=="string"?e+=n.text.length:n.type==="hardBreak"&&(e+=1);return e}function ku(t,e,n){if(!(t!=null&&t.content)||!Array.isArray(t.content))return;const r=m$(t);let s=Math.max(0,Math.min(e,r));for(let i=0;i<t.content.length;i++){const o=t.content[i];if(o.type==="text"&&typeof o.text=="string"){if(s<=o.text.length){const c=Math.max(0,Math.min(o.text.length,s));o.text=o.text.slice(0,c)+n+o.text.slice(c);return}s-=o.text.length;continue}if(o.type==="hardBreak"){if(s===0){t.content.splice(i+1,0,{type:"text",text:n});return}s-=1;continue}if(s===0){t.content.splice(i,0,{type:"text",text:n});return}}t.content.push({type:"text",text:n})}function g$(t,e,n){const r=JSON.parse(JSON.stringify(t));return r.length===0?r:r.length===1?(ku(r[0],n,Sk),ku(r[0],e,kk),r):(ku(r[0],e,kk),ku(r[r.length-1],n,Sk),r)}function v$(t){const e=r=>r.replace(/\[\[(START|END)_SELECTION]]/g,""),n=r=>{r.type==="text"&&typeof r.text=="string"&&(r.text=e(r.text)),r.content&&Array.isArray(r.content)&&r.content.forEach(n)};Array.isArray(t)?t.forEach(n):n(t)}let vi=null;function b$(){return vi&&document.body.contains(vi)||(vi=document.createElement("div"),vi.style.cssText=["position:fixed","left:50%","bottom:32px","transform:translateX(-50%)","z-index:99999","display:flex","flex-direction:column","gap:8px","align-items:center","pointer-events:none"].join(";"),document.body.appendChild(vi)),vi}function Ai(t,e="info",n=3500,r){const s=b$(),i=document.createElement("div");i.style.cssText=["background:var(--bg-surface)","border:1px solid var(--border)",e==="error"?"border-left:3px solid var(--color-pending-delete)":"","color:var(--ink-dark)","font-family:var(--font-body)","padding:10px 14px","border-radius:8px","font-size:13px","line-height:1.4","max-width:420px","box-shadow:0 4px 20px rgba(0,0,0,0.15)","pointer-events:auto","opacity:0","transition:opacity 160ms ease, transform 160ms ease","transform:translateY(6px)",r?"display:flex;align-items:center;gap:12px":""].filter(Boolean).join(";");const o=document.createElement("span");if(o.textContent=t,i.appendChild(o),r){const d=document.createElement("button");d.textContent=r.label,d.style.cssText=["flex-shrink:0","padding:4px 12px","border-radius:6px","border:1px solid var(--accent)","background:var(--accent)","color:var(--bg-surface)","font-family:var(--font-body)","font-size:12px","font-weight:600","cursor:pointer"].join(";"),d.addEventListener("click",()=>{try{r.onClick()}finally{c()}}),i.appendChild(d)}function c(){i.style.opacity="0",i.style.transform="translateY(6px)",setTimeout(()=>{i.remove(),s.childElementCount===0&&(s.remove(),vi=null)},200)}s.appendChild(i),requestAnimationFrame(()=>{i.style.opacity="1",i.style.transform="translateY(0)"}),setTimeout(c,n)}function y$(t){return`$${(t/100).toFixed(2)}`}async function x$(){try{const t=await fetch("/api/voice/billing");return t.ok?await t.json():null}catch{return null}}async function w$(){try{const t=await fetch("/api/voice/billing/topup-options");if(!t.ok)return[];const e=await t.json();return Array.isArray(e==null?void 0:e.options)?e.options:[]}catch{return[]}}async function IT(t){try{const e=await fetch("/api/voice/billing/topup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({amount:t})});if(!e.ok){Ai("Could not start top-up. Please try again.","error");return}const n=await e.json();n!=null&&n.url?window.open(n.url,"_blank"):Ai("Could not start top-up. Please try again.","error")}catch{Ai("Could not start top-up. Please try again.","error")}}const Ek=5e3;function Nk(t,e){return t.docId&&e.includes(t.docId)?!0:e.includes(t.filename)}const k$=[{action:"comment",label:"Comment",shortcut:"M",condition:"has-selection"},{action:"delete",label:"Delete",shortcut:"D"}];function S$({editorRef:t,allEditors:e,documentId:n}){const[r,s]=y.useState(!1),[i,o]=y.useState({x:0,y:0}),[c,d]=y.useState(!1),[f,h]=y.useState(""),[m,g]=y.useState(!1),[v,x]=y.useState(""),[k,w]=y.useState(!1),[S,N]=y.useState([]),[j,M]=y.useState([]),[_,R]=y.useState(!1),[L,$]=y.useState(""),[B,U]=y.useState([]),[X,z]=y.useState(!1),[ee,P]=y.useState(""),[F,G]=y.useState(null),[ie,K]=y.useState(null),[ce,J]=y.useState(null),[A,D]=y.useState(!1),[q,le]=y.useState(null),[ye,oe]=y.useState(null),Se=y.useRef(null),Ee=y.useRef(null),Le=y.useRef(null),Ie=y.useCallback(ne=>{if(e&&e.length>0){for(const me of e)if(me.view.dom.contains(ne))return me}const he=t.current;return he&&he.view.dom.contains(ne)?he:null},[e,t]);y.useLayoutEffect(()=>{const ne=Se.current;if(!ne||!r)return;const he=ne.getBoundingClientRect(),me=8;let{x:ze,y:Ae}=i;Ae+he.height+me>window.innerHeight&&(Ae=i.y-he.height),ze+he.width+me>window.innerWidth&&(ze=i.x-he.width),Ae<me&&(Ae=me),ze<me&&(ze=me),(ze!==i.x||Ae!==i.y)&&o({x:ze,y:Ae})},[r,i]);const Ve=y.useCallback(()=>{fetch("/api/plugins").then(ne=>ne.json()).then(ne=>{const he=[];for(const me of ne.plugins||[]){const ze=me.displayName||void 0;for(const Ae of me.contextMenuItems||[])he.push({...Ae,pluginDisplayName:ze})}U(he)}).catch(()=>{})},[]);y.useEffect(()=>{Ve()},[Ve]),y.useEffect(()=>{const ne=()=>Ve();return window.addEventListener("ow-plugins-changed",ne),()=>window.removeEventListener("ow-plugins-changed",ne)},[Ve]),y.useEffect(()=>{const ne=he=>{Se.current&&!Se.current.contains(he.target)&&(s(!1),g(!1),w(!1),z(!1),P(""),G(null),K(null),le(null))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[]);const Te=y.useCallback(()=>{const ne=Le.current||t.current;return ne?ne.isActive("link"):!1},[t]),qe=y.useCallback(()=>{const ne=Le.current||t.current,he=Ee.current;if(!ne||!he)return!1;const{from:me,to:ze}=he;let Ae=!1;return ne.state.doc.nodesBetween(me,ze,Xe=>{var Qe;return(Qe=Xe.attrs)!=null&&Qe.pendingStatus&&(Ae=!0),!Ae}),Ae},[t]),pt=y.useCallback(()=>{const ne=Le.current||t.current,he=Ee.current,me=(he==null?void 0:he.from)??0,ze=(he==null?void 0:he.to)??0,Ae=me!==ze,Xe=(()=>{if(!ne)return!1;try{return ne.state.doc.resolve(me).parent.content.size===0}catch{return!1}})(),Qe=qe(),tt=[];for(const We of B)We.condition==="has-selection"&&!Ae||We.condition==="empty-node"&&!Xe||tt.push({action:We.action,label:We.label,shortcut:We.shortcut,isPlugin:!0,promptForInput:We.promptForInput,pluginDisplayName:We.pluginDisplayName});for(const We of k$)We.condition==="has-selection"&&(!Ae||Qe)||tt.push(We);if(Ae&&tt.push({action:"link",label:"Link to doc",shortcut:"L"}),Te()&&tt.push({action:"unlink",label:"Unlink"}),ce&&ce.entries.length>0&&tt.unshift({action:"see-connections",label:`See connections (${ce.entries.length})`}),q){const We=q.title?`Go to "${q.title}"`:"Go to target";tt.unshift({action:"go-to-target",label:We})}return tt},[t,Te,B,qe,ce,q]);y.useEffect(()=>{const ne=me=>{var We;if(me.button!==2)return;const ze=Ie(me.target);if(!ze)return;Le.current=ze;const{from:Ae,to:Xe}=ze.state.selection,Qe=[],tt=[];if(Ae!==Xe&&ze.state.doc.nodesBetween(Ae,Xe,Ue=>{Ue.isBlock&&Ue.type.name!=="doc"&&(Qe.push(Ue.toJSON()),Ue.attrs.id&&tt.push(Ue.attrs.id))}),Qe.length===0){const{$from:Ue}=ze.state.selection,st=Ue.parent;st&&st.type.name!=="doc"&&(Qe.push(st.toJSON()),(We=st.attrs)!=null&&We.id&&tt.push(st.attrs.id))}Ee.current={from:Ae,to:Xe,nodes:Qe,nodeIds:tt}},he=me=>{var st,mt,Nt,Mt,Jt,nn;if(!Ie(me.target)||me.shiftKey)return;const Ae=(mt=(st=me.target)==null?void 0:st.closest)==null?void 0:mt.call(st,"[data-comment-id]"),Xe=(Ae==null?void 0:Ae.getAttribute("data-comment-id"))||null,Qe=(Mt=(Nt=me.target)==null?void 0:Nt.closest)==null?void 0:Mt.call(Nt,".linked-paragraph[data-backlinks-node]"),tt=(Qe==null?void 0:Qe.getAttribute("data-backlinks-node"))||null,We=(nn=(Jt=me.target)==null?void 0:Jt.closest)==null?void 0:nn.call(Jt,"span.doc-link[data-doc]"),Ue=(We==null?void 0:We.getAttribute("data-doc"))||null;if(me.preventDefault(),o({x:me.clientX,y:me.clientY}),s(!0),g(!1),w(!1),D(!1),z(!1),P(""),G(null),Xe){const at=Ee.current;if(!(!!at&&at.from!==at.to)){const T=$u().find(W=>W.id===Xe);if(T){K({id:T.id,text:T.text,note:T.note}),J(null);return}}}if(K(null),tt){const at=B5(tt);J(at.length>0?{nodeId:tt,entries:at}:null)}else J(null);if(Ue){const at=Ue.indexOf("?"),Ht=at>=0?Ue.slice(0,at):Ue,[T,W]=Ht.split("#"),ae=T&&/^[a-f0-9]{8}$/.test(T)?T:null,I=W&&/^[a-f0-9]{8}$/.test(W)?W:null;if(ae){const V=S.find(re=>re.docId===ae);le({docId:ae,nodeId:I,title:(V==null?void 0:V.title)||null}),V||fetch("/api/documents").then(re=>re.json()).then(re=>{if(Array.isArray(re)){const Q=re.map(ve=>({filename:ve.filename,title:ve.title,docId:ve.docId}));N(Q);const ue=Q.find(ve=>ve.docId===ae);ue&&le(ve=>ve&&ve.docId===ae?{...ve,title:ue.title}:ve)}}).catch(()=>{})}else le(null)}else le(null)};return document.addEventListener("mousedown",ne,!0),document.addEventListener("contextmenu",he),()=>{document.removeEventListener("mousedown",ne,!0),document.removeEventListener("contextmenu",he)}},[Ie]);const ut=y.useCallback(async(ne,he)=>{var mt,Nt,Mt,Jt,nn;const me=Le.current||t.current;if(!me)return;const ze=Ee.current;if(!ze||ze.nodes.length===0){console.warn("[ContextMenu] No captured selection for action:",ne);return}let{nodes:Ae,nodeIds:Xe}=ze;const{from:Qe,to:tt}=ze;d(!0),s(!1),g(!1);const We=`ctx-${Date.now()}`,Ue=ne.includes(":")?ne.split(":").slice(1).join(":"):ne,st=["insert","fill","fill-sentence"].includes(Ue);if(st)me.commands.showInsertionLoading(We,Qe);else{const at=me.state.doc.resolve(Qe),Ht=me.state.doc.resolve(tt),T=at.sameParent(Ht)&&Qe!==tt;me.commands.applyLoadingEffect(We,Qe,tt,T?"selection":"paragraph")}try{const at=[],Ht=[],T=new Set(Xe);let W=!1;const ae=me.state.doc;for(let $e=0;$e<ae.childCount;$e++){const zt=ae.child($e),qn=(mt=zt.attrs)==null?void 0:mt.id;if(qn&&T.has(qn))W=!0;else if(W){const fn=zt.textContent.trim();fn&&Ht.push(fn)}else{const fn=zt.textContent.trim();fn&&at.push(fn)}}let I=Ae,V=!1,re=0,Q=0;const ue=Qe!==tt?me.state.doc.resolve(Qe):null,ve=Qe!==tt?me.state.doc.resolve(tt):null;if((ue&&ve?ue.sameParent(ve):!1)&&ue&&Ae.length===1){const $e=ue.start(ue.depth);re=Qe-$e,Q=tt-$e;const zt=((Mt=(Nt=Ae[0])==null?void 0:Nt.content)==null?void 0:Mt.reduce((qn,fn)=>{var gr;return qn+(((gr=fn.text)==null?void 0:gr.length)||(fn.type==="hardBreak"?1:0))},0))??0;(re>0||Q<zt)&&(I=g$(Ae,re,Q),V=!0)}const xe=me.state.doc.textContent,Dt={nodes:I,action:Ue,nodeIds:Xe,contextBefore:at.slice(-3),contextAfter:Ht.slice(0,3),fullDocument:xe,documentId:n,debug:!0};V&&(Dt.hasSelectionMarkers=!0),he&&(Dt.instruction=he);const dn=((Ae||[]).map($e=>Array.isArray($e==null?void 0:$e.content)?$e.content.map(zt=>(zt==null?void 0:zt.text)||"").join(" "):"").join(" ").match(/\S+/g)||[]).length;if(dn>Ek){Ai(`Selection too large: ${dn.toLocaleString()} words (max ${Ek.toLocaleString()}). Select a smaller section.`,"error"),st?me.commands.removeInsertionLoading(We):me.commands.removeLoadingEffect(We);return}const Xt=await fetch(`${window.location.origin}/api/voice/apply-editor`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Dt)});if(!Xt.ok){const $e=await Xt.json().catch(()=>({}));console.error("[ContextMenu] API error:",Xt.status,$e);const zt=typeof($e==null?void 0:$e.message)=="string"&&$e.message||typeof($e==null?void 0:$e.error)=="string"&&$e.error||`Enhance failed (${Xt.status}). Please try again.`;Xt.status===402&&($e==null?void 0:$e.error)==="insufficient_balance"?Ai(zt,"error",9e3,{label:"Top up",onClick:()=>IT(5)}):Ai(zt,"error");return}const ln=await Xt.json();if(ln.success&&ln.nodes){let $e=ln.nodes;if($e.length===1&&Array.isArray($e[0])&&($e=$e[0]),v$($e),V&&$e.length===1&&Xe.length===1){const zt=ur=>(ur??[]).reduce((Xs,Wt)=>Xs+(typeof Wt.text=="string"?Wt.text:Wt.type==="hardBreak"?`
206
206
  `:""),""),qn=zt((Jt=Ae[0])==null?void 0:Jt.content),fn=zt((nn=$e[0])==null?void 0:nn.content),gr=Math.min(qn.length,fn.length);let vr=0;for(;vr<gr&&qn[vr]===fn[vr];)vr++;let _r=0;const hn=gr-vr;for(;_r<hn&&qn[qn.length-1-_r]===fn[fn.length-1-_r];)_r++;const An={selectionFrom:vr,selectionTo:fn.length-_r,originalFrom:vr,originalTo:qn.length-_r};ub(me,Xe[0],$e[0],An)}else p$(me,$e,Xe,Ue);window.dispatchEvent(new CustomEvent("ow-pending-write-applied")),ln.debug&&fetch("/api/prompt-debug",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:Ue,debug:ln.debug,metadata:ln.metadata})}).catch(()=>{})}else console.warn("[ContextMenu] Unexpected response:",ln)}catch(at){console.error("[ContextMenu] Plugin action failed:",at)}finally{st?me.commands.removeInsertionLoading(We):me.commands.removeLoadingEffect(We),d(!1)}},[t]),be=y.useCallback(async ne=>{const he=Le.current||t.current;if(!he)return;const{$from:me}=he.state.selection,ze=me.before(me.depth),Ae=me.after(me.depth),Xe=me.parent.content.size===0;d(!0),s(!1),g(!1),Xe?he.chain().focus().deleteRange({from:ze,to:Ae}).insertContentAt(ze,{type:"imageLoading"}).run():he.chain().focus().insertContentAt(Ae,{type:"imageLoading"}).run();let Qe=-1;he.state.doc.descendants((tt,We)=>{if(tt.type.name==="imageLoading"&&Qe===-1)return Qe=We,tt.nodeSize,!1});try{const tt=await fetch("/api/image-gen/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:ne})}),We=await tt.json().catch(()=>({success:!1,error:`Generation failed (${tt.status})`}));if(We.success&&We.src){let Ue=-1,st=0;if(he.state.doc.descendants((mt,Nt)=>{if(mt.type.name==="imageLoading"&&Ue===-1)return Ue=Nt,st=mt.nodeSize,!1}),Ue>=0){const{tr:mt}=he.state;mt.replaceWith(Ue,Ue+st,he.schema.nodes.image.create({src:We.src,alt:ne})),he.view.dispatch(mt)}}else{console.error("[ContextMenu] Image generation failed:",We.error);let Ue=-1,st=0;if(he.state.doc.descendants((mt,Nt)=>{if(mt.type.name==="imageLoading"&&Ue===-1)return Ue=Nt,st=mt.nodeSize,!1}),Ue>=0){const{tr:mt}=he.state;mt.delete(Ue,Ue+st),he.view.dispatch(mt)}}}catch(tt){console.error("[ContextMenu] Image generation failed:",tt);let We=-1,Ue=0;if(he.state.doc.descendants((st,mt)=>{if(st.type.name==="imageLoading"&&We===-1)return We=mt,Ue=st.nodeSize,!1}),We>=0){const{tr:st}=he.state;st.delete(We,We+Ue),he.view.dispatch(st)}}finally{d(!1)}},[t]),ht=y.useCallback(ne=>{const{action:he,isPlugin:me,promptForInput:ze}=ne;if(me&&ze){x(he),g(!0);return}if(me){if(he.startsWith("img:"))return;ut(he);return}if(he==="comment"){z(!0);return}if(he==="delete"){const Ae=Le.current||t.current,Xe=Ee.current;if(Ae&&Xe&&Xe.nodeIds.length>0){const{tr:Qe}=Ae.state,tt=new Set(Xe.nodeIds),We=[];Ae.state.doc.descendants((Ue,st)=>{var mt;if((mt=Ue.attrs)!=null&&mt.id&&tt.has(Ue.attrs.id))return We.push({from:st,to:st+Ue.nodeSize}),!1});for(const Ue of We.reverse())Qe.delete(Ue.from,Ue.to);We.length>0&&Ae.view.dispatch(Qe)}s(!1);return}if(he==="link"){const Ae=Le.current||t.current;if(Ae){const Xe=[];Ae.state.doc.descendants(Qe=>{var tt;(tt=Qe.marks)==null||tt.forEach(We=>{var Ue,st;if(We.type.name==="link"&&((st=(Ue=We.attrs)==null?void 0:Ue.href)!=null&&st.startsWith("doc:"))){const mt=G5(We.attrs.href);mt&&!Xe.includes(mt)&&Xe.push(mt)}})}),M(Xe)}fetch("/api/documents").then(Xe=>Xe.json()).then(Xe=>{Array.isArray(Xe)&&N(Xe.map(Qe=>({filename:Qe.filename,title:Qe.title,docId:Qe.docId}))),R(!1),$(""),w(!0)}).catch(()=>{});return}if(he==="unlink"){const Ae=Le.current||t.current;Ae&&Ae.chain().focus().unsetLink().run(),s(!1);return}if(he==="see-connections"){fetch("/api/documents").then(Ae=>Ae.json()).then(Ae=>{Array.isArray(Ae)&&N(Ae.map(Xe=>({filename:Xe.filename,title:Xe.title,docId:Xe.docId})))}).catch(()=>{}),D(!0);return}if(he==="go-to-target"){q&&window.dispatchEvent(new CustomEvent("ow-navigate-to-link",{detail:{docId:q.docId,nodeId:q.nodeId,filename:null,quote:null}})),s(!1),le(null);return}},[ut,t,q]),xt=y.useCallback(()=>{f.trim()&&(v.startsWith("img:")?be(f.trim()):ut(v,f.trim()),h(""),x(""))},[ut,be,v,f]),St=y.useCallback(()=>{if(!n)return;if(F){fetch("/api/comments",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:n,id:F.id,note:ee.trim()})}).then(()=>{s(!1),z(!1),P(""),G(null)}).catch(Qe=>{console.error("[ContextMenu] Comment edit failed:",Qe)});return}const ne=Le.current||t.current,he=Ee.current;if(!ne||!he)return;const{from:me,to:ze,nodeIds:Ae}=he;if(me===ze||Ae.length===0)return;const Xe=ne.state.doc.textBetween(me,ze,`
207
207
  `);Xe.trim()&&fetch("/api/comments",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:n,text:Xe,note:ee.trim(),nodeId:Ae[Ae.length-1],nodeIds:Ae})}).then(()=>{s(!1),z(!1),P("")}).catch(Qe=>{console.error("[ContextMenu] Comment create failed:",Qe)})},[t,n,ee,F]),At=y.useCallback(()=>{ie&&(G({id:ie.id,text:ie.text}),P(ie.note),z(!0),K(null))},[ie]),Ye=y.useCallback(()=>{ie&&fetch("/api/comments/resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[ie.id]})}).then(()=>{s(!1),K(null)}).catch(ne=>{console.error("[ContextMenu] Comment resolve failed:",ne)})},[ie]),ct=y.useCallback(()=>{ie&&fetch("/api/comments",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[ie.id]})}).then(()=>{s(!1),K(null)}).catch(ne=>{console.error("[ContextMenu] Comment delete failed:",ne)})},[ie]),Fe=y.useCallback((ne,he)=>{const me=Le.current||t.current;if(me){const ze=ne.docId?Ap({docId:ne.docId,nodeId:he==null?void 0:he.nodeId,quote:he==null?void 0:he.quote}):Ap({filename:ne.filename});me.chain().focus().setLink({href:ze}).run()}fetch("/api/auto-tag-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetFile:ne.filename})}).catch(()=>{}),s(!1),w(!1),oe(null)},[t]),Y=y.useCallback(ne=>{if(!ne.docId){Fe(ne);return}oe({docId:ne.docId,filename:ne.filename,title:ne.title,paragraphs:[],loading:!0}),fetch(`/api/documents/by-doc-id/${ne.docId}/paragraphs`).then(he=>he.json()).then(he=>{oe(me=>me&&me.docId===ne.docId?{...me,paragraphs:Array.isArray(he.paragraphs)?he.paragraphs:[],loading:!1}:me)}).catch(()=>{oe(he=>he&&he.docId===ne.docId?{...he,paragraphs:[],loading:!1}:he)})},[Fe]),ge=y.useCallback(()=>{const ne=L.trim();if(!ne)return;const he=Le.current||t.current;he&&(fetch("/api/create-link-doc",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:ne})}).then(me=>me.json()).then(me=>{if(me.filename){const ze=Ap(me.docId?{docId:me.docId}:{filename:me.filename});he.chain().focus().setLink({href:ze}).run()}}).catch(()=>{}),s(!1),w(!1),R(!1),$(""))},[t,L]);return r?l.jsx("div",{ref:Se,className:"context-menu",style:{left:i.x,top:i.y},children:c?l.jsx("div",{className:"context-menu-loading",children:"Applying..."}):X?l.jsxs("div",{className:"context-menu-comment-editor",children:[(()=>{const ne=(F==null?void 0:F.text)??(()=>{const he=Le.current||t.current,me=Ee.current;return!he||!me||me.from===me.to?"":he.state.doc.textBetween(me.from,me.to,`
208
- `)})();return ne?l.jsx("div",{className:"context-menu-comment-quote",children:ne}):null})(),l.jsx("textarea",{autoFocus:!0,className:"context-menu-comment-textarea",value:ee,onChange:ne=>P(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"&&(ne.metaKey||ne.ctrlKey)&&(ne.preventDefault(),St()),ne.key==="Escape"&&(s(!1),z(!1),P(""),G(null))},placeholder:"Note for agent (optional)...",rows:4}),l.jsxs("div",{className:"context-menu-comment-actions",children:[l.jsx("span",{className:"context-menu-comment-hint",children:"⌘↵ to save · Esc to cancel"}),l.jsx("button",{onClick:St,children:F?"Save":"Comment"})]})]}):ie?l.jsxs(l.Fragment,{children:[l.jsx("button",{className:"context-menu-item",onClick:At,children:l.jsx("span",{children:"Edit comment"})}),l.jsx("button",{className:"context-menu-item",onClick:Ye,children:l.jsx("span",{children:"Resolve comment"})}),l.jsx("button",{className:"context-menu-item",onClick:ct,children:l.jsx("span",{children:"Delete comment"})})]}):m?l.jsxs("div",{className:"context-menu-custom",children:[l.jsx("input",{autoFocus:!0,value:f,onChange:ne=>h(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"&&xt(),ne.key==="Escape"&&s(!1)},placeholder:"Custom instruction..."}),l.jsx("button",{onClick:xt,children:"Apply"})]}):ye?l.jsxs("div",{className:"context-menu-link-picker",children:[l.jsxs("div",{className:"context-menu-link-header",children:[l.jsx("button",{className:"context-menu-link-back",onClick:()=>oe(null),title:"Back to doc list",children:"←"}),l.jsxs("span",{children:['Pick paragraph in "',ye.title,'"']})]}),l.jsx("button",{className:"context-menu-item context-menu-new-link",onClick:()=>Fe({filename:ye.filename,docId:ye.docId}),children:l.jsx("span",{children:"Link whole doc"})}),l.jsx("div",{className:"context-menu-link-list",children:ye.loading?l.jsx("div",{className:"context-menu-loading",children:"Loading…"}):ye.paragraphs.length===0?l.jsx("div",{className:"context-menu-loading",children:"No paragraphs"}):ye.paragraphs.map(ne=>{const he=ne.preview.replace(/…$/,"").slice(0,50),me=ne.type==="heading"?Math.max(0,(ne.level||1)-1)*12:12;return l.jsx("button",{className:`context-menu-item context-menu-paragraph-row context-menu-paragraph-row--${ne.type}`,style:{paddingLeft:8+me},onClick:()=>Fe({filename:ye.filename,docId:ye.docId},{nodeId:ne.nodeId,quote:he}),children:l.jsx("span",{children:ne.preview})},ne.nodeId)})})]}):A&&ce?l.jsxs("div",{className:"context-menu-link-picker",children:[l.jsxs("div",{className:"context-menu-link-header",children:["Linked from ",ce.entries.length," ",ce.entries.length===1?"place":"places"]}),l.jsx("div",{className:"context-menu-link-list",children:ce.entries.map((ne,he)=>{const me=S.find(Ae=>Ae.docId===ne.from_doc),ze=(me==null?void 0:me.title)||ne.from_doc;return l.jsxs("button",{className:"context-menu-item",onClick:()=>{window.dispatchEvent(new CustomEvent("ow-navigate-to-link",{detail:{docId:ne.from_doc,nodeId:ne.from_node,filename:null,quote:null}})),s(!1),D(!1)},children:[l.jsx("span",{children:ze}),l.jsxs("span",{className:"context-menu-shortcut",children:['"',ne.text,'"']})]},`${ne.from_doc}-${ne.from_node}-${he}`)})})]}):k?l.jsxs("div",{className:"context-menu-link-picker",children:[l.jsx("div",{className:"context-menu-link-header",children:"Link to document"}),_?l.jsxs("div",{className:"context-menu-custom",children:[l.jsx("input",{autoFocus:!0,value:L,onChange:ne=>$(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"&&ge(),ne.key==="Escape"&&R(!1)},placeholder:"New document title..."}),l.jsx("button",{onClick:ge,children:"Create"})]}):l.jsx("button",{className:"context-menu-item context-menu-new-link",onClick:()=>R(!0),children:l.jsx("span",{children:"+ New link doc"})}),l.jsxs("div",{className:"context-menu-link-list",children:[j.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-section-header",children:"Linked in this doc"}),S.filter(ne=>Nk(ne,j)).map(ne=>l.jsxs("div",{className:"context-menu-link-row",children:[l.jsx("button",{className:"context-menu-item context-menu-link-row__main",onClick:()=>Fe(ne),children:l.jsx("span",{children:ne.title})}),ne.docId&&l.jsx("button",{className:"context-menu-link-row__drill",title:"Pick a paragraph in this doc",onClick:()=>Y(ne),children:"▸"})]},`linked-${ne.filename}`))]}),l.jsx("div",{className:"context-menu-section-header",children:"All documents"}),S.filter(ne=>!Nk(ne,j)).map(ne=>l.jsxs("div",{className:"context-menu-link-row",children:[l.jsx("button",{className:"context-menu-item context-menu-link-row__main",onClick:()=>Fe(ne),children:l.jsx("span",{children:ne.title})}),ne.docId&&l.jsx("button",{className:"context-menu-link-row__drill",title:"Pick a paragraph in this doc",onClick:()=>Y(ne),children:"▸"})]},ne.filename)),S.length===0&&l.jsx("div",{className:"context-menu-loading",children:"No documents"})]})]}):(()=>{const ne=pt();let he;return ne.map((me,ze)=>{const Ae=me.isPlugin&&me.pluginDisplayName&&me.pluginDisplayName!==he,Xe=he!==void 0;me.isPlugin?he=me.pluginDisplayName:he=void 0;const Qe=!me.isPlugin&&Xe;return l.jsxs("span",{children:[Ae&&l.jsx("div",{className:"context-menu-section-header",children:me.pluginDisplayName}),Qe&&l.jsx("div",{className:"context-menu-divider"}),l.jsxs("button",{className:"context-menu-item",onClick:()=>ht(me),children:[l.jsx("span",{children:me.label}),me.shortcut&&l.jsx("span",{className:"context-menu-shortcut",children:me.shortcut})]})]},me.action)})})()}):null}const E$=80,Op=8,Zo=8,N$=400;function Ck(t){return t.nodeIds&&t.nodeIds.length>0?t.nodeIds:[t.nodeId]}function _k(t,e){const n=new Set(e);return t.every(r=>n.has(r))}function C$(t,e){const n=e.find(s=>s.id===t);if(!n)return[];const r=Ck(n);return e.filter(s=>{if(s.id===n.id)return!0;const i=Ck(s);return _k(i,r)||_k(r,i)}).sort((s,i)=>(s.createdAt||"").localeCompare(i.createdAt||""))}function _$({documentId:t}){const[e,n]=y.useState(null),[r,s]=y.useState({kind:"view"}),[i,o]=y.useState(""),[c,d]=y.useState(0),[f,h]=y.useState({left:0,top:0,placement:"above"}),m=y.useRef(null),g=y.useRef(null),v=y.useRef(null),x=y.useRef(null),k=y.useRef({kind:"view"});y.useEffect(()=>{x.current=e},[e]),y.useEffect(()=>{k.current=r},[r]),y.useEffect(()=>{const ee=()=>d(P=>P+1);return window.addEventListener("ow-comments-changed",ee),()=>window.removeEventListener("ow-comments-changed",ee)},[]);const w=y.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},[]),S=y.useCallback(()=>{w(),v.current=window.setTimeout(()=>{k.current.kind==="view"&&n(null)},E$)},[w]),N=y.useCallback(()=>{w(),n(null),s({kind:"view"}),o("")},[w]),j=y.useMemo(()=>e?C$(e.commentId,$u()):[],[e,c]);y.useEffect(()=>{e&&j.length===0&&N()},[e,j.length,N]),y.useLayoutEffect(()=>{if(!e)return;const ee=m.current;if(!ee)return;const P=ee.getBoundingClientRect(),{rect:F}=e,G=F.top,ie=window.innerHeight-F.bottom,K=G>=P.height+Op||G>=ie?"above":"below",ce=K==="above"?Math.max(Zo,F.top-P.height-Op):Math.min(window.innerHeight-P.height-Zo,F.bottom+Op);let J=F.left;J+P.width>window.innerWidth-Zo&&(J=window.innerWidth-P.width-Zo),J<Zo&&(J=Zo),h({left:J,top:ce,placement:K})},[e,r,j.length,c]),y.useEffect(()=>{const ee=ie=>{var J,A,D;const K=ie.target,ce=(J=K==null?void 0:K.closest)==null?void 0:J.call(K,"[data-comment-id]");if(ce){const q=ce.getAttribute("data-comment-id");if(!q)return;if(((A=x.current)==null?void 0:A.commentId)===q){w();return}w(),s({kind:"view"}),o(""),n({commentId:q,rect:ce.getBoundingClientRect()});return}if((D=m.current)!=null&&D.contains(K)){w();return}x.current&&S()},P=ie=>{var ce,J;const K=ie.relatedTarget;if(K&&((ce=m.current)!=null&&ce.contains(K))){w();return}K&&((J=K.closest)!=null&&J.call(K,"[data-comment-id]"))||x.current&&S()},F=ie=>{if(ie.key==="Escape"&&x.current){if(ie.preventDefault(),k.current.kind!=="view"){s({kind:"view"}),o("");return}N()}},G=ie=>{var K;x.current&&k.current.kind==="view"&&((K=m.current)!=null&&K.contains(ie.target)||N())};return document.addEventListener("mouseover",ee),document.addEventListener("mouseout",P),document.addEventListener("keydown",F),document.addEventListener("scroll",G,!0),()=>{document.removeEventListener("mouseover",ee),document.removeEventListener("mouseout",P),document.removeEventListener("keydown",F),document.removeEventListener("scroll",G,!0),w()}},[w,S,N]),y.useEffect(()=>{var ee;r.kind!=="view"&&((ee=g.current)==null||ee.focus())},[r]);const M=y.useCallback(ee=>{const P=$u().find(F=>F.id===ee);P&&(o(P.note||""),s({kind:"edit",commentId:ee}))},[]),_=y.useCallback(ee=>{o(""),s({kind:"compose",parentCommentId:ee})},[]),R=y.useCallback(()=>{s({kind:"view"}),o("")},[]),L=y.useCallback(()=>{r.kind!=="edit"||!t||fetch("/api/comments",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:t,id:r.commentId,note:i.trim()})}).then(()=>{s({kind:"view"}),o("")}).catch(ee=>console.error("[CommentPopover] Save failed:",ee))},[r,t,i]),$=y.useCallback(()=>{if(r.kind!=="compose"||!t)return;const ee=$u().find(P=>P.id===r.parentCommentId);ee&&fetch("/api/comments",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:t,text:ee.text,note:i.trim(),nodeId:ee.nodeId,nodeIds:ee.nodeIds})}).then(()=>{s({kind:"view"}),o("")}).catch(P=>console.error("[CommentPopover] Create failed:",P))},[r,t,i]),B=y.useCallback(ee=>{fetch("/api/comments/resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[ee]})}).catch(P=>console.error("[CommentPopover] Resolve failed:",P))},[]),U=y.useCallback(ee=>{fetch("/api/comments",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[ee]})}).catch(P=>console.error("[CommentPopover] Delete failed:",P))},[]);if(!e||j.length===0)return null;const X=r.kind!=="view",z=r.kind==="compose"?"Adding a new comment on the same range":null;return l.jsx("div",{ref:m,className:`ow-comment-popover ow-comment-popover-${f.placement}`,style:{left:f.left,top:f.top,maxHeight:N$},onMouseEnter:w,onMouseLeave:S,children:X?l.jsxs(l.Fragment,{children:[z&&l.jsx("div",{className:"ow-comment-popover-empty",children:z}),l.jsx("textarea",{ref:g,className:"ow-comment-popover-textarea",value:i,onChange:ee=>o(ee.target.value),onKeyDown:ee=>{ee.key==="Enter"&&(ee.metaKey||ee.ctrlKey)&&(ee.preventDefault(),r.kind==="edit"?L():r.kind==="compose"&&$()),ee.key==="Escape"&&(ee.preventDefault(),R())},rows:4,placeholder:"Note for agent (optional)..."}),l.jsxs("div",{className:"ow-comment-popover-actions",children:[l.jsx("span",{className:"ow-comment-popover-hint",children:"⌘↵ to save · Esc to cancel"}),l.jsx("button",{className:"ow-icon-btn",onClick:r.kind==="edit"?L:$,title:"Save",children:l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"M20 6 9 17l-5-5"})})})]})]}):l.jsx("div",{className:"ow-comment-popover-stack",children:j.map((ee,P)=>l.jsxs("div",{className:`ow-comment-popover-card${P>0?" ow-comment-popover-card-divider":""}`,children:[ee.note?l.jsx("div",{className:"ow-comment-popover-text",children:ee.note}):l.jsx("div",{className:"ow-comment-popover-empty",children:"No note"}),l.jsxs("div",{className:"ow-comment-popover-actions",children:[l.jsx("button",{className:"ow-icon-btn",onClick:()=>M(ee.id),title:"Edit comment",children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M12 20h9"}),l.jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"})]})}),l.jsx("button",{className:"ow-icon-btn",onClick:()=>_(ee.id),title:"Add another comment on this range",children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M12 5v14"}),l.jsx("path",{d:"M5 12h14"})]})}),l.jsx("button",{className:"ow-icon-btn",onClick:()=>B(ee.id),title:"Resolve (mark addressed)",children:l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"M20 6 9 17l-5-5"})})}),l.jsx("button",{className:"ow-icon-btn ow-icon-btn-danger",onClick:()=>U(ee.id),title:"Delete (remove permanently)",children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M18 6 6 18"}),l.jsx("path",{d:"m6 6 12 12"})]})})]})]},ee.id))})})}function Su(t){return t.type==="doc"?t.file:t.id}function Ll(t,e){for(const n of t)n.type==="doc"?e.add(n.file):n.type==="container"&&Ll(n.items,e)}function LT(t,e,n,r){for(const s of t){if(s.type==="doc"&&s.file===e)return n||r;if(s.type==="container"){const i=s.autoAccept===!0,o=LT(s.items,e,n,r||i);if(o!==null)return o}}return null}function Pd(t,e){for(const n of t){const r=n.workspace;if(!r)continue;const s=r.autoAccept===!0;if(LT(r.root,e,s,!1)===!0)return!0}return!1}function ba(t){const e=new Date(t),n=Date.now()-e.getTime();return n<6e4?"just now":n<36e5?`${Math.floor(n/6e4)}m ago`:n<864e5?`${Math.floor(n/36e5)}h ago`:n<6048e5?`${Math.floor(n/864e5)}d ago`:e.toLocaleDateString()}function Vs(t){return/^[A-Z]:[/\\]|^\//.test(t)}function DT(t){const e=t.replace(/\\/g,"/").split("/");return e.length>=2?e[e.length-2]:""}function T$(t){const e=new Date(t),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()),s=new Date(r.getTime()-864e5),i=new Date(e.getFullYear(),e.getMonth(),e.getDate());return i.getTime()===r.getTime()?"Today":i.getTime()===s.getTime()?"Yesterday":n.getTime()-i.getTime()<6048e5?e.toLocaleDateString(void 0,{weekday:"long"}):e.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function j$(t,e){const[n,r]=y.useState([]),[s,i]=y.useState([]),o=y.useRef(null),c=y.useRef(new Set),d=y.useCallback(g=>{c.current.add(g)},[]),f=y.useMemo(()=>{const g=new Set;for(const v of s)v.workspace&&Ll(v.workspace.root,g);return g},[s]),h=y.useCallback(()=>{fetch("/api/documents").then(g=>g.json()).then(g=>{if(!Array.isArray(g))return;const v=c.current;if(v.size>0){const k=new Set(g.map(w=>w.filename));for(const w of[...v])k.has(w)||v.delete(w)}const x=v.size>0?g.filter(k=>!v.has(k.filename)):g;r(x)}).catch(()=>{})},[]),m=y.useCallback(()=>{fetch("/api/workspaces").then(g=>g.json()).then(async g=>{if(!Array.isArray(g))return;const v=await Promise.all(g.map(async x=>{try{const w=await(await fetch(`/api/workspaces/${encodeURIComponent(x.filename)}`)).json();return{...x,workspace:w}}catch{return x}}));i(v)}).catch(()=>{})},[]);return y.useEffect(()=>{h()},[h,t]),y.useEffect(()=>{m()},[m,e]),{docs:n,setDocs:r,workspaces:s,setWorkspaces:i,assignedFiles:f,fetchDocs:h,fetchWorkspaces:m,scrollRef:o,markPendingDelete:d}}function Zg(t,e){return t.filter(n=>!e(n)).map(n=>n.type==="container"?{...n,items:Zg(n.items,e)}:n)}function PT(t,e,n){return t.map(r=>r.type==="container"&&r.id===e?{...r,name:n}:r.type==="container"?{...r,items:PT(r.items,e,n)}:r)}function M$(t,e,n,r,s,i){const o=y.useCallback(_=>{n(R=>R.filter(L=>L.filename!==_)),i==null||i(_),fetch(`/api/documents/${encodeURIComponent(_)}`,{method:"DELETE"}).catch(()=>t())},[n,t]),c=y.useCallback(_=>{n(R=>R.filter(L=>L.filename!==_)),fetch(`/api/documents/${encodeURIComponent(_)}/archive`,{method:"POST"}).catch(()=>t())},[n,t]),d=y.useCallback(_=>{n(R=>R.filter(L=>L.filename!==_)),fetch(`/api/documents/${encodeURIComponent(_)}/unarchive`,{method:"POST"}).catch(()=>t())},[n,t]),f=y.useCallback((_,R,L)=>{!L.trim()||L.trim()===R||(n($=>$.map(B=>B.filename===_?{...B,title:L.trim()}:B)),fetch(`/api/documents/${encodeURIComponent(_)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:L.trim()})}).catch(()=>t()))},[n,t]),h=y.useCallback(_=>{r(R=>R.filter(L=>L.filename!==_)),fetch(`/api/workspaces/${encodeURIComponent(_)}`,{method:"DELETE"}).catch(()=>e())},[r,e]),m=y.useCallback((_,R)=>{R.trim()&&(r(L=>L.map($=>$.filename===_?{...$,title:R.trim()}:$)),fetch(`/api/workspaces/${encodeURIComponent(_)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:R.trim()})}).catch(()=>e()))},[r,e]),g=y.useCallback((_,R)=>{r(L=>L.map($=>$.filename!==_||!$.workspace?$:{...$,docCount:Math.max(0,$.docCount-1),workspace:{...$.workspace,root:Zg($.workspace.root,B=>B.type==="doc"&&B.file===R)}})),fetch(`/api/workspaces/${encodeURIComponent(_)}/docs/${encodeURIComponent(R)}`,{method:"DELETE"}).catch(()=>e())},[r,e]),v=y.useCallback((_,R,L=!1)=>{r(B=>B.map(U=>U.filename!==_||!U.workspace?U:{...U,workspace:{...U.workspace,root:Zg(U.workspace.root,X=>X.type==="container"&&X.id===R)}}));const $=`/api/workspaces/${encodeURIComponent(_)}/containers/${encodeURIComponent(R)}${L?"?cascade=true":""}`;fetch($,{method:"DELETE"}).then(()=>{L&&t()}).catch(()=>e())},[r,e,t]),x=y.useCallback((_,R,L)=>{L.trim()&&(r($=>$.map(B=>B.filename!==_||!B.workspace?B:{...B,workspace:{...B.workspace,root:PT(B.workspace.root,R,L.trim())}})),fetch(`/api/workspaces/${encodeURIComponent(_)}/containers/${encodeURIComponent(R)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L.trim()})}).catch(()=>e()))},[r,e]),k=y.useCallback(()=>{fetch("/api/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:"Untitled Workspace"})}).catch(()=>{})},[]),w=y.useCallback((_,R,L)=>{fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L?{metadata:L}:{})}).then($=>$.json()).then($=>{if($.filename)return fetch(`/api/workspaces/${encodeURIComponent(_)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:$.filename,title:$.title||"Untitled",containerId:R})})}).catch(()=>{})},[]),S=y.useCallback((_,R)=>{fetch(`/api/workspaces/${encodeURIComponent(_)}/containers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:"Untitled",parentContainerId:R})}).catch(()=>{})},[]),N=y.useCallback(_=>{const R=s.find(L=>L.filename===_);return(R==null?void 0:R.tags)??[]},[s]),j=y.useCallback((_,R)=>{const L=R.trim();L&&(n($=>$.map(B=>{if(B.filename!==_)return B;const U=B.tags??[];return U.includes(L)?B:{...B,tags:[...U,L]}})),fetch(`/api/doc-tags/${encodeURIComponent(_)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag:L})}).catch(()=>{}))},[n]),M=y.useCallback((_,R)=>{n(L=>L.map($=>{if($.filename!==_)return $;const B=$.tags??[],U=B.filter(X=>X!==R);return U.length===B.length?$:U.length>0?{...$,tags:U}:{...$,tags:void 0}})),fetch(`/api/doc-tags/${encodeURIComponent(_)}/${encodeURIComponent(R)}`,{method:"DELETE"}).catch(()=>{})},[n]);return{fetchDocs:t,handleDelete:o,handleArchive:c,handleUnarchive:d,handleRename:f,handleCreateWorkspace:k,handleDeleteWorkspace:h,handleCreateInWorkspace:w,handleRemoveFromWorkspace:g,handleCreateContainer:S,handleDeleteContainer:v,handleRenameContainer:x,handleRenameWorkspace:m,getDocTags:N,handleAddTag:j,handleRemoveTag:M}}function BT({docs:t,workspaces:e,assignedFiles:n,scrollRef:r,setCollapsedSections:s}){const[i,o]=y.useState(null),[c,d]=y.useState(null),f=y.useRef(null),h=y.useRef(null),m=y.useRef(null),g=y.useRef(null),v=y.useRef(null),x=5,k=(U,X,z)=>z==="before"?X>0?Su(U[X-1]):null:Su(U[X]),w=y.useCallback((U,X)=>{if(X===null){const P=t.filter(G=>!n.has(G.filename)).map(G=>({type:"doc",file:G.filename,title:G.title})),F=P.findIndex(G=>Su(G)===U);return F>=0?{siblings:P,index:F,containerId:null}:null}const z=e.find(P=>P.filename===X);if(!(z!=null&&z.workspace))return null;const ee=(P,F)=>{for(let G=0;G<P.length;G++){if(Su(P[G])===U)return{siblings:P,index:G,containerId:F};if(P[G].type==="container"){const ie=ee(P[G].items,P[G].id);if(ie)return ie}}return null};return ee(z.workspace.root,null)},[t,n,e]),S=y.useCallback(()=>{o(null),d(null),v.current=null,g.current=null,m.current&&(m.current.remove(),m.current=null),f.current&&(clearTimeout(f.current),f.current=null),h.current&&(cancelAnimationFrame(h.current),h.current=null),document.body.style.userSelect=""},[]),N=y.useCallback((U,X)=>{if(!U||!X)return;if(U.type==="workspace"){const K=X.itemId;if(K===U.filename)return;const ce=e.map(D=>D.filename),J=ce.indexOf(U.filename);if(J<0)return;ce.splice(J,1);let A=ce.indexOf(K);if(A<0)return;X.position==="after"&&(A+=1),ce.splice(A,0,U.filename),fetch("/api/workspaces/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:ce})}).catch(()=>{});return}const{wsFilename:z,containerId:ee,afterId:P}=X,F=U.type==="doc"?U.file:U.id,G=U.sourceWs;if(X.itemId===F)return;if(U.type==="container"){if(z===null&&ee===null&&X.itemId!=="__section__"){const K=X.itemId,ce=X.position==="after"?K:(()=>{const J=e.findIndex(A=>A.filename===K);return J>0?e[J-1].filename:null})();fetch("/api/workspaces/promote-container",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:G,containerId:F,afterWorkspaceFilename:ce})}).catch(()=>{});return}if(G!==z&&z){fetch(`/api/workspaces/${encodeURIComponent(z)}/containers/${encodeURIComponent(F)}/cross-move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:G,targetContainerId:ee??null,afterIdentifier:P})}).catch(()=>{});return}if(!z)return;fetch(`/api/workspaces/${encodeURIComponent(z)}/docs/${encodeURIComponent(F)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:ee??null,afterFile:P})}).catch(()=>{});return}const ie=U.file;if(G===null&&z===null){const K=t.filter(q=>!n.has(q.filename)).map(q=>q.filename),ce=K.indexOf(ie);if(ce<0)return;K.splice(ce,1);let J=P?K.indexOf(P):-1;J>=0?J+=1:J=0,K.splice(J,0,ie);const A=[];let D=0;for(const q of t)n.has(q.filename)?A.push(q.filename):A.push(K[D++]);fetch("/api/documents/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:A})}).catch(()=>{});return}if(G===null&&z!==null){fetch(`/api/workspaces/${encodeURIComponent(z)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:ie,title:ie.replace(/\.md$/,""),containerId:ee??null,afterFile:P})}).catch(()=>{});return}if(G!==null&&z===null){fetch(`/api/workspaces/${encodeURIComponent(G)}/docs/${encodeURIComponent(ie)}`,{method:"DELETE"}).catch(()=>{});return}if(G===z&&z!==null){fetch(`/api/workspaces/${encodeURIComponent(z)}/docs/${encodeURIComponent(ie)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:ee??null,afterFile:P})}).catch(()=>{});return}G!==null&&z!==null&&fetch(`/api/workspaces/${encodeURIComponent(z)}/docs/${encodeURIComponent(ie)}/cross-move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:G,containerId:ee??null,afterFile:P,title:ie.replace(/\.md$/,"")})}).catch(()=>{})},[e,t,n]),j=y.useCallback((U,X)=>{const z=m.current;z&&(z.style.display="none");const ee=document.elementFromPoint(U,X);if(z&&(z.style.display=""),!ee)return null;if((i==null?void 0:i.type)==="workspace"||(i==null?void 0:i.type)==="container"){const q=ee.closest("[data-ws-drag]");if(q){const le=q.dataset.wsDrag,ye=q.getBoundingClientRect(),oe=(X-ye.top)/ye.height;return{itemId:le,position:oe<.5?"before":"after",wsFilename:null,containerId:null,afterId:null}}if((i==null?void 0:i.type)==="workspace")return null}if((i==null?void 0:i.type)==="doc"){const q=ee.closest("[data-ws-drag]");if(q)return{itemId:"__section__",position:"inside",wsFilename:q.dataset.wsDrag,containerId:null,afterId:null}}const P=ee.closest("[data-drag-id]");if(!P){const q=ee.closest("[data-drop-ws]");return q?{itemId:"__section__",position:"inside",wsFilename:q.dataset.dropWs==="__docs__"?null:q.dataset.dropWs,containerId:q.dataset.dropContainer||null,afterId:null}:null}const F=P.dataset.dragId,G=P.dataset.dragType,ie=P.dataset.dragWs==="__docs__"?null:P.dataset.dragWs,K=P.getBoundingClientRect(),ce=(X-K.top)/K.height;if(G==="container-header"){const q=F,le=P.dataset.dragParent||null,ye=w(q,ie);if(!ye)return null;const oe=(i==null?void 0:i.type)==="container"?.33:.25;return ce<oe?{itemId:q,position:"before",wsFilename:ie,containerId:le,afterId:k(ye.siblings,ye.index,"before")}:ce>1-oe?{itemId:q,position:"after",wsFilename:ie,containerId:le,afterId:k(ye.siblings,ye.index,"after")}:{itemId:q,position:"inside",wsFilename:ie,containerId:q,afterId:null}}const J=P.dataset.dragContainer||null,A=w(F,ie);if(!A)return null;const D=ce<.5?"before":"after";return{itemId:F,position:D,wsFilename:ie,containerId:J,afterId:k(A.siblings,A.index,D)}},[w,i]),M=y.useCallback(U=>{const X=r.current;if(!X)return;const z=X.getBoundingClientRect(),ee=80,P=18;let F=0;if(U<z.top+ee?F=-P*Math.max(0,1-(U-z.top)/ee):U>z.bottom-ee&&(F=P*Math.max(0,1-(z.bottom-U)/ee)),h.current&&(cancelAnimationFrame(h.current),h.current=null),F!==0){const G=()=>{X.scrollTop+=F,h.current=requestAnimationFrame(G)};h.current=requestAnimationFrame(G)}},[r]),_=y.useCallback((U,X)=>{const z=m.current;z&&(z.style.display="none");const ee=document.elementFromPoint(U,X);z&&(z.style.display="");const P=ee==null?void 0:ee.closest("[data-section-key]");if(!P){f.current&&(clearTimeout(f.current),f.current=null);return}const F=P.dataset.sectionKey;f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{s(G=>{if(!G.has(F))return G;const ie=new Set(G);return ie.delete(F),ie})},500)},[s]);y.useEffect(()=>{if(!i)return;const U=z=>{m.current&&(m.current.style.left=`${z.clientX+12}px`,m.current.style.top=`${z.clientY-8}px`),d(j(z.clientX,z.clientY)),M(z.clientY),_(z.clientX,z.clientY)},X=z=>{N(i,j(z.clientX,z.clientY)),S()};return window.addEventListener("pointermove",U),window.addEventListener("pointerup",X),()=>{window.removeEventListener("pointermove",U),window.removeEventListener("pointerup",X)}},[i,j,N,S,M,_]);const R=y.useCallback((U,X,z)=>{if(U.button!==0||U.target.closest("input, button, .sidebar-tag-remove, .sidebar-tag-add, .sidebar-container-actions, .sidebar-delete-btn, .sidebar-confirm-delete, .sidebar-inline-confirm"))return;g.current={x:U.clientX,y:U.clientY},v.current=X;const P=G=>{if(!g.current||!v.current)return;const ie=G.clientX-g.current.x,K=G.clientY-g.current.y;if(Math.abs(ie)+Math.abs(K)>=x){document.body.style.userSelect="none",window.removeEventListener("pointermove",P),window.removeEventListener("pointerup",F),o(v.current),v.current=null;const ce=document.createElement("div");ce.style.cssText="position:fixed;pointer-events:none;z-index:9999;padding:4px 10px;background:var(--bg-surface, white);border:1px solid var(--border, #cbd5e1);border-radius:6px;font-size:12px;box-shadow:0 2px 8px rgba(0,0,0,0.12);max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ink-dark, #334155);",ce.textContent=z,document.body.appendChild(ce),m.current=ce,ce.style.left=`${G.clientX+12}px`,ce.style.top=`${G.clientY-8}px`}},F=()=>{window.removeEventListener("pointermove",P),window.removeEventListener("pointerup",F),g.current=null,v.current=null,document.body.style.userSelect=""};window.addEventListener("pointermove",P),window.addEventListener("pointerup",F)},[]);return{draggedItem:i,dropIndicator:c,handlePointerDown:R,dropClass:U=>!c||c.itemId!==U?"":c.position==="before"?"drop-before":c.position==="after"?"drop-after":c.position==="inside"?"drop-inside":"",isDragging:U=>i?i.type==="doc"?i.file===U:i.type==="workspace"?i.filename===U:i.id===U:!1,isContainerDropTarget:U=>!c||!i?!1:c.containerId===U}}function Wl(t,e,n,r){var h;const s=y.useRef(e);s.current=e;const i=y.useRef(r);i.current=r;const o=y.useRef(null),c=y.useRef(null),d=y.useCallback(m=>{var v,x;const g=m||((v=s.current.find(k=>k.isActive))==null?void 0:v.filename);g&&((x=i.current)==null||x.call(i,g),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{const k=t.current;if(!k)return;const w=k.querySelector(`[data-drag-id="${CSS.escape(g)}"]`)||k.querySelector(".active");if(!w||w.offsetParent===null)return;const S=o.current===g,N=w.getBoundingClientRect(),j=k.getBoundingClientRect(),M=N.top<j.top||N.bottom>j.bottom;if(S||M){const _=N.top-j.top-(j.height/2-N.height/2);k.scrollTop+=_}S&&(o.current=null,w.classList.remove("reveal-pulse"),w.offsetWidth,w.classList.add("reveal-pulse"),setTimeout(()=>w.classList.remove("reveal-pulse"),1200))},60))},[t]),f=(h=e.find(m=>m.isActive))==null?void 0:h.filename;y.useEffect(()=>{d(f)},[f,n,d]),y.useEffect(()=>{const m=g=>{var x,k;const v=((x=g.detail)==null?void 0:x.filename)||((k=s.current.find(w=>w.isActive))==null?void 0:k.filename);v&&(o.current=v,d(v))};return window.addEventListener("ow-reveal-active-doc",m),()=>window.removeEventListener("ow-reveal-active-doc",m)},[d]),y.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[])}const A$=[{key:"document",label:"Document"},{key:"tweet",label:"Tweet"},{key:"article",label:"Article"},{key:"linkedin",label:"LinkedIn"},{key:"newsletter",label:"Newsletter"},{key:"blog",label:"Blog"}];function R$({onPick:t}){const[e,n]=y.useState(!1),r=y.useRef(null),s=y.useRef(null),[i,o]=y.useState({});return y.useLayoutEffect(()=>{if(!e||!r.current||!s.current)return;const c=s.current.getBoundingClientRect(),d=r.current.getBoundingClientRect(),f=8;let h=c.right-4,m=c.top-4;h+d.width+f>window.innerWidth&&(h=c.left-d.width+4),m+d.height+f>window.innerHeight&&(m=window.innerHeight-d.height-f),m<f&&(m=f),o({position:"fixed",left:h,top:m})},[e]),l.jsxs("span",{onMouseLeave:()=>n(!1),children:[l.jsx("div",{className:"context-menu-divider"}),l.jsxs("button",{ref:s,className:"context-menu-item context-menu-submenu-trigger",onMouseEnter:()=>n(!0),onClick:()=>n(c=>!c),children:[l.jsx("span",{children:"Create variant"}),l.jsx("span",{className:"context-menu-submenu-arrow",children:"▸"})]}),e&&l.jsx("div",{ref:r,className:"context-menu context-menu-submenu",style:i,children:A$.map(c=>l.jsx("button",{className:"context-menu-item",onClick:()=>t(c.key),children:l.jsx("span",{children:c.label})},c.key))})]})}function Tk({items:t,onAction:e}){const[n,r]=y.useState(null),s=y.useRef(null),i=y.useRef({}),o=y.useMemo(()=>{const h=new Map;for(const m of t){const g=m.pluginDisplayName||"_ungrouped",v=h.get(g)||[];v.push(m),h.set(g,v)}return h},[t]),[c,d]=y.useState({});y.useLayoutEffect(()=>{const h=n?i.current[n]:null;if(!n||!s.current||!h)return;const m=h.getBoundingClientRect(),g=s.current.getBoundingClientRect(),v=8;let x=m.right-4,k=m.top-4;x+g.width+v>window.innerWidth&&(x=m.left-g.width+4),k+g.height+v>window.innerHeight&&(k=window.innerHeight-g.height-v),k<v&&(k=v),d({position:"fixed",left:x,top:k})},[n]);const f=[];for(const[h,m]of o)if(h!=="_ungrouped"&&m.length>=3)f.push(l.jsxs("span",{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsxs("button",{ref:g=>{i.current[h]=g},className:"context-menu-item context-menu-submenu-trigger",onMouseEnter:()=>r(h),onClick:()=>r(n===h?null:h),children:[l.jsx("span",{children:"Transform"}),l.jsx("span",{className:"context-menu-submenu-arrow",children:"▸"})]}),n===h&&l.jsx("div",{ref:s,className:"context-menu context-menu-submenu",style:c,onMouseLeave:()=>r(null),children:m.map(g=>l.jsx("button",{className:"context-menu-item",onClick:()=>e(g),children:l.jsx("span",{children:g.label})},g.action))})]},`sub-${h}`));else{let g=!0;for(const v of m){const x=g&&h!=="_ungrouped";g=!1,f.push(l.jsxs("span",{children:[x&&l.jsx("div",{className:"context-menu-divider"}),x&&l.jsx("div",{className:"context-menu-section-header",children:h}),l.jsx("button",{className:"context-menu-item",onClick:()=>e(v),children:l.jsx("span",{children:v.label})})]},v.action))}}return l.jsx(l.Fragment,{children:f})}function Bd({x:t,y:e,filename:n,title:r,onClose:s,onDuplicate:i,onCreateVariant:o,onRename:c,onArchive:d,onDelete:f,onPluginAction:h,pluginItems:m,onSchedulePost:g,onPostNow:v,isAlreadyPublished:x,onViewAnalytics:k,viewAnalyticsLabel:w,onMarkSent:S,isAlreadySent:N,isApproved:j,onToggleApprove:M,isAutoAccept:_,onToggleAutoAccept:R,sortState:L,sortProposalLabel:$,sortProposalReasoning:B,onRequestSort:U,onCancelSort:X,onAcceptSortProposal:z,onRejectSortProposal:ee,folderMode:P,onNewDoc:F,onNewContainer:G,onAcceptAll:ie,onRejectAll:K,folderAutoAccept:ce,onToggleFolderAutoAccept:J,folderAutoAcceptLabel:A,onRequestSortAll:D,folderDocCount:q,onDeleteWithDocs:le,bulkCount:ye,onBulkDelete:oe,onBulkRequestSort:Se}){const Ee=y.useRef(null),[Le,Ie]=y.useState(!1),[Ve,Te]=y.useState(!1),[qe,pt]=y.useState({left:t,top:e});y.useLayoutEffect(()=>{const be=Ee.current;if(!be)return;const ht=be.getBoundingClientRect(),xt=8;let St=t,At=e;e+ht.height+xt>window.innerHeight&&(At=e-ht.height),t+ht.width+xt>window.innerWidth&&(St=t-ht.width),At<xt&&(At=xt),St<xt&&(St=xt),pt({left:St,top:At})},[t,e]),y.useEffect(()=>{const be=ht=>{Ee.current&&!Ee.current.contains(ht.target)&&s()};return document.addEventListener("mousedown",be),()=>document.removeEventListener("mousedown",be)},[s]),y.useEffect(()=>{const be=ht=>{ht.key==="Escape"&&s()};return document.addEventListener("keydown",be),()=>document.removeEventListener("keydown",be)},[s]);const ut=y.useCallback(be=>{h(be.action,be),s()},[h,s]);return ye&&ye>1&&oe?l.jsxs("div",{ref:Ee,className:"context-menu",style:{left:qe.left,top:qe.top},children:[l.jsxs("div",{className:"context-menu-section-header",children:[ye," selected"]}),Se&&l.jsx("button",{className:"context-menu-item",onClick:()=>{Se(),s()},children:l.jsxs("span",{children:["Request sort (",ye,")"]})}),Le?l.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:be=>be.stopPropagation(),children:[l.jsxs("span",{children:["Delete ",ye,"?"]}),l.jsx("button",{onClick:()=>{oe(),s()},children:"Yes"}),l.jsx("button",{onClick:()=>Ie(!1),children:"No"})]}):l.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>Ie(!0),children:l.jsxs("span",{children:["Delete (",ye,")"]})})]}):P?l.jsxs("div",{ref:Ee,className:"context-menu",style:{left:qe.left,top:qe.top},children:[l.jsx("button",{className:"context-menu-item",onClick:()=>{c(),s()},children:l.jsx("span",{children:"Rename"})}),F&&l.jsx("button",{className:"context-menu-item",onClick:be=>{F(be),s()},children:l.jsx("span",{children:"New Document"})}),G&&l.jsx("button",{className:"context-menu-item",onClick:()=>{G(),s()},children:l.jsx("span",{children:"New Container"})}),(ie||K)&&l.jsx("div",{className:"context-menu-divider"}),ie&&l.jsx("button",{className:"context-menu-item",onClick:()=>{ie(),s()},children:l.jsx("span",{children:"Accept All Changes"})}),K&&l.jsx("button",{className:"context-menu-item",onClick:()=>{K(),s()},children:l.jsx("span",{children:"Reject All Changes"})}),J&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{J(),s()},children:l.jsx("span",{children:ce?`Turn off auto-accept${A?" "+A:""}`:`Turn on auto-accept${A?" "+A:""}`})})]}),D&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{D(),s()},children:l.jsx("span",{children:"Request sort all"})})]}),m.length>0&&l.jsx(Tk,{items:m,onAction:ut}),l.jsx("div",{className:"context-menu-divider"}),Le?q&&q>0&&le?l.jsxs("div",{className:"sidebar-ctx-folder-delete",onClick:be=>be.stopPropagation(),children:[l.jsx("div",{className:"sidebar-ctx-folder-delete-prompt",children:"Delete this folder?"}),l.jsxs("button",{className:"context-menu-item sidebar-ctx-delete-option",onClick:()=>{f(),s()},children:[l.jsx("span",{children:"Folder only"}),l.jsxs("span",{className:"sidebar-ctx-delete-hint",children:[q," doc",q===1?"":"s"," → Documents"]})]}),l.jsxs("button",{className:"context-menu-item sidebar-ctx-delete-option sidebar-ctx-delete",onClick:()=>{le(),s()},children:[l.jsxs("span",{children:["Folder + ",q," doc",q===1?"":"s"]}),l.jsx("span",{className:"sidebar-ctx-delete-hint",children:"permanently deletes files"})]}),l.jsx("button",{className:"context-menu-item sidebar-ctx-delete-cancel",onClick:()=>Ie(!1),children:l.jsx("span",{children:"Cancel"})})]}):l.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:be=>be.stopPropagation(),children:[l.jsx("span",{children:"Delete?"}),l.jsx("button",{onClick:()=>{f(),s()},children:"Yes"}),l.jsx("button",{onClick:()=>Ie(!1),children:"No"})]}):l.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>Ie(!0),children:l.jsx("span",{children:"Delete"})})]}):l.jsxs("div",{ref:Ee,className:"context-menu",style:{left:qe.left,top:qe.top},children:[l.jsx("button",{className:"context-menu-item",onClick:()=>{i(),s()},children:l.jsx("span",{children:"Duplicate"})}),o&&l.jsx(R$,{onPick:be=>{o(be),s()}}),l.jsx("button",{className:"context-menu-item",onClick:()=>{c(),s()},children:l.jsx("span",{children:"Rename"})}),Ve?l.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:be=>be.stopPropagation(),children:[l.jsx("span",{children:"Archive?"}),l.jsx("button",{onClick:()=>{d(),s()},children:"Yes"}),l.jsx("button",{onClick:()=>Te(!1),children:"No"})]}):l.jsx("button",{className:"context-menu-item",onClick:()=>{Ie(!1),Te(!0)},children:l.jsx("span",{children:"Archive"})}),Le?l.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:be=>be.stopPropagation(),children:[l.jsx("span",{children:Vs(n)?"Remove?":"Delete?"}),l.jsx("button",{onClick:()=>{f(),s()},children:"Yes"}),l.jsx("button",{onClick:()=>Ie(!1),children:"No"})]}):l.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>{Te(!1),Ie(!0)},children:l.jsx("span",{children:Vs(n)?"Remove":"Delete"})}),M&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{M(),s()},children:l.jsx("span",{children:j?"Remove Approval":"Approve"})})]}),R&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{R(),s()},children:l.jsx("span",{children:_?"Turn off auto-accept":"Turn on auto-accept"})})]}),L==="proposal"&&z&&ee&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsxs("div",{className:"sidebar-ctx-sort-proposal",onClick:be=>be.stopPropagation(),children:[l.jsxs("div",{className:"sidebar-ctx-sort-proposal-label",children:["Sort to ",$]}),B&&l.jsx("div",{className:"sidebar-ctx-sort-proposal-reason",children:B}),l.jsxs("div",{className:"sidebar-ctx-sort-proposal-actions",children:[l.jsx("button",{onClick:()=>{z(),s()},children:"Accept"}),l.jsx("button",{onClick:()=>{ee(),s()},children:"Reject"})]})]})]}),L==="pending"&&X&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsxs("div",{className:"sidebar-ctx-sort-pending",onClick:be=>be.stopPropagation(),children:[l.jsx("span",{className:"sidebar-ctx-sort-pending-label",children:"Sort requested"}),l.jsx("button",{onClick:()=>{X(),s()},children:"Cancel"})]})]}),L==="none"&&U&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{U(),s()},children:l.jsx("span",{children:"Request sort"})})]}),g&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{g(),s()},children:l.jsx("span",{children:"Schedule Post"})})]}),v&&l.jsx("button",{className:"context-menu-item",onClick:()=>{v(),s()},children:l.jsx("span",{children:x?"Republish to Blog":"Post to Blog Now"})}),S&&!N&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{S(),s()},children:l.jsx("span",{children:"Mark as Sent"})})]}),k&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{k(),s()},children:l.jsx("span",{children:w||"View Analytics"})})]}),m.length>0&&l.jsx(Tk,{items:m,onAction:ut})]})}const jk=5e3;function $T(t,e){return!t.promptForFocus||!e?!1:e.wordCount>jk?(Ai(`Document too large to transform: ${e.wordCount.toLocaleString()} words (max ${jk.toLocaleString()}). Trim it down first.`,"error"),!0):!1}function FT({actionLabel:t,docTitle:e,onConfirm:n,onClose:r}){const[s,i]=y.useState(""),o=y.useRef(null);y.useEffect(()=>{var d;(d=o.current)==null||d.focus()},[]),y.useEffect(()=>{const d=f=>{f.key==="Escape"&&r()};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const c=y.useCallback(()=>{n(s.trim())},[s,n]);return l.jsx("div",{className:"focus-modal-overlay",onClick:r,children:l.jsxs("div",{className:"focus-modal",onClick:d=>d.stopPropagation(),children:[l.jsxs("div",{className:"focus-modal-header",children:[l.jsx("h2",{children:t}),l.jsx("button",{className:"focus-modal-close",onClick:r,children:"×"})]}),l.jsxs("div",{className:"focus-modal-body",children:[l.jsxs("label",{children:['Focus instructions for "',e,'"',l.jsx("textarea",{ref:o,value:s,onChange:d=>i(d.target.value.slice(0,500)),placeholder:"Optional: guide the transformation (e.g. 'focus on the intro section', 'keep it professional')...",onKeyDown:d=>{d.key==="Enter"&&(d.ctrlKey||d.metaKey)&&c()}})]}),l.jsxs("div",{className:"focus-modal-hint",children:[s.length,"/500"]}),l.jsxs("div",{className:"focus-modal-actions",children:[l.jsx("button",{className:"focus-modal-btn secondary",onClick:r,children:"Cancel"}),l.jsx("button",{className:"focus-modal-btn primary",onClick:c,children:"Go"})]})]})]})})}function Ip(t,e){if(!e)return[t];const n=[],r=t.toLowerCase(),s=e.toLowerCase();let i=0;for(;i<t.length;){const o=r.indexOf(s,i);if(o===-1){n.push(t.slice(i));break}o>i&&n.push(t.slice(i,o)),n.push(l.jsx("mark",{children:t.slice(o,o+e.length)},o)),i=o+e.length}return n}function Mk({r:t,query:e,onClick:n}){return l.jsxs("div",{className:`sidebar-item search-result-item ${t.isActive?"active":""} ${t.isArchived?"search-result-archived":""}`,onClick:n,children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-item-title-text",children:t.matchType==="title"?Ip(t.title,e):t.title}),t.isArchived&&l.jsx("span",{className:"search-archived-badge",children:"archived"})]}),t.matchType==="tag"&&t.matchedTag&&l.jsxs("div",{className:"search-result-tag",children:["Tag: ",Ip(t.matchedTag,e)]}),t.matchType==="content"&&t.snippet&&l.jsx("div",{className:"search-result-snippet",children:Ip(t.snippet,e)}),l.jsxs("div",{className:"sidebar-item-meta",children:[t.wordCount.toLocaleString()," words · ",ba(t.lastModified)]})]})}function rf({results:t,query:e,onSwitchDocument:n,actions:r}){if(t.length===0)return l.jsx("div",{className:"sidebar-scroll",children:l.jsxs("div",{className:"search-empty",children:['No results for "',e,'"']})});const s=t.filter(o=>!o.isArchived),i=t.filter(o=>o.isArchived);return l.jsx("div",{className:"sidebar-scroll",children:l.jsxs("div",{className:"search-results",children:[s.map(o=>l.jsx(Mk,{r:o,query:e,onClick:()=>n(o.filename)},o.filename)),i.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"search-archived-divider",children:l.jsx("span",{children:"Archived"})}),i.map(o=>l.jsx(Mk,{r:o,query:e,onClick:()=>r.handleUnarchive(o.filename)},o.filename))]})]})})}async function Lp(t,e={}){var s,i;const r=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:t,arguments:e})})).json();return(i=(s=r.content)==null?void 0:s[0])!=null&&i.text?JSON.parse(r.content[0].text):r}function Dp(t,e){return e?(t/e*100).toFixed(1)+"%":"0%"}function Ak(t){return new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function Rk(t,e=50){try{const n=new URL(t),r=n.hostname+n.pathname+n.search;return r.length>e?r.slice(0,e)+"...":r}catch{return t.length>e?t.slice(0,e)+"...":t}}function zT({docId:t,title:e,onClose:n}){const[r,s]=y.useState("loading"),[i,o]=y.useState([]),[c,d]=y.useState(""),[f,h]=y.useState(null),[m,g]=y.useState(null),[v,x]=y.useState("links"),[k,w]=y.useState("all"),[S,N]=y.useState(!1),[j,M]=y.useState(!1),[_,R]=y.useState(""),[L,$]=y.useState(!1),[B,U]=y.useState(null),X=y.useRef(null);y.useEffect(()=>{let oe=!1;return(async()=>{try{const Se=await Lp("list_newsletter_issues",{limit:20});if(oe)return;if(!Se.issues||Se.issues.length===0){s("no-data");return}o(Se.issues);const Ee=Se.issues[0].id;d(Ee)}catch(Se){oe||(g(Se.message),s("error"))}})(),()=>{oe=!0}},[]),y.useEffect(()=>{if(!c)return;let oe=!1;return N(!0),M(!1),U(null),R(""),(async()=>{try{const Se=await Lp("get_newsletter_analytics",{issue_id:c});if(oe)return;if(Se.error){g(Se.error),s("error");return}h(Se),s("loaded")}catch(Se){oe||(g(Se.message),s("error"))}finally{oe||N(!1)}})(),()=>{oe=!0}},[c]),y.useEffect(()=>{const oe=Se=>{X.current&&!X.current.contains(Se.target)&&n()};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[n]),y.useEffect(()=>{const oe=Se=>{Se.key==="Escape"&&n()};return document.addEventListener("keydown",oe),()=>document.removeEventListener("keydown",oe)},[n]);const z=f?I$(f.subscriber_events):[],ee=(f==null?void 0:f.issue.recipient_count)??0,P=f?f.stats.delivered||ee-f.stats.bounces:0,F=f?new Set(f.subscriber_events.filter(oe=>{var Se;return oe.event_type==="click"&&((Se=oe.url)==null?void 0:Se.includes("/newsletter/unsubscribe/"))}).map(oe=>oe.email)).size:0,G=f?f.stats.unsubscribes||F:0,ie=f?f.subscriber_events.filter(oe=>oe.event_type==="dropped").length:0,K=f?Math.max(0,ee-f.stats.unique_opens):0,ce=f!=null&&f.issue.sent_at?Date.now()-new Date(f.issue.sent_at).getTime():0,J=Math.floor(ce/36e5),A=!!(f!=null&&f.issue.resent_at||B),D=oe=>{const Se=Math.floor(oe/36e5);return Se<1?"just now":Se<24?`${Se}h ago`:`${Math.floor(Se/24)}d ${Se%24}h ago`},q=async()=>{if(!(!_.trim()||L)){$(!0);try{const oe=await Lp("resend_to_unopened",{issue_id:c,subject:_});oe.error?(g(oe.error),s("error")):(U({sent:oe.sent,failed:oe.failed}),M(!1))}catch(oe){g(oe.message),s("error")}finally{$(!1)}}},le=oe=>{var Se;return oe.event_type==="unsubscribe"||oe.event_type==="click"&&!!((Se=oe.url)!=null&&Se.includes("/newsletter/unsubscribe/"))},ye=f?O$(f.subscriber_events.filter(oe=>k==="all"?!0:k==="unsubscribe"?le(oe):oe.event_type===k)):[];return l.jsx("div",{className:"newsletter-modal-overlay",children:l.jsxs("div",{className:"na-modal",ref:X,children:[l.jsxs("div",{className:"na-header",children:[l.jsx("h3",{children:"Newsletter Analytics"}),l.jsx("button",{className:"newsletter-modal__close",onClick:n,children:"×"})]}),r==="loading"&&!f&&l.jsx("div",{className:"na-body",children:l.jsxs("div",{className:"newsletter-modal__status",children:[l.jsx("div",{className:"newsletter-modal__spinner"}),l.jsx("span",{children:"Loading analytics..."})]})}),r==="no-data"&&l.jsxs("div",{className:"na-body",children:[l.jsx("div",{className:"newsletter-modal__status",children:l.jsx("span",{children:"No newsletter sends found yet."})}),l.jsx("div",{className:"newsletter-modal__actions",children:l.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:n,children:"Done"})})]}),r==="error"&&l.jsxs("div",{className:"na-body",children:[l.jsx("div",{className:"newsletter-modal__error",children:m}),l.jsx("div",{className:"newsletter-modal__actions",children:l.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:n,children:"Done"})})]}),r==="loaded"&&f&&l.jsxs("div",{className:"na-body",children:[i.length>1&&l.jsx("select",{className:"newsletter-modal__select na-issue-select",value:c,onChange:oe=>d(oe.target.value),children:i.map(oe=>l.jsxs("option",{value:oe.id,children:[oe.subject," — ",Ak(oe.sent_at)]},oe.id))}),S?l.jsxs("div",{className:"newsletter-modal__status",children:[l.jsx("div",{className:"newsletter-modal__spinner"}),l.jsx("span",{children:"Loading..."})]}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"na-kpi-row",children:[l.jsxs("div",{className:"na-kpi",children:[l.jsx("div",{className:"na-kpi__value",children:P.toLocaleString()}),l.jsx("div",{className:"na-kpi__label",children:"Delivered"}),l.jsxs("div",{className:"na-kpi__sub",children:[ee.toLocaleString()," sent"]})]}),l.jsxs("div",{className:"na-kpi",children:[l.jsx("div",{className:"na-kpi__value",children:Dp(f.stats.unique_opens,P)}),l.jsx("div",{className:"na-kpi__label",children:"Open rate"}),l.jsxs("div",{className:"na-kpi__sub",children:[f.stats.unique_opens.toLocaleString()," opens"]})]}),l.jsxs("div",{className:"na-kpi",children:[l.jsx("div",{className:"na-kpi__value",children:Dp(f.stats.unique_clicks,P)}),l.jsx("div",{className:"na-kpi__label",children:"Click rate"}),l.jsxs("div",{className:"na-kpi__sub",children:[f.stats.unique_clicks.toLocaleString()," clicks"]})]})]}),l.jsxs("div",{className:"na-kpi-row na-kpi-row--secondary",children:[l.jsxs("div",{className:"na-kpi na-kpi--sm",children:[l.jsx("span",{className:"na-kpi__value--sm",children:f.stats.bounces}),l.jsx("span",{className:"na-kpi__label--sm",children:"Bounces"})]}),l.jsxs("div",{className:"na-kpi na-kpi--sm",children:[l.jsx("span",{className:"na-kpi__value--sm",children:G}),l.jsx("span",{className:"na-kpi__label--sm",children:"Unsubs"})]}),l.jsxs("div",{className:"na-kpi na-kpi--sm",children:[l.jsx("span",{className:"na-kpi__value--sm",children:ie}),l.jsx("span",{className:"na-kpi__label--sm",children:"Dropped"})]}),f.stats.complaints>0&&l.jsxs("div",{className:"na-kpi na-kpi--sm",children:[l.jsx("span",{className:"na-kpi__value--sm",children:f.stats.complaints}),l.jsx("span",{className:"na-kpi__label--sm",children:"Spam"})]})]}),K>0&&!A&&l.jsx("div",{className:"na-resend",children:j?l.jsxs("div",{className:"na-resend-panel",children:[l.jsxs("div",{className:"na-resend-label-row",children:[l.jsx("span",{className:"na-resend-label",children:"New subject line"}),l.jsxs("span",{className:"na-resend-meta",children:["sent ",D(ce),J<48?" · consider waiting 48h":""]})]}),l.jsx("input",{className:"na-resend-input",type:"text",value:_,onChange:oe=>R(oe.target.value),placeholder:"Try a different angle"}),l.jsxs("div",{className:"na-resend-actions",children:[l.jsx("button",{className:"na-resend-cancel",onClick:()=>M(!1),children:"Cancel"}),l.jsx("button",{className:"na-resend-send",onClick:q,disabled:L||!_.trim(),children:L?"Sending...":`Send to ${K.toLocaleString()}`})]})]}):l.jsxs("button",{className:"na-resend-toggle",onClick:()=>{M(!0),R(f.issue.subject)},children:["Resend to ",K.toLocaleString()," non-openers ",l.jsx("span",{style:{float:"right"},children:"›"})]})}),A&&l.jsxs("div",{className:"na-resend-done",children:["Resent ",f.issue.resent_at?D(Date.now()-new Date(f.issue.resent_at).getTime()):"just now",B?` — ${B.sent} sent`:"",f.issue.resend_subject?` — "${f.issue.resend_subject}"`:""]}),l.jsxs("div",{className:"na-tabs",children:[l.jsxs("button",{className:`na-tab${v==="links"?" active":""}`,onClick:()=>x("links"),children:["Links (",z.length,")"]}),l.jsxs("button",{className:`na-tab${v==="activity"?" active":""}`,onClick:()=>x("activity"),children:["Activity (",f.subscriber_events.length,")"]})]}),v==="links"&&l.jsx("div",{className:"na-table-wrap",children:z.length===0?l.jsx("div",{className:"na-empty",children:"No link clicks recorded yet."}):l.jsxs("table",{className:"na-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"Link"}),l.jsx("th",{children:"Unique"}),l.jsx("th",{children:"Total"}),l.jsx("th",{children:"CTR"})]})}),l.jsx("tbody",{children:z.map(oe=>l.jsxs("tr",{children:[l.jsx("td",{className:"na-table__url",title:oe.url,children:l.jsx("a",{href:oe.url,target:"_blank",rel:"noopener noreferrer",children:Rk(oe.url)})}),l.jsx("td",{children:oe.uniqueClicks}),l.jsx("td",{children:oe.totalClicks}),l.jsx("td",{children:Dp(oe.uniqueClicks,P)})]},oe.url))})]})}),v==="activity"&&l.jsxs("div",{className:"na-activity",children:[l.jsx("div",{className:"na-filter-row",children:["all","open","click","bounce","dropped","unsubscribe"].map(oe=>l.jsx("button",{className:`na-filter-btn${k===oe?" active":""}`,onClick:()=>w(oe),children:oe==="all"?"All":oe.charAt(0).toUpperCase()+oe.slice(1)+"s"},oe))}),l.jsxs("div",{className:"na-table-wrap",children:[ye.length===0?l.jsxs("div",{className:"na-empty",children:["No ",k==="all"?"":k+" ","events recorded."]}):l.jsxs("table",{className:"na-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"Email"}),l.jsx("th",{children:"Event"}),l.jsx("th",{children:"Detail"}),l.jsx("th",{children:"Time"})]})}),l.jsx("tbody",{children:ye.slice(0,100).map(oe=>l.jsxs("tr",{children:[l.jsx("td",{className:"na-table__email",children:oe.email}),l.jsxs("td",{children:[l.jsx("span",{className:`na-badge na-badge--${oe.event_type}`,children:oe.event_type}),oe.count>1&&l.jsxs("span",{className:"na-count",children:[oe.count,"x"]})]}),l.jsx("td",{className:"na-table__url",children:oe.url?l.jsx("a",{href:oe.url,target:"_blank",rel:"noopener noreferrer",children:Rk(oe.url,35)}):"—"}),l.jsx("td",{className:"na-table__time",children:Ak(oe.latestTimestamp)})]},oe.key))})]}),ye.length>100&&l.jsxs("div",{className:"na-truncated",children:["Showing 100 of ",ye.length," events"]})]})]})]})]})]})})}function O$(t){const e=new Map;for(const n of t){const r=`${n.email}|${n.event_type}|${n.url||""}`,s=e.get(r);s?(s.count++,n.timestamp>s.latestTimestamp&&(s.latestTimestamp=n.timestamp)):e.set(r,{key:r,email:n.email,event_type:n.event_type,url:n.url,latestTimestamp:n.timestamp,count:1})}return Array.from(e.values()).sort((n,r)=>new Date(r.latestTimestamp).getTime()-new Date(n.latestTimestamp).getTime())}function I$(t){const e=t.filter(r=>r.event_type==="click"&&r.url),n=new Map;for(const r of e){const s=r.url;let i=n.get(s);i||(i={emails:new Set,total:0},n.set(s,i)),i.emails.add(r.email),i.total++}return Array.from(n.entries()).map(([r,{emails:s,total:i}])=>({url:r,uniqueClicks:s.size,totalClicks:i})).sort((r,s)=>s.uniqueClicks-r.uniqueClicks)}function L$(t){return t.tweetContext?"tweet":t.articleContext?"article":t.linkedinContext?"linkedin":t.newsletterContext?"newsletter":t.blogContext?"blog":"tweet"}function Vl({filename:t,title:e,onClose:n}){const[r,s]=y.useState("queue"),[i,o]=y.useState(null),[c,d]=y.useState(null),[f,h]=y.useState(""),[m,g]=y.useState(!1),[v,x]=y.useState(null),[k,w]=y.useState(null);y.useEffect(()=>{fetch(`/api/documents/${encodeURIComponent(t)}/text`).then(j=>{if(!j.ok)throw new Error("Failed to load document");return j.json()}).then(j=>{d(j.text||""),o(L$(j.meta||{}))}).catch(j=>w(j.message))},[t]);const S=async()=>{var j;if(!(!c||!i)){g(!0);try{const M={content:c,content_type:i,mode:r};r==="custom"&&f&&(M.scheduled_at=new Date(f).toISOString());const _=await fetch("/api/scheduler/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)}),R=await _.json();if(_.ok){const L=(j=R.item)!=null&&j.scheduled_at?new Date(R.item.scheduled_at).toLocaleString():"now";x({success:!0,message:`Scheduled for ${L}`})}else x({success:!1,message:R.error||"Failed to schedule"})}catch(M){x({success:!1,message:M.message})}finally{g(!1)}}},N=i===null&&!k;return l.jsx("div",{className:"schedule-post-overlay",onClick:n,children:l.jsxs("div",{className:"schedule-post-modal",onClick:j=>j.stopPropagation(),children:[l.jsxs("div",{className:"schedule-post-modal-header",children:[l.jsx("h3",{children:"Schedule Post"}),l.jsx("button",{className:"schedule-post-modal-close",onClick:n,children:"×"})]}),l.jsx("div",{className:"schedule-post-modal-doc",children:e}),k?l.jsxs("div",{className:"schedule-post-modal-result error",children:[k,l.jsx("button",{className:"schedule-post-modal-done",onClick:n,children:"Done"})]}):v?l.jsxs("div",{className:`schedule-post-modal-result ${v.success?"success":"error"}`,children:[v.message,l.jsx("button",{className:"schedule-post-modal-done",onClick:n,children:"Done"})]}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"schedule-post-modal-field",children:[l.jsx("label",{children:"Content Type"}),l.jsx("div",{className:"schedule-post-modal-type",children:N?"...":i})]}),l.jsxs("div",{className:"schedule-post-modal-field",children:[l.jsx("label",{children:"Mode"}),l.jsxs("div",{className:"schedule-post-modal-modes",children:[l.jsx("button",{className:`schedule-post-mode ${r==="queue"?"active":""}`,onClick:()=>s("queue"),children:"Queue Next"}),l.jsx("button",{className:`schedule-post-mode ${r==="now"?"active":""}`,onClick:()=>s("now"),children:"Post Now"}),l.jsx("button",{className:`schedule-post-mode ${r==="custom"?"active":""}`,onClick:()=>s("custom"),children:"Custom Time"})]})]}),r==="custom"&&l.jsxs("div",{className:"schedule-post-modal-field",children:[l.jsx("label",{children:"Date & Time"}),l.jsx("input",{type:"datetime-local",value:f,onChange:j=>h(j.target.value)})]}),l.jsxs("div",{className:"schedule-post-modal-actions",children:[l.jsx("button",{className:"schedule-post-modal-cancel",onClick:n,children:"Cancel"}),l.jsx("button",{className:"schedule-post-modal-submit",onClick:S,disabled:m||N||r==="custom"&&!f,children:m?"Scheduling...":r==="now"?"Post Now":"Schedule"})]})]})]})})}const Ok=[{key:"document",label:"Document"},{key:"tweet",label:"Tweet",metadata:{content_type:"tweet",tweetContext:{mode:"tweet"}}},{key:"reply",label:"Reply",needsUrl:!0,urlPlaceholder:"Paste tweet URL...",metadata:{content_type:"reply",tweetContext:{mode:"reply"}}},{key:"quote",label:"Quote Tweet",needsUrl:!0,urlPlaceholder:"Paste tweet URL...",metadata:{content_type:"quote",tweetContext:{mode:"quote"}}},{key:"article",label:"Article",metadata:{content_type:"article",articleContext:{active:!0}}},{key:"linkedin",label:"LinkedIn",metadata:{content_type:"linkedin",linkedinContext:{active:!0}}},{key:"newsletter",label:"Newsletter",metadata:{content_type:"newsletter",newsletterContext:{active:!0}}},{key:"blog",label:"Blog",metadata:{content_type:"blog",blogContext:{active:!0}}},{key:"manuscript",label:"Manuscript",metadata:{content_type:"manuscript",manuscriptContext:{active:!0}}}];function UT({anchorRect:t,onSelect:e,onClose:n}){const r=y.useRef(null),[s,i]=y.useState(null),[o,c]=y.useState(""),d=y.useRef(null),[f,h]=y.useState({left:t.left,top:t.bottom+4});y.useLayoutEffect(()=>{const x=r.current;if(!x)return;const k=x.getBoundingClientRect(),w=8;let S=t.left,N=t.bottom+4;N+k.height+w>window.innerHeight&&(N=t.top-k.height-4),S+k.width+w>window.innerWidth&&(S=t.right-k.width),N<w&&(N=w),S<w&&(S=w),h({left:S,top:N})},[t]),y.useEffect(()=>{const x=k=>{r.current&&!r.current.contains(k.target)&&n()};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[n]),y.useEffect(()=>{const x=k=>{k.key==="Escape"&&n()};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[n]),y.useEffect(()=>{s&&setTimeout(()=>{var x;return(x=d.current)==null?void 0:x.focus()},0)},[s]);const m=x=>{if(x.needsUrl){i(x.key),c("");return}e(x.metadata)},g=()=>{if(!s||!o.trim())return;const x=o.trim();if(!x.includes("x.com")&&!x.includes("twitter.com"))return;const k=Ok.find(S=>S.key===s);if(!(k!=null&&k.metadata))return;const w=JSON.parse(JSON.stringify(k.metadata));w.tweetContext&&(w.tweetContext.url=x),e(w)},v=o.trim().includes("x.com")||o.trim().includes("twitter.com");return l.jsx("div",{ref:r,className:"create-doc-dropdown",style:{left:f.left,top:f.top},children:Ok.map(x=>l.jsxs("div",{children:[l.jsx("button",{className:`create-doc-dropdown-item${s===x.key?" active":""}`,onClick:()=>m(x),children:x.label}),s===x.key&&l.jsxs("div",{className:"create-doc-dropdown-url",children:[l.jsx("input",{ref:d,type:"text",placeholder:x.urlPlaceholder,value:o,onChange:k=>c(k.target.value),onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),g()),k.key==="Escape"&&(i(null),c(""))}}),l.jsx("button",{onClick:g,disabled:!v,children:l.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"9 18 15 12 9 6"})})})]})]},x.key))})}const D$=[{id:"full",label:"Full"},{id:"compact",label:"Compact"},{id:"minimal",label:"Minimal"}];function ev(t,e){for(const n of t){if(n.type==="doc"&&n.file===e)return[];if(n.type==="container"){const r=ev(n.items,e);if(r)return[n.id,...r]}}return null}function P$({docs:t,archivedDocs:e,workspaces:n,assignedFiles:r,pendingDocs:s,onSwitchDocument:i,onCreateDocument:o,actions:c,scrollRef:d,writingTitle:f,writingTarget:h,pendingWriteFilenames:m,searchQuery:g,searchResults:v,onSearchChange:x}){const k=I=>!!m&&m.has(I),[w,S]=y.useState(null),[N,j]=y.useState(""),[M,_]=y.useState(null),[R,L]=y.useState(()=>{try{const I=localStorage.getItem("ow-collapsed-sections");return I?new Set(JSON.parse(I)):new Set}catch{return new Set}}),[$,B]=y.useState(null),[U,X]=y.useState(null),[z,ee]=y.useState(""),[P,F]=y.useState(null),[G,ie]=y.useState(""),[K,ce]=y.useState(null),[J,A]=y.useState(""),[D,q]=y.useState(null),[le,ye]=y.useState(null),[oe,Se]=y.useState([]),[Ee,Le]=y.useState(!1),[Ie,Ve]=y.useState(null),[Te,qe]=y.useState(null),[pt,ut]=y.useState(null),[be,ht]=y.useState(null),[xt,St]=y.useState(null),[At,Ye]=y.useState(BE),ct=y.useRef(null);y.useEffect(()=>{if(!xt)return;const I=V=>{ct.current&&!ct.current.contains(V.target)&&St(null)};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[xt]);const Fe=I=>{Ye(I),LM(I),St(null)},Y=I=>{I.preventDefault(),St({x:I.clientX,y:I.clientY})},ge=y.useCallback((I,V)=>{fetch("/api/documents/batch-resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filenames:I,action:V})}).catch(()=>{})},[]),{draggedItem:ne,dropIndicator:he,handlePointerDown:me,dropClass:ze,isDragging:Ae,isContainerDropTarget:Xe}=BT({docs:t,workspaces:n,assignedFiles:r,scrollRef:d,setCollapsedSections:L}),Qe=y.useCallback(()=>{fetch("/api/plugins").then(I=>I.json()).then(I=>{const V=[];let re=!1;for(const Q of I.plugins||[]){const ue=Q.displayName||void 0;for(const ve of Q.sidebarMenuItems||[])V.push({...ve,pluginDisplayName:ue});Q.name==="@openwriter/plugin-publish"&&Q.enabled&&(re=!0)}Se(V),Le(re)}).catch(()=>{})},[]);y.useEffect(()=>{Qe()},[Qe]),y.useEffect(()=>{const I=()=>Qe();return window.addEventListener("ow-plugins-changed",I),()=>window.removeEventListener("ow-plugins-changed",I)},[Qe]);const{variantsByMaster:tt,variantFilenames:We}=y.useMemo(()=>{const I=new Map,V=new Set;for(const re of t)if(re.masterDocId){const Q=I.get(re.masterDocId)||[];Q.push(re),I.set(re.masterDocId,Q),V.add(re.filename)}return{variantsByMaster:I,variantFilenames:V}},[t]),Ue=y.useCallback((I,V)=>{I.preventDefault(),I.stopPropagation(),q({x:I.clientX,y:I.clientY,filename:V.filename,title:V.title,docId:V.docId,lastSent:V.lastSent,postedUrl:V.postedUrl,isNewsletter:V.isNewsletter})},[]),st=y.useCallback(I=>{fetch("/api/documents/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:I})}).catch(()=>{})},[]),mt=y.useCallback((I,V,re)=>{fetch("/api/documents/variant",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:I,masterDocId:V,variantType:re})}).catch(()=>{})},[]),Nt=y.useCallback((I,V,re,Q,ue)=>{if(!$T(V,t.find(ve=>ve.filename===re))){if(V.promptForFocus&&ue===void 0){Ve({action:I,label:V.label,filename:re,title:Q});return}fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:I,filename:re,title:Q,instructions:ue||"",label:V.label})}).catch(()=>{})}},[t]),Mt=I=>{L(V=>{const re=new Set(V);return re.has(I)?re.delete(I):re.add(I),localStorage.setItem("ow-collapsed-sections",JSON.stringify([...re])),re})},Jt=y.useRef(n);Jt.current=n;const nn=y.useCallback(I=>{var V;for(const re of Jt.current){const Q=ev(((V=re.workspace)==null?void 0:V.root)||[],I);if(Q){L(ue=>{const ve=[re.filename,...Q.map(xe=>`container-${xe}`)];if(ve.every(xe=>!ue.has(xe)))return ue;const Re=new Set(ue);for(const xe of ve)Re.delete(xe);return localStorage.setItem("ow-collapsed-sections",JSON.stringify([...Re])),Re});break}}},[]);Wl(d,t,n.length,nn);const at=y.useMemo(()=>{var Q;const I=t.find(ue=>ue.isActive);if(!I)return null;const V=I.masterDocId?t.find(ue=>ue.docId===I.masterDocId):void 0,re=(V==null?void 0:V.filename)??I.filename;for(const ue of n){const ve=ev(((Q=ue.workspace)==null?void 0:Q.root)||[],re);if(ve)return{wsFilename:ue.filename,containerKeys:new Set(ve.map(Re=>`container-${Re}`)),masterDocId:(V==null?void 0:V.docId)??null}}return{wsFilename:null,containerKeys:new Set,masterDocId:(V==null?void 0:V.docId)??null}},[t,n]);if(v!==null)return l.jsx(rf,{results:v,query:g,onSwitchDocument:i,actions:c});const Ht=t.filter(I=>!r.has(I.filename)&&!We.has(I.filename)),T=(I,V,re,Q,ue,ve=!1)=>l.jsxs("div",{className:`sidebar-item ${I.isActive?"active":""} ${Ae(I.filename)?"dragging":""} ${ze(I.filename)}`,"data-drag-id":I.filename,"data-drag-type":"doc","data-drag-ws":V||"__docs__","data-drag-container":re||"",onPointerDown:Re=>me(Re,{type:"doc",file:I.filename,sourceWs:V||null},I.title),onClick:()=>!I.isActive&&!ne&&i(I.filename),onDoubleClick:()=>{S(I.filename),j(I.title)},onContextMenu:Re=>Ue(Re,I),children:[w===I.filename?l.jsx("input",{className:"sidebar-rename-input",value:N,onChange:Re=>j(Re.target.value),onBlur:()=>{c.handleRename(I.filename,I.title,N),S(null)},onKeyDown:Re=>{Re.key==="Enter"&&(c.handleRename(I.filename,I.title,N),S(null)),Re.key==="Escape"&&S(null)},autoFocus:!0,onClick:Re=>Re.stopPropagation()}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-item-title-text",children:I.title}),I.variantType&&l.jsx("span",{className:"files-badge-variant",children:I.variantType}),c.getDocTags(I.filename).includes("✓")&&l.jsx("svg",{className:"sidebar-approved-icon",title:"Approved",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"20 6 9 17 4 12"})}),I.lastSent&&l.jsx("svg",{className:"sidebar-sent-icon",title:"Sent",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"20 6 9 17 4 12"})}),(I.autoAccept===!0||I.autoAccept!==!1&&ve)&&l.jsx("span",{className:"sidebar-auto-accept-dot",title:I.autoAccept===!0?"Auto-accept on":"Auto-accept inherited"}),s.filenames.includes(I.filename)&&l.jsx("span",{className:"sidebar-pending-dot"})]}),Vs(I.filename)&&l.jsx("div",{className:"sidebar-item-context",children:DT(I.filename)}),l.jsxs("div",{className:"sidebar-item-meta",children:[I.wordCount.toLocaleString()," words · ",ba(I.lastModified)]}),l.jsxs("div",{className:"sidebar-tags",children:[c.getDocTags(I.filename).filter(Re=>Re!=="✓").map(Re=>l.jsxs("span",{className:"sidebar-tag",onClick:xe=>xe.stopPropagation(),children:[Re,l.jsx("span",{className:"sidebar-tag-remove",onClick:xe=>{xe.stopPropagation(),c.handleRemoveTag(I.filename,Re)},children:"×"})]},Re)),K===I.filename?l.jsx("input",{className:"sidebar-tag-input",value:J,onChange:Re=>A(Re.target.value),onBlur:()=>{J.trim()&&c.handleAddTag(I.filename,J),ce(null)},onKeyDown:Re=>{Re.key==="Enter"&&(c.handleAddTag(I.filename,J),ce(null),A("")),Re.key==="Escape"&&(ce(null),A(""))},autoFocus:!0,onClick:Re=>Re.stopPropagation(),placeholder:"tag..."}):l.jsx("button",{className:"sidebar-tag-add",onClick:Re=>{Re.stopPropagation(),ce(I.filename),A("")},children:"+"})]})]}),M===I.filename?l.jsxs("div",{className:"sidebar-confirm-delete",onClick:Re=>Re.stopPropagation(),children:[l.jsx("span",{children:Vs(I.filename)?"Remove?":"Delete?"}),l.jsx("button",{onClick:()=>{c.handleDelete(I.filename),_(null)},children:"Yes"}),l.jsx("button",{onClick:()=>_(null),children:"No"})]}):l.jsx("button",{className:"sidebar-delete-btn",onClick:Re=>{Re.stopPropagation(),_(I.filename)},title:Vs(I.filename)?"Remove document":"Delete document",children:"×"})]},I.filename),W=(I,V,re,Q,ue,ve=!1)=>{const Re=I.docId?tt.get(I.docId):void 0,xe=f&&(h==null?void 0:h.parentDocId)&&h.parentDocId===I.docId;if(!(Re&&Re.length>0||xe))return T(I,V,re,Q,ue,ve);const Et=`variants-${I.docId}`,dn=!R.has(Et);return l.jsxs("div",{className:"sidebar-variant-group",children:[l.jsxs("div",{className:`sidebar-variant-master${!dn&&(at==null?void 0:at.masterDocId)===I.docId?" active-within":""}`,onClick:Xt=>{Xt.target.closest(".sidebar-variant-chevron")&&(Xt.stopPropagation(),Mt(Et))},children:[T(I,V,re,Q,ue,ve),l.jsx("span",{className:`sidebar-variant-chevron${dn?"":" collapsed"}`,children:l.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"6 9 12 15 18 9"})})})]}),dn&&l.jsxs("div",{className:"sidebar-variant-children",children:[Re==null?void 0:Re.map((Xt,ln)=>T(Xt,V,re,Q,ln,ve)),xe&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:f})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]})]})]},`vg-${I.filename}`)},ae=(I,V,re,Q,ue,ve,Re=!1)=>{if(I.type==="doc"){const $e=t.find(zt=>zt.filename===I.file);return $e?We.has($e.filename)?l.jsx(l.Fragment,{}):W($e,re,Q,ue,ve,Re):Vs(I.file)?l.jsx("div",{className:"sidebar-item sidebar-unavailable",children:l.jsxs("div",{className:"sidebar-item-title",children:[I.title||I.file," (unavailable)"]})},I.file):l.jsxs("div",{className:"sidebar-item sidebar-missing",children:[l.jsxs("div",{className:"sidebar-item-title",children:[I.title||I.file," (missing)"]}),l.jsx("button",{className:"sidebar-delete-btn",onClick:()=>c.handleRemoveFromWorkspace(re,I.file),title:"Remove",children:"×"})]},I.file)}const xe=I,Dt=`container-${xe.id}`,Et=R.has(Dt),dn=V<=2?`depth-${V}`:"depth-2",Xt=xe.autoAccept===!0,ln=Xt||Re;return l.jsxs("div",{className:`sidebar-container ${dn} ${Et?"collapsed":""} ${ze(xe.id)} ${Xe(xe.id)?"drop-inside":""}`,children:[l.jsxs("div",{className:`sidebar-container-header${Et&&(at!=null&&at.containerKeys.has(Dt))?" active-within":""} ${(he==null?void 0:he.itemId)===xe.id&&he.position==="inside"?"drop-inside":""}`,"data-drag-id":xe.id,"data-drag-type":"container-header","data-drag-ws":re,"data-drag-parent":Q||"","data-section-key":Dt,onPointerDown:$e=>me($e,{type:"container",id:xe.id,sourceWs:re},xe.name),onClick:()=>!ne&&Mt(Dt),onContextMenu:$e=>{$e.preventDefault(),$e.stopPropagation(),ht({x:$e.clientX,y:$e.clientY,type:"container",wsFilename:re,containerId:xe.id,title:xe.name,nodes:xe.items,autoAccept:Xt})},children:[l.jsx("span",{className:`sidebar-chevron ${Et?"collapsed":""}`,children:"▾"}),U===xe.id?l.jsx("input",{className:"sidebar-rename-input",value:z,onChange:$e=>ee($e.target.value),onBlur:()=>{c.handleRenameContainer(re,xe.id,z),X(null)},onKeyDown:$e=>{$e.key==="Enter"&&(c.handleRenameContainer(re,xe.id,z),X(null)),$e.key==="Escape"&&X(null)},autoFocus:!0,onClick:$e=>$e.stopPropagation()}):l.jsx("span",{className:"sidebar-container-name",onDoubleClick:$e=>{$e.stopPropagation(),X(xe.id),ee(xe.name)},children:xe.name}),ln&&l.jsx("span",{className:"sidebar-auto-accept-dot",title:Xt?"Auto-accept on for this container":"Auto-accept inherited from workspace"}),l.jsxs("div",{className:"sidebar-container-actions",children:[l.jsx("button",{className:"sidebar-new-btn",onClick:$e=>{$e.stopPropagation(),ut({anchor:$e.target.getBoundingClientRect(),wsFilename:re,containerId:xe.id})},title:"New doc",children:"+"}),V<2&&l.jsx("button",{className:"sidebar-new-btn",onClick:$e=>{$e.stopPropagation(),c.handleCreateContainer(re,xe.id)},title:"New sub-container",children:"☐"}),l.jsx("button",{className:"sidebar-new-btn sidebar-container-delete",onClick:$e=>{$e.stopPropagation(),c.handleDeleteContainer(re,xe.id)},title:"Delete container",children:"×"})]})]}),!Et&&l.jsxs("div",{className:"sidebar-container-list","data-drop-ws":re,"data-drop-container":xe.id,children:[f&&!(h!=null&&h.parentDocId)&&(h==null?void 0:h.wsFilename)===re&&h.containerId===xe.id&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:f})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),xe.items.filter($e=>$e.type!=="doc"?!0:!(k($e.file)||f&&(h==null?void 0:h.wsFilename)===re&&h.containerId===xe.id&&$e.title===f)).map(($e,zt)=>ae($e,V+1,re,xe.id,xe.items,zt,ln)),xe.items.length===0&&!f&&l.jsx("div",{className:"sidebar-empty",children:ne?"Drop here":"Empty"})]})]},xe.id)};return l.jsxs("div",{className:"sidebar-scroll",ref:d,children:[l.jsxs("div",{className:`sidebar-section sidebar-docs-section ${R.has("docs")?"docs-collapsed":""}`,children:[l.jsxs("div",{className:`sidebar-section-header${R.has("docs")&&at!==null&&at.wsFilename===null?" active-within":""}`,"data-section-key":"docs",onClick:()=>Mt("docs"),onContextMenu:Y,children:[l.jsx("span",{className:`sidebar-chevron ${R.has("docs")?"collapsed":""}`,children:"▾"}),l.jsx("span",{className:"sidebar-label",children:"Documents"}),l.jsx("button",{className:"sidebar-new-btn",onClick:I=>{I.stopPropagation(),ut({anchor:I.target.getBoundingClientRect()})},title:"New document",children:"+"})]}),!R.has("docs")&&l.jsxs("div",{className:"sidebar-section-list","data-drop-ws":"__docs__",children:[f&&!(h!=null&&h.parentDocId)&&(!h||!n.some(I=>I.filename===(h==null?void 0:h.wsFilename)))&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:f})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),Ht.filter(I=>!k(I.filename)&&(!f||I.title!==f)).map((I,V)=>{const re=Ht.map(Q=>({type:"doc",file:Q.filename,title:Q.title}));return W(I,void 0,null,re,V)}),Ht.length===0&&l.jsx("div",{className:"sidebar-empty",children:ne?"Drop here to unassign":"No unassigned documents"})]})]}),n.map(I=>{var ue,ve,Re;const V=((ue=I.workspace)==null?void 0:ue.root)||[],re=R.has(I.filename),Q=((ve=I.workspace)==null?void 0:ve.autoAccept)===!0||I.autoAccept===!0;return l.jsxs("div",{className:`sidebar-section sidebar-workspace-section ${re?"ws-collapsed":""} ${Ae(I.filename)?"dragging":""} ${(he==null?void 0:he.itemId)===I.filename?he.position==="before"?"drop-before":"drop-after":""}`,children:[l.jsxs("div",{className:`sidebar-section-header${re&&(at==null?void 0:at.wsFilename)===I.filename?" active-within":""}`,"data-section-key":I.filename,"data-ws-drag":I.filename,onPointerDown:xe=>me(xe,{type:"workspace",filename:I.filename},I.title),onClick:()=>!ne&&Mt(I.filename),onContextMenu:xe=>{var Dt;xe.preventDefault(),xe.stopPropagation(),ht({x:xe.clientX,y:xe.clientY,type:"workspace",wsFilename:I.filename,title:I.title,nodes:V,autoAccept:((Dt=I.workspace)==null?void 0:Dt.autoAccept)===!0||I.autoAccept===!0})},children:[l.jsx("span",{className:`sidebar-chevron ${re?"collapsed":""}`,children:"▾"}),P===I.filename?l.jsx("input",{className:"sidebar-rename-input",value:G,onChange:xe=>ie(xe.target.value),onBlur:()=>{c.handleRenameWorkspace(I.filename,G),F(null)},onKeyDown:xe=>{xe.key==="Enter"&&(c.handleRenameWorkspace(I.filename,G),F(null)),xe.key==="Escape"&&F(null)},autoFocus:!0,onClick:xe=>xe.stopPropagation()}):l.jsx("span",{className:"sidebar-label sidebar-workspace-label",onDoubleClick:xe=>{xe.stopPropagation(),F(I.filename),ie(I.title)},children:I.title}),(((Re=I.workspace)==null?void 0:Re.autoAccept)===!0||I.autoAccept===!0)&&l.jsx("span",{className:"sidebar-auto-accept-dot",title:"Auto-accept on for this workspace"}),l.jsxs("div",{className:"sidebar-workspace-actions",children:[l.jsx("button",{className:"sidebar-new-btn",onClick:xe=>{xe.stopPropagation(),ut({anchor:xe.target.getBoundingClientRect(),wsFilename:I.filename,containerId:null})},title:"New document",children:"+"}),l.jsx("button",{className:"sidebar-new-btn",onClick:xe=>{xe.stopPropagation(),c.handleCreateContainer(I.filename,null)},title:"New container",children:"☐"}),$===I.filename?l.jsxs("span",{className:"sidebar-inline-confirm",onClick:xe=>xe.stopPropagation(),children:[l.jsx("button",{onClick:()=>{c.handleDeleteWorkspace(I.filename),B(null)},children:"Yes"}),l.jsx("button",{onClick:()=>B(null),children:"No"})]}):l.jsx("button",{className:"sidebar-new-btn sidebar-workspace-delete",onClick:xe=>{xe.stopPropagation(),B(I.filename)},title:"Delete workspace",children:"×"})]})]}),!re&&l.jsxs("div",{className:"sidebar-section-list","data-drop-ws":I.filename,children:[f&&!(h!=null&&h.parentDocId)&&(h==null?void 0:h.wsFilename)===I.filename&&h.containerId===null&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:f})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),V.filter(xe=>xe.type!=="doc"?!0:!(k(xe.file)||f&&(h==null?void 0:h.wsFilename)===I.filename&&h.containerId===null&&xe.title===f)).map((xe,Dt)=>ae(xe,0,I.filename,null,V,Dt,Q)),V.length===0&&!f&&l.jsx("div",{className:"sidebar-empty",children:ne?"Drop here to add":"Empty workspace"})]})]},I.filename)}),l.jsx("div",{className:"sidebar-new-workspace",children:l.jsx("button",{onClick:c.handleCreateWorkspace,children:"+ New Workspace"})}),be&&l.jsx(Bd,{x:be.x,y:be.y,filename:be.wsFilename,title:be.title,onClose:()=>ht(null),onDuplicate:()=>{},onRename:()=>{be.type==="workspace"?(F(be.wsFilename),ie(be.title)):be.containerId&&(X(be.containerId),ee(be.title)),ht(null)},onArchive:()=>{},onDelete:()=>{be.type==="workspace"?c.handleDeleteWorkspace(be.wsFilename):be.containerId&&c.handleDeleteContainer(be.wsFilename,be.containerId)},onPluginAction:()=>{},pluginItems:[],folderMode:!0,onNewDoc:I=>{ut({anchor:I.target.getBoundingClientRect(),wsFilename:be.wsFilename,containerId:be.type==="container"?be.containerId:null}),ht(null)},onNewContainer:()=>{c.handleCreateContainer(be.wsFilename,be.type==="container"?be.containerId:null),ht(null)},onAcceptAll:()=>{const I=new Set;Ll(be.nodes,I),I.size&&ge([...I],"accept"),ht(null)},onRejectAll:()=>{const I=new Set;Ll(be.nodes,I),I.size&&ge([...I],"reject"),ht(null)},folderAutoAccept:be.autoAccept,folderAutoAcceptLabel:be.type==="workspace"?"for workspace":"for container",onToggleFolderAutoAccept:()=>{fetch("/api/auto-accept/inherit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wsFile:be.wsFilename,...be.type==="container"?{containerId:be.containerId}:{},enabled:!be.autoAccept})}).catch(()=>{})}}),D&&l.jsx(Bd,{x:D.x,y:D.y,filename:D.filename,title:D.title,onClose:()=>q(null),onDuplicate:()=>st(D.filename),onCreateVariant:D.docId?I=>mt(D.filename,D.docId,I):void 0,onRename:()=>{S(D.filename),j(D.title)},onArchive:()=>c.handleArchive(D.filename),onDelete:()=>c.handleDelete(D.filename),onPluginAction:(I,V)=>Nt(I,V,D.filename,D.title),pluginItems:oe,onSchedulePost:Ee?()=>{qe({filename:D.filename,title:D.title}),q(null)}:void 0,onViewAnalytics:D.docId&&D.lastSent&&(D.postedUrl||D.isNewsletter)?()=>{D.isNewsletter?ye({docId:D.docId,title:D.title}):D.postedUrl&&window.open(D.postedUrl,"_blank"),q(null)}:void 0,viewAnalyticsLabel:D.isNewsletter?"View Analytics":D.postedUrl?"View on X":"View Analytics",isApproved:c.getDocTags(D.filename).includes("✓"),onToggleApprove:()=>{c.getDocTags(D.filename).includes("✓")?c.handleRemoveTag(D.filename,"✓"):(c.handleAddTag(D.filename,"✓"),setTimeout(()=>window.dispatchEvent(new CustomEvent("ow-accept-all")),50))},isAutoAccept:(()=>{var V;const I=(V=t.find(re=>re.filename===D.filename))==null?void 0:V.autoAccept;return I===!0?!0:I===!1?!1:Pd(n,D.filename)})(),onToggleAutoAccept:()=>{var re;const I=(re=t.find(Q=>Q.filename===D.filename))==null?void 0:re.autoAccept,V=I===!0?!0:I===!1?!1:Pd(n,D.filename);fetch("/api/auto-accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:D.filename,enabled:!V})}).then(()=>c.fetchDocs()).catch(()=>{})},isAlreadySent:!!D.lastSent,onMarkSent:()=>{const I=D.filename;c.getDocTags(I).includes("✓")&&c.handleRemoveTag(I,"✓"),i(I),setTimeout(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualPost:{postedAt:new Date().toISOString()}})}).then(()=>c.fetchDocs()).catch(()=>{})},100),q(null)}}),Ie&&l.jsx(FT,{actionLabel:Ie.label,docTitle:Ie.title,onClose:()=>Ve(null),onConfirm:I=>{const V=oe.find(re=>re.action===Ie.action);V&&Nt(Ie.action,V,Ie.filename,Ie.title,I),Ve(null)}}),le&&l.jsx(zT,{docId:le.docId,title:le.title,onClose:()=>ye(null)}),Te&&l.jsx(Vl,{filename:Te.filename,title:Te.title,onClose:()=>qe(null)}),pt&&l.jsx(UT,{anchorRect:pt.anchor,onClose:()=>ut(null),onSelect:I=>{ut(null),pt.wsFilename?c.handleCreateInWorkspace(pt.wsFilename,pt.containerId??null,I):I?fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:I})}).catch(()=>{}):o()}}),xt&&l.jsx("div",{ref:ct,className:"sidebar-density-dropdown",style:{position:"fixed",left:xt.x,top:xt.y,zIndex:200},children:D$.map(I=>l.jsx("button",{className:`sidebar-density-option ${At===I.id?"active":""}`,onClick:()=>Fe(I.id),children:I.label},I.id))})]})}function B$({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,onCreateDocument:i,actions:o,scrollRef:c,searchQuery:d,searchResults:f}){const[h,m]=y.useState(null);if(Wl(c,t,e.length),f!==null)return l.jsx(rf,{results:f,query:d,onSwitchDocument:s});const g=[...t].sort((w,S)=>new Date(S.lastModified).getTime()-new Date(w.lastModified).getTime()),v=[];let x="";for(const w of g){const S=T$(w.lastModified);S!==x&&(v.push({label:S,docs:[]}),x=S),v[v.length-1].docs.push(w)}const k=w=>{for(const S of e){if(!S.workspace)continue;const N=j=>{for(const M of j)if(M.type==="doc"&&M.file===w||M.type==="container"&&N(M.items))return!0;return!1};if(N(S.workspace.root))return S.title}return null};return l.jsxs("div",{className:"sidebar-scroll tl-scroll",ref:c,children:[l.jsxs("div",{className:"tl-header",children:[l.jsx("span",{className:"tl-title",children:"Timeline"}),l.jsx("button",{className:"sidebar-new-btn",onClick:i,title:"New document",children:"+"})]}),v.map(w=>l.jsxs("div",{className:"tl-group",children:[l.jsx("div",{className:"tl-date",children:w.label}),w.docs.map(S=>{const N=k(S.filename);return l.jsxs("div",{className:`tl-item ${S.isActive?"active":""}`,onClick:()=>!S.isActive&&s(S.filename),children:[l.jsx("div",{className:"tl-dot"}),l.jsxs("div",{className:"tl-content",children:[l.jsxs("div",{className:"tl-item-title",children:[l.jsx("span",{children:S.title}),r.filenames.includes(S.filename)&&l.jsx("span",{className:"sidebar-pending-dot"})]}),Vs(S.filename)&&l.jsx("div",{className:"tl-item-context",children:DT(S.filename)}),l.jsxs("div",{className:"tl-item-meta",children:[S.wordCount.toLocaleString()," words · ",ba(S.lastModified)]}),N&&l.jsx("div",{className:"tl-badge",children:N})]}),h===S.filename?l.jsxs("div",{className:"sidebar-confirm-delete",onClick:j=>j.stopPropagation(),children:[l.jsx("span",{children:Vs(S.filename)?"Remove?":"Delete?"}),l.jsx("button",{onClick:()=>{o.handleDelete(S.filename),m(null)},children:"Yes"}),l.jsx("button",{onClick:()=>m(null),children:"No"})]}):l.jsx("button",{className:"sidebar-delete-btn",onClick:j=>{j.stopPropagation(),m(S.filename)},title:Vs(S.filename)?"Remove":"Delete",children:"×"})]},S.filename)})]},w.label)),t.length===0&&l.jsx("div",{className:"sidebar-empty",children:"No documents yet"})]})}function $$({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:o,searchQuery:c,searchResults:d,onSearchChange:f}){const[h,m]=y.useState([]),[g,v]=y.useState(null);Wl(o,t,e.length);const[x,k]=y.useState(null),w=y.useRef(null);y.useEffect(()=>{if(!g)return;const A=D=>{w.current&&!w.current.contains(D.target)&&v(null)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[g]);const S=(A,D)=>{for(const q of A)if(q.type==="container"){if(q.id===D)return q;const le=S(q.items,D);if(le)return le}return null},N=A=>{let D=0;for(const q of A)q.type==="doc"?D++:q.type==="container"&&(D+=N(q.items));return D},j=A=>{const D=[];for(const q of A)q.type==="doc"?D.push(q.file):q.type==="container"&&D.push(...j(q.items));return D},M=y.useMemo(()=>{if(h.length===0)return[];const A=h[h.length-1],D=e.find(le=>le.filename===A.wsFilename);if(!(D!=null&&D.workspace))return[];if(A.type==="workspace")return D.workspace.root;const q=S(D.workspace.root,A.key);return q?q.items:[]},[h,e]),_=M.filter(A=>A.type==="container"),R=y.useMemo(()=>{const A=M.filter(D=>D.type==="doc").map(D=>D.file);return t.filter(D=>A.includes(D.filename))},[M,t]),L=A=>{const D=j(A.items);return t.filter(q=>D.includes(q.filename))},$=A=>{const D=e.find(le=>le.filename===A);if(!(D!=null&&D.workspace))return[];const q=j(D.workspace.root);return t.filter(le=>q.includes(le.filename))},B=y.useMemo(()=>t.filter(A=>!n.has(A.filename)),[t,n]),U=A=>{m(D=>[...D,A]),v(null)},X=()=>{m(A=>A.slice(0,-1)),v(null)},z=(A,D)=>{if(g===A){v(null);return}const le=D.currentTarget.getBoundingClientRect();k({top:le.bottom+4,left:le.left}),v(A)},ee=A=>{s(A),v(null)},P=h.length>1?h[h.length-2].title:"All",F=y.useRef(null),G=y.useRef(null),[ie,K]=y.useState(null),ce=y.useCallback(A=>{const q=A.currentTarget.getBoundingClientRect();K({top:q.bottom+4,left:q.left})},[]);y.useEffect(()=>{if(!d)return;const A=D=>{G.current&&!G.current.contains(D.target)&&F.current&&!F.current.contains(D.target)&&f("")};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[d,f]);const J=()=>{if(!g)return[];if(g==="__unassigned__")return B;if(g==="__level-docs__")return R;const A=e.find(D=>D.filename===g);if(A)return $(A.filename);for(const D of e){if(!D.workspace)continue;const q=S(D.workspace.root,g);if(q)return L(q)}return[]};return l.jsxs("div",{className:"board-scroll",ref:o,children:[l.jsxs("div",{className:"board-search-pill",children:[l.jsxs("svg",{className:"board-search-icon",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("circle",{cx:"11",cy:"11",r:"8"}),l.jsx("path",{d:"m21 21-4.3-4.3"})]}),l.jsx("input",{ref:F,className:"board-search-input",type:"text",placeholder:"Search...",value:c,onChange:A=>f(A.target.value),onFocus:ce}),c&&l.jsx("button",{className:"board-search-clear",onClick:()=>f(""),children:"×"})]}),h.length===0?l.jsx("button",{className:"board-back board-back--static",tabIndex:-1,children:"All"}):l.jsxs("button",{className:"board-back",onClick:X,title:`Back to ${P}`,children:["← ",P]}),h.length===0&&l.jsxs(l.Fragment,{children:[B.length>0&&l.jsxs("button",{className:`board-chip ${g==="__unassigned__"?"open":""}`,onClick:A=>z("__unassigned__",A),children:["Documents ",l.jsx("span",{className:"board-chip-count",children:B.length})]}),e.map(A=>{var q;const D=(q=A.workspace)==null?void 0:q.root.some(le=>le.type==="container");return l.jsxs("button",{className:`board-chip ${g===A.filename?"open":""}`,onClick:le=>D?U({type:"workspace",key:A.filename,title:A.title,wsFilename:A.filename}):z(A.filename,le),children:[A.title," ",l.jsx("span",{className:"board-chip-count",children:A.docCount}),D&&l.jsx("span",{className:"board-chip-arrow",children:"›"})]},A.filename)}),l.jsx("button",{className:"board-chip board-chip-add",onClick:i.handleCreateWorkspace,title:"New workspace",children:"+"})]}),h.length>0&&l.jsxs(l.Fragment,{children:[R.length>0&&l.jsxs("button",{className:`board-chip board-chip-docs ${g==="__level-docs__"?"open":""}`,onClick:A=>z("__level-docs__",A),children:["Docs ",l.jsx("span",{className:"board-chip-count",children:R.length})]}),_.map(A=>{const D=A.items.some(q=>q.type==="container");return l.jsxs("button",{className:`board-chip ${g===A.id?"open":""}`,onClick:q=>D?U({type:"container",key:A.id,title:A.name,wsFilename:h[h.length-1].wsFilename}):z(A.id,q),children:[A.name," ",l.jsx("span",{className:"board-chip-count",children:N(A.items)}),D&&l.jsx("span",{className:"board-chip-arrow",children:"›"})]},A.id)})]}),g&&x&&(()=>{const A=J();return l.jsxs("div",{className:"board-dropdown",ref:w,style:{position:"fixed",top:x.top,left:x.left},children:[A.map(D=>l.jsxs("div",{className:`board-dropdown-item ${D.isActive?"active":""}`,onClick:()=>ee(D.filename),children:[l.jsxs("span",{className:"board-dropdown-title",children:[D.title,r.filenames.includes(D.filename)&&l.jsx("span",{className:"board-pending-dot"})]}),l.jsxs("span",{className:"board-dropdown-meta",children:[D.wordCount.toLocaleString()," words · ",ba(D.lastModified)]})]},D.filename)),A.length===0&&l.jsx("div",{className:"board-dropdown-empty",children:"No documents"})]})})(),d&&ie&&l.jsxs("div",{className:"board-dropdown board-search-dropdown",ref:G,style:{position:"fixed",top:ie.top,left:ie.left},children:[d.map(A=>l.jsxs("div",{className:`board-dropdown-item ${A.isActive?"active":""}`,onClick:()=>{s(A.filename),f("")},children:[l.jsx("span",{className:"board-dropdown-title",children:A.title}),A.matchType==="tag"&&A.matchedTag&&l.jsxs("span",{className:"board-dropdown-meta",children:["Tag: ",A.matchedTag]}),A.matchType==="content"&&A.snippet&&l.jsx("span",{className:"board-dropdown-meta board-search-snippet",children:A.snippet}),l.jsxs("span",{className:"board-dropdown-meta",children:[A.wordCount.toLocaleString()," words · ",ba(A.lastModified)]})]},A.filename)),d.length===0&&l.jsx("div",{className:"board-dropdown-empty",children:"No results"})]})]})}function F$({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:o,searchQuery:c,searchResults:d}){const[f,h]=y.useState([]);if(Wl(o,t,e.length),d!==null)return l.jsx(rf,{results:d,query:c,onSwitchDocument:s});const m=(M,_)=>{for(const R of M)if(R.type==="container"){if(R.id===_)return R;const L=m(R.items,_);if(L)return L}return null},g=M=>{let _=0;for(const R of M)R.type==="doc"?_++:R.type==="container"&&(_+=g(R.items));return _},v=y.useMemo(()=>{if(f.length===0)return[];const M=f[f.length-1],_=e.find(L=>L.filename===M.wsFilename);if(!(_!=null&&_.workspace))return[];if(M.type==="workspace")return _.workspace.root;const R=m(_.workspace.root,M.key);return R?R.items:[]},[f,e]),x=v.filter(M=>M.type==="container"),k=y.useMemo(()=>{if(f.length===0)return t.filter(_=>!n.has(_.filename));const M=v.filter(_=>_.type==="doc").map(_=>_.file);return t.filter(_=>M.includes(_.filename))},[f,v,t,n]),w=M=>h(_=>[..._,M]),S=()=>h(M=>M.slice(0,-1)),N=f.length>1?f[f.length-2].title:"Shelf",j=f.length>0?f[f.length-1].title:"Documents";return l.jsxs("div",{className:"shelf-wrapper",children:[l.jsxs("div",{className:"shelf-spines",ref:o,children:[f.length>0&&l.jsxs("button",{className:"shelf-back",onClick:S,title:`Back to ${N}`,children:[l.jsx("span",{className:"shelf-back-arrow",children:"←"}),l.jsx("span",{className:"shelf-back-label",children:N})]}),f.length===0&&l.jsxs(l.Fragment,{children:[e.map(M=>l.jsxs("div",{className:"shelf-section-spine",onClick:()=>w({type:"workspace",key:M.filename,title:M.title,wsFilename:M.filename}),title:M.title,children:[l.jsx("span",{className:"shelf-section-title",children:M.title}),l.jsx("span",{className:"shelf-section-count",children:M.docCount})]},M.filename)),l.jsx("button",{className:"shelf-add",onClick:i.handleCreateWorkspace,title:"New workspace",children:"+"})]}),f.length>0&&x.map(M=>l.jsxs("div",{className:"shelf-section-spine shelf-section-container",onClick:()=>w({type:"container",key:M.id,title:M.name,wsFilename:f[f.length-1].wsFilename}),title:M.name,children:[l.jsx("span",{className:"shelf-section-title",children:M.name}),l.jsx("span",{className:"shelf-section-count",children:g(M.items)})]},M.id))]}),l.jsxs("div",{className:"shelf-docs",children:[l.jsx("div",{className:"shelf-docs-header",children:j}),l.jsxs("div",{className:"shelf-docs-list",children:[k.map(M=>l.jsxs("div",{className:`shelf-doc-item ${M.isActive?"active":""}`,onClick:()=>s(M.filename),children:[l.jsxs("div",{className:"shelf-doc-title",children:[l.jsx("span",{children:M.title}),r.filenames.includes(M.filename)&&l.jsx("span",{className:"shelf-pending-dot"})]}),l.jsxs("div",{className:"shelf-doc-meta",children:[M.wordCount.toLocaleString()," words · ",ba(M.lastModified)]})]},M.filename)),k.length===0&&l.jsx("div",{className:"shelf-docs-empty",children:"No documents"})]})]})]})}async function Ik(t,e={}){var s,i;const r=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:t,arguments:e})})).json();if((i=(s=r==null?void 0:r.content)==null?void 0:s[0])!=null&&i.text)try{return JSON.parse(r.content[0].text)}catch{return r.content[0].text}return r}function HT({filename:t,title:e,isActive:n,onSwitchDocument:r,onClose:s}){const[i,o]=y.useState("loading"),[c,d]=y.useState([]),[f,h]=y.useState(null),[m,g]=y.useState(null),[v,x]=y.useState(null);y.useEffect(()=>{Ik("list_blog_sites").then(S=>{if(S.error){g(S.error),o("error");return}const N=S.sites||[];d(N),N.length===0?o("pick"):N.length===1?(h(N[0].id),o("confirm")):o("pick")}).catch(S=>{g((S==null?void 0:S.message)||"Failed to load blog sites"),o("error")})},[]);const k=c.find(S=>S.id===f)||null,w=async()=>{if(k){o("posting"),g(null),n||(r(t),await new Promise(S=>setTimeout(S,350)));try{const S=await Ik("post_to_blog",{site_id:k.id});if(S!=null&&S.error){g(S.error),o("error");return}const N=S.commit?`https://github.com/${k.owner}/${k.repo}/commit/${S.commit}`:void 0;x({message:S.message,file:S.file,commit:S.commit,images_committed:S.images_committed,liveUrl:S.live_url,commitUrl:N,warning:S.warning}),o("done")}catch(S){g((S==null?void 0:S.message)||"Publish failed"),o("error")}}};return l.jsx("div",{className:"post-blog-overlay",onClick:()=>{i!=="posting"&&s()},children:l.jsxs("div",{className:"post-blog-modal",onClick:S=>S.stopPropagation(),children:[l.jsxs("div",{className:"post-blog-modal-header",children:[l.jsx("h3",{children:"Post to Blog"}),l.jsx("button",{className:"post-blog-modal-close",onClick:s,disabled:i==="posting",children:"×"})]}),l.jsx("div",{className:"post-blog-modal-doc",children:e}),i==="loading"&&l.jsx("div",{className:"post-blog-modal-loading",children:"Loading blog sites…"}),i==="pick"&&c.length===0&&l.jsxs("div",{className:"post-blog-modal-empty",children:["No blog sites registered. Add one in ",l.jsx("strong",{children:"Settings → Plugins → GitHub"})," first.",l.jsx("button",{className:"post-blog-modal-done",onClick:s,children:"Close"})]}),i==="pick"&&c.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"post-blog-modal-label",children:"Choose a destination"}),l.jsx("div",{className:"post-blog-modal-sites",children:c.map(S=>l.jsxs("button",{className:`post-blog-modal-site${f===S.id?" post-blog-modal-site--selected":""}`,onClick:()=>{h(S.id),o("confirm")},children:[l.jsx("div",{className:"post-blog-modal-site-label",children:S.label}),l.jsxs("div",{className:"post-blog-modal-site-repo",children:[S.owner,"/",S.repo,"@",S.branch]})]},S.id))})]}),i==="confirm"&&k&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"post-blog-modal-confirm",children:["Publish to ",l.jsxs("strong",{children:[k.owner,"/",k.repo,"@",k.branch]}),"?",l.jsxs("div",{className:"post-blog-modal-target-dir",children:["→ ",k.content_dir]})]}),l.jsxs("div",{className:"post-blog-modal-actions",children:[l.jsx("button",{className:"post-blog-modal-btn post-blog-modal-btn--primary",onClick:w,children:"Publish now"}),c.length>1&&l.jsx("button",{className:"post-blog-modal-btn",onClick:()=>o("pick"),children:"Back"}),l.jsx("button",{className:"post-blog-modal-btn",onClick:s,children:"Cancel"})]})]}),i==="posting"&&l.jsx("div",{className:"post-blog-modal-loading",children:"Publishing…"}),i==="done"&&v&&l.jsxs("div",{className:"post-blog-modal-result post-blog-modal-result--success",children:[l.jsx("div",{children:v.message||"Published"}),v.file&&l.jsx("div",{className:"post-blog-modal-meta",children:v.file}),typeof v.images_committed=="number"&&v.images_committed>0&&l.jsxs("div",{className:"post-blog-modal-meta",children:[v.images_committed," image",v.images_committed===1?"":"s"," committed"]}),v.warning&&l.jsx("div",{className:"post-blog-modal-warning",children:v.warning}),l.jsxs("div",{className:"post-blog-modal-actions",children:[v.liveUrl?l.jsx("button",{className:"post-blog-modal-btn post-blog-modal-btn--primary",onClick:()=>window.open(v.liveUrl,"_blank"),children:"View Post"}):v.commitUrl?l.jsx("button",{className:"post-blog-modal-btn post-blog-modal-btn--primary",onClick:()=>window.open(v.commitUrl,"_blank"),children:"View commit"}):null,l.jsx("button",{className:"post-blog-modal-btn",onClick:s,children:"Done"})]}),v.liveUrl&&v.commitUrl&&l.jsx("button",{className:"post-blog-modal-commit-link",onClick:()=>window.open(v.commitUrl,"_blank"),children:"View commit"})]}),i==="error"&&l.jsxs("div",{className:"post-blog-modal-result post-blog-modal-result--error",children:[l.jsx("div",{children:m||"Publish failed"}),l.jsx("div",{className:"post-blog-modal-actions",children:l.jsx("button",{className:"post-blog-modal-btn",onClick:s,children:"Close"})})]})]})})}const z$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M20 20H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4l2 2h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2z"}),l.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14",opacity:"0.5"})]}),U$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),l.jsx("polyline",{points:"14 2 14 8 20 8"}),l.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),l.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]}),H$=()=>l.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:l.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"})}),W$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[l.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z",opacity:"0.5"}),l.jsx("path",{d:"M7 15l-4-3.5L7 8",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),V$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[l.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z",opacity:"0.5"}),l.jsx("path",{d:"M3 8V6.5C3 5.67 3.67 5 4.5 5h2C7.33 5 8 5.67 8 6.5V8c0 2-1.5 3-3 3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),q$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[l.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z",opacity:"0.5"}),l.jsx("rect",{x:"2",y:"16",width:"8",height:"7",rx:"1.5",fill:"none",stroke:"currentColor",strokeWidth:"1.5"}),l.jsx("line",{x1:"4",y1:"18.5",x2:"8",y2:"18.5",stroke:"currentColor",strokeWidth:"1",opacity:"0.7"}),l.jsx("line",{x1:"4",y1:"20.5",x2:"7",y2:"20.5",stroke:"currentColor",strokeWidth:"1",opacity:"0.7"})]}),K$=()=>l.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:l.jsx("path",{d:"M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 0 1-2.063-2.065 2.064 2.064 0 1 1 2.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"})}),G$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),l.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),J$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("circle",{cx:"12",cy:"12",r:"10"}),l.jsx("path",{d:"M2 12h20"}),l.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]}),Lk=()=>l.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"20 6 9 17 4 12"})});function Y$({type:t}){switch(t){case"tweet":return l.jsx(H$,{});case"reply":return l.jsx(W$,{});case"quote":return l.jsx(V$,{});case"article":return l.jsx(q$,{});case"linkedin":return l.jsx(K$,{});case"newsletter":return l.jsx(G$,{});case"blog":return l.jsx(J$,{});default:return l.jsx(U$,{})}}function Fu(t){let e=0;for(const n of t)n.type==="doc"?e++:n.type==="container"&&(e+=Fu(n.items));return e}function tv(t,e){for(const n of t){if(n.type==="doc"&&n.file===e)return[];if(n.type==="container"){const r=tv(n.items,e);if(r)return[n.id,...r]}}return null}function Eu(t){const e=new Set;return Ll(t,e),[...e]}function WT(t,e,n=0){for(const r of t)if(r.type==="container"){if(r.id===e)return n;const s=WT(r.items,e,n+1);if(s>=0)return s}return-1}function X$(t,e){if(!e)return 12;for(const n of t){if(!n.workspace)continue;const r=WT(n.workspace.root,e);if(r>=0)return 12+(r+1)*16}return 12}function Q$({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,onCreateDocument:i,actions:o,scrollRef:c,writingTitle:d,writingTarget:f,pendingWriteFilenames:h,searchQuery:m,searchResults:g,onSearchChange:v}){var nn,at,Ht;const x=T=>!!h&&h.has(T),[k,w]=y.useState(()=>{try{const T=localStorage.getItem("ow-files-collapsed");return T?new Set(JSON.parse(T)):new Set}catch{return new Set}}),{draggedItem:S,dropIndicator:N,handlePointerDown:j,dropClass:M,isDragging:_,isContainerDropTarget:R}=BT({docs:t,workspaces:e,assignedFiles:n,scrollRef:c,setCollapsedSections:w}),L=T=>!N||N.itemId!==T||N.position==="inside"?void 0:{"--drop-indent":`${X$(e,N.containerId)}px`},{variantsByMaster:$,variantFilenames:B}=y.useMemo(()=>{const T=new Map,W=new Set;for(const ae of t)if(ae.masterDocId){const I=T.get(ae.masterDocId)||[];I.push(ae),T.set(ae.masterDocId,I),W.add(ae.filename)}return{variantsByMaster:T,variantFilenames:W}},[t]),[U,X]=y.useState(null),[z,ee]=y.useState(null),[P,F]=y.useState(new Set),[G,ie]=y.useState(null),[K,ce]=y.useState([]),[J,A]=y.useState(!1),[D,q]=y.useState(null),[le,ye]=y.useState(null),[oe,Se]=y.useState(null),[Ee,Le]=y.useState(null),[Ie,Ve]=y.useState(null),[Te,qe]=y.useState(null),[pt,ut]=y.useState(new Set);y.useEffect(()=>{ut(new Set)},[r]);const be=y.useCallback(()=>{fetch("/api/plugins").then(T=>T.json()).then(T=>{const W=[];let ae=!1;for(const I of T.plugins||[]){const V=I.displayName||void 0;for(const re of I.sidebarMenuItems||[])W.push({...re,pluginDisplayName:V});I.name==="@openwriter/plugin-publish"&&I.enabled&&(ae=!0)}ce(W),A(ae)}).catch(()=>{})},[]);y.useEffect(()=>{be()},[be]),y.useEffect(()=>{const T=()=>be();return window.addEventListener("ow-plugins-changed",T),()=>window.removeEventListener("ow-plugins-changed",T)},[be]);const ht=y.useCallback((T,W)=>{if(T.preventDefault(),T.stopPropagation(),P.has(W.filename)&&P.size>1){ee({x:T.clientX,y:T.clientY,filename:W.filename,title:W.title,bulkCount:P.size});return}P.size>0&&!P.has(W.filename)&&F(new Set),ee({x:T.clientX,y:T.clientY,filename:W.filename,title:W.title,docId:W.docId,lastSent:W.lastSent,postedUrl:W.postedUrl,isNewsletter:W.isNewsletter,contentType:W.contentType,sortRequest:W.sortRequest})},[P]),xt=y.useCallback(T=>{fetch("/api/documents/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:T})}).catch(()=>{})},[]),St=y.useCallback((T,W,ae,I,V)=>{if(!$T(W,t.find(re=>re.filename===ae))){if(W.promptForFocus&&V===void 0){q({action:T,label:W.label,filename:ae,title:I});return}fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:T,filename:ae,title:I,instructions:V||"",label:W.label})}).catch(()=>{})}},[t]),At=y.useCallback((T,W,ae)=>{for(const I of Eu(ae)){const V=t.find(re=>re.filename===I);fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:T,filename:I,title:(V==null?void 0:V.title)||I,instructions:"",label:W.label})}).catch(()=>{})}},[t]),Ye=y.useCallback((T,W)=>{ut(ae=>{const I=new Set(ae);for(const V of T)I.add(V);return I}),fetch("/api/documents/batch-resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filenames:T,action:W})}).catch(()=>{})},[]),ct=T=>{w(W=>{const ae=new Set(W);return ae.has(T)?ae.delete(T):ae.add(T),localStorage.setItem("ow-files-collapsed",JSON.stringify([...ae])),ae})},Fe=(T,W,ae,I)=>{X({type:T,key:W,value:ae,wsFilename:I})},Y=()=>{if(!U)return;const{type:T,key:W,value:ae,wsFilename:I}=U;T==="doc"?o.handleRename(W,"",ae):T==="workspace"?o.handleRenameWorkspace(W,ae):T==="container"&&I&&o.handleRenameContainer(I,W,ae),X(null)},ge=t.find(T=>T.isActive),ne=y.useMemo(()=>{var I;const T=t.find(V=>V.isActive);if(!T)return null;const W=T.masterDocId?t.find(V=>V.docId===T.masterDocId):void 0,ae=(W==null?void 0:W.filename)??T.filename;for(const V of e){const re=tv(((I=V.workspace)==null?void 0:I.root)||[],ae);if(re)return{wsFilename:V.filename,containerKeys:new Set(re.map(Q=>`container-${Q}`)),masterDocId:(W==null?void 0:W.docId)??null}}return{wsFilename:null,containerKeys:new Set,masterDocId:(W==null?void 0:W.docId)??null}},[t,e]),he=y.useRef(e);he.current=e;const me=y.useCallback(T=>{var W;for(const ae of he.current){const I=tv(((W=ae.workspace)==null?void 0:W.root)||[],T);if(I){w(V=>{const re=[ae.filename,...I.map(ue=>`container-${ue}`)];if(re.every(ue=>!V.has(ue)))return V;const Q=new Set(V);for(const ue of re)Q.delete(ue);return localStorage.setItem("ow-files-collapsed",JSON.stringify([...Q])),Q});break}}},[]);Wl(c,t,e.length,me);const ze=y.useMemo(()=>t.filter(T=>!n.has(T.filename)&&!B.has(T.filename)&&!x(T.filename)),[t,n,B,h]),Ae=y.useMemo(()=>{var I;const T=[],W=V=>{T.push(V.filename);const re=V.docId?$.get(V.docId):void 0,Q=V.docId&&!k.has(`variants-${V.docId}`);if(re&&Q)for(const ue of re)T.push(ue.filename)},ae=V=>{for(const re of V)if(re.type==="doc"){const Q=t.find(ue=>ue.filename===re.file);Q&&!B.has(Q.filename)&&W(Q)}else k.has(`container-${re.id}`)||ae(re.items)};k.has("docs")||ze.forEach(W);for(const V of e)k.has(V.filename)||ae(((I=V.workspace)==null?void 0:I.root)||[]);return T},[t,e,ze,B,$,k]),Xe=y.useCallback(()=>{F(new Set)},[]),Qe=y.useCallback((T,W)=>{if(S)return;const ae=T.shiftKey,I=T.ctrlKey||T.metaKey;if(ae){const re=G||(ge==null?void 0:ge.filename)||W,Q=Ae.indexOf(re),ue=Ae.indexOf(W);if(Q<0||ue<0){F(new Set([W])),ie(W);return}const[ve,Re]=Q<ue?[Q,ue]:[ue,Q];F(new Set(Ae.slice(ve,Re+1)));return}if(I){F(re=>{const Q=new Set(re);return Q.has(W)?Q.delete(W):Q.add(W),Q}),ie(W);return}F(new Set),ie(W);const V=t.find(re=>re.filename===W);V&&!V.isActive&&s(W)},[S,G,ge==null?void 0:ge.filename,Ae,s,t]);y.useEffect(()=>{if(P.size===0)return;const T=W=>{W.key==="Escape"&&Xe()};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[P.size,Xe]);const tt=y.useCallback(()=>{for(const T of P)o.handleDelete(T);F(new Set),ie(null)},[P,o]),We=y.useCallback(T=>{T.length!==0&&fetch("/api/documents/sort-request",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filenames:T})}).then(()=>o.fetchDocs()).catch(()=>{})},[o]),Ue=y.useCallback(T=>{fetch("/api/documents/sort-reject",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:T})}).then(()=>o.fetchDocs()).catch(()=>{})},[o]),st=y.useCallback(T=>{fetch("/api/documents/sort-accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:T})}).then(()=>o.fetchDocs()).catch(()=>{})},[o]);if(g!==null)return l.jsx(rf,{results:g,query:m,onSwitchDocument:s,actions:o});const mt=T=>l.jsx("input",{className:"sidebar-rename-input",value:U.value,onChange:W=>X(ae=>ae?{...ae,value:W.target.value}:null),onBlur:T,onKeyDown:W=>{W.key==="Enter"&&T(),W.key==="Escape"&&X(null)},autoFocus:!0,onClick:W=>W.stopPropagation()}),Nt=(T,W,ae,I,V,re=!1)=>l.jsxs("div",{className:`files-row${T.isActive?" active":""}${T.docId&&(ne==null?void 0:ne.masterDocId)===T.docId&&k.has(`variants-${T.docId}`)?" active-within":""}${P.has(T.filename)?" selected":""} ${_(T.filename)?"dragging":""} ${M(T.filename)}${T.masterDocId?" is-variant":""}`,style:{paddingLeft:W,...L(T.filename)},"data-drag-id":T.filename,"data-drag-type":"doc","data-drag-ws":ae||"__docs__","data-drag-container":I||"",onPointerDown:Q=>j(Q,{type:"doc",file:T.filename,sourceWs:ae||null},T.title),onClick:Q=>Qe(Q,T.filename),onDoubleClick:()=>Fe("doc",T.filename,T.title),onContextMenu:Q=>ht(Q,T),children:[l.jsx("span",{className:"files-row-icon",children:l.jsx(Y$,{type:T.contentType})}),(U==null?void 0:U.type)==="doc"&&U.key===T.filename?mt(Y):l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"files-row-label",children:T.title}),T.variantType&&l.jsx("span",{className:"files-badge-variant",children:T.variantType}),(T.autoAccept===!0||T.autoAccept!==!1&&re)&&l.jsx("span",{className:"sidebar-auto-accept-dot",title:T.autoAccept===!0?"Auto-accept on":"Auto-accept inherited"}),r.filenames.includes(T.filename)&&!pt.has(T.filename)&&l.jsx("span",{className:"files-badge-pending"}),T.sortRequest&&(T.sortRequest.proposal?l.jsx("span",{className:"files-badge-sort-proposal",title:"Sort proposal ready — right-click to review"}):l.jsx("span",{className:"files-badge-sort-pending",title:"Sort requested"})),o.getDocTags(T.filename).includes("✓")&&l.jsx("span",{className:"files-badge-approved",children:l.jsx(Lk,{})}),T.lastSent&&l.jsx("span",{className:"files-badge-sent",children:l.jsx(Lk,{})}),V&&l.jsx("span",{className:`files-row-chevron${k.has(`variants-${T.docId}`)?" collapsed":""}`,onClick:Q=>{Q.stopPropagation(),ct(`variants-${T.docId}`)},children:l.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"6 9 12 15 18 9"})})})]})]},T.filename),Mt=(T,W,ae,I,V=!1)=>{const re=T.docId?$.get(T.docId):void 0,Q=!!(re&&re.length>0),ue=d&&(f==null?void 0:f.parentDocId)&&f.parentDocId===T.docId,ve=Q||ue,Re=!k.has(`variants-${T.docId}`);return ve?l.jsxs("div",{className:"files-variant-group",children:[Nt(T,W,ae,I,Q,V),Re&&(re==null?void 0:re.map(xe=>Nt(xe,W+16,ae,I,!1,V))),ue&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:W+16},children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:d})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]})]},`vg-${T.filename}`):Nt(T,W,ae,I,!1,V)},Jt=(T,W,ae,I,V=!1)=>{const re=12+W*16;if(T.type==="doc"){const Et=t.find(dn=>dn.filename===T.file);return!Et||B.has(Et.filename)?null:Mt(Et,re,ae,I,V)}const Q=T,ue=`container-${Q.id}`,ve=k.has(ue),Re=Fu(Q.items),xe=Q.autoAccept===!0,Dt=xe||V;return l.jsxs("div",{className:`${M(Q.id)} ${R(Q.id)?"files-drop-inside":""}`,children:[l.jsxs("div",{className:`files-row is-container${ve&&(ne!=null&&ne.containerKeys.has(ue))?" active-within":""} ${_(Q.id)?"dragging":""} ${M(Q.id)}`,style:{paddingLeft:re,...L(Q.id)},"data-drag-id":Q.id,"data-drag-type":"container-header","data-drag-ws":ae,"data-drag-parent":I||"","data-section-key":ue,onPointerDown:Et=>j(Et,{type:"container",id:Q.id,sourceWs:ae},Q.name),onClick:()=>!S&&ct(ue),onDoubleClick:Et=>{Et.stopPropagation(),Fe("container",Q.id,Q.name,ae)},onContextMenu:Et=>{Et.preventDefault(),Et.stopPropagation(),qe({x:Et.clientX,y:Et.clientY,type:"container",wsFilename:ae,containerId:Q.id,title:Q.name,nodes:Q.items,autoAccept:xe})},children:[l.jsx("span",{className:"files-row-icon",children:l.jsx(z$,{})}),(U==null?void 0:U.type)==="container"&&U.key===Q.id?mt(Y):l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"files-row-label",children:Q.name}),Dt&&l.jsx("span",{className:"sidebar-auto-accept-dot",title:xe?"Auto-accept on for this container":"Auto-accept inherited from workspace"}),l.jsx("span",{className:"files-row-count",children:Re})]})]}),l.jsxs("div",{className:`files-children${ve?" collapsed":""}`,"data-drop-ws":ae,"data-drop-container":Q.id,children:[d&&!(f!=null&&f.parentDocId)&&(f==null?void 0:f.wsFilename)===ae&&f.containerId===Q.id&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:12+(W+1)*16},children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:d})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),Q.items.filter(Et=>Et.type!=="doc"||!x(Et.file)).map(Et=>Jt(Et,W+1,ae,Q.id,Dt))]})]},Q.id)};return l.jsxs("div",{className:"files-scroll",ref:c,children:[l.jsxs("div",{className:"files-section",children:[l.jsxs("div",{className:`files-row is-section${k.has("docs")&&ne!==null&&ne.wsFilename===null?" active-within":""}`,"data-section-key":"docs",onClick:()=>ct("docs"),children:[l.jsx("span",{className:`files-row-chevron leading${k.has("docs")?" collapsed":""}`,children:l.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"6 9 12 15 18 9"})})}),l.jsx("span",{className:"files-row-label",children:"Documents"}),l.jsx("button",{className:"files-section-btn",onClick:T=>{T.stopPropagation(),Ve({anchor:T.target.getBoundingClientRect()})},title:"New document",children:"+"})]}),l.jsxs("div",{className:`files-section-list files-children${k.has("docs")?" collapsed":""}`,"data-drop-ws":"__docs__",children:[d&&!(f!=null&&f.parentDocId)&&(!f||!e.some(T=>T.filename===(f==null?void 0:f.wsFilename)))&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:28},children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:d})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),ze.map(T=>Mt(T,28))]})]}),e.map(T=>{var re,Q,ue;const W=((re=T.workspace)==null?void 0:re.root)||[],ae=k.has(T.filename),I=Fu(W),V=((Q=T.workspace)==null?void 0:Q.autoAccept)===!0||T.autoAccept===!0;return l.jsxs("div",{className:`files-section ${_(T.filename)?"dragging":""} ${(N==null?void 0:N.itemId)===T.filename?N.position==="before"?"files-ws-drop-before":"files-ws-drop-after":""}`,children:[l.jsx("div",{className:`files-row is-section${ae&&(ne==null?void 0:ne.wsFilename)===T.filename?" active-within":""}${(N==null?void 0:N.itemId)==="__section__"&&N.wsFilename===T.filename&&N.position==="inside"?" files-ws-drop-target":""}`,"data-section-key":T.filename,"data-ws-drag":T.filename,onPointerDown:ve=>j(ve,{type:"workspace",filename:T.filename},T.title),onClick:()=>!S&&ct(T.filename),onDoubleClick:ve=>{ve.stopPropagation(),Fe("workspace",T.filename,T.title)},onContextMenu:ve=>{var Re;ve.preventDefault(),ve.stopPropagation(),qe({x:ve.clientX,y:ve.clientY,type:"workspace",wsFilename:T.filename,title:T.title,nodes:W,autoAccept:((Re=T.workspace)==null?void 0:Re.autoAccept)===!0||T.autoAccept===!0})},children:(U==null?void 0:U.type)==="workspace"&&U.key===T.filename?l.jsxs(l.Fragment,{children:[l.jsx("span",{className:`files-row-chevron leading${ae?" collapsed":""}`,children:l.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"6 9 12 15 18 9"})})}),mt(Y)]}):l.jsxs(l.Fragment,{children:[l.jsx("span",{className:`files-row-chevron leading${ae?" collapsed":""}`,children:l.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"6 9 12 15 18 9"})})}),l.jsx("span",{className:"files-row-label",children:T.title}),(((ue=T.workspace)==null?void 0:ue.autoAccept)===!0||T.autoAccept===!0)&&l.jsx("span",{className:"sidebar-auto-accept-dot",title:"Auto-accept on for this workspace"}),l.jsx("span",{className:"files-row-count",children:I}),l.jsxs("div",{className:"files-section-actions",children:[l.jsx("button",{className:"files-section-btn",onClick:ve=>{ve.stopPropagation(),Ve({anchor:ve.target.getBoundingClientRect(),wsFilename:T.filename,containerId:null})},title:"New document",children:"+"}),l.jsx("button",{className:"files-section-btn",onClick:ve=>{ve.stopPropagation(),o.handleCreateContainer(T.filename,null)},title:"New container",children:"☐"})]})]})}),l.jsxs("div",{className:`files-section-list files-children${ae?" collapsed":""}`,"data-drop-ws":T.filename,children:[d&&!(f!=null&&f.parentDocId)&&(f==null?void 0:f.wsFilename)===T.filename&&f.containerId===null&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:28},children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:d})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),W.filter(ve=>ve.type!=="doc"||!x(ve.file)).map(ve=>Jt(ve,1,T.filename,null,V))]})]},T.filename)}),l.jsx("div",{className:"files-new-ws",children:l.jsx("button",{onClick:o.handleCreateWorkspace,children:"+ New Workspace"})}),Te&&l.jsx(Bd,{x:Te.x,y:Te.y,filename:Te.wsFilename,title:Te.title,onClose:()=>qe(null),onDuplicate:()=>{},onRename:()=>{Te.type==="workspace"?Fe("workspace",Te.wsFilename,Te.title):Te.containerId&&Fe("container",Te.containerId,Te.title,Te.wsFilename),qe(null)},onArchive:()=>{},onDelete:()=>{Te.type==="workspace"?o.handleDeleteWorkspace(Te.wsFilename):Te.containerId&&o.handleDeleteContainer(Te.wsFilename,Te.containerId,!1)},folderDocCount:Te.type==="container"?Fu(Te.nodes):0,onDeleteWithDocs:Te.type==="container"&&Te.containerId?()=>{o.handleDeleteContainer(Te.wsFilename,Te.containerId,!0)}:void 0,onPluginAction:(T,W)=>At(T,W,Te.nodes),pluginItems:K.filter(T=>T.folderCapable),folderMode:!0,onNewDoc:T=>{Ve({anchor:T.target.getBoundingClientRect(),wsFilename:Te.wsFilename,containerId:Te.type==="container"?Te.containerId:null}),qe(null)},onNewContainer:()=>{o.handleCreateContainer(Te.wsFilename,Te.type==="container"?Te.containerId:null),qe(null)},onAcceptAll:()=>{const T=Eu(Te.nodes);T.length&&Ye(T,"accept"),qe(null)},onRejectAll:()=>{const T=Eu(Te.nodes);T.length&&Ye(T,"reject"),qe(null)},folderAutoAccept:Te.autoAccept,folderAutoAcceptLabel:Te.type==="workspace"?"for workspace":"for container",onToggleFolderAutoAccept:()=>{fetch("/api/auto-accept/inherit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wsFile:Te.wsFilename,...Te.type==="container"?{containerId:Te.containerId}:{},enabled:!Te.autoAccept})}).catch(()=>{})},onRequestSortAll:()=>{const T=Eu(Te.nodes);T.length&&We(T)}}),z&&l.jsx(Bd,{x:z.x,y:z.y,filename:z.filename,title:z.title,bulkCount:z.bulkCount,onBulkDelete:tt,onBulkRequestSort:z.bulkCount?()=>We([...P]):void 0,onClose:()=>ee(null),onDuplicate:()=>xt(z.filename),onCreateVariant:z.docId?T=>{fetch("/api/documents/variant",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:z.filename,masterDocId:z.docId,variantType:T})}).catch(()=>{})}:void 0,onRename:()=>{Fe("doc",z.filename,z.title),ee(null)},onArchive:()=>o.handleArchive(z.filename),onDelete:()=>o.handleDelete(z.filename),onPluginAction:(T,W)=>St(T,W,z.filename,z.title),pluginItems:K,onSchedulePost:J?()=>{ye({filename:z.filename,title:z.title}),ee(null)}:void 0,onPostNow:z.contentType==="blog"?()=>{const T=(ge==null?void 0:ge.filename)===z.filename;Se({filename:z.filename,title:z.title,isActive:T}),ee(null)}:void 0,isAlreadyPublished:z.contentType==="blog"&&!!z.postedUrl,onViewAnalytics:z.docId&&z.lastSent&&(z.postedUrl||z.isNewsletter)?()=>{z.isNewsletter?Le({docId:z.docId,title:z.title}):z.postedUrl&&window.open(z.postedUrl,"_blank"),ee(null)}:void 0,viewAnalyticsLabel:z.isNewsletter?"View Analytics":z.contentType==="blog"&&z.postedUrl?"View Post":z.postedUrl?"View on X":"View Analytics",isApproved:o.getDocTags(z.filename).includes("✓"),onToggleApprove:()=>{o.getDocTags(z.filename).includes("✓")?o.handleRemoveTag(z.filename,"✓"):(o.handleAddTag(z.filename,"✓"),setTimeout(()=>window.dispatchEvent(new CustomEvent("ow-accept-all")),50))},isAutoAccept:(()=>{var W;const T=(W=t.find(ae=>ae.filename===z.filename))==null?void 0:W.autoAccept;return T===!0?!0:T===!1?!1:Pd(e,z.filename)})(),onToggleAutoAccept:()=>{var ae;const T=(ae=t.find(I=>I.filename===z.filename))==null?void 0:ae.autoAccept,W=T===!0?!0:T===!1?!1:Pd(e,z.filename);fetch("/api/auto-accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:z.filename,enabled:!W})}).then(()=>o.fetchDocs()).catch(()=>{})},isAlreadySent:!!z.lastSent,onMarkSent:()=>{const T=z.filename;o.getDocTags(T).includes("✓")&&o.handleRemoveTag(T,"✓"),s(T),setTimeout(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualPost:{postedAt:new Date().toISOString()}})}).then(()=>o.fetchDocs()).catch(()=>{})},100),ee(null)},sortState:z.bulkCount?void 0:(nn=z.sortRequest)!=null&&nn.proposal?"proposal":z.sortRequest?"pending":"none",sortProposalLabel:(()=>{var re;const T=(re=z.sortRequest)==null?void 0:re.proposal;if(!T)return;const W=e.find(Q=>Q.filename===T.wsFilename),ae=(W==null?void 0:W.title)||T.wsFilename;if(!T.containerId)return ae;const I=Q=>{for(const ue of Q){if(ue.type==="container"&&ue.id===T.containerId)return ue.name;if(ue.type==="container"){const ve=I(ue.items);if(ve)return ve}}return null},V=W!=null&&W.workspace?I(W.workspace.root):null;return V?`${ae} / ${V}`:ae})(),sortProposalReasoning:(Ht=(at=z.sortRequest)==null?void 0:at.proposal)==null?void 0:Ht.reasoning,onRequestSort:z.bulkCount?void 0:()=>We([z.filename]),onCancelSort:()=>Ue(z.filename),onAcceptSortProposal:()=>st(z.filename),onRejectSortProposal:()=>Ue(z.filename)}),D&&l.jsx(FT,{actionLabel:D.label,docTitle:D.title,onClose:()=>q(null),onConfirm:T=>{const W=K.find(ae=>ae.action===D.action);W&&St(D.action,W,D.filename,D.title,T),q(null)}}),Ee&&l.jsx(zT,{docId:Ee.docId,title:Ee.title,onClose:()=>Le(null)}),le&&l.jsx(Vl,{filename:le.filename,title:le.title,onClose:()=>ye(null)}),oe&&l.jsx(HT,{filename:oe.filename,title:oe.title,isActive:oe.isActive,onSwitchDocument:s,onClose:()=>Se(null)}),Ie&&l.jsx(UT,{anchorRect:Ie.anchor,onClose:()=>Ve(null),onSelect:T=>{Ve(null),Ie.wsFilename?o.handleCreateInWorkspace(Ie.wsFilename,Ie.containerId??null,T):T?fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:T})}).catch(()=>{}):i()}})]})}const Z$=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],e8=[{value:"any",label:"Any"},{value:"content_type",label:"Content Type"},{value:"connection",label:"Connection"}],VT=["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Anchorage","Pacific/Honolulu","America/Phoenix","America/Toronto","America/Vancouver","America/Sao_Paulo","America/Mexico_City","Europe/London","Europe/Paris","Europe/Berlin","Europe/Amsterdam","Europe/Rome","Europe/Madrid","Europe/Moscow","Asia/Tokyo","Asia/Shanghai","Asia/Kolkata","Asia/Dubai","Asia/Singapore","Asia/Seoul","Australia/Sydney","Australia/Melbourne","Pacific/Auckland"];function Dk(t){var e;try{const n=new Date,i=((e=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"short"}).formatToParts(n).find(c=>c.type==="timeZoneName"))==null?void 0:e.value)||"";return`${t.split("/").pop().replace(/_/g," ")} (${i})`}catch{return t}}function t8(t){if(t.length>0)return t[0].timezone;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;if(VT.includes(e))return e}catch{}return"America/New_York"}function n8({slots:t,onBack:e}){const[n,r]=y.useState(t),[s,i]=y.useState(()=>t8(t)),[o,c]=y.useState(!1),[d,f]=y.useState("09:00"),[h,m]=y.useState(["default"]),[g,v]=y.useState("any"),[x,k]=y.useState(!1),w=y.useRef(null);y.useEffect(()=>{if(!o)return;function _(R){w.current&&!w.current.contains(R.target)&&c(!1)}return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[o]);async function S(_){i(_);const R=[];for(const L of n){const $=await fetch(`/api/scheduler/slots/${L.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({timezone:_})});if($.ok){const B=await $.json();R.push(B.slot)}else R.push(L)}R.length>0&&r(R)}async function N(){const _=await fetch("/api/scheduler/slots",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({time:d,days:h.includes("default")?["default"]:h,filter_type:g,timezone:s})});if(_.ok){const R=await _.json();r(L=>[...L,R.slot]),k(!1),f("09:00"),m(["default"]),v("any")}}async function j(_){(await fetch(`/api/scheduler/slots/${_}`,{method:"DELETE"})).ok&&r(L=>L.filter($=>$.id!==_))}function M(_){m(R=>{if(_==="default")return["default"];const L=R.filter($=>$!=="default");if(L.includes(_)){const $=L.filter(B=>B!==_);return $.length===0?["default"]:$}return[...L,_]})}return l.jsxs("div",{className:"sidebar-schedule",children:[l.jsxs("div",{className:"sidebar-schedule-header",children:[l.jsx("button",{className:"sidebar-schedule-btn",onClick:e,title:"Back",children:l.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"m15 18-6-6 6-6"})})}),l.jsx("h3",{children:"Slot Settings"}),l.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>k(!x),children:x?"Cancel":"+ Add"})]}),l.jsxs("div",{className:"slot-tz",ref:w,children:[l.jsx("label",{className:"slot-tz-label",children:"Timezone"}),l.jsxs("button",{className:"slot-tz-trigger",onClick:()=>c(!o),children:[l.jsx("span",{children:Dk(s)}),l.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:`slot-tz-chevron ${o?"slot-tz-chevron--open":""}`,children:l.jsx("path",{d:"m6 9 6 6 6-6"})})]}),o&&l.jsx("div",{className:"slot-tz-dropdown",children:VT.map(_=>l.jsx("div",{className:`slot-tz-option ${_===s?"active":""}`,onClick:()=>{S(_),c(!1)},children:Dk(_)},_))})]}),x&&l.jsxs("div",{className:"slot-add-form",children:[l.jsxs("div",{className:"slot-add-row",children:[l.jsx("input",{type:"time",className:"slot-input",value:d,onChange:_=>f(_.target.value)}),l.jsx("select",{className:"slot-input",value:g,onChange:_=>v(_.target.value),children:e8.map(_=>l.jsx("option",{value:_.value,children:_.label},_.value))})]}),l.jsxs("div",{className:"slot-add-days",children:[l.jsx("button",{className:`sidebar-schedule-btn slot-day-btn ${h.includes("default")?"sidebar-schedule-btn--active":""}`,onClick:()=>M("default"),children:"Every day"}),Z$.map(_=>l.jsx("button",{className:`sidebar-schedule-btn slot-day-btn ${h.includes(_.toLowerCase())?"sidebar-schedule-btn--active":""}`,onClick:()=>M(_.toLowerCase()),children:_},_))]}),l.jsx("button",{className:"sidebar-schedule-btn sidebar-schedule-btn--active slot-create-btn",onClick:N,children:"Create Slot"})]}),l.jsx("div",{className:"slot-list",children:n.length===0?l.jsxs("div",{className:"schedule-empty",children:[l.jsx("div",{className:"schedule-empty-title",children:"No slots"}),l.jsx("div",{className:"schedule-empty-desc",children:"Create time slots to define your posting schedule."})]}):n.map(_=>l.jsxs("div",{className:"schedule-item slot-item",children:[l.jsx("div",{className:"schedule-item-time slot-item-time",children:r8(_.time)}),l.jsxs("div",{className:"schedule-item-content",children:[l.jsx("div",{className:"schedule-item-text",children:_.days.includes("default")?"Every day":_.days.join(", ")}),l.jsxs("div",{className:"schedule-item-meta",children:[l.jsxs("span",{children:["Filter: ",_.filter_type]}),_.filter_value&&l.jsxs("span",{children:["(",_.filter_value,")"]})]})]}),l.jsx("button",{className:"schedule-item-action schedule-item-action--danger slot-delete-btn",onClick:()=>j(_.id),title:"Delete slot",children:"×"})]},_.id))})]})}function r8(t){const[e,n]=t.split(":").map(Number),r=e>=12?"PM":"AM";return`${e%12||12}:${String(n).padStart(2,"0")} ${r}`}function s8({onBack:t}){const[e,n]=y.useState([]),[r,s]=y.useState([]),[i,o]=y.useState(null),[c,d]=y.useState(!1),[f,h]=y.useState(!0),m=y.useCallback(async()=>{try{const[S,N]=await Promise.all([fetch("/api/scheduler/autoplugs/goals"),fetch("/api/scheduler/autoplugs/tracking")]);if(S.ok){const j=await S.json();n(j.goals||[])}if(N.ok){const j=await N.json();s(j.tracking||[])}}catch{}h(!1)},[]);y.useEffect(()=>{m()},[m]);const g=async S=>{(await fetch(`/api/scheduler/autoplugs/goals/${S.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!S.enabled})})).ok&&n(j=>j.map(M=>M.id===S.id?{...M,enabled:!M.enabled}:M))},v=async S=>{(await fetch(`/api/scheduler/autoplugs/goals/${S}`,{method:"DELETE"})).ok&&(n(j=>j.filter(M=>M.id!==S)),o(null))},x=async S=>{(await fetch(`/api/scheduler/autoplugs/tracking/${S}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({skipped:!0})})).ok&&s(j=>j.map(M=>M.id===S?{...M,skipped:!0}:M))},k=e.reduce((S,N)=>N.rule&&N.enabled?Math.min(S,N.rule.threshold):S,1/0),w=k===1/0?50:k;return l.jsxs("div",{className:"sidebar-schedule",children:[l.jsxs("div",{className:"sidebar-schedule-header",children:[l.jsx("button",{className:"sidebar-schedule-back",onClick:t,title:"Back",children:l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"m15 18-6-6 6-6"})})}),l.jsx("h3",{children:"Autoplugs"}),l.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>d(!c),children:c?"Cancel":"+ Add"})]}),c&&l.jsx(o8,{onCreated:S=>{n(N=>[...N,S]),d(!1)}}),f?null:l.jsxs(l.Fragment,{children:[e.length===0?l.jsxs("div",{className:"schedule-empty",children:[l.jsx("div",{className:"schedule-empty-title",children:"No goals"}),l.jsx("div",{className:"schedule-empty-desc",children:"Create a goal to start autoplugging your tweets."})]}):e.map(S=>l.jsxs("div",{children:[l.jsxs("div",{className:"schedule-item",onClick:()=>o(i===S.id?null:S.id),children:[l.jsxs("div",{className:"schedule-item-content",children:[l.jsx("div",{className:"schedule-item-text",children:S.name}),l.jsx("div",{className:"schedule-item-meta",children:i8(S).map((N,j)=>l.jsx("span",{children:N},j))})]}),l.jsx("button",{className:`autoplug-toggle ${S.enabled?"autoplug-toggle--on":"autoplug-toggle--off"}`,onClick:N=>{N.stopPropagation(),g(S)},title:S.enabled?"Disable":"Enable"})]}),i===S.id&&l.jsx(a8,{goal:S,onSaved:N=>{n(j=>j.map(M=>M.id===N.id?N:M))},onDeleted:()=>v(S.id),onRefresh:m})]},S.id)),l.jsx("div",{className:"schedule-day-header",children:"Tracking"}),r.length===0?l.jsxs("div",{className:"schedule-empty",children:[l.jsx("div",{className:"schedule-empty-title",children:"No tracked tweets"}),l.jsx("div",{className:"schedule-empty-desc",children:"Tweets will appear here after posting."})]}):r.map(S=>l.jsxs("div",{className:"schedule-item",children:[l.jsxs("div",{className:"schedule-item-content",children:[l.jsx("div",{className:"schedule-item-text",children:S.original_text||`Tweet ${S.tweet_id}`}),l.jsxs("div",{className:"schedule-item-meta",children:[l.jsx("span",{children:l8(S.posted_at)}),l.jsxs("span",{children:[S.likes," likes"]}),l.jsxs("span",{children:[S.retweets," RTs"]}),S.views>0&&l.jsxs("span",{children:[c8(S.views)," views"]})]}),S.triggered?l.jsxs("div",{className:"autoplug-tracking-triggered",children:[l.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Autoplugged ",S.goal_name?`→ ${S.goal_name}`:""]}):S.skipped?l.jsx("div",{className:"autoplug-tracking-skipped",children:"Skipped"}):l.jsx("div",{className:"autoplug-tracking-bar",children:l.jsx("div",{className:"autoplug-tracking-bar-fill",style:{width:`${Math.min(100,S.likes/w*100)}%`}})})]}),!S.triggered&&!S.skipped&&l.jsx("button",{className:"autoplug-tracking-skip",onClick:()=>x(S.id),title:"Skip autoplug for this tweet",children:"×"})]},S.id))]})]})}function i8(t){const e=[];return t.rule&&(e.push(`${t.rule.threshold}+ ${t.rule.metric}`),e.push(t.rule.mode.charAt(0).toUpperCase()+t.rule.mode.slice(1)),t.rule.delay_minutes>0&&e.push(`${t.rule.delay_minutes}m delay`)),e.push(`${t.pool_count} msg${t.pool_count!==1?"s":""}`),e}function o8({onCreated:t}){const[e,n]=y.useState(""),[r,s]=y.useState(""),[i,o]=y.useState(""),[c,d]=y.useState("likes"),[f,h]=y.useState(50),[m,g]=y.useState(30),[v,x]=y.useState("static"),[k,w]=y.useState(!1),S=async()=>{if(e.trim()){w(!0);try{const N=await fetch("/api/scheduler/autoplugs/goals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e.trim(),link:r.trim()||null,description:i.trim()||null})});if(!N.ok){w(!1);return}const{goal:j}=await N.json();await fetch("/api/scheduler/autoplugs/rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({goal_id:j.id,metric:c,threshold:f,delay_minutes:m,mode:v})});const M=await fetch("/api/scheduler/autoplugs/goals");if(M.ok){const R=((await M.json()).goals||[]).find(L=>L.id===j.id);if(R){t(R);return}}t({...j,rule_count:1,pool_count:0,rule:{metric:c,threshold:f,delay_minutes:m,mode:v,id:""}})}finally{w(!1)}}};return l.jsxs("div",{className:"autoplug-editor",children:[l.jsxs("label",{children:["Name",l.jsx("input",{value:e,onChange:N=>n(N.target.value),placeholder:"Newsletter, Course..."})]}),l.jsxs("label",{children:["Link",l.jsx("input",{value:r,onChange:N=>s(N.target.value),placeholder:"https://..."})]}),l.jsxs("label",{children:["Description (context for LLM)",l.jsx("textarea",{value:i,onChange:N=>o(N.target.value),placeholder:"Weekly engineering insights...",rows:2})]}),l.jsxs("div",{className:"autoplug-editor-row",children:[l.jsx("input",{type:"number",value:f,onChange:N=>h(Number(N.target.value)),min:1}),l.jsxs("select",{value:c,onChange:N=>d(N.target.value),children:[l.jsx("option",{value:"likes",children:"likes"}),l.jsx("option",{value:"retweets",children:"retweets"}),l.jsx("option",{value:"views",children:"views"})]}),l.jsx("span",{className:"autoplug-editor-row-label",children:"wait"}),l.jsx("input",{type:"number",value:m,onChange:N=>g(Number(N.target.value)),min:0,className:"autoplug-delay-input"}),l.jsx("span",{className:"autoplug-editor-row-label",children:"min"})]}),l.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map(N=>l.jsx("button",{className:v===N?"active":"",onClick:()=>x(N),children:N==="llm"?"LLM":N.charAt(0).toUpperCase()+N.slice(1)},N))}),l.jsx("button",{className:"sidebar-schedule-btn sidebar-schedule-btn--active autoplug-create-btn",onClick:S,disabled:k||!e.trim(),children:k?"Creating...":"Create Goal"})]})}function a8({goal:t,onSaved:e,onDeleted:n,onRefresh:r}){var X,z,ee,P;const[s,i]=y.useState(t.name),[o,c]=y.useState(t.link||""),[d,f]=y.useState(t.description||""),[h,m]=y.useState(((X=t.rule)==null?void 0:X.metric)||"likes"),[g,v]=y.useState(((z=t.rule)==null?void 0:z.threshold)||50),[x,k]=y.useState(((ee=t.rule)==null?void 0:ee.delay_minutes)||30),[w,S]=y.useState(((P=t.rule)==null?void 0:P.mode)||"static"),[N,j]=y.useState([]),[M,_]=y.useState(""),[R,L]=y.useState(!1);y.useEffect(()=>{fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`).then(F=>F.json()).then(F=>j(F.pool||[])).catch(()=>{})},[t.id]);const $=async()=>{var F;L(!0);try{await fetch(`/api/scheduler/autoplugs/goals/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s,link:o||null,description:d||null})}),(F=t.rule)!=null&&F.id?await fetch(`/api/scheduler/autoplugs/rules/${t.rule.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({metric:h,threshold:g,delay_minutes:x,mode:w})}):await fetch("/api/scheduler/autoplugs/rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({goal_id:t.id,metric:h,threshold:g,delay_minutes:x,mode:w})}),r()}finally{L(!1)}},B=async()=>{if(!M.trim())return;const F=await fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:M.trim()})});if(F.ok){const G=await F.json();j(ie=>[...ie,G.message]),_("")}},U=async F=>{(await fetch(`/api/scheduler/autoplugs/pool/${F}`,{method:"DELETE"})).ok&&j(ie=>ie.filter(K=>K.id!==F))};return l.jsxs("div",{className:"autoplug-editor",children:[l.jsxs("label",{children:["Name",l.jsx("input",{value:s,onChange:F=>i(F.target.value)})]}),l.jsxs("label",{children:["Link",l.jsx("input",{value:o,onChange:F=>c(F.target.value),placeholder:"https://..."})]}),l.jsxs("label",{children:["Description",l.jsx("textarea",{value:d,onChange:F=>f(F.target.value),rows:2})]}),l.jsx("div",{className:"autoplug-editor-section-label",children:"Trigger"}),l.jsxs("div",{className:"autoplug-editor-row",children:[l.jsx("input",{type:"number",value:g,onChange:F=>v(Number(F.target.value)),min:1}),l.jsxs("select",{value:h,onChange:F=>m(F.target.value),children:[l.jsx("option",{value:"likes",children:"likes"}),l.jsx("option",{value:"retweets",children:"retweets"}),l.jsx("option",{value:"views",children:"views"})]}),l.jsx("span",{className:"autoplug-editor-row-label",children:"wait"}),l.jsx("input",{type:"number",value:x,onChange:F=>k(Number(F.target.value)),min:0,className:"autoplug-delay-input"}),l.jsx("span",{className:"autoplug-editor-row-label",children:"min"})]}),l.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map(F=>l.jsx("button",{className:w===F?"active":"",onClick:()=>S(F),children:F==="llm"?"LLM":F.charAt(0).toUpperCase()+F.slice(1)},F))}),l.jsxs("div",{className:"autoplug-pool-section",children:[l.jsx("div",{className:"autoplug-editor-section-label",children:"Static Pool"}),N.map(F=>l.jsxs("div",{className:"autoplug-pool-item",children:[l.jsx("span",{children:F.content}),l.jsx("button",{onClick:()=>U(F.id),title:"Remove",children:"×"})]},F.id)),l.jsxs("div",{className:"autoplug-pool-add",children:[l.jsx("input",{value:M,onChange:F=>_(F.target.value),placeholder:"Add message... (use {{link}} for link)",onKeyDown:F=>F.key==="Enter"&&B()}),l.jsx("button",{onClick:B,children:"+"})]})]}),(w==="llm"||w==="hybrid")&&l.jsx("div",{className:"autoplug-llm-hint",children:"LLM mode uses Author's Voice to generate contextual replies referencing the original tweet."}),l.jsxs("div",{className:"autoplug-editor-actions",children:[l.jsx("button",{className:"schedule-item-action",onClick:$,disabled:R,children:R?"Saving...":"Save"}),l.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:n,children:"Delete"})]})]})}function l8(t){const e=Date.now()-new Date(t).getTime(),n=Math.floor(e/6e4);if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function c8(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function u8({onBack:t}){const[e,n]=y.useState([]),[r,s]=y.useState([]),[i,o]=y.useState(!1),[c,d]=y.useState(!1),[f,h]=y.useState(null),[m,g]=y.useState(!0),v=y.useCallback(async()=>{try{const[w,S]=await Promise.all([fetch("/api/scheduler/queue"),fetch("/api/scheduler/slots"),fetch("/api/scheduler/sync",{method:"POST"})]);if(w.ok){const N=await w.json();n(N.items||[])}if(S.ok){const N=await S.json();s(N.slots||[])}}catch{}g(!1)},[]);y.useEffect(()=>{v()},[v]);const x=async w=>{(await fetch(`/api/scheduler/queue/${w}`,{method:"DELETE"})).ok&&(n(N=>N.filter(j=>j.id!==w)),h(null))};if(c)return l.jsx(s8,{onBack:()=>{d(!1),v()}});if(i)return l.jsx(n8,{slots:r,onBack:()=>{o(!1),v()}});const k=d8(r,e);return l.jsxs("div",{className:"sidebar-schedule",children:[l.jsxs("div",{className:"sidebar-schedule-header",children:[l.jsx("button",{className:"sidebar-schedule-back",onClick:t,title:"Back to documents",children:l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"m15 18-6-6 6-6"})})}),l.jsx("h3",{children:"Schedule"}),l.jsxs("div",{className:"sidebar-schedule-actions",children:[l.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>d(!0),title:"Autoplugs",children:l.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}),l.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>o(!0),title:"Manage slots",children:l.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),l.jsx("circle",{cx:"12",cy:"12",r:"3"})]})})]})]}),m?null:r.length===0?l.jsxs("div",{className:"schedule-empty",children:[l.jsx("div",{className:"schedule-empty-title",children:"No time slots"}),l.jsx("div",{className:"schedule-empty-desc",children:"Create time slots to define your posting schedule."})]}):k.map(({label:w,entries:S})=>l.jsxs("div",{className:"schedule-day",children:[l.jsx("div",{className:"schedule-day-header",children:w}),S.map((N,j)=>{var M,_,R,L,$;return N.type==="empty"?l.jsxs("div",{className:"schedule-slot-empty",children:[l.jsx("div",{className:"schedule-item-time",children:Bk(N.time)}),l.jsx("div",{className:"schedule-slot-empty-label",children:((M=N.slot)==null?void 0:M.filter_type)==="any"?"Open slot":`${(_=N.slot)==null?void 0:_.filter_type}: ${((R=N.slot)==null?void 0:R.filter_value)||"any"}`})]},`empty-${j}`):l.jsxs("div",{children:[l.jsxs("div",{className:"schedule-item",onClick:()=>h(f===N.item.id?null:N.item.id),children:[l.jsx("div",{className:"schedule-item-time",children:Bk(N.time)}),l.jsxs("div",{className:"schedule-item-content",children:[l.jsx("div",{className:"schedule-item-text",children:((L=N.item.content)==null?void 0:L.text)||JSON.stringify(N.item.content)}),l.jsxs("div",{className:"schedule-item-meta",children:[l.jsx("span",{className:`schedule-item-status schedule-item-status--${N.item.status}`}),l.jsx("span",{children:N.item.status}),N.item.connection_name&&l.jsx("span",{children:N.item.connection_name}),N.item.provider&&l.jsx("span",{children:N.item.provider})]})]})]}),f===N.item.id&&l.jsxs("div",{className:"schedule-item-expanded",children:[l.jsx("div",{className:"schedule-item-full-text",children:(($=N.item.content)==null?void 0:$.text)||JSON.stringify(N.item.content,null,2)}),l.jsx("div",{className:"schedule-item-actions",children:l.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:()=>x(N.item.id),children:"Cancel"})})]})]},N.item.id)})]},w))]})}function d8(t,e){const n=new Date,r=[];for(let c=0;c<7;c++){const d=new Date(n);d.setDate(d.getDate()+c),d.setHours(0,0,0,0);let f;c===0?f="Today":c===1?f="Tomorrow":f=d.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}),r.push({label:f,date:d})}const s=new Map;for(const c of e){const d=new Date(c.scheduled_at),f=`${d.getFullYear()}-${d.getMonth()}-${d.getDate()}-${d.getHours()}-${d.getMinutes()}`;s.set(f,c)}const i=new Set,o=[];for(const{label:c,date:d}of r){const f=[],h=d.getDay(),g=["sun","mon","tue","wed","thu","fri","sat"][h];for(const v of t){if(!(v.days.includes("default")||v.days.includes(g)))continue;const[k,w]=v.time.split(":").map(Number),S=new Date(d);if(S.setHours(k,w,0,0),Pk(d,n)&&S<n)continue;const N=`${S.getFullYear()}-${S.getMonth()}-${S.getDate()}-${k}-${w}`,j=s.get(N);j?(f.push({type:"filled",time:S,item:j,slot:v}),i.add(j.id)):f.push({type:"empty",time:S,slot:v})}for(const v of e){if(i.has(v.id))continue;const x=new Date(v.scheduled_at);Pk(x,d)&&(f.push({type:"filled",time:x,item:v}),i.add(v.id))}f.sort((v,x)=>v.time.getTime()-x.time.getTime()),f.length>0&&o.push({label:c,entries:f})}return o}function Pk(t,e){return t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate()}function Bk(t){return t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function f8({onBack:t}){const[e,n]=y.useState([]),[r,s]=y.useState(""),[i,o]=y.useState(null),[c,d]=y.useState(!1),f=y.useRef(null),h=y.useCallback(async()=>{try{const w=await fetch("/api/tasks");if(w.ok){const S=await w.json();n(S.tasks||[])}}catch{}},[]);y.useEffect(()=>{h()},[h]);const m=async()=>{const w=r.trim();if(w){s("");try{const S=await fetch("/api/tasks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:w})});if(S.ok){const N=await S.json();n(j=>[...j,N.task])}}catch{}}},g=w=>{o(w),fetch(`/api/tasks/${w}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({completed:!0})}).catch(()=>{}),setTimeout(()=>{n(S=>S.filter(N=>N.id!==w)),o(null)},400)},v=async w=>{try{(await fetch(`/api/tasks/${w}`,{method:"DELETE"})).ok&&n(N=>N.filter(j=>j.id!==w))}catch{}},x=()=>{d(!0),setTimeout(()=>{var w;return(w=f.current)==null?void 0:w.focus()},0)},k=e.filter(w=>!w.completed);return l.jsxs("div",{className:"sidebar-tasks",children:[l.jsxs("div",{className:"sidebar-tasks-header",children:[l.jsx("button",{className:"sidebar-tasks-back",onClick:t,title:"Back to documents",children:l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"m15 18-6-6 6-6"})})}),l.jsx("h3",{children:"Tasks"}),l.jsx("button",{className:"sidebar-tasks-add-btn",onClick:x,title:"Add task",children:"+"})]}),k.length===0&&!c?l.jsxs("div",{className:"sidebar-tasks-empty",children:[l.jsx("div",{className:"sidebar-tasks-empty-title",children:"No tasks"}),l.jsx("div",{className:"sidebar-tasks-empty-desc",children:"Add tasks to track your checklist."})]}):l.jsx("div",{className:"sidebar-tasks-list",children:k.map(w=>l.jsxs("div",{className:`sidebar-tasks-item${i===w.id?" completing":""}`,children:[l.jsx("input",{type:"checkbox",className:"sidebar-tasks-checkbox",checked:i===w.id,onChange:()=>g(w.id)}),l.jsx("span",{className:`sidebar-tasks-text${i===w.id?" completed":""}`,children:w.text}),l.jsx("button",{className:"sidebar-tasks-delete",onClick:()=>v(w.id),title:"Remove",children:"×"})]},w.id))}),c&&l.jsx("div",{className:"sidebar-tasks-add",children:l.jsx("input",{ref:f,type:"text",placeholder:"New task...",value:r,onChange:w=>s(w.target.value),onKeyDown:w=>{w.key==="Enter"&&m(),w.key==="Escape"&&(d(!1),s(""))},onBlur:()=>{r.trim()||d(!1)}})})]})}function h8({profiles:t,activeProfile:e,trashedProfiles:n,onSwitch:r,onCreate:s,onDelete:i,onRestore:o}){const[c,d]=y.useState(!1),[f,h]=y.useState(!1),[m,g]=y.useState(""),[v,x]=y.useState(null),k=y.useRef(null),w=y.useRef(null);y.useEffect(()=>{if(!c)return;const N=j=>{k.current&&!k.current.contains(j.target)&&(d(!1),h(!1),g(""),x(null))};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[c]),y.useEffect(()=>{f&&w.current&&w.current.focus()},[f]);const S=()=>{const N=m.trim();N&&(s(N),g(""),h(!1))};return l.jsxs("div",{className:"sidebar-profile-wrapper",ref:k,children:[l.jsx("button",{className:"sidebar-collapse-btn",onClick:()=>d(!c),title:`Profile: ${e}`,children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("circle",{cx:"12",cy:"8",r:"4"}),l.jsx("path",{d:"M5.5 21a8.38 8.38 0 0 1 13 0"})]})}),c&&l.jsxs("div",{className:"sidebar-profile-dropdown",children:[t.map(N=>l.jsxs("div",{className:"sidebar-profile-row",children:[v===N?l.jsxs("div",{className:"sidebar-profile-confirm",children:[l.jsx("span",{children:"Delete?"}),l.jsxs("div",{className:"sidebar-inline-confirm",children:[l.jsx("button",{onClick:()=>{i(N),x(null)},children:"Yes"}),l.jsx("button",{onClick:()=>x(null),children:"No"})]})]}):l.jsx(l.Fragment,{children:l.jsxs("button",{className:`sidebar-profile-option ${N===e?"active":""}`,onClick:()=>{N!==e&&r(N),d(!1)},children:[l.jsx("span",{className:"sidebar-profile-check",children:N===e?"✓":""}),l.jsx("span",{children:N})]})}),N!=="Default"&&N!==e&&v!==N&&l.jsx("button",{className:"sidebar-profile-delete-btn",onClick:j=>{j.stopPropagation(),x(N)},title:"Delete profile",children:"×"})]},N)),n.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"sidebar-profile-divider"}),l.jsx("div",{className:"sidebar-profile-trash-label",children:"Trash"}),n.map(N=>l.jsxs("div",{className:"sidebar-profile-row sidebar-profile-trashed",children:[l.jsx("span",{className:"sidebar-profile-trash-name",children:N}),l.jsx("button",{className:"sidebar-profile-restore-btn",onClick:()=>o(N),children:"Restore"})]},N))]}),l.jsx("div",{className:"sidebar-profile-divider"}),f?l.jsx("div",{className:"sidebar-profile-add-input",children:l.jsx("input",{ref:w,type:"text",value:m,onChange:N=>g(N.target.value),onKeyDown:N=>{N.key==="Enter"&&S(),N.key==="Escape"&&(h(!1),g(""))},placeholder:"Profile name..."})}):l.jsxs("button",{className:"sidebar-profile-option sidebar-profile-add",onClick:()=>h(!0),children:[l.jsx("span",{className:"sidebar-profile-check",children:"+"}),l.jsx("span",{children:"New Profile"})]})]})]})}const qT=200,KT=600,nv=260;function $k({open:t,onSwitchDocument:e,onCreateDocument:n,refreshKey:r,docTagsRefreshKey:s,workspacesRefreshKey:i,pendingDocs:o,writingTitle:c,writingTarget:d,pendingWriteFilenames:f,activeFilename:h,onClose:m,width:g,onWidthChange:v,floating:x}){const{docs:k,setDocs:w,workspaces:S,setWorkspaces:N,assignedFiles:j,fetchDocs:M,fetchWorkspaces:_,scrollRef:R,markPendingDelete:L}=j$(r,i),$=M$(M,_,w,N,k,L),B=$d(),U=y.useRef(!1),X=y.useCallback(Ye=>{Ye.preventDefault(),U.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";let ct=g;const Fe=ge=>{U.current&&(ct=Math.min(KT,Math.max(qT,ge.clientX)),v(ct))},Y=()=>{U.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("pointermove",Fe),window.removeEventListener("pointerup",Y);try{localStorage.setItem("ow-sidebar-width",String(ct))}catch{}};window.addEventListener("pointermove",Fe),window.addEventListener("pointerup",Y)},[g,v]),z=y.useCallback(Ye=>{w(ct=>ct.map(Fe=>({...Fe,isActive:Fe.filename===Ye}))),e(Ye)},[w,e]);y.useEffect(()=>{h&&w(Ye=>Ye.some(ct=>ct.filename===h?!ct.isActive:ct.isActive)?Ye.map(ct=>({...ct,isActive:ct.filename===h})):Ye)},[h,w,r]);const[ee,P]=y.useState(!1),[F,G]=y.useState(!1),[ie,K]=y.useState([]),[ce,J]=y.useState("Default"),A=y.useCallback(async()=>{try{const Ye=await fetch("/api/profiles");if(Ye.ok){const ct=await Ye.json();K(ct.profiles),J(ct.active)}}catch{}},[]);y.useEffect(()=>{A()},[A]);const D=y.useCallback(async Ye=>{try{(await fetch("/api/profiles/switch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Ye})})).ok&&(J(Ye),A())}catch{}},[A]),q=y.useCallback(async Ye=>{try{(await fetch("/api/profiles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Ye})})).ok&&A()}catch{}},[A]),[le,ye]=y.useState([]),oe=y.useCallback(async()=>{try{const Ye=await fetch("/api/profiles/trash");if(Ye.ok){const ct=await Ye.json();ye(ct.profiles)}}catch{}},[]);y.useEffect(()=>{oe()},[oe]);const Se=y.useCallback(async Ye=>{try{(await fetch(`/api/profiles/${encodeURIComponent(Ye)}`,{method:"DELETE"})).ok&&(A(),oe())}catch{}},[A,oe]),Ee=y.useCallback(async Ye=>{try{(await fetch("/api/profiles/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Ye})})).ok&&(A(),oe())}catch{}},[A,oe]),[Le,Ie]=y.useState(""),[Ve,Te]=y.useState(null),qe=y.useRef(),pt=y.useRef(null),ut=y.useCallback(Ye=>{if(Ie(Ye),qe.current&&clearTimeout(qe.current),!Ye.trim()){Te(null);return}qe.current=setTimeout(async()=>{try{const ct=await fetch(`/api/documents/search?q=${encodeURIComponent(Ye.trim())}&archived=true`);ct.ok&&Te(await ct.json())}catch{}},250)},[]);y.useEffect(()=>()=>{qe.current&&clearTimeout(qe.current)},[]);const be={docs:k,archivedDocs:[],workspaces:S,assignedFiles:j,pendingDocs:o,writingTitle:c,writingTarget:d,pendingWriteFilenames:f,onSwitchDocument:z,onCreateDocument:n,actions:$,scrollRef:R,searchQuery:Le,searchResults:Ve,onSearchChange:ut},ht=()=>{switch(B){case"files":return l.jsx(Q$,{...be});case"timeline":return l.jsx(B$,{...be});case"board":return l.jsx($$,{...be});case"shelf":return l.jsx(F$,{...be});default:return l.jsx(P$,{...be})}},xt=l.jsxs("div",{className:"sidebar-search",children:[l.jsxs("svg",{className:"sidebar-search-icon",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("circle",{cx:"10.5",cy:"10.5",r:"7"}),l.jsx("path",{d:"m20 20-4.5-4.5"})]}),l.jsx("input",{ref:pt,className:"sidebar-search-input",type:"text",placeholder:"Search...",value:Le,onChange:Ye=>ut(Ye.target.value)}),Le&&l.jsx("button",{className:"sidebar-search-clear",onClick:()=>ut(""),title:"Clear search",children:"×"})]}),St=t?{width:`${g}px`,minWidth:`${g}px`}:void 0,At=t&&!x?l.jsx("div",{className:"sidebar-resize-handle",onPointerDown:X,onDoubleClick:()=>{v(nv);try{localStorage.setItem("ow-sidebar-width",String(nv))}catch{}},title:"Drag to resize · double-click to reset"}):null;return B==="board"?l.jsxs("div",{className:`sidebar sidebar-board-mode ${t?"open":""}`,style:St,children:[ht(),At]}):l.jsxs("div",{className:`sidebar ${t?"open":""}`,style:St,children:[l.jsxs("div",{className:"sidebar-topbar",children:[l.jsxs("div",{className:"sidebar-logo",children:[l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[l.jsx("path",{d:"M17 3a2.83 2.83 0 0 1 4 4L7.5 20.5 2 22l1.5-5.5Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),l.jsx("path",{d:"M15 5l4 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),l.jsx("span",{className:"sidebar-logo-text",children:"OpenWriter"})]}),l.jsxs("div",{className:"sidebar-topbar-actions",children:[l.jsx(h8,{profiles:ie,activeProfile:ce,trashedProfiles:le,onSwitch:D,onCreate:q,onDelete:Se,onRestore:Ee}),l.jsx("button",{className:`sidebar-collapse-btn${ee?" sidebar-collapse-btn--active":""}`,onClick:()=>{P(!ee),G(!1)},title:"Schedule",children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),l.jsx("line",{x1:"16",x2:"16",y1:"1",y2:"5"}),l.jsx("line",{x1:"8",x2:"8",y1:"1",y2:"5"}),l.jsx("line",{x1:"3",x2:"21",y1:"9",y2:"9"})]})}),l.jsx("button",{className:`sidebar-collapse-btn${F?" sidebar-collapse-btn--active":""}`,onClick:()=>{G(!F),P(!1)},title:"Tasks",children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),l.jsx("path",{d:"m9 12 2 2 4-4"})]})}),m&&l.jsx("button",{className:"sidebar-collapse-btn",onClick:m,title:"Close sidebar",children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[l.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",stroke:"currentColor",strokeWidth:"2"}),l.jsx("path",{d:"M9 3v18",stroke:"currentColor",strokeWidth:"2"}),l.jsx("path",{d:"M15 10l-2 2 2 2",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})]}),F?l.jsx(f8,{onBack:()=>G(!1)}):ee?l.jsx(u8,{onBack:()=>P(!1)}):l.jsxs(l.Fragment,{children:[xt,ht()]}),At]})}function db(t,e,n){let r=t.resolve(e);for(;r.depth>0;){const s=r.node(r.depth),i=r.before(r.depth),o=i+s.nodeSize;if(s.childCount===1)e=i,n=o,r=t.resolve(e);else break}return{from:e,to:n}}function p8(t,e){const n=Wn(t,e);if(!n)return!1;const{node:r,pos:s}=n;return t.chain().command(({tr:i})=>(i.setNodeMarkup(s,void 0,{...r.attrs,pendingStatus:null}),!0)).run(),!0}function m8(t,e){const n=Wn(t,e);if(!n)return!1;const{node:r,pos:s}=n;return t.chain().command(({tr:i})=>(i.setNodeMarkup(s,void 0,{...r.attrs,pendingStatus:null,pendingOriginalContent:null,pendingSelectionFrom:null,pendingSelectionTo:null,pendingOriginalFrom:null,pendingOriginalTo:null}),!0)).run(),!0}function g8(t,e){var o;const n=Wn(t,e);if(!n)return!1;const{node:r,pos:s}=n;if(((o=r.attrs)==null?void 0:o.pendingStatus)!=="delete")return!0;const i=db(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function v8(t,e){var o;const n=Wn(t,e);if(!n)return!0;const{node:r,pos:s}=n;if(((o=r.attrs)==null?void 0:o.pendingStatus)!=="insert")return!0;const i=db(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function b8(t,e){var o,c;const n=Wn(t,e);if(!n)return!1;const{node:r,pos:s}=n;if(((o=r.attrs)==null?void 0:o.pendingStatus)!=="rewrite")return!0;const i=(c=r.attrs)==null?void 0:c.pendingOriginalContent;if(i)t.chain().deleteRange({from:s,to:s+r.nodeSize}).insertContentAt(s,i).run();else{const d=db(t.state.doc,s,s+r.nodeSize);t.chain().deleteRange(d).run()}return!0}function y8(t,e){var i;const n=Wn(t,e);if(!n)return!1;const{node:r,pos:s}=n;return((i=r.attrs)==null?void 0:i.pendingStatus)!=="delete"||t.chain().command(({tr:o})=>(o.setNodeMarkup(s,void 0,{...r.attrs,pendingStatus:null}),!0)).run(),!0}function x8(t,e){const n=nf(t,e);if(n.length===0)return!1;for(const r of[...n].reverse()){const s=Wn(t,r.nodeId);s&&t.chain().command(({tr:i})=>(i.setNodeMarkup(s.pos,void 0,{...s.node.attrs,pendingStatus:null,pendingOriginalContent:null,pendingGroupId:null,pendingSelectionFrom:null,pendingSelectionTo:null,pendingOriginalFrom:null,pendingOriginalTo:null}),!0)).run()}return!0}function w8(t,e){var c;const n=nf(t,e);if(n.length===0)return!1;const r=(c=n[0].node.attrs)==null?void 0:c.pendingOriginalContent,s=n[0].pos,i=n[n.length-1],o=i.pos+i.node.nodeSize;try{return r&&Array.isArray(r)&&r.length>0?t.chain().deleteRange({from:s,to:o}).insertContentAt(s,r).run():t.chain().deleteRange({from:s,to:o}).run(),!0}catch{return!1}}function GT(t,e){var i,o;const n=Wn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return x8(t,r);switch((o=n.node.attrs)==null?void 0:o.pendingStatus){case"insert":return p8(t,e);case"rewrite":return m8(t,e);case"delete":return g8(t,e);default:return!1}}function JT(t,e){var i,o;const n=Wn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return w8(t,r);switch((o=n.node.attrs)==null?void 0:o.pendingStatus){case"insert":return v8(t,e);case"rewrite":return b8(t,e);case"delete":return y8(t,e);default:return!1}}function k8(t){const e=YT(t).reverse();for(const n of e)GT(t,n);t.view&&lb(t.view)}function S8(t){const e=YT(t).reverse();for(const n of e)JT(t,n);t.view&&lb(t.view)}function fb(t){const e=[],n=new Set;return t.state.doc.descendants((r,s)=>{var o,c,d;const i=(o=r.attrs)==null?void 0:o.pendingStatus;if(i&&((c=r.attrs)!=null&&c.id)){const f=(d=r.attrs)==null?void 0:d.pendingGroupId;if(f){if(n.has(f))return!0;n.add(f)}e.push({nodeId:r.attrs.id,pos:s,pendingStatus:i,groupId:f,editor:t})}return!0}),e}function Pp(t){const e=[];for(const n of t)n&&!n.isDestroyed&&e.push(...fb(n));return e}function YT(t){return fb(t).map(e=>e.nodeId)}function E8(t){let e=0,n=0,r=0;for(const s of t)s.pendingStatus==="insert"?e++:s.pendingStatus==="rewrite"?n++:s.pendingStatus==="delete"&&r++;return{insert:e,rewrite:n,delete:r,total:t.length}}function rl(t,e){if(t.isDestroyed)return;let n=-1;if(t.state.doc.descendants((i,o)=>{var c;return((c=i.attrs)==null?void 0:c.id)===e?(n=o,!1):!0}),n===-1)return;const r=t.view.nodeDOM(n),s=r instanceof HTMLElement?r:r==null?void 0:r.parentElement;if(s){s.scrollIntoView({behavior:"smooth",block:"center"});return}try{const i=t.view.coordsAtPos(n),o=t.view.dom.closest(".editor-container");if(o){const c=o.getBoundingClientRect(),d=i.top-c.top+o.scrollTop-o.clientHeight/2;o.scrollTo({top:d,behavior:"smooth"})}}catch{}}function N8(t){const[e,n]=y.useState([]),[r,s]=y.useState(0),i=y.useRef(),o=y.useRef(new Set),c=y.useCallback(()=>{const S=t.filter(R=>R&&!R.isDestroyed);if(S.length===0){n([]),o.current=new Set;return}const N=Pp(S);n(N);const j=o.current,M=new Set(N.map(R=>R.nodeId));let _=-1;if(j.size>0){for(let R=0;R<N.length;R++)if(!j.has(N[R].nodeId)){_=R;break}}o.current=M,_>=0?(s(_),rl(N[_].editor,N[_].nodeId)):N.length===0?s(0):s(R=>Math.min(R,N.length-1))},[t]);y.useEffect(()=>{const S=t.filter(M=>M&&!M.isDestroyed);if(S.length===0)return;const N=()=>{clearTimeout(i.current),i.current=setTimeout(c,50)};for(const M of S)M.on("transaction",N);c();const j=setTimeout(()=>{const M=Pp(S.filter(_=>!_.isDestroyed));M.length>0&&rl(M[0].editor,M[0].nodeId)},150);return()=>{for(const M of S)M.isDestroyed||M.off("transaction",N);clearTimeout(i.current),clearTimeout(j)}},[t,c]),y.useEffect(()=>{const S=e[r]??null;return lk((S==null?void 0:S.nodeId)??null,(S==null?void 0:S.groupId)??null),S!=null&&S.editor&&!S.editor.isDestroyed&&S.editor.view&&lb(S.editor.view),()=>{lk(null)}},[r,e]);const d=E8(e),f=e[r]??null,h=y.useCallback(()=>{if(e.length===0)return;const S=(r+1)%e.length;s(S),e[S]&&rl(e[S].editor,e[S].nodeId)},[e,r]),m=y.useCallback(()=>{if(e.length===0)return;const S=(r-1+e.length)%e.length;s(S),e[S]&&rl(e[S].editor,e[S].nodeId)},[e,r]),g=y.useCallback(()=>{const S=t.filter(M=>M&&!M.isDestroyed),N=Pp(S);if(N.length===0)return;const j=Math.min(r,N.length-1);rl(N[j].editor,N[j].nodeId)},[t,r]),v=y.useCallback(()=>{f&&(GT(f.editor,f.nodeId),c(),g())},[f,c,g]),x=y.useCallback(()=>{f&&(JT(f.editor,f.nodeId),c(),g())},[f,c,g]),k=y.useCallback(()=>{const S=t.filter(N=>N&&!N.isDestroyed);for(const N of S)k8(N);c()},[t,c]),w=y.useCallback(()=>{const S=t.filter(N=>N&&!N.isDestroyed);for(const N of S)S8(N);c()},[t,c]);return{pendingNodes:e,counts:d,currentNode:f,currentIndex:r,hasPending:d.total>0,goToNext:h,goToPrevious:m,acceptCurrent:v,rejectCurrent:x,acceptAll:k,rejectAll:w,refresh:c}}const C8=[{fmt:"epub",label:"EPUB"},{fmt:"html",label:"HTML"},{fmt:"docx",label:"DOCX"},{fmt:"md",label:"MD"}];function Fk({contentType:t,docId:e,manuscriptStyle:n,onSwitchDocument:r}){const[s,i]=y.useState([]),[o,c]=y.useState("manifest"),d=t==="manuscript",f=n==="indented"?"indented":"spaced",[h,m]=y.useState(null),g=h??f;y.useEffect(()=>{m(null)},[n,e]);const v=S=>{S!==g&&(m(S),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manuscriptContext:{paragraphStyle:S}})}).then(()=>{window.dispatchEvent(new CustomEvent("ow-manuscript-restyle"))}).catch(()=>m(null)))};y.useEffect(()=>{let S=!1;const N=()=>{fetch("/api/manuscripts").then(j=>j.json()).then(j=>{S||i(j.manuscripts||[])}).catch(()=>{})};return N(),window.addEventListener("ow-documents-changed",N),()=>{S=!0,window.removeEventListener("ow-documents-changed",N)}},[]),y.useEffect(()=>{c("manifest")},[e]);const x=S=>{c(S),window.dispatchEvent(new CustomEvent(S==="preview"?"ow-manuscript-preview":"ow-manuscript-manifest"))},k=S=>`/api/manuscript/export?docId=${encodeURIComponent(e||"")}&format=${S}`,w=S=>`review-panel__toggle-btn${S?" review-panel__toggle-btn--active":""}`;return l.jsxs(l.Fragment,{children:[d&&e&&l.jsxs("div",{className:"review-tab__section",children:[l.jsx("div",{className:"review-tab__section-label",children:"This Manuscript"}),l.jsxs("div",{className:"review-tab__toggle",role:"tablist","aria-label":"Manuscript view",children:[l.jsx("button",{type:"button",className:w(o==="manifest"),onClick:()=>x("manifest"),children:"Manifest"}),l.jsx("button",{type:"button",className:w(o==="preview"),onClick:()=>x("preview"),title:o==="preview"?"Re-render":"Preview the compiled book",children:"Preview"})]}),l.jsx("div",{className:"ms-style-label",children:"Paragraph style"}),l.jsxs("div",{className:"review-tab__toggle",role:"tablist","aria-label":"Paragraph style",children:[l.jsx("button",{type:"button",className:w(g==="spaced"),onClick:()=>v("spaced"),title:"Blank line between paragraphs, no indent",children:"Spaced"}),l.jsx("button",{type:"button",className:w(g==="indented"),onClick:()=>v("indented"),title:"First-line indent, no gap — traditional print",children:"Indented"})]}),l.jsx("div",{className:"ms-dl-row",children:C8.map(S=>l.jsx("a",{className:"ms-dl-btn",href:k(S.fmt),download:!0,children:S.label},S.fmt))})]}),l.jsxs("div",{className:"review-tab__section",children:[l.jsx("div",{className:"review-tab__section-label",children:"Manuscripts"}),s.length===0?l.jsx("div",{className:"ms-empty",children:"None yet — create one from the “+” menu."}):l.jsx("ul",{className:"ms-list",children:s.map(S=>l.jsx("li",{children:l.jsx("button",{type:"button",className:S.docId===e?"ms-item ms-item--active":"ms-item",onClick:()=>r(S.filename),title:S.title,children:S.title})},S.docId))})]})]})}const XT="ow-review-scope";function _8(){try{return localStorage.getItem(XT)==="workspace"?"workspace":"all"}catch{return"all"}}function T8(t){try{localStorage.setItem(XT,t)}catch{}}function QT(t){if(!t)return[];const e=[];for(const n of t)n.type==="doc"&&n.file&&e.push(n.file),n.type==="container"&&n.items&&e.push(...QT(n.items));return e}function ZT(t,e){if(!t)return!1;for(const n of t)if(n.type==="doc"&&n.file===e||n.type==="container"&&n.items&&ZT(n.items,e))return!0;return!1}const Di={strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},j8=()=>l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:l.jsx("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",...Di})}),M8=()=>l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:l.jsx("path",{d:"M6 3l5 5-5 5",stroke:"currentColor",...Di})}),A8=()=>l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:l.jsx("path",{d:"M3 10l5-5 5 5",stroke:"currentColor",...Di})}),R8=()=>l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:l.jsx("path",{d:"M3 6l5 5 5-5",stroke:"currentColor",...Di})}),O8=()=>l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:l.jsx("path",{d:"M3 8.5l3.5 3.5L13 5",stroke:"currentColor",...Di})}),I8=()=>l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[l.jsx("path",{d:"M1 8.5l3.5 3.5L11 5",stroke:"currentColor",...Di}),l.jsx("path",{d:"M8 12l.5.5L15 6",stroke:"currentColor",...Di})]}),zk=()=>l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:l.jsx("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor",...Di})});function e2(t,e,n){const r=Wn(t,e);if(!r)return!1;const{pos:s,node:i}=r,o={type:n.type||i.type.name,attrs:{...n.attrs||{},id:i.attrs.id,pendingStatus:i.attrs.pendingStatus,pendingOriginalContent:i.attrs.pendingOriginalContent,pendingSelectionFrom:i.attrs.pendingSelectionFrom,pendingSelectionTo:i.attrs.pendingSelectionTo,pendingOriginalFrom:i.attrs.pendingOriginalFrom,pendingOriginalTo:i.attrs.pendingOriginalTo},content:n.content};try{return t.chain().command(({tr:c})=>(c.setMeta("addToHistory",!1),!0)).deleteRange({from:s,to:s+i.nodeSize}).insertContentAt(s,o).run(),!0}catch{return!1}}function t2(t,e,n){const r=nf(t,e);if(r.length===0)return!1;const s=r[0].pos,i=r[r.length-1].pos+r[r.length-1].node.nodeSize;try{return t.chain().command(({tr:o})=>(o.setMeta("addToHistory",!1),!0)).deleteRange({from:s,to:i}).insertContentAt(s,n).run(),!0}catch{return!1}}function Nu(t,e){if(!ab()||!e)return!1;const n=M5();return j5()&&n&&Array.isArray(n)?t2(t,e,n):n&&e2(t,e,n),ul(!1),!0}function L8(t,e){return t.indexOf(e)}function D8({editors:t,pendingDocs:e,currentFilename:n,docId:r,contentType:s,manuscriptStyle:i,pendingTitle:o,onSwitchDocument:c,sendMessage:d,getDocument:f,docVersionRef:h}){const{counts:m,currentNode:g,currentIndex:v,hasPending:x,goToNext:k,goToPrevious:w,acceptCurrent:S,rejectCurrent:N,acceptAll:j,rejectAll:M}=N8(t),[_,R]=y.useState(o?"title":"body");y.useEffect(()=>{o&&_!=="title"&&m.total===0?R("title"):!o&&_==="title"&&R("body")},[o,m.total,_]);const L=!!o,$=m.total+(L?1:0),B=_==="title"?0:(L?1:0)+v,[U,X]=y.useState(!1);y.useEffect(()=>{_!=="title"&&X(!1)},[_]),y.useEffect(()=>{const Y=!!o&&_==="title",ge={docId:r,titleFocused:Y,titleShowOriginal:Y&&U};return window.dispatchEvent(new CustomEvent("ow-pending-review-cursor",{detail:ge})),()=>{window.dispatchEvent(new CustomEvent("ow-pending-review-cursor",{detail:{docId:r,titleFocused:!1,titleShowOriginal:!1}}))}},[r,o,_,U]);const z=y.useCallback(()=>{r&&d({type:"accept-pending-title",docId:r})},[r,d]),ee=y.useCallback(()=>{r&&d({type:"reject-pending-title",docId:r})},[r,d]),P=y.useRef(null),F=y.useRef(null),[G,ie]=y.useState(()=>_8()),[K,ce]=y.useState([]);y.useEffect(()=>{let Y=!1;async function ge(){try{const me=await(await fetch("/api/workspaces")).json();if(!Array.isArray(me))return;const ze=await Promise.all(me.map(async Ae=>{try{const Qe=await(await fetch(`/api/workspaces/${encodeURIComponent(Ae.filename)}`)).json();return{...Ae,workspace:Qe}}catch{return Ae}}));Y||ce(ze)}catch{}}ge();const ne=()=>ge();return window.addEventListener("ow-workspaces-changed",ne),()=>{Y=!0,window.removeEventListener("ow-workspaces-changed",ne)}},[]);const J=y.useMemo(()=>{var ge;if(K.length===0||!n)return null;const Y=K.find(ne=>{var he;return ZT((he=ne.workspace)==null?void 0:he.root,n)});return Y?new Set(QT((ge=Y.workspace)==null?void 0:ge.root)):null},[K,n]),A=y.useMemo(()=>G==="all"||!J?e.filenames:e.filenames.filter(Y=>J.has(Y)),[G,e.filenames,J]),D=y.useCallback(Y=>{ie(Y),T8(Y)},[]),q=A.length,le=L8(A,n),ye=(g==null?void 0:g.pendingStatus)==="rewrite",oe=!!(g!=null&&g.groupId),Se=ye,Ee=y.useCallback(()=>{var ge,ne;const Y=g==null?void 0:g.editor;if(!(!Y||!g||g.pendingStatus!=="rewrite"))if(U)F.current&&Nu(F.current,P.current),P.current=null,F.current=null,X(!1);else if(oe&&g.groupId){const he=nf(Y,g.groupId);if(he.length===0)return;const me=(ge=he[0].node.attrs)==null?void 0:ge.pendingOriginalContent;if(!me||!Array.isArray(me))return;const ze=he.map(Qe=>Qe.node.toJSON()),Ae=me.map((Qe,tt)=>({...Qe,attrs:{...Qe.attrs||{},pendingStatus:"rewrite",pendingGroupId:g.groupId,...tt===0?{pendingOriginalContent:me}:{}}}));if(ul(!0,g.nodeId,ze,g.groupId),!t2(Y,g.groupId,Ae)){ul(!1);return}P.current=g.nodeId,F.current=Y,X(!0)}else{const he=Wn(Y,g.nodeId);if(!he)return;const{node:me}=he,ze=(ne=me.attrs)==null?void 0:ne.pendingOriginalContent;if(!ze)return;const Ae=me.toJSON();if(ul(!0,g.nodeId,Ae),!e2(Y,g.nodeId,ze)){ul(!1);return}P.current=g.nodeId,F.current=Y,X(!0)}},[g,U,oe]);y.useEffect(()=>{if(!U)return;const Y=P.current,ge=F.current;Y&&ge&&(g==null?void 0:g.nodeId)!==Y&&(Nu(ge,Y),P.current=null,F.current=null,X(!1))},[g==null?void 0:g.nodeId,U]),y.useEffect(()=>{if(t.length!==0)return()=>{ab()&&P.current&&F.current&&(Nu(F.current,P.current),P.current=null,F.current=null)}},[t]);const Le=y.useCallback(Y=>{if(!n)return;if(!t.some(ne=>!ne||ne.isDestroyed?!1:fb(ne).length>0)){const ne=f==null?void 0:f();ne&&d({type:"doc-update",document:ne,filename:n,version:(h==null?void 0:h.current)??0}),d({type:"pending-resolved",filename:n,action:Y})}},[t,n,d,f,h]),Ie=y.useCallback(()=>{F.current&&U&&P.current&&(Nu(F.current,P.current),P.current=null,F.current=null,X(!1))},[U]),Ve=y.useCallback(()=>{if(_==="title"&&o){z(),m.total>0&&R("body");return}Ie(),S(),Le("accept")},[_,o,z,m.total,Ie,S,Le]),Te=y.useCallback(()=>{if(_==="title"&&o){ee(),m.total>0&&R("body");return}Ie(),N(),Le("reject")},[_,o,ee,m.total,Ie,N,Le]),qe=y.useCallback(()=>{Ie(),o&&z(),j(),Le("accept")},[Ie,o,z,j,Le]);y.useEffect(()=>{const Y=()=>qe();return window.addEventListener("ow-accept-all",Y),()=>window.removeEventListener("ow-accept-all",Y)},[qe]);const pt=y.useCallback(()=>{Ie(),o&&ee(),M(),Le("reject")},[Ie,o,ee,M,Le]),ut=y.useCallback(()=>{if(!($<=1)){if(_==="title"){R("body");return}if(L&&v>=m.total-1){k(),R("title");return}k()}},[$,_,L,v,m.total,k]),be=y.useCallback(()=>{if(!($<=1)){if(_==="title"){w(),R("body");return}if(L&&v===0){R("title");return}w()}},[$,_,L,v,w]),ht=y.useCallback(()=>{if(q===0||q===1&&le===0)return;const Y=le<=0?q-1:le-1;c(A[Y])},[q,le,A,c]),xt=y.useCallback(()=>{if(q===0||q===1&&le===0)return;const Y=le>=q-1?0:le+1;c(A[Y])},[q,le,A,c]);y.useEffect(()=>{if(!x&&!o)return;const Y=ge=>{if(!(ge.target instanceof HTMLInputElement||ge.target instanceof HTMLTextAreaElement)&&!(ge.target instanceof HTMLElement&&ge.target.closest("[contenteditable]")))switch(ge.key){case"j":case"ArrowDown":!ge.metaKey&&!ge.ctrlKey&&(ge.preventDefault(),ut());break;case"k":case"ArrowUp":!ge.metaKey&&!ge.ctrlKey&&(ge.preventDefault(),be());break;case"h":case"ArrowLeft":!ge.metaKey&&!ge.ctrlKey&&!ge.altKey&&(ge.preventDefault(),ht());break;case"l":case"ArrowRight":!ge.metaKey&&!ge.ctrlKey&&!ge.altKey&&(ge.preventDefault(),xt());break;case"a":!ge.metaKey&&!ge.ctrlKey&&!ge.shiftKey&&(ge.preventDefault(),Ve());break;case"r":!ge.metaKey&&!ge.ctrlKey&&(ge.preventDefault(),Te());break;case"A":ge.shiftKey&&!ge.metaKey&&!ge.ctrlKey&&(ge.preventDefault(),qe());break;case"R":ge.shiftKey&&!ge.metaKey&&!ge.ctrlKey&&(ge.preventDefault(),pt());break;case"o":!ge.metaKey&&!ge.ctrlKey&&!ge.shiftKey&&(ge.preventDefault(),_==="title"?X(ne=>!ne):Ee());break}};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[x,o,ut,be,ht,xt,Ve,Te,qe,pt,Ee]);const St=le>=0?`${le+1} / ${q}`:`— / ${q}`,At=e.filenames.length,Ye=!J,Fe=At>0?l.jsxs("div",{className:"review-tab__section",children:[l.jsx("div",{className:"review-tab__section-label",children:"Scope"}),l.jsxs("div",{className:"review-tab__toggle",children:[l.jsx("button",{type:"button",className:`review-panel__toggle-btn${G==="all"?" review-panel__toggle-btn--active":""}`,onClick:()=>D("all"),title:"Cycle every pending doc in the profile",children:"All"}),l.jsx("button",{type:"button",className:`review-panel__toggle-btn${G==="workspace"?" review-panel__toggle-btn--active":""}`,onClick:()=>!Ye&&D("workspace"),disabled:Ye,title:Ye?"Current doc is not in a workspace":"Only cycle pending docs in this workspace",children:"Workspace"})]})]}):null;return!x&&!o?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"review-tab__empty",children:[l.jsx("div",{className:"review-tab__empty-title",children:"All caught up"}),l.jsx("div",{className:"review-tab__empty-note",children:"No pending agent changes. New writes from agents will land here for review."})]}),l.jsx("div",{className:"review-tab",children:l.jsx(Fk,{contentType:s,docId:r,manuscriptStyle:i,onSwitchDocument:c})})]}):l.jsxs("div",{className:"review-tab",children:[Fe,q>1&&l.jsxs("div",{className:"review-tab__section",children:[l.jsx("div",{className:"review-tab__section-label",children:"Document"}),l.jsxs("div",{className:"review-tab__row",children:[l.jsx("button",{className:"review-panel__btn",onClick:ht,title:"Previous doc (h)",children:l.jsx(j8,{})}),l.jsx("button",{className:"review-panel__btn",onClick:xt,title:"Next doc (l)",children:l.jsx(M8,{})}),l.jsx("span",{className:"review-panel__counter",children:St})]})]}),l.jsx("div",{className:"review-tab__section review-tab__section--actions",children:l.jsxs("div",{className:"review-tab__toggle",children:[l.jsx("button",{className:`review-panel__toggle-btn${(Se||_==="title")&&!U?" review-panel__toggle-btn--active":""}`,onClick:()=>{_==="title"?U&&X(!1):Se&&U&&Ee()},disabled:!Se&&_!=="title",title:"Show modified (o)",children:"Modified"}),l.jsx("button",{className:`review-panel__toggle-btn${(Se||_==="title")&&U?" review-panel__toggle-btn--active":""}`,onClick:()=>{_==="title"?U||X(!0):Se&&!U&&Ee()},disabled:!Se&&_!=="title",title:"Show original (o)",children:"Original"})]})}),l.jsxs("div",{className:"review-tab__section",children:[l.jsx("div",{className:"review-tab__section-label",children:_==="title"?"Title":"Change"}),l.jsxs("div",{className:"review-tab__row",children:[l.jsx("button",{className:"review-panel__btn",onClick:be,disabled:$<=1,title:"Previous (k)",children:l.jsx(A8,{})}),l.jsx("button",{className:"review-panel__btn",onClick:ut,disabled:$<=1,title:"Next (j)",children:l.jsx(R8,{})}),l.jsxs("span",{className:"review-panel__counter",children:[B+1," / ",$]})]})]}),l.jsx("div",{className:"review-tab__section",children:l.jsxs("div",{className:"review-tab__row",children:[l.jsxs("button",{className:"review-tab__judge-btn review-tab__judge-btn--accept",onClick:Ve,title:"Accept (a)",children:[l.jsx(O8,{}),l.jsx("span",{children:"Accept"})]}),l.jsxs("button",{className:"review-tab__judge-btn review-tab__judge-btn--reject",onClick:Te,title:"Reject (r)",children:[l.jsx(zk,{}),l.jsx("span",{children:"Reject"})]})]})}),l.jsx("div",{className:"review-tab__section",children:l.jsxs("div",{className:"review-tab__row",children:[l.jsxs("button",{className:"review-tab__bulk-btn review-tab__bulk-btn--accept",onClick:qe,title:"Accept all (Shift+A)",children:[l.jsx(I8,{}),l.jsx("span",{children:"Accept all"})]}),l.jsxs("button",{className:"review-tab__bulk-btn review-tab__bulk-btn--reject",onClick:pt,title:"Reject all (Shift+R)",children:[l.jsx(zk,{}),l.jsx("span",{children:"Reject all"})]})]})}),l.jsx(Fk,{contentType:s,docId:r,manuscriptStyle:i,onSwitchDocument:c})]})}const P8={"agent-finished":"Agent finished",accept:"Accepted",manual:"Saved"};function B8(t){const e=Date.now()-t,n=Math.floor(e/1e3);if(n<60)return"Just now";const r=Math.floor(n/60);if(r<60)return`${r}m ago`;const s=Math.floor(r/60);if(s<24)return`${s}h ago`;const i=Math.floor(s/24);return i<7?`${i}d ago`:new Date(t).toLocaleDateString()}function Uk(t){return t==="human"?"you":t}function $8({docId:t}){const[e,n]=y.useState([]),[r,s]=y.useState(null),[i,o]=y.useState(!1),c=y.useCallback(()=>{if(!t){n([]);return}fetch(`/api/commits/${t}`).then(h=>h.ok?h.json():{commits:[]}).then(h=>n(Array.isArray(h.commits)?h.commits:[])).catch(()=>n([]))},[t]);y.useEffect(()=>{c()},[c]);const d=y.useCallback(async()=>{if(!t||i)return;const h=window.prompt('Save version — optional note (e.g. "first full draft"):')??void 0;o(!0);try{(await(await fetch("/api/commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({docId:t,note:h||void 0})})).json().catch(()=>({}))).committed||window.setTimeout(()=>{},0),c()}catch{}o(!1)},[t,i,c]),f=y.useCallback(async h=>{if(!i){o(!0);try{(await fetch(`/api/versions/${h}/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:"full"})})).ok&&c()}catch{}o(!1)}},[i,c]);return l.jsxs("div",{className:"versions-tab",children:[l.jsx("div",{className:"versions-tab__actions",children:l.jsx("button",{className:"versions-tab__save-btn",disabled:!t||i,onClick:d,children:"+ Save version"})}),l.jsx("div",{className:"versions-tab__list",children:e.length===0?l.jsx("div",{className:"versions-tab__empty",children:'No versions yet. A version is committed when an agent finishes writing, when you accept changes, or when you hit "Save version."'}):e.map(h=>l.jsxs("div",{className:`commit-row${r===h.ts?" commit-row--expanded":""}`,onClick:()=>s(r===h.ts?null:h.ts),children:[l.jsxs("div",{className:"commit-row__head",children:[l.jsx("span",{className:"commit-row__time",children:B8(h.ts)}),l.jsx("span",{className:"commit-row__authors",children:h.actors.map(m=>l.jsx("span",{className:`commit-badge commit-badge--${m}`,children:Uk(m)},m))})]}),l.jsx("div",{className:"commit-row__label",children:h.label}),h.note&&l.jsxs("div",{className:"commit-row__note",children:["“",h.note,"”"]}),r===h.ts&&l.jsxs("div",{className:"commit-row__detail",onClick:m=>m.stopPropagation(),children:[l.jsx("div",{className:"commit-row__trigger",children:P8[h.trigger]??h.trigger}),l.jsx("ul",{className:"commit-row__breakdown",children:Object.keys(h.summary.byActor).map(m=>{const g=h.summary.byActor[m];return l.jsxs("li",{children:[l.jsx("span",{className:`commit-badge commit-badge--${m}`,children:Uk(m)}),g.added>0&&l.jsxs("span",{children:[" ",g.added," added"]}),g.edited>0&&l.jsxs("span",{children:[" ",g.edited," edited"]}),g.removed>0&&l.jsxs("span",{children:[" ",g.removed," removed"]})]},m)})}),l.jsx("button",{className:"commit-row__restore",disabled:i||!h.restorable,title:h.restorable?"Restore the document to this version":"Snapshot pruned — cannot restore",onClick:()=>f(h.snapshotTs),children:"Restore this version"})]})]},h.ts))})]})}function F8({docId:t,currentFilename:e,onSwitchDocument:n}){const[r,s]=y.useState(new Map),[i,o]=y.useState([]),[c,d]=y.useState([]),[f,h]=y.useState(!0),[m,g]=y.useState(!1);y.useEffect(()=>{let w=!1;const S=async()=>{try{const M=await(await fetch("/api/documents")).json();if(w)return;const _=new Map;if(Array.isArray(M))for(const R of M)R!=null&&R.docId&&_.set(R.docId,{docId:R.docId,filename:R.filename,title:R.title||R.filename});s(_)}catch{}finally{w||h(!1)}};S();const N=()=>S();return window.addEventListener("ow-documents-changed",N),()=>{w=!0,window.removeEventListener("ow-documents-changed",N)}},[]),y.useEffect(()=>{if(!t){o([]);return}let w=!1;const S=()=>{g(!0),fetch(`/api/backlinks/${t}`).then(j=>j.ok?j.json():[]).then(j=>{w||o(Array.isArray(j)?j:[])}).catch(()=>{w||o([])}).finally(()=>{w||g(!1)})};S();const N=()=>S();return window.addEventListener("ow-metadata-changed",N),()=>{w=!0,window.removeEventListener("ow-metadata-changed",N)}},[t]),y.useEffect(()=>{let w=!1;const S=()=>{fetch("/api/document").then(j=>j.json()).then(j=>{var _;if(w)return;const M=(_=j==null?void 0:j.metadata)==null?void 0:_.references;d(Array.isArray(M)?M:[])}).catch(()=>{w||d([])})};S();const N=()=>S();return window.addEventListener("ow-metadata-changed",N),()=>{w=!0,window.removeEventListener("ow-metadata-changed",N)}},[e,t]);const v=y.useMemo(()=>i.map(w=>{const S=r.get(w.from_doc);return S?{docId:w.from_doc,title:S.title,filename:S.filename,snippet:w.text}:null}).filter(w=>w!==null),[i,r]),x=y.useMemo(()=>c.map(w=>{const S=r.get(w);return S?{docId:w,title:S.title,filename:S.filename}:null}).filter(w=>w!==null),[c,r]);if(!t)return l.jsxs("div",{className:"backlinks-tab__empty",children:[l.jsx("div",{className:"backlinks-tab__empty-title",children:"No document open"}),l.jsx("div",{className:"backlinks-tab__empty-note",children:"Open a doc to see what links to it and what it links out to."})]});const k=f||m;return l.jsxs("div",{className:"backlinks-tab",children:[l.jsxs("div",{className:"backlinks-tab__group",children:[l.jsxs("div",{className:"backlinks-tab__group-label",children:["Inbound ",l.jsx("span",{className:"backlinks-tab__count",children:v.length})]}),k&&v.length===0?l.jsx("div",{className:"backlinks-tab__empty-note backlinks-tab__inline-note",children:"Loading…"}):v.length===0?l.jsx("div",{className:"backlinks-tab__empty-note backlinks-tab__inline-note",children:"No docs link to this one yet."}):v.map(w=>l.jsxs("button",{type:"button",className:"backlinks-tab__entry",onClick:()=>n(w.filename),children:[l.jsx("div",{className:"backlinks-tab__entry-title",children:w.title}),w.snippet&&l.jsx("div",{className:"backlinks-tab__entry-snippet",children:w.snippet})]},w.docId))]}),l.jsxs("div",{className:"backlinks-tab__group",children:[l.jsxs("div",{className:"backlinks-tab__group-label",children:["Outbound ",l.jsx("span",{className:"backlinks-tab__count",children:x.length})]}),x.length===0?l.jsx("div",{className:"backlinks-tab__empty-note backlinks-tab__inline-note",children:"This doc doesn’t reference others yet."}):x.map(w=>l.jsx("button",{type:"button",className:"backlinks-tab__entry",onClick:()=>n(w.filename),children:l.jsx("div",{className:"backlinks-tab__entry-title",children:w.title})},w.docId))]})]})}const z8=[{key:"md",label:"Markdown",desc:"Plain .md file",icon:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),l.jsx("path",{d:"M14 2v6h6"})]})},{key:"html",label:"HTML",desc:"Styled web page",icon:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("polyline",{points:"16 18 22 12 16 6"}),l.jsx("polyline",{points:"8 6 2 12 8 18"})]})},{key:"docx",label:"Word",desc:"Microsoft Word .docx",icon:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),l.jsx("path",{d:"M14 2v6h6"}),l.jsx("path",{d:"M16 13H8"}),l.jsx("path",{d:"M16 17H8"}),l.jsx("path",{d:"M10 9H8"})]})},{key:"txt",label:"Plain Text",desc:"Unformatted .txt file",icon:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M17 6.1H3"}),l.jsx("path",{d:"M21 12.1H3"}),l.jsx("path",{d:"M15.1 18H3"})]})},{key:"pdf",label:"PDF",desc:"Print preview for save as PDF",icon:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("polyline",{points:"6 9 6 2 18 2 18 9"}),l.jsx("path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"}),l.jsx("rect",{x:"6",y:"14",width:"12",height:"8"})]})}];function U8(t){const e=n=>{if(n==="pdf"){window.open("/api/export?format=pdf","_blank");return}const r=document.createElement("a");r.href=`/api/export?format=${n}`,r.download="",document.body.appendChild(r),r.click(),document.body.removeChild(r)};return l.jsx("div",{className:"exports-tab",children:l.jsx("div",{className:"exports-tab__list",children:z8.map(n=>l.jsxs("button",{type:"button",className:"exports-tab__item",onClick:()=>e(n.key),children:[l.jsx("span",{className:"exports-tab__item-icon",children:n.icon}),l.jsxs("span",{className:"exports-tab__item-text",children:[l.jsx("span",{className:"exports-tab__item-label",children:n.label}),l.jsx("span",{className:"exports-tab__item-desc",children:n.desc})]})]},n.key))})})}const H8=3e4,W8=500;let Ei={entries:[],freshKeys:new Set};const rv=new Set;function n2(t){return`${t.ts}:${t.kind}:${t.headline}`}function V8(){for(const t of rv)t(Ei)}function sv(t){Ei=t,V8()}function q8(t){return rv.add(t),()=>{rv.delete(t)}}function K8(){return Ei}function G8(t){const e=t.detail;e!=null&&e.entries&&sv({entries:e.entries,freshKeys:new Set})}function J8(t){const e=t.detail;if(!(e!=null&&e.event))return;const n=e.event,r=n2(n),s={entries:[n,...Ei.entries].slice(0,W8),freshKeys:new Set([...Ei.freshKeys,r])};sv(s),window.setTimeout(()=>{if(Ei.freshKeys.has(r)){const i=new Set(Ei.freshKeys);i.delete(r),sv({...Ei,freshKeys:i})}},H8)}typeof window<"u"&&(window.addEventListener("ow-activity-seed",G8),window.addEventListener("ow-activity-event",J8));function Y8(){const[t,e]=y.useState(K8);return y.useEffect(()=>q8(e),[]),t}function X8(){const[t,e]=y.useState(()=>({byDocId:new Map,filenameSet:new Set}));return y.useEffect(()=>{let n=!1;const r=()=>{fetch("/api/documents").then(s=>s.json()).then(s=>{if(n||!Array.isArray(s))return;const i=new Map,o=new Set;for(const c of s)c.filename&&o.add(c.filename),c.docId&&c.filename&&i.set(c.docId,c.filename);e({byDocId:i,filenameSet:o})}).catch(()=>{})};return r(),window.addEventListener("ow-documents-changed",r),()=>{n=!0,window.removeEventListener("ow-documents-changed",r)}},[]),t}function Q8(t,e){return t.docId?e.byDocId.get(t.docId)??null:t.filename&&e.filenameSet.has(t.filename)?t.filename:null}function Z8(t,e){const n=Math.max(0,e-t),r=Math.floor(n/1e3);if(r<45)return"just now";const s=Math.floor(r/60);if(s<60)return`${s}m ago`;const i=Math.floor(s/60);if(i<24)return`${i}h ago`;const o=Math.floor(i/24);return o<7?`${o}d ago`:new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function eF({onSwitchDocument:t}){const{entries:e,freshKeys:n}=Y8(),r=X8(),[s,i]=y.useState(()=>Date.now());y.useEffect(()=>{const c=setInterval(()=>i(Date.now()),3e4);return()=>clearInterval(c)},[]);const o=y.useMemo(()=>tF(e,s),[e,s]);return e.length===0?l.jsxs("div",{className:"activity-tab__empty",children:[l.jsx("div",{className:"activity-tab__empty-title",children:"No activity yet"}),l.jsx("div",{className:"activity-tab__empty-note",children:"Agent actions — writes, enrichment, backlink propagation — will appear here as they happen."})]}):l.jsx("div",{className:"activity-tab",children:o.map(c=>l.jsxs("div",{className:"activity-tab__group",children:[l.jsx("div",{className:"activity-tab__group-label",children:c.label}),c.entries.map(d=>{const f=n2(d),h=n.has(f),m=d.kind==="doc-deleted"?null:Q8(d,r),g=m!==null,v=!g,x=v&&d.kind!=="doc-deleted"?"Doc no longer available":void 0,k=()=>{m&&t(m)};return l.jsxs("div",{className:`activity-tab__entry${h?" activity-tab__entry--fresh":""}${g?" activity-tab__entry--clickable":""}${v?" activity-tab__entry--muted":""}`,role:g?"button":void 0,tabIndex:g?0:void 0,title:x,onClick:k,onKeyDown:w=>{g&&(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),k())},children:[l.jsx("span",{className:`activity-tab__kind-dot activity-tab__kind-dot--${d.kind}`,"aria-hidden":"true"}),l.jsxs("div",{className:"activity-tab__entry-body",children:[l.jsx("div",{className:"activity-tab__headline",children:d.headline}),d.detail&&l.jsx("div",{className:"activity-tab__detail",children:d.detail})]}),l.jsx("div",{className:"activity-tab__ts",title:new Date(d.ts).toLocaleString(),children:Z8(d.ts,s)})]},f)})]},c.label))})}function tF(t,e){if(t.length===0)return[];const n=Hk(e),r=n-1440*60*1e3,s=[];let i=null;for(const o of t){const c=Hk(o.ts);let d;c===n?d="Today":c===r?d="Yesterday":d=new Date(o.ts).toLocaleDateString(void 0,{weekday:"long",month:"short",day:"numeric"}),(!i||i.label!==d)&&(i={label:d,entries:[]},s.push(i)),i.entries.push(o)}return s}function Hk(t){const e=new Date(t);return e.setHours(0,0,0,0),e.getTime()}async function Cu(t,e={}){var s,i;const r=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:t,arguments:e})})).json();if((i=(s=r==null?void 0:r.content)==null?void 0:s[0])!=null&&i.text)try{return JSON.parse(r.content[0].text)}catch{return r.content[0].text}return r}function nF(){const[t,e]=y.useState([]),[n,r]=y.useState(!0),[s,i]=y.useState("closed"),[o,c]=y.useState(""),[d,f]=y.useState(!1),[h,m]=y.useState(null),[g,v]=y.useState(null),[x,k]=y.useState(null),w=y.useCallback(async()=>{r(!0);try{const _=await Cu("list_blog_sites");e((_==null?void 0:_.sites)||[])}finally{r(!1)}},[]);y.useEffect(()=>{w()},[w]);const S=()=>{i("closed"),c(""),m(null),v(null),k(null)},N=async()=>{if(o.trim()){f(!0),m(null);try{const _=await Cu("inspect_blog_repo",{repo_url:o.trim()});if(_.error){m(_.error);return}v({..._,label:_.repo,branch:"main",site_url:_.site_url||"",blog_url_pattern:_.blog_url_pattern||"/blog/{slug}/"}),i("review")}catch(_){m((_==null?void 0:_.message)||"Inspection failed")}finally{f(!1)}}},j=async()=>{if(g){i("saving"),k(null);try{const _=await Cu("add_blog_site",{label:g.label,owner:g.owner,repo:g.repo,branch:g.branch||"main",content_dir:g.content_dir,image_dir:g.image_dir,image_public_prefix:g.image_public_prefix,framework:g.framework,frontmatter_defaults:g.frontmatter_defaults||{},frontmatter_field_map:g.frontmatter_field_map||{},frontmatter_schema:g.frontmatter_schema||[],site_url:g.site_url||"",blog_url_pattern:g.blog_url_pattern||"/blog/{slug}/"});if(_!=null&&_.error){k(_.error),i("review");return}S(),await w()}catch(_){k((_==null?void 0:_.message)||"Save failed"),i("review")}}},M=async _=>{if(!window.confirm(`Remove "${_.label}" (${_.owner}/${_.repo})?
208
+ `)})();return ne?l.jsx("div",{className:"context-menu-comment-quote",children:ne}):null})(),l.jsx("textarea",{autoFocus:!0,className:"context-menu-comment-textarea",value:ee,onChange:ne=>P(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"&&(ne.metaKey||ne.ctrlKey)&&(ne.preventDefault(),St()),ne.key==="Escape"&&(s(!1),z(!1),P(""),G(null))},placeholder:"Note for agent (optional)...",rows:4}),l.jsxs("div",{className:"context-menu-comment-actions",children:[l.jsx("span",{className:"context-menu-comment-hint",children:"⌘↵ to save · Esc to cancel"}),l.jsx("button",{onClick:St,children:F?"Save":"Comment"})]})]}):ie?l.jsxs(l.Fragment,{children:[l.jsx("button",{className:"context-menu-item",onClick:At,children:l.jsx("span",{children:"Edit comment"})}),l.jsx("button",{className:"context-menu-item",onClick:Ye,children:l.jsx("span",{children:"Resolve comment"})}),l.jsx("button",{className:"context-menu-item",onClick:ct,children:l.jsx("span",{children:"Delete comment"})})]}):m?l.jsxs("div",{className:"context-menu-custom",children:[l.jsx("input",{autoFocus:!0,value:f,onChange:ne=>h(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"&&xt(),ne.key==="Escape"&&s(!1)},placeholder:"Custom instruction..."}),l.jsx("button",{onClick:xt,children:"Apply"})]}):ye?l.jsxs("div",{className:"context-menu-link-picker",children:[l.jsxs("div",{className:"context-menu-link-header",children:[l.jsx("button",{className:"context-menu-link-back",onClick:()=>oe(null),title:"Back to doc list",children:"←"}),l.jsxs("span",{children:['Pick paragraph in "',ye.title,'"']})]}),l.jsx("button",{className:"context-menu-item context-menu-new-link",onClick:()=>Fe({filename:ye.filename,docId:ye.docId}),children:l.jsx("span",{children:"Link whole doc"})}),l.jsx("div",{className:"context-menu-link-list",children:ye.loading?l.jsx("div",{className:"context-menu-loading",children:"Loading…"}):ye.paragraphs.length===0?l.jsx("div",{className:"context-menu-loading",children:"No paragraphs"}):ye.paragraphs.map(ne=>{const he=ne.preview.replace(/…$/,"").slice(0,50),me=ne.type==="heading"?Math.max(0,(ne.level||1)-1)*12:12;return l.jsx("button",{className:`context-menu-item context-menu-paragraph-row context-menu-paragraph-row--${ne.type}`,style:{paddingLeft:8+me},onClick:()=>Fe({filename:ye.filename,docId:ye.docId},{nodeId:ne.nodeId,quote:he}),children:l.jsx("span",{children:ne.preview})},ne.nodeId)})})]}):A&&ce?l.jsxs("div",{className:"context-menu-link-picker",children:[l.jsxs("div",{className:"context-menu-link-header",children:["Linked from ",ce.entries.length," ",ce.entries.length===1?"place":"places"]}),l.jsx("div",{className:"context-menu-link-list",children:ce.entries.map((ne,he)=>{const me=S.find(Ae=>Ae.docId===ne.from_doc),ze=(me==null?void 0:me.title)||ne.from_doc;return l.jsxs("button",{className:"context-menu-item",onClick:()=>{window.dispatchEvent(new CustomEvent("ow-navigate-to-link",{detail:{docId:ne.from_doc,nodeId:ne.from_node,filename:null,quote:null}})),s(!1),D(!1)},children:[l.jsx("span",{children:ze}),l.jsxs("span",{className:"context-menu-shortcut",children:['"',ne.text,'"']})]},`${ne.from_doc}-${ne.from_node}-${he}`)})})]}):k?l.jsxs("div",{className:"context-menu-link-picker",children:[l.jsx("div",{className:"context-menu-link-header",children:"Link to document"}),_?l.jsxs("div",{className:"context-menu-custom",children:[l.jsx("input",{autoFocus:!0,value:L,onChange:ne=>$(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"&&ge(),ne.key==="Escape"&&R(!1)},placeholder:"New document title..."}),l.jsx("button",{onClick:ge,children:"Create"})]}):l.jsx("button",{className:"context-menu-item context-menu-new-link",onClick:()=>R(!0),children:l.jsx("span",{children:"+ New link doc"})}),l.jsxs("div",{className:"context-menu-link-list",children:[j.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-section-header",children:"Linked in this doc"}),S.filter(ne=>Nk(ne,j)).map(ne=>l.jsxs("div",{className:"context-menu-link-row",children:[l.jsx("button",{className:"context-menu-item context-menu-link-row__main",onClick:()=>Fe(ne),children:l.jsx("span",{children:ne.title})}),ne.docId&&l.jsx("button",{className:"context-menu-link-row__drill",title:"Pick a paragraph in this doc",onClick:()=>Y(ne),children:"▸"})]},`linked-${ne.filename}`))]}),l.jsx("div",{className:"context-menu-section-header",children:"All documents"}),S.filter(ne=>!Nk(ne,j)).map(ne=>l.jsxs("div",{className:"context-menu-link-row",children:[l.jsx("button",{className:"context-menu-item context-menu-link-row__main",onClick:()=>Fe(ne),children:l.jsx("span",{children:ne.title})}),ne.docId&&l.jsx("button",{className:"context-menu-link-row__drill",title:"Pick a paragraph in this doc",onClick:()=>Y(ne),children:"▸"})]},ne.filename)),S.length===0&&l.jsx("div",{className:"context-menu-loading",children:"No documents"})]})]}):(()=>{const ne=pt();let he;return ne.map((me,ze)=>{const Ae=me.isPlugin&&me.pluginDisplayName&&me.pluginDisplayName!==he,Xe=he!==void 0;me.isPlugin?he=me.pluginDisplayName:he=void 0;const Qe=!me.isPlugin&&Xe;return l.jsxs("span",{children:[Ae&&l.jsx("div",{className:"context-menu-section-header",children:me.pluginDisplayName}),Qe&&l.jsx("div",{className:"context-menu-divider"}),l.jsxs("button",{className:"context-menu-item",onClick:()=>ht(me),children:[l.jsx("span",{children:me.label}),me.shortcut&&l.jsx("span",{className:"context-menu-shortcut",children:me.shortcut})]})]},me.action)})})()}):null}const E$=80,Op=8,Zo=8,N$=400;function Ck(t){return t.nodeIds&&t.nodeIds.length>0?t.nodeIds:[t.nodeId]}function _k(t,e){const n=new Set(e);return t.every(r=>n.has(r))}function C$(t,e){const n=e.find(s=>s.id===t);if(!n)return[];const r=Ck(n);return e.filter(s=>{if(s.id===n.id)return!0;const i=Ck(s);return _k(i,r)||_k(r,i)}).sort((s,i)=>(s.createdAt||"").localeCompare(i.createdAt||""))}function _$({documentId:t}){const[e,n]=y.useState(null),[r,s]=y.useState({kind:"view"}),[i,o]=y.useState(""),[c,d]=y.useState(0),[f,h]=y.useState({left:0,top:0,placement:"above"}),m=y.useRef(null),g=y.useRef(null),v=y.useRef(null),x=y.useRef(null),k=y.useRef({kind:"view"});y.useEffect(()=>{x.current=e},[e]),y.useEffect(()=>{k.current=r},[r]),y.useEffect(()=>{const ee=()=>d(P=>P+1);return window.addEventListener("ow-comments-changed",ee),()=>window.removeEventListener("ow-comments-changed",ee)},[]);const w=y.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},[]),S=y.useCallback(()=>{w(),v.current=window.setTimeout(()=>{k.current.kind==="view"&&n(null)},E$)},[w]),N=y.useCallback(()=>{w(),n(null),s({kind:"view"}),o("")},[w]),j=y.useMemo(()=>e?C$(e.commentId,$u()):[],[e,c]);y.useEffect(()=>{e&&j.length===0&&N()},[e,j.length,N]),y.useLayoutEffect(()=>{if(!e)return;const ee=m.current;if(!ee)return;const P=ee.getBoundingClientRect(),{rect:F}=e,G=F.top,ie=window.innerHeight-F.bottom,K=G>=P.height+Op||G>=ie?"above":"below",ce=K==="above"?Math.max(Zo,F.top-P.height-Op):Math.min(window.innerHeight-P.height-Zo,F.bottom+Op);let J=F.left;J+P.width>window.innerWidth-Zo&&(J=window.innerWidth-P.width-Zo),J<Zo&&(J=Zo),h({left:J,top:ce,placement:K})},[e,r,j.length,c]),y.useEffect(()=>{const ee=ie=>{var J,A,D;const K=ie.target,ce=(J=K==null?void 0:K.closest)==null?void 0:J.call(K,"[data-comment-id]");if(ce){const q=ce.getAttribute("data-comment-id");if(!q)return;if(((A=x.current)==null?void 0:A.commentId)===q){w();return}w(),s({kind:"view"}),o(""),n({commentId:q,rect:ce.getBoundingClientRect()});return}if((D=m.current)!=null&&D.contains(K)){w();return}x.current&&S()},P=ie=>{var ce,J;const K=ie.relatedTarget;if(K&&((ce=m.current)!=null&&ce.contains(K))){w();return}K&&((J=K.closest)!=null&&J.call(K,"[data-comment-id]"))||x.current&&S()},F=ie=>{if(ie.key==="Escape"&&x.current){if(ie.preventDefault(),k.current.kind!=="view"){s({kind:"view"}),o("");return}N()}},G=ie=>{var K;x.current&&k.current.kind==="view"&&((K=m.current)!=null&&K.contains(ie.target)||N())};return document.addEventListener("mouseover",ee),document.addEventListener("mouseout",P),document.addEventListener("keydown",F),document.addEventListener("scroll",G,!0),()=>{document.removeEventListener("mouseover",ee),document.removeEventListener("mouseout",P),document.removeEventListener("keydown",F),document.removeEventListener("scroll",G,!0),w()}},[w,S,N]),y.useEffect(()=>{var ee;r.kind!=="view"&&((ee=g.current)==null||ee.focus())},[r]);const M=y.useCallback(ee=>{const P=$u().find(F=>F.id===ee);P&&(o(P.note||""),s({kind:"edit",commentId:ee}))},[]),_=y.useCallback(ee=>{o(""),s({kind:"compose",parentCommentId:ee})},[]),R=y.useCallback(()=>{s({kind:"view"}),o("")},[]),L=y.useCallback(()=>{r.kind!=="edit"||!t||fetch("/api/comments",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:t,id:r.commentId,note:i.trim()})}).then(()=>{s({kind:"view"}),o("")}).catch(ee=>console.error("[CommentPopover] Save failed:",ee))},[r,t,i]),$=y.useCallback(()=>{if(r.kind!=="compose"||!t)return;const ee=$u().find(P=>P.id===r.parentCommentId);ee&&fetch("/api/comments",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:t,text:ee.text,note:i.trim(),nodeId:ee.nodeId,nodeIds:ee.nodeIds})}).then(()=>{s({kind:"view"}),o("")}).catch(P=>console.error("[CommentPopover] Create failed:",P))},[r,t,i]),B=y.useCallback(ee=>{fetch("/api/comments/resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[ee]})}).catch(P=>console.error("[CommentPopover] Resolve failed:",P))},[]),U=y.useCallback(ee=>{fetch("/api/comments",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[ee]})}).catch(P=>console.error("[CommentPopover] Delete failed:",P))},[]);if(!e||j.length===0)return null;const X=r.kind!=="view",z=r.kind==="compose"?"Adding a new comment on the same range":null;return l.jsx("div",{ref:m,className:`ow-comment-popover ow-comment-popover-${f.placement}`,style:{left:f.left,top:f.top,maxHeight:N$},onMouseEnter:w,onMouseLeave:S,children:X?l.jsxs(l.Fragment,{children:[z&&l.jsx("div",{className:"ow-comment-popover-empty",children:z}),l.jsx("textarea",{ref:g,className:"ow-comment-popover-textarea",value:i,onChange:ee=>o(ee.target.value),onKeyDown:ee=>{ee.key==="Enter"&&(ee.metaKey||ee.ctrlKey)&&(ee.preventDefault(),r.kind==="edit"?L():r.kind==="compose"&&$()),ee.key==="Escape"&&(ee.preventDefault(),R())},rows:4,placeholder:"Note for agent (optional)..."}),l.jsxs("div",{className:"ow-comment-popover-actions",children:[l.jsx("span",{className:"ow-comment-popover-hint",children:"⌘↵ to save · Esc to cancel"}),l.jsx("button",{className:"ow-icon-btn",onClick:r.kind==="edit"?L:$,title:"Save",children:l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"M20 6 9 17l-5-5"})})})]})]}):l.jsx("div",{className:"ow-comment-popover-stack",children:j.map((ee,P)=>l.jsxs("div",{className:`ow-comment-popover-card${P>0?" ow-comment-popover-card-divider":""}`,children:[ee.note?l.jsx("div",{className:"ow-comment-popover-text",children:ee.note}):l.jsx("div",{className:"ow-comment-popover-empty",children:"No note"}),l.jsxs("div",{className:"ow-comment-popover-actions",children:[l.jsx("button",{className:"ow-icon-btn",onClick:()=>M(ee.id),title:"Edit comment",children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M12 20h9"}),l.jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"})]})}),l.jsx("button",{className:"ow-icon-btn",onClick:()=>_(ee.id),title:"Add another comment on this range",children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M12 5v14"}),l.jsx("path",{d:"M5 12h14"})]})}),l.jsx("button",{className:"ow-icon-btn",onClick:()=>B(ee.id),title:"Resolve (mark addressed)",children:l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"M20 6 9 17l-5-5"})})}),l.jsx("button",{className:"ow-icon-btn ow-icon-btn-danger",onClick:()=>U(ee.id),title:"Delete (remove permanently)",children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M18 6 6 18"}),l.jsx("path",{d:"m6 6 12 12"})]})})]})]},ee.id))})})}function Su(t){return t.type==="doc"?t.file:t.id}function Ll(t,e){for(const n of t)n.type==="doc"?e.add(n.file):n.type==="container"&&Ll(n.items,e)}function LT(t,e,n,r){for(const s of t){if(s.type==="doc"&&s.file===e)return n||r;if(s.type==="container"){const i=s.autoAccept===!0,o=LT(s.items,e,n,r||i);if(o!==null)return o}}return null}function Pd(t,e){for(const n of t){const r=n.workspace;if(!r)continue;const s=r.autoAccept===!0;if(LT(r.root,e,s,!1)===!0)return!0}return!1}function ba(t){const e=new Date(t),n=Date.now()-e.getTime();return n<6e4?"just now":n<36e5?`${Math.floor(n/6e4)}m ago`:n<864e5?`${Math.floor(n/36e5)}h ago`:n<6048e5?`${Math.floor(n/864e5)}d ago`:e.toLocaleDateString()}function Vs(t){return/^[A-Z]:[/\\]|^\//.test(t)}function DT(t){const e=t.replace(/\\/g,"/").split("/");return e.length>=2?e[e.length-2]:""}function T$(t){const e=new Date(t),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()),s=new Date(r.getTime()-864e5),i=new Date(e.getFullYear(),e.getMonth(),e.getDate());return i.getTime()===r.getTime()?"Today":i.getTime()===s.getTime()?"Yesterday":n.getTime()-i.getTime()<6048e5?e.toLocaleDateString(void 0,{weekday:"long"}):e.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function j$(t,e){const[n,r]=y.useState([]),[s,i]=y.useState([]),o=y.useRef(null),c=y.useRef(new Set),d=y.useCallback(g=>{c.current.add(g)},[]),f=y.useMemo(()=>{const g=new Set;for(const v of s)v.workspace&&Ll(v.workspace.root,g);return g},[s]),h=y.useCallback(()=>{fetch("/api/documents").then(g=>g.json()).then(g=>{if(!Array.isArray(g))return;const v=c.current;if(v.size>0){const k=new Set(g.map(w=>w.filename));for(const w of[...v])k.has(w)||v.delete(w)}const x=v.size>0?g.filter(k=>!v.has(k.filename)):g;r(x)}).catch(()=>{})},[]),m=y.useCallback(()=>{fetch("/api/workspaces").then(g=>g.json()).then(async g=>{if(!Array.isArray(g))return;const v=await Promise.all(g.map(async x=>{try{const w=await(await fetch(`/api/workspaces/${encodeURIComponent(x.filename)}`)).json();return{...x,workspace:w}}catch{return x}}));i(v)}).catch(()=>{})},[]);return y.useEffect(()=>{h()},[h,t]),y.useEffect(()=>{m()},[m,e]),{docs:n,setDocs:r,workspaces:s,setWorkspaces:i,assignedFiles:f,fetchDocs:h,fetchWorkspaces:m,scrollRef:o,markPendingDelete:d}}function Zg(t,e){return t.filter(n=>!e(n)).map(n=>n.type==="container"?{...n,items:Zg(n.items,e)}:n)}function PT(t,e,n){return t.map(r=>r.type==="container"&&r.id===e?{...r,name:n}:r.type==="container"?{...r,items:PT(r.items,e,n)}:r)}function M$(t,e,n,r,s,i){const o=y.useCallback(_=>{n(R=>R.filter(L=>L.filename!==_)),i==null||i(_),fetch(`/api/documents/${encodeURIComponent(_)}`,{method:"DELETE"}).catch(()=>t())},[n,t]),c=y.useCallback(_=>{n(R=>R.filter(L=>L.filename!==_)),fetch(`/api/documents/${encodeURIComponent(_)}/archive`,{method:"POST"}).catch(()=>t())},[n,t]),d=y.useCallback(_=>{n(R=>R.filter(L=>L.filename!==_)),fetch(`/api/documents/${encodeURIComponent(_)}/unarchive`,{method:"POST"}).catch(()=>t())},[n,t]),f=y.useCallback((_,R,L)=>{!L.trim()||L.trim()===R||(n($=>$.map(B=>B.filename===_?{...B,title:L.trim()}:B)),fetch(`/api/documents/${encodeURIComponent(_)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:L.trim()})}).catch(()=>t()))},[n,t]),h=y.useCallback(_=>{r(R=>R.filter(L=>L.filename!==_)),fetch(`/api/workspaces/${encodeURIComponent(_)}`,{method:"DELETE"}).catch(()=>e())},[r,e]),m=y.useCallback((_,R)=>{R.trim()&&(r(L=>L.map($=>$.filename===_?{...$,title:R.trim()}:$)),fetch(`/api/workspaces/${encodeURIComponent(_)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:R.trim()})}).catch(()=>e()))},[r,e]),g=y.useCallback((_,R)=>{r(L=>L.map($=>$.filename!==_||!$.workspace?$:{...$,docCount:Math.max(0,$.docCount-1),workspace:{...$.workspace,root:Zg($.workspace.root,B=>B.type==="doc"&&B.file===R)}})),fetch(`/api/workspaces/${encodeURIComponent(_)}/docs/${encodeURIComponent(R)}`,{method:"DELETE"}).catch(()=>e())},[r,e]),v=y.useCallback((_,R,L=!1)=>{r(B=>B.map(U=>U.filename!==_||!U.workspace?U:{...U,workspace:{...U.workspace,root:Zg(U.workspace.root,X=>X.type==="container"&&X.id===R)}}));const $=`/api/workspaces/${encodeURIComponent(_)}/containers/${encodeURIComponent(R)}${L?"?cascade=true":""}`;fetch($,{method:"DELETE"}).then(()=>{L&&t()}).catch(()=>e())},[r,e,t]),x=y.useCallback((_,R,L)=>{L.trim()&&(r($=>$.map(B=>B.filename!==_||!B.workspace?B:{...B,workspace:{...B.workspace,root:PT(B.workspace.root,R,L.trim())}})),fetch(`/api/workspaces/${encodeURIComponent(_)}/containers/${encodeURIComponent(R)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L.trim()})}).catch(()=>e()))},[r,e]),k=y.useCallback(()=>{fetch("/api/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:"Untitled Workspace"})}).catch(()=>{})},[]),w=y.useCallback((_,R,L)=>{fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L?{metadata:L}:{})}).then($=>$.json()).then($=>{if($.filename)return fetch(`/api/workspaces/${encodeURIComponent(_)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:$.filename,title:$.title||"Untitled",containerId:R})})}).catch(()=>{})},[]),S=y.useCallback((_,R)=>{fetch(`/api/workspaces/${encodeURIComponent(_)}/containers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:"Untitled",parentContainerId:R})}).catch(()=>{})},[]),N=y.useCallback(_=>{const R=s.find(L=>L.filename===_);return(R==null?void 0:R.tags)??[]},[s]),j=y.useCallback((_,R)=>{const L=R.trim();L&&(n($=>$.map(B=>{if(B.filename!==_)return B;const U=B.tags??[];return U.includes(L)?B:{...B,tags:[...U,L]}})),fetch(`/api/doc-tags/${encodeURIComponent(_)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag:L})}).catch(()=>{}))},[n]),M=y.useCallback((_,R)=>{n(L=>L.map($=>{if($.filename!==_)return $;const B=$.tags??[],U=B.filter(X=>X!==R);return U.length===B.length?$:U.length>0?{...$,tags:U}:{...$,tags:void 0}})),fetch(`/api/doc-tags/${encodeURIComponent(_)}/${encodeURIComponent(R)}`,{method:"DELETE"}).catch(()=>{})},[n]);return{fetchDocs:t,handleDelete:o,handleArchive:c,handleUnarchive:d,handleRename:f,handleCreateWorkspace:k,handleDeleteWorkspace:h,handleCreateInWorkspace:w,handleRemoveFromWorkspace:g,handleCreateContainer:S,handleDeleteContainer:v,handleRenameContainer:x,handleRenameWorkspace:m,getDocTags:N,handleAddTag:j,handleRemoveTag:M}}function BT({docs:t,workspaces:e,assignedFiles:n,scrollRef:r,setCollapsedSections:s}){const[i,o]=y.useState(null),[c,d]=y.useState(null),f=y.useRef(null),h=y.useRef(null),m=y.useRef(null),g=y.useRef(null),v=y.useRef(null),x=5,k=(U,X,z)=>z==="before"?X>0?Su(U[X-1]):null:Su(U[X]),w=y.useCallback((U,X)=>{if(X===null){const P=t.filter(G=>!n.has(G.filename)).map(G=>({type:"doc",file:G.filename,title:G.title})),F=P.findIndex(G=>Su(G)===U);return F>=0?{siblings:P,index:F,containerId:null}:null}const z=e.find(P=>P.filename===X);if(!(z!=null&&z.workspace))return null;const ee=(P,F)=>{for(let G=0;G<P.length;G++){if(Su(P[G])===U)return{siblings:P,index:G,containerId:F};if(P[G].type==="container"){const ie=ee(P[G].items,P[G].id);if(ie)return ie}}return null};return ee(z.workspace.root,null)},[t,n,e]),S=y.useCallback(()=>{o(null),d(null),v.current=null,g.current=null,m.current&&(m.current.remove(),m.current=null),f.current&&(clearTimeout(f.current),f.current=null),h.current&&(cancelAnimationFrame(h.current),h.current=null),document.body.style.userSelect=""},[]),N=y.useCallback((U,X)=>{if(!U||!X)return;if(U.type==="workspace"){const K=X.itemId;if(K===U.filename)return;const ce=e.map(D=>D.filename),J=ce.indexOf(U.filename);if(J<0)return;ce.splice(J,1);let A=ce.indexOf(K);if(A<0)return;X.position==="after"&&(A+=1),ce.splice(A,0,U.filename),fetch("/api/workspaces/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:ce})}).catch(()=>{});return}const{wsFilename:z,containerId:ee,afterId:P}=X,F=U.type==="doc"?U.file:U.id,G=U.sourceWs;if(X.itemId===F)return;if(U.type==="container"){if(z===null&&ee===null&&X.itemId!=="__section__"){const K=X.itemId,ce=X.position==="after"?K:(()=>{const J=e.findIndex(A=>A.filename===K);return J>0?e[J-1].filename:null})();fetch("/api/workspaces/promote-container",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:G,containerId:F,afterWorkspaceFilename:ce})}).catch(()=>{});return}if(G!==z&&z){fetch(`/api/workspaces/${encodeURIComponent(z)}/containers/${encodeURIComponent(F)}/cross-move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:G,targetContainerId:ee??null,afterIdentifier:P})}).catch(()=>{});return}if(!z)return;fetch(`/api/workspaces/${encodeURIComponent(z)}/docs/${encodeURIComponent(F)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:ee??null,afterFile:P})}).catch(()=>{});return}const ie=U.file;if(G===null&&z===null){const K=t.filter(q=>!n.has(q.filename)).map(q=>q.filename),ce=K.indexOf(ie);if(ce<0)return;K.splice(ce,1);let J=P?K.indexOf(P):-1;J>=0?J+=1:J=0,K.splice(J,0,ie);const A=[];let D=0;for(const q of t)n.has(q.filename)?A.push(q.filename):A.push(K[D++]);fetch("/api/documents/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:A})}).catch(()=>{});return}if(G===null&&z!==null){fetch(`/api/workspaces/${encodeURIComponent(z)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:ie,title:ie.replace(/\.md$/,""),containerId:ee??null,afterFile:P})}).catch(()=>{});return}if(G!==null&&z===null){fetch(`/api/workspaces/${encodeURIComponent(G)}/docs/${encodeURIComponent(ie)}`,{method:"DELETE"}).catch(()=>{});return}if(G===z&&z!==null){fetch(`/api/workspaces/${encodeURIComponent(z)}/docs/${encodeURIComponent(ie)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:ee??null,afterFile:P})}).catch(()=>{});return}G!==null&&z!==null&&fetch(`/api/workspaces/${encodeURIComponent(z)}/docs/${encodeURIComponent(ie)}/cross-move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:G,containerId:ee??null,afterFile:P,title:ie.replace(/\.md$/,"")})}).catch(()=>{})},[e,t,n]),j=y.useCallback((U,X)=>{const z=m.current;z&&(z.style.display="none");const ee=document.elementFromPoint(U,X);if(z&&(z.style.display=""),!ee)return null;if((i==null?void 0:i.type)==="workspace"||(i==null?void 0:i.type)==="container"){const q=ee.closest("[data-ws-drag]");if(q){const le=q.dataset.wsDrag,ye=q.getBoundingClientRect(),oe=(X-ye.top)/ye.height;return{itemId:le,position:oe<.5?"before":"after",wsFilename:null,containerId:null,afterId:null}}if((i==null?void 0:i.type)==="workspace")return null}if((i==null?void 0:i.type)==="doc"){const q=ee.closest("[data-ws-drag]");if(q)return{itemId:"__section__",position:"inside",wsFilename:q.dataset.wsDrag,containerId:null,afterId:null}}const P=ee.closest("[data-drag-id]");if(!P){const q=ee.closest("[data-drop-ws]");return q?{itemId:"__section__",position:"inside",wsFilename:q.dataset.dropWs==="__docs__"?null:q.dataset.dropWs,containerId:q.dataset.dropContainer||null,afterId:null}:null}const F=P.dataset.dragId,G=P.dataset.dragType,ie=P.dataset.dragWs==="__docs__"?null:P.dataset.dragWs,K=P.getBoundingClientRect(),ce=(X-K.top)/K.height;if(G==="container-header"){const q=F,le=P.dataset.dragParent||null,ye=w(q,ie);if(!ye)return null;const oe=(i==null?void 0:i.type)==="container"?.33:.25;return ce<oe?{itemId:q,position:"before",wsFilename:ie,containerId:le,afterId:k(ye.siblings,ye.index,"before")}:ce>1-oe?{itemId:q,position:"after",wsFilename:ie,containerId:le,afterId:k(ye.siblings,ye.index,"after")}:{itemId:q,position:"inside",wsFilename:ie,containerId:q,afterId:null}}const J=P.dataset.dragContainer||null,A=w(F,ie);if(!A)return null;const D=ce<.5?"before":"after";return{itemId:F,position:D,wsFilename:ie,containerId:J,afterId:k(A.siblings,A.index,D)}},[w,i]),M=y.useCallback(U=>{const X=r.current;if(!X)return;const z=X.getBoundingClientRect(),ee=80,P=18;let F=0;if(U<z.top+ee?F=-P*Math.max(0,1-(U-z.top)/ee):U>z.bottom-ee&&(F=P*Math.max(0,1-(z.bottom-U)/ee)),h.current&&(cancelAnimationFrame(h.current),h.current=null),F!==0){const G=()=>{X.scrollTop+=F,h.current=requestAnimationFrame(G)};h.current=requestAnimationFrame(G)}},[r]),_=y.useCallback((U,X)=>{const z=m.current;z&&(z.style.display="none");const ee=document.elementFromPoint(U,X);z&&(z.style.display="");const P=ee==null?void 0:ee.closest("[data-section-key]");if(!P){f.current&&(clearTimeout(f.current),f.current=null);return}const F=P.dataset.sectionKey;f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{s(G=>{if(!G.has(F))return G;const ie=new Set(G);return ie.delete(F),ie})},500)},[s]);y.useEffect(()=>{if(!i)return;const U=z=>{m.current&&(m.current.style.left=`${z.clientX+12}px`,m.current.style.top=`${z.clientY-8}px`),d(j(z.clientX,z.clientY)),M(z.clientY),_(z.clientX,z.clientY)},X=z=>{N(i,j(z.clientX,z.clientY)),S()};return window.addEventListener("pointermove",U),window.addEventListener("pointerup",X),()=>{window.removeEventListener("pointermove",U),window.removeEventListener("pointerup",X)}},[i,j,N,S,M,_]);const R=y.useCallback((U,X,z)=>{if(U.button!==0||U.target.closest("input, button, .sidebar-tag-remove, .sidebar-tag-add, .sidebar-container-actions, .sidebar-delete-btn, .sidebar-confirm-delete, .sidebar-inline-confirm"))return;g.current={x:U.clientX,y:U.clientY},v.current=X;const P=G=>{if(!g.current||!v.current)return;const ie=G.clientX-g.current.x,K=G.clientY-g.current.y;if(Math.abs(ie)+Math.abs(K)>=x){document.body.style.userSelect="none",window.removeEventListener("pointermove",P),window.removeEventListener("pointerup",F),o(v.current),v.current=null;const ce=document.createElement("div");ce.style.cssText="position:fixed;pointer-events:none;z-index:9999;padding:4px 10px;background:var(--bg-surface, white);border:1px solid var(--border, #cbd5e1);border-radius:6px;font-size:12px;box-shadow:0 2px 8px rgba(0,0,0,0.12);max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ink-dark, #334155);",ce.textContent=z,document.body.appendChild(ce),m.current=ce,ce.style.left=`${G.clientX+12}px`,ce.style.top=`${G.clientY-8}px`}},F=()=>{window.removeEventListener("pointermove",P),window.removeEventListener("pointerup",F),g.current=null,v.current=null,document.body.style.userSelect=""};window.addEventListener("pointermove",P),window.addEventListener("pointerup",F)},[]);return{draggedItem:i,dropIndicator:c,handlePointerDown:R,dropClass:U=>!c||c.itemId!==U?"":c.position==="before"?"drop-before":c.position==="after"?"drop-after":c.position==="inside"?"drop-inside":"",isDragging:U=>i?i.type==="doc"?i.file===U:i.type==="workspace"?i.filename===U:i.id===U:!1,isContainerDropTarget:U=>!c||!i?!1:c.containerId===U}}function Wl(t,e,n,r){var h;const s=y.useRef(e);s.current=e;const i=y.useRef(r);i.current=r;const o=y.useRef(null),c=y.useRef(null),d=y.useCallback(m=>{var v,x;const g=m||((v=s.current.find(k=>k.isActive))==null?void 0:v.filename);g&&((x=i.current)==null||x.call(i,g),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{const k=t.current;if(!k)return;const w=k.querySelector(`[data-drag-id="${CSS.escape(g)}"]`)||k.querySelector(".active");if(!w||w.offsetParent===null)return;const S=o.current===g,N=w.getBoundingClientRect(),j=k.getBoundingClientRect(),M=N.top<j.top||N.bottom>j.bottom;if(S||M){const _=N.top-j.top-(j.height/2-N.height/2);k.scrollTop+=_}S&&(o.current=null,w.classList.remove("reveal-pulse"),w.offsetWidth,w.classList.add("reveal-pulse"),setTimeout(()=>w.classList.remove("reveal-pulse"),1200))},60))},[t]),f=(h=e.find(m=>m.isActive))==null?void 0:h.filename;y.useEffect(()=>{d(f)},[f,n,d]),y.useEffect(()=>{const m=g=>{var x,k;const v=((x=g.detail)==null?void 0:x.filename)||((k=s.current.find(w=>w.isActive))==null?void 0:k.filename);v&&(o.current=v,d(v))};return window.addEventListener("ow-reveal-active-doc",m),()=>window.removeEventListener("ow-reveal-active-doc",m)},[d]),y.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[])}const A$=[{key:"document",label:"Document"},{key:"tweet",label:"Tweet"},{key:"article",label:"Article"},{key:"linkedin",label:"LinkedIn"},{key:"newsletter",label:"Newsletter"},{key:"blog",label:"Blog"}];function R$({onPick:t}){const[e,n]=y.useState(!1),r=y.useRef(null),s=y.useRef(null),[i,o]=y.useState({});return y.useLayoutEffect(()=>{if(!e||!r.current||!s.current)return;const c=s.current.getBoundingClientRect(),d=r.current.getBoundingClientRect(),f=8;let h=c.right-4,m=c.top-4;h+d.width+f>window.innerWidth&&(h=c.left-d.width+4),m+d.height+f>window.innerHeight&&(m=window.innerHeight-d.height-f),m<f&&(m=f),o({position:"fixed",left:h,top:m})},[e]),l.jsxs("span",{onMouseLeave:()=>n(!1),children:[l.jsx("div",{className:"context-menu-divider"}),l.jsxs("button",{ref:s,className:"context-menu-item context-menu-submenu-trigger",onMouseEnter:()=>n(!0),onClick:()=>n(c=>!c),children:[l.jsx("span",{children:"Create variant"}),l.jsx("span",{className:"context-menu-submenu-arrow",children:"▸"})]}),e&&l.jsx("div",{ref:r,className:"context-menu context-menu-submenu",style:i,children:A$.map(c=>l.jsx("button",{className:"context-menu-item",onClick:()=>t(c.key),children:l.jsx("span",{children:c.label})},c.key))})]})}function Tk({items:t,onAction:e}){const[n,r]=y.useState(null),s=y.useRef(null),i=y.useRef({}),o=y.useMemo(()=>{const h=new Map;for(const m of t){const g=m.pluginDisplayName||"_ungrouped",v=h.get(g)||[];v.push(m),h.set(g,v)}return h},[t]),[c,d]=y.useState({});y.useLayoutEffect(()=>{const h=n?i.current[n]:null;if(!n||!s.current||!h)return;const m=h.getBoundingClientRect(),g=s.current.getBoundingClientRect(),v=8;let x=m.right-4,k=m.top-4;x+g.width+v>window.innerWidth&&(x=m.left-g.width+4),k+g.height+v>window.innerHeight&&(k=window.innerHeight-g.height-v),k<v&&(k=v),d({position:"fixed",left:x,top:k})},[n]);const f=[];for(const[h,m]of o)if(h!=="_ungrouped"&&m.length>=3)f.push(l.jsxs("span",{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsxs("button",{ref:g=>{i.current[h]=g},className:"context-menu-item context-menu-submenu-trigger",onMouseEnter:()=>r(h),onClick:()=>r(n===h?null:h),children:[l.jsx("span",{children:"Transform"}),l.jsx("span",{className:"context-menu-submenu-arrow",children:"▸"})]}),n===h&&l.jsx("div",{ref:s,className:"context-menu context-menu-submenu",style:c,onMouseLeave:()=>r(null),children:m.map(g=>l.jsx("button",{className:"context-menu-item",onClick:()=>e(g),children:l.jsx("span",{children:g.label})},g.action))})]},`sub-${h}`));else{let g=!0;for(const v of m){const x=g&&h!=="_ungrouped";g=!1,f.push(l.jsxs("span",{children:[x&&l.jsx("div",{className:"context-menu-divider"}),x&&l.jsx("div",{className:"context-menu-section-header",children:h}),l.jsx("button",{className:"context-menu-item",onClick:()=>e(v),children:l.jsx("span",{children:v.label})})]},v.action))}}return l.jsx(l.Fragment,{children:f})}function Bd({x:t,y:e,filename:n,title:r,onClose:s,onDuplicate:i,onCreateVariant:o,onRename:c,onArchive:d,onDelete:f,onPluginAction:h,pluginItems:m,onSchedulePost:g,onPostNow:v,isAlreadyPublished:x,onViewAnalytics:k,viewAnalyticsLabel:w,onMarkSent:S,isAlreadySent:N,isApproved:j,onToggleApprove:M,isAutoAccept:_,onToggleAutoAccept:R,sortState:L,sortProposalLabel:$,sortProposalReasoning:B,onRequestSort:U,onCancelSort:X,onAcceptSortProposal:z,onRejectSortProposal:ee,folderMode:P,onNewDoc:F,onNewContainer:G,onAcceptAll:ie,onRejectAll:K,folderAutoAccept:ce,onToggleFolderAutoAccept:J,folderAutoAcceptLabel:A,onRequestSortAll:D,folderDocCount:q,onDeleteWithDocs:le,bulkCount:ye,onBulkDelete:oe,onBulkRequestSort:Se}){const Ee=y.useRef(null),[Le,Ie]=y.useState(!1),[Ve,Te]=y.useState(!1),[qe,pt]=y.useState({left:t,top:e});y.useLayoutEffect(()=>{const be=Ee.current;if(!be)return;const ht=be.getBoundingClientRect(),xt=8;let St=t,At=e;e+ht.height+xt>window.innerHeight&&(At=e-ht.height),t+ht.width+xt>window.innerWidth&&(St=t-ht.width),At<xt&&(At=xt),St<xt&&(St=xt),pt({left:St,top:At})},[t,e]),y.useEffect(()=>{const be=ht=>{Ee.current&&!Ee.current.contains(ht.target)&&s()};return document.addEventListener("mousedown",be),()=>document.removeEventListener("mousedown",be)},[s]),y.useEffect(()=>{const be=ht=>{ht.key==="Escape"&&s()};return document.addEventListener("keydown",be),()=>document.removeEventListener("keydown",be)},[s]);const ut=y.useCallback(be=>{h(be.action,be),s()},[h,s]);return ye&&ye>1&&oe?l.jsxs("div",{ref:Ee,className:"context-menu",style:{left:qe.left,top:qe.top},children:[l.jsxs("div",{className:"context-menu-section-header",children:[ye," selected"]}),Se&&l.jsx("button",{className:"context-menu-item",onClick:()=>{Se(),s()},children:l.jsxs("span",{children:["Request sort (",ye,")"]})}),Le?l.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:be=>be.stopPropagation(),children:[l.jsxs("span",{children:["Delete ",ye,"?"]}),l.jsx("button",{onClick:()=>{oe(),s()},children:"Yes"}),l.jsx("button",{onClick:()=>Ie(!1),children:"No"})]}):l.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>Ie(!0),children:l.jsxs("span",{children:["Delete (",ye,")"]})})]}):P?l.jsxs("div",{ref:Ee,className:"context-menu",style:{left:qe.left,top:qe.top},children:[l.jsx("button",{className:"context-menu-item",onClick:()=>{c(),s()},children:l.jsx("span",{children:"Rename"})}),F&&l.jsx("button",{className:"context-menu-item",onClick:be=>{F(be),s()},children:l.jsx("span",{children:"New Document"})}),G&&l.jsx("button",{className:"context-menu-item",onClick:()=>{G(),s()},children:l.jsx("span",{children:"New Container"})}),(ie||K)&&l.jsx("div",{className:"context-menu-divider"}),ie&&l.jsx("button",{className:"context-menu-item",onClick:()=>{ie(),s()},children:l.jsx("span",{children:"Accept All Changes"})}),K&&l.jsx("button",{className:"context-menu-item",onClick:()=>{K(),s()},children:l.jsx("span",{children:"Reject All Changes"})}),J&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{J(),s()},children:l.jsx("span",{children:ce?`Turn off auto-accept${A?" "+A:""}`:`Turn on auto-accept${A?" "+A:""}`})})]}),D&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{D(),s()},children:l.jsx("span",{children:"Request sort all"})})]}),m.length>0&&l.jsx(Tk,{items:m,onAction:ut}),l.jsx("div",{className:"context-menu-divider"}),Le?q&&q>0&&le?l.jsxs("div",{className:"sidebar-ctx-folder-delete",onClick:be=>be.stopPropagation(),children:[l.jsx("div",{className:"sidebar-ctx-folder-delete-prompt",children:"Delete this folder?"}),l.jsxs("button",{className:"context-menu-item sidebar-ctx-delete-option",onClick:()=>{f(),s()},children:[l.jsx("span",{children:"Folder only"}),l.jsxs("span",{className:"sidebar-ctx-delete-hint",children:[q," doc",q===1?"":"s"," → Documents"]})]}),l.jsxs("button",{className:"context-menu-item sidebar-ctx-delete-option sidebar-ctx-delete",onClick:()=>{le(),s()},children:[l.jsxs("span",{children:["Folder + ",q," doc",q===1?"":"s"]}),l.jsx("span",{className:"sidebar-ctx-delete-hint",children:"permanently deletes files"})]}),l.jsx("button",{className:"context-menu-item sidebar-ctx-delete-cancel",onClick:()=>Ie(!1),children:l.jsx("span",{children:"Cancel"})})]}):l.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:be=>be.stopPropagation(),children:[l.jsx("span",{children:"Delete?"}),l.jsx("button",{onClick:()=>{f(),s()},children:"Yes"}),l.jsx("button",{onClick:()=>Ie(!1),children:"No"})]}):l.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>Ie(!0),children:l.jsx("span",{children:"Delete"})})]}):l.jsxs("div",{ref:Ee,className:"context-menu",style:{left:qe.left,top:qe.top},children:[l.jsx("button",{className:"context-menu-item",onClick:()=>{i(),s()},children:l.jsx("span",{children:"Duplicate"})}),o&&l.jsx(R$,{onPick:be=>{o(be),s()}}),l.jsx("button",{className:"context-menu-item",onClick:()=>{c(),s()},children:l.jsx("span",{children:"Rename"})}),Ve?l.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:be=>be.stopPropagation(),children:[l.jsx("span",{children:"Archive?"}),l.jsx("button",{onClick:()=>{d(),s()},children:"Yes"}),l.jsx("button",{onClick:()=>Te(!1),children:"No"})]}):l.jsx("button",{className:"context-menu-item",onClick:()=>Te(!0),children:l.jsx("span",{children:"Archive"})}),Le?l.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:be=>be.stopPropagation(),children:[l.jsx("span",{children:Vs(n)?"Remove?":"Delete?"}),l.jsx("button",{onClick:()=>{f(),s()},children:"Yes"}),l.jsx("button",{onClick:()=>Ie(!1),children:"No"})]}):l.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>Ie(!0),children:l.jsx("span",{children:Vs(n)?"Remove":"Delete"})}),M&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{M(),s()},children:l.jsx("span",{children:j?"Remove Approval":"Approve"})})]}),R&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{R(),s()},children:l.jsx("span",{children:_?"Turn off auto-accept":"Turn on auto-accept"})})]}),L==="proposal"&&z&&ee&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsxs("div",{className:"sidebar-ctx-sort-proposal",onClick:be=>be.stopPropagation(),children:[l.jsxs("div",{className:"sidebar-ctx-sort-proposal-label",children:["Sort to ",$]}),B&&l.jsx("div",{className:"sidebar-ctx-sort-proposal-reason",children:B}),l.jsxs("div",{className:"sidebar-ctx-sort-proposal-actions",children:[l.jsx("button",{onClick:()=>{z(),s()},children:"Accept"}),l.jsx("button",{onClick:()=>{ee(),s()},children:"Reject"})]})]})]}),L==="pending"&&X&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsxs("div",{className:"sidebar-ctx-sort-pending",onClick:be=>be.stopPropagation(),children:[l.jsx("span",{className:"sidebar-ctx-sort-pending-label",children:"Sort requested"}),l.jsx("button",{onClick:()=>{X(),s()},children:"Cancel"})]})]}),L==="none"&&U&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{U(),s()},children:l.jsx("span",{children:"Request sort"})})]}),g&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{g(),s()},children:l.jsx("span",{children:"Schedule Post"})})]}),v&&l.jsx("button",{className:"context-menu-item",onClick:()=>{v(),s()},children:l.jsx("span",{children:x?"Republish to Blog":"Post to Blog Now"})}),S&&!N&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{S(),s()},children:l.jsx("span",{children:"Mark as Sent"})})]}),k&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"context-menu-divider"}),l.jsx("button",{className:"context-menu-item",onClick:()=>{k(),s()},children:l.jsx("span",{children:w||"View Analytics"})})]}),m.length>0&&l.jsx(Tk,{items:m,onAction:ut})]})}const jk=5e3;function $T(t,e){return!t.promptForFocus||!e?!1:e.wordCount>jk?(Ai(`Document too large to transform: ${e.wordCount.toLocaleString()} words (max ${jk.toLocaleString()}). Trim it down first.`,"error"),!0):!1}function FT({actionLabel:t,docTitle:e,onConfirm:n,onClose:r}){const[s,i]=y.useState(""),o=y.useRef(null);y.useEffect(()=>{var d;(d=o.current)==null||d.focus()},[]),y.useEffect(()=>{const d=f=>{f.key==="Escape"&&r()};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const c=y.useCallback(()=>{n(s.trim())},[s,n]);return l.jsx("div",{className:"focus-modal-overlay",onClick:r,children:l.jsxs("div",{className:"focus-modal",onClick:d=>d.stopPropagation(),children:[l.jsxs("div",{className:"focus-modal-header",children:[l.jsx("h2",{children:t}),l.jsx("button",{className:"focus-modal-close",onClick:r,children:"×"})]}),l.jsxs("div",{className:"focus-modal-body",children:[l.jsxs("label",{children:['Focus instructions for "',e,'"',l.jsx("textarea",{ref:o,value:s,onChange:d=>i(d.target.value.slice(0,500)),placeholder:"Optional: guide the transformation (e.g. 'focus on the intro section', 'keep it professional')...",onKeyDown:d=>{d.key==="Enter"&&(d.ctrlKey||d.metaKey)&&c()}})]}),l.jsxs("div",{className:"focus-modal-hint",children:[s.length,"/500"]}),l.jsxs("div",{className:"focus-modal-actions",children:[l.jsx("button",{className:"focus-modal-btn secondary",onClick:r,children:"Cancel"}),l.jsx("button",{className:"focus-modal-btn primary",onClick:c,children:"Go"})]})]})]})})}function Ip(t,e){if(!e)return[t];const n=[],r=t.toLowerCase(),s=e.toLowerCase();let i=0;for(;i<t.length;){const o=r.indexOf(s,i);if(o===-1){n.push(t.slice(i));break}o>i&&n.push(t.slice(i,o)),n.push(l.jsx("mark",{children:t.slice(o,o+e.length)},o)),i=o+e.length}return n}function Mk({r:t,query:e,onClick:n}){return l.jsxs("div",{className:`sidebar-item search-result-item ${t.isActive?"active":""} ${t.isArchived?"search-result-archived":""}`,onClick:n,children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-item-title-text",children:t.matchType==="title"?Ip(t.title,e):t.title}),t.isArchived&&l.jsx("span",{className:"search-archived-badge",children:"archived"})]}),t.matchType==="tag"&&t.matchedTag&&l.jsxs("div",{className:"search-result-tag",children:["Tag: ",Ip(t.matchedTag,e)]}),t.matchType==="content"&&t.snippet&&l.jsx("div",{className:"search-result-snippet",children:Ip(t.snippet,e)}),l.jsxs("div",{className:"sidebar-item-meta",children:[t.wordCount.toLocaleString()," words · ",ba(t.lastModified)]})]})}function rf({results:t,query:e,onSwitchDocument:n,actions:r}){if(t.length===0)return l.jsx("div",{className:"sidebar-scroll",children:l.jsxs("div",{className:"search-empty",children:['No results for "',e,'"']})});const s=t.filter(o=>!o.isArchived),i=t.filter(o=>o.isArchived);return l.jsx("div",{className:"sidebar-scroll",children:l.jsxs("div",{className:"search-results",children:[s.map(o=>l.jsx(Mk,{r:o,query:e,onClick:()=>n(o.filename)},o.filename)),i.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"search-archived-divider",children:l.jsx("span",{children:"Archived"})}),i.map(o=>l.jsx(Mk,{r:o,query:e,onClick:()=>r.handleUnarchive(o.filename)},o.filename))]})]})})}async function Lp(t,e={}){var s,i;const r=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:t,arguments:e})})).json();return(i=(s=r.content)==null?void 0:s[0])!=null&&i.text?JSON.parse(r.content[0].text):r}function Dp(t,e){return e?(t/e*100).toFixed(1)+"%":"0%"}function Ak(t){return new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function Rk(t,e=50){try{const n=new URL(t),r=n.hostname+n.pathname+n.search;return r.length>e?r.slice(0,e)+"...":r}catch{return t.length>e?t.slice(0,e)+"...":t}}function zT({docId:t,title:e,onClose:n}){const[r,s]=y.useState("loading"),[i,o]=y.useState([]),[c,d]=y.useState(""),[f,h]=y.useState(null),[m,g]=y.useState(null),[v,x]=y.useState("links"),[k,w]=y.useState("all"),[S,N]=y.useState(!1),[j,M]=y.useState(!1),[_,R]=y.useState(""),[L,$]=y.useState(!1),[B,U]=y.useState(null),X=y.useRef(null);y.useEffect(()=>{let oe=!1;return(async()=>{try{const Se=await Lp("list_newsletter_issues",{limit:20});if(oe)return;if(!Se.issues||Se.issues.length===0){s("no-data");return}o(Se.issues);const Ee=Se.issues[0].id;d(Ee)}catch(Se){oe||(g(Se.message),s("error"))}})(),()=>{oe=!0}},[]),y.useEffect(()=>{if(!c)return;let oe=!1;return N(!0),M(!1),U(null),R(""),(async()=>{try{const Se=await Lp("get_newsletter_analytics",{issue_id:c});if(oe)return;if(Se.error){g(Se.error),s("error");return}h(Se),s("loaded")}catch(Se){oe||(g(Se.message),s("error"))}finally{oe||N(!1)}})(),()=>{oe=!0}},[c]),y.useEffect(()=>{const oe=Se=>{X.current&&!X.current.contains(Se.target)&&n()};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[n]),y.useEffect(()=>{const oe=Se=>{Se.key==="Escape"&&n()};return document.addEventListener("keydown",oe),()=>document.removeEventListener("keydown",oe)},[n]);const z=f?I$(f.subscriber_events):[],ee=(f==null?void 0:f.issue.recipient_count)??0,P=f?f.stats.delivered||ee-f.stats.bounces:0,F=f?new Set(f.subscriber_events.filter(oe=>{var Se;return oe.event_type==="click"&&((Se=oe.url)==null?void 0:Se.includes("/newsletter/unsubscribe/"))}).map(oe=>oe.email)).size:0,G=f?f.stats.unsubscribes||F:0,ie=f?f.subscriber_events.filter(oe=>oe.event_type==="dropped").length:0,K=f?Math.max(0,ee-f.stats.unique_opens):0,ce=f!=null&&f.issue.sent_at?Date.now()-new Date(f.issue.sent_at).getTime():0,J=Math.floor(ce/36e5),A=!!(f!=null&&f.issue.resent_at||B),D=oe=>{const Se=Math.floor(oe/36e5);return Se<1?"just now":Se<24?`${Se}h ago`:`${Math.floor(Se/24)}d ${Se%24}h ago`},q=async()=>{if(!(!_.trim()||L)){$(!0);try{const oe=await Lp("resend_to_unopened",{issue_id:c,subject:_});oe.error?(g(oe.error),s("error")):(U({sent:oe.sent,failed:oe.failed}),M(!1))}catch(oe){g(oe.message),s("error")}finally{$(!1)}}},le=oe=>{var Se;return oe.event_type==="unsubscribe"||oe.event_type==="click"&&!!((Se=oe.url)!=null&&Se.includes("/newsletter/unsubscribe/"))},ye=f?O$(f.subscriber_events.filter(oe=>k==="all"?!0:k==="unsubscribe"?le(oe):oe.event_type===k)):[];return l.jsx("div",{className:"newsletter-modal-overlay",children:l.jsxs("div",{className:"na-modal",ref:X,children:[l.jsxs("div",{className:"na-header",children:[l.jsx("h3",{children:"Newsletter Analytics"}),l.jsx("button",{className:"newsletter-modal__close",onClick:n,children:"×"})]}),r==="loading"&&!f&&l.jsx("div",{className:"na-body",children:l.jsxs("div",{className:"newsletter-modal__status",children:[l.jsx("div",{className:"newsletter-modal__spinner"}),l.jsx("span",{children:"Loading analytics..."})]})}),r==="no-data"&&l.jsxs("div",{className:"na-body",children:[l.jsx("div",{className:"newsletter-modal__status",children:l.jsx("span",{children:"No newsletter sends found yet."})}),l.jsx("div",{className:"newsletter-modal__actions",children:l.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:n,children:"Done"})})]}),r==="error"&&l.jsxs("div",{className:"na-body",children:[l.jsx("div",{className:"newsletter-modal__error",children:m}),l.jsx("div",{className:"newsletter-modal__actions",children:l.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:n,children:"Done"})})]}),r==="loaded"&&f&&l.jsxs("div",{className:"na-body",children:[i.length>1&&l.jsx("select",{className:"newsletter-modal__select na-issue-select",value:c,onChange:oe=>d(oe.target.value),children:i.map(oe=>l.jsxs("option",{value:oe.id,children:[oe.subject," — ",Ak(oe.sent_at)]},oe.id))}),S?l.jsxs("div",{className:"newsletter-modal__status",children:[l.jsx("div",{className:"newsletter-modal__spinner"}),l.jsx("span",{children:"Loading..."})]}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"na-kpi-row",children:[l.jsxs("div",{className:"na-kpi",children:[l.jsx("div",{className:"na-kpi__value",children:P.toLocaleString()}),l.jsx("div",{className:"na-kpi__label",children:"Delivered"}),l.jsxs("div",{className:"na-kpi__sub",children:[ee.toLocaleString()," sent"]})]}),l.jsxs("div",{className:"na-kpi",children:[l.jsx("div",{className:"na-kpi__value",children:Dp(f.stats.unique_opens,P)}),l.jsx("div",{className:"na-kpi__label",children:"Open rate"}),l.jsxs("div",{className:"na-kpi__sub",children:[f.stats.unique_opens.toLocaleString()," opens"]})]}),l.jsxs("div",{className:"na-kpi",children:[l.jsx("div",{className:"na-kpi__value",children:Dp(f.stats.unique_clicks,P)}),l.jsx("div",{className:"na-kpi__label",children:"Click rate"}),l.jsxs("div",{className:"na-kpi__sub",children:[f.stats.unique_clicks.toLocaleString()," clicks"]})]})]}),l.jsxs("div",{className:"na-kpi-row na-kpi-row--secondary",children:[l.jsxs("div",{className:"na-kpi na-kpi--sm",children:[l.jsx("span",{className:"na-kpi__value--sm",children:f.stats.bounces}),l.jsx("span",{className:"na-kpi__label--sm",children:"Bounces"})]}),l.jsxs("div",{className:"na-kpi na-kpi--sm",children:[l.jsx("span",{className:"na-kpi__value--sm",children:G}),l.jsx("span",{className:"na-kpi__label--sm",children:"Unsubs"})]}),l.jsxs("div",{className:"na-kpi na-kpi--sm",children:[l.jsx("span",{className:"na-kpi__value--sm",children:ie}),l.jsx("span",{className:"na-kpi__label--sm",children:"Dropped"})]}),f.stats.complaints>0&&l.jsxs("div",{className:"na-kpi na-kpi--sm",children:[l.jsx("span",{className:"na-kpi__value--sm",children:f.stats.complaints}),l.jsx("span",{className:"na-kpi__label--sm",children:"Spam"})]})]}),K>0&&!A&&l.jsx("div",{className:"na-resend",children:j?l.jsxs("div",{className:"na-resend-panel",children:[l.jsxs("div",{className:"na-resend-label-row",children:[l.jsx("span",{className:"na-resend-label",children:"New subject line"}),l.jsxs("span",{className:"na-resend-meta",children:["sent ",D(ce),J<48?" · consider waiting 48h":""]})]}),l.jsx("input",{className:"na-resend-input",type:"text",value:_,onChange:oe=>R(oe.target.value),placeholder:"Try a different angle"}),l.jsxs("div",{className:"na-resend-actions",children:[l.jsx("button",{className:"na-resend-cancel",onClick:()=>M(!1),children:"Cancel"}),l.jsx("button",{className:"na-resend-send",onClick:q,disabled:L||!_.trim(),children:L?"Sending...":`Send to ${K.toLocaleString()}`})]})]}):l.jsxs("button",{className:"na-resend-toggle",onClick:()=>{M(!0),R(f.issue.subject)},children:["Resend to ",K.toLocaleString()," non-openers ",l.jsx("span",{style:{float:"right"},children:"›"})]})}),A&&l.jsxs("div",{className:"na-resend-done",children:["Resent ",f.issue.resent_at?D(Date.now()-new Date(f.issue.resent_at).getTime()):"just now",B?` — ${B.sent} sent`:"",f.issue.resend_subject?` — "${f.issue.resend_subject}"`:""]}),l.jsxs("div",{className:"na-tabs",children:[l.jsxs("button",{className:`na-tab${v==="links"?" active":""}`,onClick:()=>x("links"),children:["Links (",z.length,")"]}),l.jsxs("button",{className:`na-tab${v==="activity"?" active":""}`,onClick:()=>x("activity"),children:["Activity (",f.subscriber_events.length,")"]})]}),v==="links"&&l.jsx("div",{className:"na-table-wrap",children:z.length===0?l.jsx("div",{className:"na-empty",children:"No link clicks recorded yet."}):l.jsxs("table",{className:"na-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"Link"}),l.jsx("th",{children:"Unique"}),l.jsx("th",{children:"Total"}),l.jsx("th",{children:"CTR"})]})}),l.jsx("tbody",{children:z.map(oe=>l.jsxs("tr",{children:[l.jsx("td",{className:"na-table__url",title:oe.url,children:l.jsx("a",{href:oe.url,target:"_blank",rel:"noopener noreferrer",children:Rk(oe.url)})}),l.jsx("td",{children:oe.uniqueClicks}),l.jsx("td",{children:oe.totalClicks}),l.jsx("td",{children:Dp(oe.uniqueClicks,P)})]},oe.url))})]})}),v==="activity"&&l.jsxs("div",{className:"na-activity",children:[l.jsx("div",{className:"na-filter-row",children:["all","open","click","bounce","dropped","unsubscribe"].map(oe=>l.jsx("button",{className:`na-filter-btn${k===oe?" active":""}`,onClick:()=>w(oe),children:oe==="all"?"All":oe.charAt(0).toUpperCase()+oe.slice(1)+"s"},oe))}),l.jsxs("div",{className:"na-table-wrap",children:[ye.length===0?l.jsxs("div",{className:"na-empty",children:["No ",k==="all"?"":k+" ","events recorded."]}):l.jsxs("table",{className:"na-table",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"Email"}),l.jsx("th",{children:"Event"}),l.jsx("th",{children:"Detail"}),l.jsx("th",{children:"Time"})]})}),l.jsx("tbody",{children:ye.slice(0,100).map(oe=>l.jsxs("tr",{children:[l.jsx("td",{className:"na-table__email",children:oe.email}),l.jsxs("td",{children:[l.jsx("span",{className:`na-badge na-badge--${oe.event_type}`,children:oe.event_type}),oe.count>1&&l.jsxs("span",{className:"na-count",children:[oe.count,"x"]})]}),l.jsx("td",{className:"na-table__url",children:oe.url?l.jsx("a",{href:oe.url,target:"_blank",rel:"noopener noreferrer",children:Rk(oe.url,35)}):"—"}),l.jsx("td",{className:"na-table__time",children:Ak(oe.latestTimestamp)})]},oe.key))})]}),ye.length>100&&l.jsxs("div",{className:"na-truncated",children:["Showing 100 of ",ye.length," events"]})]})]})]})]})]})})}function O$(t){const e=new Map;for(const n of t){const r=`${n.email}|${n.event_type}|${n.url||""}`,s=e.get(r);s?(s.count++,n.timestamp>s.latestTimestamp&&(s.latestTimestamp=n.timestamp)):e.set(r,{key:r,email:n.email,event_type:n.event_type,url:n.url,latestTimestamp:n.timestamp,count:1})}return Array.from(e.values()).sort((n,r)=>new Date(r.latestTimestamp).getTime()-new Date(n.latestTimestamp).getTime())}function I$(t){const e=t.filter(r=>r.event_type==="click"&&r.url),n=new Map;for(const r of e){const s=r.url;let i=n.get(s);i||(i={emails:new Set,total:0},n.set(s,i)),i.emails.add(r.email),i.total++}return Array.from(n.entries()).map(([r,{emails:s,total:i}])=>({url:r,uniqueClicks:s.size,totalClicks:i})).sort((r,s)=>s.uniqueClicks-r.uniqueClicks)}function L$(t){return t.tweetContext?"tweet":t.articleContext?"article":t.linkedinContext?"linkedin":t.newsletterContext?"newsletter":t.blogContext?"blog":"tweet"}function Vl({filename:t,title:e,onClose:n}){const[r,s]=y.useState("queue"),[i,o]=y.useState(null),[c,d]=y.useState(null),[f,h]=y.useState(""),[m,g]=y.useState(!1),[v,x]=y.useState(null),[k,w]=y.useState(null);y.useEffect(()=>{fetch(`/api/documents/${encodeURIComponent(t)}/text`).then(j=>{if(!j.ok)throw new Error("Failed to load document");return j.json()}).then(j=>{d(j.text||""),o(L$(j.meta||{}))}).catch(j=>w(j.message))},[t]);const S=async()=>{var j;if(!(!c||!i)){g(!0);try{const M={content:c,content_type:i,mode:r};r==="custom"&&f&&(M.scheduled_at=new Date(f).toISOString());const _=await fetch("/api/scheduler/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)}),R=await _.json();if(_.ok){const L=(j=R.item)!=null&&j.scheduled_at?new Date(R.item.scheduled_at).toLocaleString():"now";x({success:!0,message:`Scheduled for ${L}`})}else x({success:!1,message:R.error||"Failed to schedule"})}catch(M){x({success:!1,message:M.message})}finally{g(!1)}}},N=i===null&&!k;return l.jsx("div",{className:"schedule-post-overlay",onClick:n,children:l.jsxs("div",{className:"schedule-post-modal",onClick:j=>j.stopPropagation(),children:[l.jsxs("div",{className:"schedule-post-modal-header",children:[l.jsx("h3",{children:"Schedule Post"}),l.jsx("button",{className:"schedule-post-modal-close",onClick:n,children:"×"})]}),l.jsx("div",{className:"schedule-post-modal-doc",children:e}),k?l.jsxs("div",{className:"schedule-post-modal-result error",children:[k,l.jsx("button",{className:"schedule-post-modal-done",onClick:n,children:"Done"})]}):v?l.jsxs("div",{className:`schedule-post-modal-result ${v.success?"success":"error"}`,children:[v.message,l.jsx("button",{className:"schedule-post-modal-done",onClick:n,children:"Done"})]}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"schedule-post-modal-field",children:[l.jsx("label",{children:"Content Type"}),l.jsx("div",{className:"schedule-post-modal-type",children:N?"...":i})]}),l.jsxs("div",{className:"schedule-post-modal-field",children:[l.jsx("label",{children:"Mode"}),l.jsxs("div",{className:"schedule-post-modal-modes",children:[l.jsx("button",{className:`schedule-post-mode ${r==="queue"?"active":""}`,onClick:()=>s("queue"),children:"Queue Next"}),l.jsx("button",{className:`schedule-post-mode ${r==="now"?"active":""}`,onClick:()=>s("now"),children:"Post Now"}),l.jsx("button",{className:`schedule-post-mode ${r==="custom"?"active":""}`,onClick:()=>s("custom"),children:"Custom Time"})]})]}),r==="custom"&&l.jsxs("div",{className:"schedule-post-modal-field",children:[l.jsx("label",{children:"Date & Time"}),l.jsx("input",{type:"datetime-local",value:f,onChange:j=>h(j.target.value)})]}),l.jsxs("div",{className:"schedule-post-modal-actions",children:[l.jsx("button",{className:"schedule-post-modal-cancel",onClick:n,children:"Cancel"}),l.jsx("button",{className:"schedule-post-modal-submit",onClick:S,disabled:m||N||r==="custom"&&!f,children:m?"Scheduling...":r==="now"?"Post Now":"Schedule"})]})]})]})})}const Ok=[{key:"document",label:"Document"},{key:"tweet",label:"Tweet",metadata:{content_type:"tweet",tweetContext:{mode:"tweet"}}},{key:"reply",label:"Reply",needsUrl:!0,urlPlaceholder:"Paste tweet URL...",metadata:{content_type:"reply",tweetContext:{mode:"reply"}}},{key:"quote",label:"Quote Tweet",needsUrl:!0,urlPlaceholder:"Paste tweet URL...",metadata:{content_type:"quote",tweetContext:{mode:"quote"}}},{key:"article",label:"Article",metadata:{content_type:"article",articleContext:{active:!0}}},{key:"linkedin",label:"LinkedIn",metadata:{content_type:"linkedin",linkedinContext:{active:!0}}},{key:"newsletter",label:"Newsletter",metadata:{content_type:"newsletter",newsletterContext:{active:!0}}},{key:"blog",label:"Blog",metadata:{content_type:"blog",blogContext:{active:!0}}},{key:"manuscript",label:"Manuscript",metadata:{content_type:"manuscript",manuscriptContext:{active:!0}}}];function UT({anchorRect:t,onSelect:e,onClose:n}){const r=y.useRef(null),[s,i]=y.useState(null),[o,c]=y.useState(""),d=y.useRef(null),[f,h]=y.useState({left:t.left,top:t.bottom+4});y.useLayoutEffect(()=>{const x=r.current;if(!x)return;const k=x.getBoundingClientRect(),w=8;let S=t.left,N=t.bottom+4;N+k.height+w>window.innerHeight&&(N=t.top-k.height-4),S+k.width+w>window.innerWidth&&(S=t.right-k.width),N<w&&(N=w),S<w&&(S=w),h({left:S,top:N})},[t]),y.useEffect(()=>{const x=k=>{r.current&&!r.current.contains(k.target)&&n()};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[n]),y.useEffect(()=>{const x=k=>{k.key==="Escape"&&n()};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[n]),y.useEffect(()=>{s&&setTimeout(()=>{var x;return(x=d.current)==null?void 0:x.focus()},0)},[s]);const m=x=>{if(x.needsUrl){i(x.key),c("");return}e(x.metadata)},g=()=>{if(!s||!o.trim())return;const x=o.trim();if(!x.includes("x.com")&&!x.includes("twitter.com"))return;const k=Ok.find(S=>S.key===s);if(!(k!=null&&k.metadata))return;const w=JSON.parse(JSON.stringify(k.metadata));w.tweetContext&&(w.tweetContext.url=x),e(w)},v=o.trim().includes("x.com")||o.trim().includes("twitter.com");return l.jsx("div",{ref:r,className:"create-doc-dropdown",style:{left:f.left,top:f.top},children:Ok.map(x=>l.jsxs("div",{children:[l.jsx("button",{className:`create-doc-dropdown-item${s===x.key?" active":""}`,onClick:()=>m(x),children:x.label}),s===x.key&&l.jsxs("div",{className:"create-doc-dropdown-url",children:[l.jsx("input",{ref:d,type:"text",placeholder:x.urlPlaceholder,value:o,onChange:k=>c(k.target.value),onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),g()),k.key==="Escape"&&(i(null),c(""))}}),l.jsx("button",{onClick:g,disabled:!v,children:l.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"9 18 15 12 9 6"})})})]})]},x.key))})}const D$=[{id:"full",label:"Full"},{id:"compact",label:"Compact"},{id:"minimal",label:"Minimal"}];function ev(t,e){for(const n of t){if(n.type==="doc"&&n.file===e)return[];if(n.type==="container"){const r=ev(n.items,e);if(r)return[n.id,...r]}}return null}function P$({docs:t,archivedDocs:e,workspaces:n,assignedFiles:r,pendingDocs:s,onSwitchDocument:i,onCreateDocument:o,actions:c,scrollRef:d,writingTitle:f,writingTarget:h,pendingWriteFilenames:m,searchQuery:g,searchResults:v,onSearchChange:x}){const k=I=>!!m&&m.has(I),[w,S]=y.useState(null),[N,j]=y.useState(""),[M,_]=y.useState(null),[R,L]=y.useState(()=>{try{const I=localStorage.getItem("ow-collapsed-sections");return I?new Set(JSON.parse(I)):new Set}catch{return new Set}}),[$,B]=y.useState(null),[U,X]=y.useState(null),[z,ee]=y.useState(""),[P,F]=y.useState(null),[G,ie]=y.useState(""),[K,ce]=y.useState(null),[J,A]=y.useState(""),[D,q]=y.useState(null),[le,ye]=y.useState(null),[oe,Se]=y.useState([]),[Ee,Le]=y.useState(!1),[Ie,Ve]=y.useState(null),[Te,qe]=y.useState(null),[pt,ut]=y.useState(null),[be,ht]=y.useState(null),[xt,St]=y.useState(null),[At,Ye]=y.useState(BE),ct=y.useRef(null);y.useEffect(()=>{if(!xt)return;const I=V=>{ct.current&&!ct.current.contains(V.target)&&St(null)};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[xt]);const Fe=I=>{Ye(I),LM(I),St(null)},Y=I=>{I.preventDefault(),St({x:I.clientX,y:I.clientY})},ge=y.useCallback((I,V)=>{fetch("/api/documents/batch-resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filenames:I,action:V})}).catch(()=>{})},[]),{draggedItem:ne,dropIndicator:he,handlePointerDown:me,dropClass:ze,isDragging:Ae,isContainerDropTarget:Xe}=BT({docs:t,workspaces:n,assignedFiles:r,scrollRef:d,setCollapsedSections:L}),Qe=y.useCallback(()=>{fetch("/api/plugins").then(I=>I.json()).then(I=>{const V=[];let re=!1;for(const Q of I.plugins||[]){const ue=Q.displayName||void 0;for(const ve of Q.sidebarMenuItems||[])V.push({...ve,pluginDisplayName:ue});Q.name==="@openwriter/plugin-publish"&&Q.enabled&&(re=!0)}Se(V),Le(re)}).catch(()=>{})},[]);y.useEffect(()=>{Qe()},[Qe]),y.useEffect(()=>{const I=()=>Qe();return window.addEventListener("ow-plugins-changed",I),()=>window.removeEventListener("ow-plugins-changed",I)},[Qe]);const{variantsByMaster:tt,variantFilenames:We}=y.useMemo(()=>{const I=new Map,V=new Set;for(const re of t)if(re.masterDocId){const Q=I.get(re.masterDocId)||[];Q.push(re),I.set(re.masterDocId,Q),V.add(re.filename)}return{variantsByMaster:I,variantFilenames:V}},[t]),Ue=y.useCallback((I,V)=>{I.preventDefault(),I.stopPropagation(),q({x:I.clientX,y:I.clientY,filename:V.filename,title:V.title,docId:V.docId,lastSent:V.lastSent,postedUrl:V.postedUrl,isNewsletter:V.isNewsletter})},[]),st=y.useCallback(I=>{fetch("/api/documents/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:I})}).catch(()=>{})},[]),mt=y.useCallback((I,V,re)=>{fetch("/api/documents/variant",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:I,masterDocId:V,variantType:re})}).catch(()=>{})},[]),Nt=y.useCallback((I,V,re,Q,ue)=>{if(!$T(V,t.find(ve=>ve.filename===re))){if(V.promptForFocus&&ue===void 0){Ve({action:I,label:V.label,filename:re,title:Q});return}fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:I,filename:re,title:Q,instructions:ue||"",label:V.label})}).catch(()=>{})}},[t]),Mt=I=>{L(V=>{const re=new Set(V);return re.has(I)?re.delete(I):re.add(I),localStorage.setItem("ow-collapsed-sections",JSON.stringify([...re])),re})},Jt=y.useRef(n);Jt.current=n;const nn=y.useCallback(I=>{var V;for(const re of Jt.current){const Q=ev(((V=re.workspace)==null?void 0:V.root)||[],I);if(Q){L(ue=>{const ve=[re.filename,...Q.map(xe=>`container-${xe}`)];if(ve.every(xe=>!ue.has(xe)))return ue;const Re=new Set(ue);for(const xe of ve)Re.delete(xe);return localStorage.setItem("ow-collapsed-sections",JSON.stringify([...Re])),Re});break}}},[]);Wl(d,t,n.length,nn);const at=y.useMemo(()=>{var Q;const I=t.find(ue=>ue.isActive);if(!I)return null;const V=I.masterDocId?t.find(ue=>ue.docId===I.masterDocId):void 0,re=(V==null?void 0:V.filename)??I.filename;for(const ue of n){const ve=ev(((Q=ue.workspace)==null?void 0:Q.root)||[],re);if(ve)return{wsFilename:ue.filename,containerKeys:new Set(ve.map(Re=>`container-${Re}`)),masterDocId:(V==null?void 0:V.docId)??null}}return{wsFilename:null,containerKeys:new Set,masterDocId:(V==null?void 0:V.docId)??null}},[t,n]);if(v!==null)return l.jsx(rf,{results:v,query:g,onSwitchDocument:i,actions:c});const Ht=t.filter(I=>!r.has(I.filename)&&!We.has(I.filename)),T=(I,V,re,Q,ue,ve=!1)=>l.jsxs("div",{className:`sidebar-item ${I.isActive?"active":""} ${Ae(I.filename)?"dragging":""} ${ze(I.filename)}`,"data-drag-id":I.filename,"data-drag-type":"doc","data-drag-ws":V||"__docs__","data-drag-container":re||"",onPointerDown:Re=>me(Re,{type:"doc",file:I.filename,sourceWs:V||null},I.title),onClick:()=>!I.isActive&&!ne&&i(I.filename),onDoubleClick:()=>{S(I.filename),j(I.title)},onContextMenu:Re=>Ue(Re,I),children:[w===I.filename?l.jsx("input",{className:"sidebar-rename-input",value:N,onChange:Re=>j(Re.target.value),onBlur:()=>{c.handleRename(I.filename,I.title,N),S(null)},onKeyDown:Re=>{Re.key==="Enter"&&(c.handleRename(I.filename,I.title,N),S(null)),Re.key==="Escape"&&S(null)},autoFocus:!0,onClick:Re=>Re.stopPropagation()}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-item-title-text",children:I.title}),I.variantType&&l.jsx("span",{className:"files-badge-variant",children:I.variantType}),c.getDocTags(I.filename).includes("✓")&&l.jsx("svg",{className:"sidebar-approved-icon",title:"Approved",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"20 6 9 17 4 12"})}),I.lastSent&&l.jsx("svg",{className:"sidebar-sent-icon",title:"Sent",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"20 6 9 17 4 12"})}),(I.autoAccept===!0||I.autoAccept!==!1&&ve)&&l.jsx("span",{className:"sidebar-auto-accept-dot",title:I.autoAccept===!0?"Auto-accept on":"Auto-accept inherited"}),s.filenames.includes(I.filename)&&l.jsx("span",{className:"sidebar-pending-dot"})]}),Vs(I.filename)&&l.jsx("div",{className:"sidebar-item-context",children:DT(I.filename)}),l.jsxs("div",{className:"sidebar-item-meta",children:[I.wordCount.toLocaleString()," words · ",ba(I.lastModified)]}),l.jsxs("div",{className:"sidebar-tags",children:[c.getDocTags(I.filename).filter(Re=>Re!=="✓").map(Re=>l.jsxs("span",{className:"sidebar-tag",onClick:xe=>xe.stopPropagation(),children:[Re,l.jsx("span",{className:"sidebar-tag-remove",onClick:xe=>{xe.stopPropagation(),c.handleRemoveTag(I.filename,Re)},children:"×"})]},Re)),K===I.filename?l.jsx("input",{className:"sidebar-tag-input",value:J,onChange:Re=>A(Re.target.value),onBlur:()=>{J.trim()&&c.handleAddTag(I.filename,J),ce(null)},onKeyDown:Re=>{Re.key==="Enter"&&(c.handleAddTag(I.filename,J),ce(null),A("")),Re.key==="Escape"&&(ce(null),A(""))},autoFocus:!0,onClick:Re=>Re.stopPropagation(),placeholder:"tag..."}):l.jsx("button",{className:"sidebar-tag-add",onClick:Re=>{Re.stopPropagation(),ce(I.filename),A("")},children:"+"})]})]}),M===I.filename?l.jsxs("div",{className:"sidebar-confirm-delete",onClick:Re=>Re.stopPropagation(),children:[l.jsx("span",{children:Vs(I.filename)?"Remove?":"Delete?"}),l.jsx("button",{onClick:()=>{c.handleDelete(I.filename),_(null)},children:"Yes"}),l.jsx("button",{onClick:()=>_(null),children:"No"})]}):l.jsx("button",{className:"sidebar-delete-btn",onClick:Re=>{Re.stopPropagation(),_(I.filename)},title:Vs(I.filename)?"Remove document":"Delete document",children:"×"})]},I.filename),W=(I,V,re,Q,ue,ve=!1)=>{const Re=I.docId?tt.get(I.docId):void 0,xe=f&&(h==null?void 0:h.parentDocId)&&h.parentDocId===I.docId;if(!(Re&&Re.length>0||xe))return T(I,V,re,Q,ue,ve);const Et=`variants-${I.docId}`,dn=!R.has(Et);return l.jsxs("div",{className:"sidebar-variant-group",children:[l.jsxs("div",{className:`sidebar-variant-master${!dn&&(at==null?void 0:at.masterDocId)===I.docId?" active-within":""}`,onClick:Xt=>{Xt.target.closest(".sidebar-variant-chevron")&&(Xt.stopPropagation(),Mt(Et))},children:[T(I,V,re,Q,ue,ve),l.jsx("span",{className:`sidebar-variant-chevron${dn?"":" collapsed"}`,children:l.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"6 9 12 15 18 9"})})})]}),dn&&l.jsxs("div",{className:"sidebar-variant-children",children:[Re==null?void 0:Re.map((Xt,ln)=>T(Xt,V,re,Q,ln,ve)),xe&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:f})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]})]})]},`vg-${I.filename}`)},ae=(I,V,re,Q,ue,ve,Re=!1)=>{if(I.type==="doc"){const $e=t.find(zt=>zt.filename===I.file);return $e?We.has($e.filename)?l.jsx(l.Fragment,{}):W($e,re,Q,ue,ve,Re):Vs(I.file)?l.jsx("div",{className:"sidebar-item sidebar-unavailable",children:l.jsxs("div",{className:"sidebar-item-title",children:[I.title||I.file," (unavailable)"]})},I.file):l.jsxs("div",{className:"sidebar-item sidebar-missing",children:[l.jsxs("div",{className:"sidebar-item-title",children:[I.title||I.file," (missing)"]}),l.jsx("button",{className:"sidebar-delete-btn",onClick:()=>c.handleRemoveFromWorkspace(re,I.file),title:"Remove",children:"×"})]},I.file)}const xe=I,Dt=`container-${xe.id}`,Et=R.has(Dt),dn=V<=2?`depth-${V}`:"depth-2",Xt=xe.autoAccept===!0,ln=Xt||Re;return l.jsxs("div",{className:`sidebar-container ${dn} ${Et?"collapsed":""} ${ze(xe.id)} ${Xe(xe.id)?"drop-inside":""}`,children:[l.jsxs("div",{className:`sidebar-container-header${Et&&(at!=null&&at.containerKeys.has(Dt))?" active-within":""} ${(he==null?void 0:he.itemId)===xe.id&&he.position==="inside"?"drop-inside":""}`,"data-drag-id":xe.id,"data-drag-type":"container-header","data-drag-ws":re,"data-drag-parent":Q||"","data-section-key":Dt,onPointerDown:$e=>me($e,{type:"container",id:xe.id,sourceWs:re},xe.name),onClick:()=>!ne&&Mt(Dt),onContextMenu:$e=>{$e.preventDefault(),$e.stopPropagation(),ht({x:$e.clientX,y:$e.clientY,type:"container",wsFilename:re,containerId:xe.id,title:xe.name,nodes:xe.items,autoAccept:Xt})},children:[l.jsx("span",{className:`sidebar-chevron ${Et?"collapsed":""}`,children:"▾"}),U===xe.id?l.jsx("input",{className:"sidebar-rename-input",value:z,onChange:$e=>ee($e.target.value),onBlur:()=>{c.handleRenameContainer(re,xe.id,z),X(null)},onKeyDown:$e=>{$e.key==="Enter"&&(c.handleRenameContainer(re,xe.id,z),X(null)),$e.key==="Escape"&&X(null)},autoFocus:!0,onClick:$e=>$e.stopPropagation()}):l.jsx("span",{className:"sidebar-container-name",onDoubleClick:$e=>{$e.stopPropagation(),X(xe.id),ee(xe.name)},children:xe.name}),ln&&l.jsx("span",{className:"sidebar-auto-accept-dot",title:Xt?"Auto-accept on for this container":"Auto-accept inherited from workspace"}),l.jsxs("div",{className:"sidebar-container-actions",children:[l.jsx("button",{className:"sidebar-new-btn",onClick:$e=>{$e.stopPropagation(),ut({anchor:$e.target.getBoundingClientRect(),wsFilename:re,containerId:xe.id})},title:"New doc",children:"+"}),V<2&&l.jsx("button",{className:"sidebar-new-btn",onClick:$e=>{$e.stopPropagation(),c.handleCreateContainer(re,xe.id)},title:"New sub-container",children:"☐"}),l.jsx("button",{className:"sidebar-new-btn sidebar-container-delete",onClick:$e=>{$e.stopPropagation(),c.handleDeleteContainer(re,xe.id)},title:"Delete container",children:"×"})]})]}),!Et&&l.jsxs("div",{className:"sidebar-container-list","data-drop-ws":re,"data-drop-container":xe.id,children:[f&&!(h!=null&&h.parentDocId)&&(h==null?void 0:h.wsFilename)===re&&h.containerId===xe.id&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:f})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),xe.items.filter($e=>$e.type!=="doc"?!0:!(k($e.file)||f&&(h==null?void 0:h.wsFilename)===re&&h.containerId===xe.id&&$e.title===f)).map(($e,zt)=>ae($e,V+1,re,xe.id,xe.items,zt,ln)),xe.items.length===0&&!f&&l.jsx("div",{className:"sidebar-empty",children:ne?"Drop here":"Empty"})]})]},xe.id)};return l.jsxs("div",{className:"sidebar-scroll",ref:d,children:[l.jsxs("div",{className:`sidebar-section sidebar-docs-section ${R.has("docs")?"docs-collapsed":""}`,children:[l.jsxs("div",{className:`sidebar-section-header${R.has("docs")&&at!==null&&at.wsFilename===null?" active-within":""}`,"data-section-key":"docs",onClick:()=>Mt("docs"),onContextMenu:Y,children:[l.jsx("span",{className:`sidebar-chevron ${R.has("docs")?"collapsed":""}`,children:"▾"}),l.jsx("span",{className:"sidebar-label",children:"Documents"}),l.jsx("button",{className:"sidebar-new-btn",onClick:I=>{I.stopPropagation(),ut({anchor:I.target.getBoundingClientRect()})},title:"New document",children:"+"})]}),!R.has("docs")&&l.jsxs("div",{className:"sidebar-section-list","data-drop-ws":"__docs__",children:[f&&!(h!=null&&h.parentDocId)&&(!h||!n.some(I=>I.filename===(h==null?void 0:h.wsFilename)))&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:f})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),Ht.filter(I=>!k(I.filename)&&(!f||I.title!==f)).map((I,V)=>{const re=Ht.map(Q=>({type:"doc",file:Q.filename,title:Q.title}));return W(I,void 0,null,re,V)}),Ht.length===0&&l.jsx("div",{className:"sidebar-empty",children:ne?"Drop here to unassign":"No unassigned documents"})]})]}),n.map(I=>{var ue,ve,Re;const V=((ue=I.workspace)==null?void 0:ue.root)||[],re=R.has(I.filename),Q=((ve=I.workspace)==null?void 0:ve.autoAccept)===!0||I.autoAccept===!0;return l.jsxs("div",{className:`sidebar-section sidebar-workspace-section ${re?"ws-collapsed":""} ${Ae(I.filename)?"dragging":""} ${(he==null?void 0:he.itemId)===I.filename?he.position==="before"?"drop-before":"drop-after":""}`,children:[l.jsxs("div",{className:`sidebar-section-header${re&&(at==null?void 0:at.wsFilename)===I.filename?" active-within":""}`,"data-section-key":I.filename,"data-ws-drag":I.filename,onPointerDown:xe=>me(xe,{type:"workspace",filename:I.filename},I.title),onClick:()=>!ne&&Mt(I.filename),onContextMenu:xe=>{var Dt;xe.preventDefault(),xe.stopPropagation(),ht({x:xe.clientX,y:xe.clientY,type:"workspace",wsFilename:I.filename,title:I.title,nodes:V,autoAccept:((Dt=I.workspace)==null?void 0:Dt.autoAccept)===!0||I.autoAccept===!0})},children:[l.jsx("span",{className:`sidebar-chevron ${re?"collapsed":""}`,children:"▾"}),P===I.filename?l.jsx("input",{className:"sidebar-rename-input",value:G,onChange:xe=>ie(xe.target.value),onBlur:()=>{c.handleRenameWorkspace(I.filename,G),F(null)},onKeyDown:xe=>{xe.key==="Enter"&&(c.handleRenameWorkspace(I.filename,G),F(null)),xe.key==="Escape"&&F(null)},autoFocus:!0,onClick:xe=>xe.stopPropagation()}):l.jsx("span",{className:"sidebar-label sidebar-workspace-label",onDoubleClick:xe=>{xe.stopPropagation(),F(I.filename),ie(I.title)},children:I.title}),(((Re=I.workspace)==null?void 0:Re.autoAccept)===!0||I.autoAccept===!0)&&l.jsx("span",{className:"sidebar-auto-accept-dot",title:"Auto-accept on for this workspace"}),l.jsxs("div",{className:"sidebar-workspace-actions",children:[l.jsx("button",{className:"sidebar-new-btn",onClick:xe=>{xe.stopPropagation(),ut({anchor:xe.target.getBoundingClientRect(),wsFilename:I.filename,containerId:null})},title:"New document",children:"+"}),l.jsx("button",{className:"sidebar-new-btn",onClick:xe=>{xe.stopPropagation(),c.handleCreateContainer(I.filename,null)},title:"New container",children:"☐"}),$===I.filename?l.jsxs("span",{className:"sidebar-inline-confirm",onClick:xe=>xe.stopPropagation(),children:[l.jsx("button",{onClick:()=>{c.handleDeleteWorkspace(I.filename),B(null)},children:"Yes"}),l.jsx("button",{onClick:()=>B(null),children:"No"})]}):l.jsx("button",{className:"sidebar-new-btn sidebar-workspace-delete",onClick:xe=>{xe.stopPropagation(),B(I.filename)},title:"Delete workspace",children:"×"})]})]}),!re&&l.jsxs("div",{className:"sidebar-section-list","data-drop-ws":I.filename,children:[f&&!(h!=null&&h.parentDocId)&&(h==null?void 0:h.wsFilename)===I.filename&&h.containerId===null&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:f})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),V.filter(xe=>xe.type!=="doc"?!0:!(k(xe.file)||f&&(h==null?void 0:h.wsFilename)===I.filename&&h.containerId===null&&xe.title===f)).map((xe,Dt)=>ae(xe,0,I.filename,null,V,Dt,Q)),V.length===0&&!f&&l.jsx("div",{className:"sidebar-empty",children:ne?"Drop here to add":"Empty workspace"})]})]},I.filename)}),l.jsx("div",{className:"sidebar-new-workspace",children:l.jsx("button",{onClick:c.handleCreateWorkspace,children:"+ New Workspace"})}),be&&l.jsx(Bd,{x:be.x,y:be.y,filename:be.wsFilename,title:be.title,onClose:()=>ht(null),onDuplicate:()=>{},onRename:()=>{be.type==="workspace"?(F(be.wsFilename),ie(be.title)):be.containerId&&(X(be.containerId),ee(be.title)),ht(null)},onArchive:()=>{},onDelete:()=>{be.type==="workspace"?c.handleDeleteWorkspace(be.wsFilename):be.containerId&&c.handleDeleteContainer(be.wsFilename,be.containerId)},onPluginAction:()=>{},pluginItems:[],folderMode:!0,onNewDoc:I=>{ut({anchor:I.target.getBoundingClientRect(),wsFilename:be.wsFilename,containerId:be.type==="container"?be.containerId:null}),ht(null)},onNewContainer:()=>{c.handleCreateContainer(be.wsFilename,be.type==="container"?be.containerId:null),ht(null)},onAcceptAll:()=>{const I=new Set;Ll(be.nodes,I),I.size&&ge([...I],"accept"),ht(null)},onRejectAll:()=>{const I=new Set;Ll(be.nodes,I),I.size&&ge([...I],"reject"),ht(null)},folderAutoAccept:be.autoAccept,folderAutoAcceptLabel:be.type==="workspace"?"for workspace":"for container",onToggleFolderAutoAccept:()=>{fetch("/api/auto-accept/inherit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wsFile:be.wsFilename,...be.type==="container"?{containerId:be.containerId}:{},enabled:!be.autoAccept})}).catch(()=>{})}}),D&&l.jsx(Bd,{x:D.x,y:D.y,filename:D.filename,title:D.title,onClose:()=>q(null),onDuplicate:()=>st(D.filename),onCreateVariant:D.docId?I=>mt(D.filename,D.docId,I):void 0,onRename:()=>{S(D.filename),j(D.title)},onArchive:()=>c.handleArchive(D.filename),onDelete:()=>c.handleDelete(D.filename),onPluginAction:(I,V)=>Nt(I,V,D.filename,D.title),pluginItems:oe,onSchedulePost:Ee?()=>{qe({filename:D.filename,title:D.title}),q(null)}:void 0,onViewAnalytics:D.docId&&D.lastSent&&(D.postedUrl||D.isNewsletter)?()=>{D.isNewsletter?ye({docId:D.docId,title:D.title}):D.postedUrl&&window.open(D.postedUrl,"_blank"),q(null)}:void 0,viewAnalyticsLabel:D.isNewsletter?"View Analytics":D.postedUrl?"View on X":"View Analytics",isApproved:c.getDocTags(D.filename).includes("✓"),onToggleApprove:()=>{c.getDocTags(D.filename).includes("✓")?c.handleRemoveTag(D.filename,"✓"):(c.handleAddTag(D.filename,"✓"),setTimeout(()=>window.dispatchEvent(new CustomEvent("ow-accept-all")),50))},isAutoAccept:(()=>{var V;const I=(V=t.find(re=>re.filename===D.filename))==null?void 0:V.autoAccept;return I===!0?!0:I===!1?!1:Pd(n,D.filename)})(),onToggleAutoAccept:()=>{var re;const I=(re=t.find(Q=>Q.filename===D.filename))==null?void 0:re.autoAccept,V=I===!0?!0:I===!1?!1:Pd(n,D.filename);fetch("/api/auto-accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:D.filename,enabled:!V})}).then(()=>c.fetchDocs()).catch(()=>{})},isAlreadySent:!!D.lastSent,onMarkSent:()=>{const I=D.filename;c.getDocTags(I).includes("✓")&&c.handleRemoveTag(I,"✓"),i(I),setTimeout(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualPost:{postedAt:new Date().toISOString()}})}).then(()=>c.fetchDocs()).catch(()=>{})},100),q(null)}}),Ie&&l.jsx(FT,{actionLabel:Ie.label,docTitle:Ie.title,onClose:()=>Ve(null),onConfirm:I=>{const V=oe.find(re=>re.action===Ie.action);V&&Nt(Ie.action,V,Ie.filename,Ie.title,I),Ve(null)}}),le&&l.jsx(zT,{docId:le.docId,title:le.title,onClose:()=>ye(null)}),Te&&l.jsx(Vl,{filename:Te.filename,title:Te.title,onClose:()=>qe(null)}),pt&&l.jsx(UT,{anchorRect:pt.anchor,onClose:()=>ut(null),onSelect:I=>{ut(null),pt.wsFilename?c.handleCreateInWorkspace(pt.wsFilename,pt.containerId??null,I):I?fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:I})}).catch(()=>{}):o()}}),xt&&l.jsx("div",{ref:ct,className:"sidebar-density-dropdown",style:{position:"fixed",left:xt.x,top:xt.y,zIndex:200},children:D$.map(I=>l.jsx("button",{className:`sidebar-density-option ${At===I.id?"active":""}`,onClick:()=>Fe(I.id),children:I.label},I.id))})]})}function B$({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,onCreateDocument:i,actions:o,scrollRef:c,searchQuery:d,searchResults:f}){const[h,m]=y.useState(null);if(Wl(c,t,e.length),f!==null)return l.jsx(rf,{results:f,query:d,onSwitchDocument:s});const g=[...t].sort((w,S)=>new Date(S.lastModified).getTime()-new Date(w.lastModified).getTime()),v=[];let x="";for(const w of g){const S=T$(w.lastModified);S!==x&&(v.push({label:S,docs:[]}),x=S),v[v.length-1].docs.push(w)}const k=w=>{for(const S of e){if(!S.workspace)continue;const N=j=>{for(const M of j)if(M.type==="doc"&&M.file===w||M.type==="container"&&N(M.items))return!0;return!1};if(N(S.workspace.root))return S.title}return null};return l.jsxs("div",{className:"sidebar-scroll tl-scroll",ref:c,children:[l.jsxs("div",{className:"tl-header",children:[l.jsx("span",{className:"tl-title",children:"Timeline"}),l.jsx("button",{className:"sidebar-new-btn",onClick:i,title:"New document",children:"+"})]}),v.map(w=>l.jsxs("div",{className:"tl-group",children:[l.jsx("div",{className:"tl-date",children:w.label}),w.docs.map(S=>{const N=k(S.filename);return l.jsxs("div",{className:`tl-item ${S.isActive?"active":""}`,onClick:()=>!S.isActive&&s(S.filename),children:[l.jsx("div",{className:"tl-dot"}),l.jsxs("div",{className:"tl-content",children:[l.jsxs("div",{className:"tl-item-title",children:[l.jsx("span",{children:S.title}),r.filenames.includes(S.filename)&&l.jsx("span",{className:"sidebar-pending-dot"})]}),Vs(S.filename)&&l.jsx("div",{className:"tl-item-context",children:DT(S.filename)}),l.jsxs("div",{className:"tl-item-meta",children:[S.wordCount.toLocaleString()," words · ",ba(S.lastModified)]}),N&&l.jsx("div",{className:"tl-badge",children:N})]}),h===S.filename?l.jsxs("div",{className:"sidebar-confirm-delete",onClick:j=>j.stopPropagation(),children:[l.jsx("span",{children:Vs(S.filename)?"Remove?":"Delete?"}),l.jsx("button",{onClick:()=>{o.handleDelete(S.filename),m(null)},children:"Yes"}),l.jsx("button",{onClick:()=>m(null),children:"No"})]}):l.jsx("button",{className:"sidebar-delete-btn",onClick:j=>{j.stopPropagation(),m(S.filename)},title:Vs(S.filename)?"Remove":"Delete",children:"×"})]},S.filename)})]},w.label)),t.length===0&&l.jsx("div",{className:"sidebar-empty",children:"No documents yet"})]})}function $$({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:o,searchQuery:c,searchResults:d,onSearchChange:f}){const[h,m]=y.useState([]),[g,v]=y.useState(null);Wl(o,t,e.length);const[x,k]=y.useState(null),w=y.useRef(null);y.useEffect(()=>{if(!g)return;const A=D=>{w.current&&!w.current.contains(D.target)&&v(null)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[g]);const S=(A,D)=>{for(const q of A)if(q.type==="container"){if(q.id===D)return q;const le=S(q.items,D);if(le)return le}return null},N=A=>{let D=0;for(const q of A)q.type==="doc"?D++:q.type==="container"&&(D+=N(q.items));return D},j=A=>{const D=[];for(const q of A)q.type==="doc"?D.push(q.file):q.type==="container"&&D.push(...j(q.items));return D},M=y.useMemo(()=>{if(h.length===0)return[];const A=h[h.length-1],D=e.find(le=>le.filename===A.wsFilename);if(!(D!=null&&D.workspace))return[];if(A.type==="workspace")return D.workspace.root;const q=S(D.workspace.root,A.key);return q?q.items:[]},[h,e]),_=M.filter(A=>A.type==="container"),R=y.useMemo(()=>{const A=M.filter(D=>D.type==="doc").map(D=>D.file);return t.filter(D=>A.includes(D.filename))},[M,t]),L=A=>{const D=j(A.items);return t.filter(q=>D.includes(q.filename))},$=A=>{const D=e.find(le=>le.filename===A);if(!(D!=null&&D.workspace))return[];const q=j(D.workspace.root);return t.filter(le=>q.includes(le.filename))},B=y.useMemo(()=>t.filter(A=>!n.has(A.filename)),[t,n]),U=A=>{m(D=>[...D,A]),v(null)},X=()=>{m(A=>A.slice(0,-1)),v(null)},z=(A,D)=>{if(g===A){v(null);return}const le=D.currentTarget.getBoundingClientRect();k({top:le.bottom+4,left:le.left}),v(A)},ee=A=>{s(A),v(null)},P=h.length>1?h[h.length-2].title:"All",F=y.useRef(null),G=y.useRef(null),[ie,K]=y.useState(null),ce=y.useCallback(A=>{const q=A.currentTarget.getBoundingClientRect();K({top:q.bottom+4,left:q.left})},[]);y.useEffect(()=>{if(!d)return;const A=D=>{G.current&&!G.current.contains(D.target)&&F.current&&!F.current.contains(D.target)&&f("")};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[d,f]);const J=()=>{if(!g)return[];if(g==="__unassigned__")return B;if(g==="__level-docs__")return R;const A=e.find(D=>D.filename===g);if(A)return $(A.filename);for(const D of e){if(!D.workspace)continue;const q=S(D.workspace.root,g);if(q)return L(q)}return[]};return l.jsxs("div",{className:"board-scroll",ref:o,children:[l.jsxs("div",{className:"board-search-pill",children:[l.jsxs("svg",{className:"board-search-icon",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("circle",{cx:"11",cy:"11",r:"8"}),l.jsx("path",{d:"m21 21-4.3-4.3"})]}),l.jsx("input",{ref:F,className:"board-search-input",type:"text",placeholder:"Search...",value:c,onChange:A=>f(A.target.value),onFocus:ce}),c&&l.jsx("button",{className:"board-search-clear",onClick:()=>f(""),children:"×"})]}),h.length===0?l.jsx("button",{className:"board-back board-back--static",tabIndex:-1,children:"All"}):l.jsxs("button",{className:"board-back",onClick:X,title:`Back to ${P}`,children:["← ",P]}),h.length===0&&l.jsxs(l.Fragment,{children:[B.length>0&&l.jsxs("button",{className:`board-chip ${g==="__unassigned__"?"open":""}`,onClick:A=>z("__unassigned__",A),children:["Documents ",l.jsx("span",{className:"board-chip-count",children:B.length})]}),e.map(A=>{var q;const D=(q=A.workspace)==null?void 0:q.root.some(le=>le.type==="container");return l.jsxs("button",{className:`board-chip ${g===A.filename?"open":""}`,onClick:le=>D?U({type:"workspace",key:A.filename,title:A.title,wsFilename:A.filename}):z(A.filename,le),children:[A.title," ",l.jsx("span",{className:"board-chip-count",children:A.docCount}),D&&l.jsx("span",{className:"board-chip-arrow",children:"›"})]},A.filename)}),l.jsx("button",{className:"board-chip board-chip-add",onClick:i.handleCreateWorkspace,title:"New workspace",children:"+"})]}),h.length>0&&l.jsxs(l.Fragment,{children:[R.length>0&&l.jsxs("button",{className:`board-chip board-chip-docs ${g==="__level-docs__"?"open":""}`,onClick:A=>z("__level-docs__",A),children:["Docs ",l.jsx("span",{className:"board-chip-count",children:R.length})]}),_.map(A=>{const D=A.items.some(q=>q.type==="container");return l.jsxs("button",{className:`board-chip ${g===A.id?"open":""}`,onClick:q=>D?U({type:"container",key:A.id,title:A.name,wsFilename:h[h.length-1].wsFilename}):z(A.id,q),children:[A.name," ",l.jsx("span",{className:"board-chip-count",children:N(A.items)}),D&&l.jsx("span",{className:"board-chip-arrow",children:"›"})]},A.id)})]}),g&&x&&(()=>{const A=J();return l.jsxs("div",{className:"board-dropdown",ref:w,style:{position:"fixed",top:x.top,left:x.left},children:[A.map(D=>l.jsxs("div",{className:`board-dropdown-item ${D.isActive?"active":""}`,onClick:()=>ee(D.filename),children:[l.jsxs("span",{className:"board-dropdown-title",children:[D.title,r.filenames.includes(D.filename)&&l.jsx("span",{className:"board-pending-dot"})]}),l.jsxs("span",{className:"board-dropdown-meta",children:[D.wordCount.toLocaleString()," words · ",ba(D.lastModified)]})]},D.filename)),A.length===0&&l.jsx("div",{className:"board-dropdown-empty",children:"No documents"})]})})(),d&&ie&&l.jsxs("div",{className:"board-dropdown board-search-dropdown",ref:G,style:{position:"fixed",top:ie.top,left:ie.left},children:[d.map(A=>l.jsxs("div",{className:`board-dropdown-item ${A.isActive?"active":""}`,onClick:()=>{s(A.filename),f("")},children:[l.jsx("span",{className:"board-dropdown-title",children:A.title}),A.matchType==="tag"&&A.matchedTag&&l.jsxs("span",{className:"board-dropdown-meta",children:["Tag: ",A.matchedTag]}),A.matchType==="content"&&A.snippet&&l.jsx("span",{className:"board-dropdown-meta board-search-snippet",children:A.snippet}),l.jsxs("span",{className:"board-dropdown-meta",children:[A.wordCount.toLocaleString()," words · ",ba(A.lastModified)]})]},A.filename)),d.length===0&&l.jsx("div",{className:"board-dropdown-empty",children:"No results"})]})]})}function F$({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:o,searchQuery:c,searchResults:d}){const[f,h]=y.useState([]);if(Wl(o,t,e.length),d!==null)return l.jsx(rf,{results:d,query:c,onSwitchDocument:s});const m=(M,_)=>{for(const R of M)if(R.type==="container"){if(R.id===_)return R;const L=m(R.items,_);if(L)return L}return null},g=M=>{let _=0;for(const R of M)R.type==="doc"?_++:R.type==="container"&&(_+=g(R.items));return _},v=y.useMemo(()=>{if(f.length===0)return[];const M=f[f.length-1],_=e.find(L=>L.filename===M.wsFilename);if(!(_!=null&&_.workspace))return[];if(M.type==="workspace")return _.workspace.root;const R=m(_.workspace.root,M.key);return R?R.items:[]},[f,e]),x=v.filter(M=>M.type==="container"),k=y.useMemo(()=>{if(f.length===0)return t.filter(_=>!n.has(_.filename));const M=v.filter(_=>_.type==="doc").map(_=>_.file);return t.filter(_=>M.includes(_.filename))},[f,v,t,n]),w=M=>h(_=>[..._,M]),S=()=>h(M=>M.slice(0,-1)),N=f.length>1?f[f.length-2].title:"Shelf",j=f.length>0?f[f.length-1].title:"Documents";return l.jsxs("div",{className:"shelf-wrapper",children:[l.jsxs("div",{className:"shelf-spines",ref:o,children:[f.length>0&&l.jsxs("button",{className:"shelf-back",onClick:S,title:`Back to ${N}`,children:[l.jsx("span",{className:"shelf-back-arrow",children:"←"}),l.jsx("span",{className:"shelf-back-label",children:N})]}),f.length===0&&l.jsxs(l.Fragment,{children:[e.map(M=>l.jsxs("div",{className:"shelf-section-spine",onClick:()=>w({type:"workspace",key:M.filename,title:M.title,wsFilename:M.filename}),title:M.title,children:[l.jsx("span",{className:"shelf-section-title",children:M.title}),l.jsx("span",{className:"shelf-section-count",children:M.docCount})]},M.filename)),l.jsx("button",{className:"shelf-add",onClick:i.handleCreateWorkspace,title:"New workspace",children:"+"})]}),f.length>0&&x.map(M=>l.jsxs("div",{className:"shelf-section-spine shelf-section-container",onClick:()=>w({type:"container",key:M.id,title:M.name,wsFilename:f[f.length-1].wsFilename}),title:M.name,children:[l.jsx("span",{className:"shelf-section-title",children:M.name}),l.jsx("span",{className:"shelf-section-count",children:g(M.items)})]},M.id))]}),l.jsxs("div",{className:"shelf-docs",children:[l.jsx("div",{className:"shelf-docs-header",children:j}),l.jsxs("div",{className:"shelf-docs-list",children:[k.map(M=>l.jsxs("div",{className:`shelf-doc-item ${M.isActive?"active":""}`,onClick:()=>s(M.filename),children:[l.jsxs("div",{className:"shelf-doc-title",children:[l.jsx("span",{children:M.title}),r.filenames.includes(M.filename)&&l.jsx("span",{className:"shelf-pending-dot"})]}),l.jsxs("div",{className:"shelf-doc-meta",children:[M.wordCount.toLocaleString()," words · ",ba(M.lastModified)]})]},M.filename)),k.length===0&&l.jsx("div",{className:"shelf-docs-empty",children:"No documents"})]})]})]})}async function Ik(t,e={}){var s,i;const r=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:t,arguments:e})})).json();if((i=(s=r==null?void 0:r.content)==null?void 0:s[0])!=null&&i.text)try{return JSON.parse(r.content[0].text)}catch{return r.content[0].text}return r}function HT({filename:t,title:e,isActive:n,onSwitchDocument:r,onClose:s}){const[i,o]=y.useState("loading"),[c,d]=y.useState([]),[f,h]=y.useState(null),[m,g]=y.useState(null),[v,x]=y.useState(null);y.useEffect(()=>{Ik("list_blog_sites").then(S=>{if(S.error){g(S.error),o("error");return}const N=S.sites||[];d(N),N.length===0?o("pick"):N.length===1?(h(N[0].id),o("confirm")):o("pick")}).catch(S=>{g((S==null?void 0:S.message)||"Failed to load blog sites"),o("error")})},[]);const k=c.find(S=>S.id===f)||null,w=async()=>{if(k){o("posting"),g(null),n||(r(t),await new Promise(S=>setTimeout(S,350)));try{const S=await Ik("post_to_blog",{site_id:k.id});if(S!=null&&S.error){g(S.error),o("error");return}const N=S.commit?`https://github.com/${k.owner}/${k.repo}/commit/${S.commit}`:void 0;x({message:S.message,file:S.file,commit:S.commit,images_committed:S.images_committed,liveUrl:S.live_url,commitUrl:N,warning:S.warning}),o("done")}catch(S){g((S==null?void 0:S.message)||"Publish failed"),o("error")}}};return l.jsx("div",{className:"post-blog-overlay",onClick:()=>{i!=="posting"&&s()},children:l.jsxs("div",{className:"post-blog-modal",onClick:S=>S.stopPropagation(),children:[l.jsxs("div",{className:"post-blog-modal-header",children:[l.jsx("h3",{children:"Post to Blog"}),l.jsx("button",{className:"post-blog-modal-close",onClick:s,disabled:i==="posting",children:"×"})]}),l.jsx("div",{className:"post-blog-modal-doc",children:e}),i==="loading"&&l.jsx("div",{className:"post-blog-modal-loading",children:"Loading blog sites…"}),i==="pick"&&c.length===0&&l.jsxs("div",{className:"post-blog-modal-empty",children:["No blog sites registered. Add one in ",l.jsx("strong",{children:"Settings → Plugins → GitHub"})," first.",l.jsx("button",{className:"post-blog-modal-done",onClick:s,children:"Close"})]}),i==="pick"&&c.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"post-blog-modal-label",children:"Choose a destination"}),l.jsx("div",{className:"post-blog-modal-sites",children:c.map(S=>l.jsxs("button",{className:`post-blog-modal-site${f===S.id?" post-blog-modal-site--selected":""}`,onClick:()=>{h(S.id),o("confirm")},children:[l.jsx("div",{className:"post-blog-modal-site-label",children:S.label}),l.jsxs("div",{className:"post-blog-modal-site-repo",children:[S.owner,"/",S.repo,"@",S.branch]})]},S.id))})]}),i==="confirm"&&k&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"post-blog-modal-confirm",children:["Publish to ",l.jsxs("strong",{children:[k.owner,"/",k.repo,"@",k.branch]}),"?",l.jsxs("div",{className:"post-blog-modal-target-dir",children:["→ ",k.content_dir]})]}),l.jsxs("div",{className:"post-blog-modal-actions",children:[l.jsx("button",{className:"post-blog-modal-btn post-blog-modal-btn--primary",onClick:w,children:"Publish now"}),c.length>1&&l.jsx("button",{className:"post-blog-modal-btn",onClick:()=>o("pick"),children:"Back"}),l.jsx("button",{className:"post-blog-modal-btn",onClick:s,children:"Cancel"})]})]}),i==="posting"&&l.jsx("div",{className:"post-blog-modal-loading",children:"Publishing…"}),i==="done"&&v&&l.jsxs("div",{className:"post-blog-modal-result post-blog-modal-result--success",children:[l.jsx("div",{children:v.message||"Published"}),v.file&&l.jsx("div",{className:"post-blog-modal-meta",children:v.file}),typeof v.images_committed=="number"&&v.images_committed>0&&l.jsxs("div",{className:"post-blog-modal-meta",children:[v.images_committed," image",v.images_committed===1?"":"s"," committed"]}),v.warning&&l.jsx("div",{className:"post-blog-modal-warning",children:v.warning}),l.jsxs("div",{className:"post-blog-modal-actions",children:[v.liveUrl?l.jsx("button",{className:"post-blog-modal-btn post-blog-modal-btn--primary",onClick:()=>window.open(v.liveUrl,"_blank"),children:"View Post"}):v.commitUrl?l.jsx("button",{className:"post-blog-modal-btn post-blog-modal-btn--primary",onClick:()=>window.open(v.commitUrl,"_blank"),children:"View commit"}):null,l.jsx("button",{className:"post-blog-modal-btn",onClick:s,children:"Done"})]}),v.liveUrl&&v.commitUrl&&l.jsx("button",{className:"post-blog-modal-commit-link",onClick:()=>window.open(v.commitUrl,"_blank"),children:"View commit"})]}),i==="error"&&l.jsxs("div",{className:"post-blog-modal-result post-blog-modal-result--error",children:[l.jsx("div",{children:m||"Publish failed"}),l.jsx("div",{className:"post-blog-modal-actions",children:l.jsx("button",{className:"post-blog-modal-btn",onClick:s,children:"Close"})})]})]})})}const z$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M20 20H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h4l2 2h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2z"}),l.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14",opacity:"0.5"})]}),U$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),l.jsx("polyline",{points:"14 2 14 8 20 8"}),l.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),l.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]}),H$=()=>l.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:l.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"})}),W$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[l.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z",opacity:"0.5"}),l.jsx("path",{d:"M7 15l-4-3.5L7 8",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),V$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[l.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z",opacity:"0.5"}),l.jsx("path",{d:"M3 8V6.5C3 5.67 3.67 5 4.5 5h2C7.33 5 8 5.67 8 6.5V8c0 2-1.5 3-3 3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),q$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[l.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z",opacity:"0.5"}),l.jsx("rect",{x:"2",y:"16",width:"8",height:"7",rx:"1.5",fill:"none",stroke:"currentColor",strokeWidth:"1.5"}),l.jsx("line",{x1:"4",y1:"18.5",x2:"8",y2:"18.5",stroke:"currentColor",strokeWidth:"1",opacity:"0.7"}),l.jsx("line",{x1:"4",y1:"20.5",x2:"7",y2:"20.5",stroke:"currentColor",strokeWidth:"1",opacity:"0.7"})]}),K$=()=>l.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:l.jsx("path",{d:"M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 0 1-2.063-2.065 2.064 2.064 0 1 1 2.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"})}),G$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),l.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),J$=()=>l.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("circle",{cx:"12",cy:"12",r:"10"}),l.jsx("path",{d:"M2 12h20"}),l.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]}),Lk=()=>l.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"20 6 9 17 4 12"})});function Y$({type:t}){switch(t){case"tweet":return l.jsx(H$,{});case"reply":return l.jsx(W$,{});case"quote":return l.jsx(V$,{});case"article":return l.jsx(q$,{});case"linkedin":return l.jsx(K$,{});case"newsletter":return l.jsx(G$,{});case"blog":return l.jsx(J$,{});default:return l.jsx(U$,{})}}function Fu(t){let e=0;for(const n of t)n.type==="doc"?e++:n.type==="container"&&(e+=Fu(n.items));return e}function tv(t,e){for(const n of t){if(n.type==="doc"&&n.file===e)return[];if(n.type==="container"){const r=tv(n.items,e);if(r)return[n.id,...r]}}return null}function Eu(t){const e=new Set;return Ll(t,e),[...e]}function WT(t,e,n=0){for(const r of t)if(r.type==="container"){if(r.id===e)return n;const s=WT(r.items,e,n+1);if(s>=0)return s}return-1}function X$(t,e){if(!e)return 12;for(const n of t){if(!n.workspace)continue;const r=WT(n.workspace.root,e);if(r>=0)return 12+(r+1)*16}return 12}function Q$({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,onCreateDocument:i,actions:o,scrollRef:c,writingTitle:d,writingTarget:f,pendingWriteFilenames:h,searchQuery:m,searchResults:g,onSearchChange:v}){var nn,at,Ht;const x=T=>!!h&&h.has(T),[k,w]=y.useState(()=>{try{const T=localStorage.getItem("ow-files-collapsed");return T?new Set(JSON.parse(T)):new Set}catch{return new Set}}),{draggedItem:S,dropIndicator:N,handlePointerDown:j,dropClass:M,isDragging:_,isContainerDropTarget:R}=BT({docs:t,workspaces:e,assignedFiles:n,scrollRef:c,setCollapsedSections:w}),L=T=>!N||N.itemId!==T||N.position==="inside"?void 0:{"--drop-indent":`${X$(e,N.containerId)}px`},{variantsByMaster:$,variantFilenames:B}=y.useMemo(()=>{const T=new Map,W=new Set;for(const ae of t)if(ae.masterDocId){const I=T.get(ae.masterDocId)||[];I.push(ae),T.set(ae.masterDocId,I),W.add(ae.filename)}return{variantsByMaster:T,variantFilenames:W}},[t]),[U,X]=y.useState(null),[z,ee]=y.useState(null),[P,F]=y.useState(new Set),[G,ie]=y.useState(null),[K,ce]=y.useState([]),[J,A]=y.useState(!1),[D,q]=y.useState(null),[le,ye]=y.useState(null),[oe,Se]=y.useState(null),[Ee,Le]=y.useState(null),[Ie,Ve]=y.useState(null),[Te,qe]=y.useState(null),[pt,ut]=y.useState(new Set);y.useEffect(()=>{ut(new Set)},[r]);const be=y.useCallback(()=>{fetch("/api/plugins").then(T=>T.json()).then(T=>{const W=[];let ae=!1;for(const I of T.plugins||[]){const V=I.displayName||void 0;for(const re of I.sidebarMenuItems||[])W.push({...re,pluginDisplayName:V});I.name==="@openwriter/plugin-publish"&&I.enabled&&(ae=!0)}ce(W),A(ae)}).catch(()=>{})},[]);y.useEffect(()=>{be()},[be]),y.useEffect(()=>{const T=()=>be();return window.addEventListener("ow-plugins-changed",T),()=>window.removeEventListener("ow-plugins-changed",T)},[be]);const ht=y.useCallback((T,W)=>{if(T.preventDefault(),T.stopPropagation(),P.has(W.filename)&&P.size>1){ee({x:T.clientX,y:T.clientY,filename:W.filename,title:W.title,bulkCount:P.size});return}P.size>0&&!P.has(W.filename)&&F(new Set),ee({x:T.clientX,y:T.clientY,filename:W.filename,title:W.title,docId:W.docId,lastSent:W.lastSent,postedUrl:W.postedUrl,isNewsletter:W.isNewsletter,contentType:W.contentType,sortRequest:W.sortRequest})},[P]),xt=y.useCallback(T=>{fetch("/api/documents/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:T})}).catch(()=>{})},[]),St=y.useCallback((T,W,ae,I,V)=>{if(!$T(W,t.find(re=>re.filename===ae))){if(W.promptForFocus&&V===void 0){q({action:T,label:W.label,filename:ae,title:I});return}fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:T,filename:ae,title:I,instructions:V||"",label:W.label})}).catch(()=>{})}},[t]),At=y.useCallback((T,W,ae)=>{for(const I of Eu(ae)){const V=t.find(re=>re.filename===I);fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:T,filename:I,title:(V==null?void 0:V.title)||I,instructions:"",label:W.label})}).catch(()=>{})}},[t]),Ye=y.useCallback((T,W)=>{ut(ae=>{const I=new Set(ae);for(const V of T)I.add(V);return I}),fetch("/api/documents/batch-resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filenames:T,action:W})}).catch(()=>{})},[]),ct=T=>{w(W=>{const ae=new Set(W);return ae.has(T)?ae.delete(T):ae.add(T),localStorage.setItem("ow-files-collapsed",JSON.stringify([...ae])),ae})},Fe=(T,W,ae,I)=>{X({type:T,key:W,value:ae,wsFilename:I})},Y=()=>{if(!U)return;const{type:T,key:W,value:ae,wsFilename:I}=U;T==="doc"?o.handleRename(W,"",ae):T==="workspace"?o.handleRenameWorkspace(W,ae):T==="container"&&I&&o.handleRenameContainer(I,W,ae),X(null)},ge=t.find(T=>T.isActive),ne=y.useMemo(()=>{var I;const T=t.find(V=>V.isActive);if(!T)return null;const W=T.masterDocId?t.find(V=>V.docId===T.masterDocId):void 0,ae=(W==null?void 0:W.filename)??T.filename;for(const V of e){const re=tv(((I=V.workspace)==null?void 0:I.root)||[],ae);if(re)return{wsFilename:V.filename,containerKeys:new Set(re.map(Q=>`container-${Q}`)),masterDocId:(W==null?void 0:W.docId)??null}}return{wsFilename:null,containerKeys:new Set,masterDocId:(W==null?void 0:W.docId)??null}},[t,e]),he=y.useRef(e);he.current=e;const me=y.useCallback(T=>{var W;for(const ae of he.current){const I=tv(((W=ae.workspace)==null?void 0:W.root)||[],T);if(I){w(V=>{const re=[ae.filename,...I.map(ue=>`container-${ue}`)];if(re.every(ue=>!V.has(ue)))return V;const Q=new Set(V);for(const ue of re)Q.delete(ue);return localStorage.setItem("ow-files-collapsed",JSON.stringify([...Q])),Q});break}}},[]);Wl(c,t,e.length,me);const ze=y.useMemo(()=>t.filter(T=>!n.has(T.filename)&&!B.has(T.filename)&&!x(T.filename)),[t,n,B,h]),Ae=y.useMemo(()=>{var I;const T=[],W=V=>{T.push(V.filename);const re=V.docId?$.get(V.docId):void 0,Q=V.docId&&!k.has(`variants-${V.docId}`);if(re&&Q)for(const ue of re)T.push(ue.filename)},ae=V=>{for(const re of V)if(re.type==="doc"){const Q=t.find(ue=>ue.filename===re.file);Q&&!B.has(Q.filename)&&W(Q)}else k.has(`container-${re.id}`)||ae(re.items)};k.has("docs")||ze.forEach(W);for(const V of e)k.has(V.filename)||ae(((I=V.workspace)==null?void 0:I.root)||[]);return T},[t,e,ze,B,$,k]),Xe=y.useCallback(()=>{F(new Set)},[]),Qe=y.useCallback((T,W)=>{if(S)return;const ae=T.shiftKey,I=T.ctrlKey||T.metaKey;if(ae){const re=G||(ge==null?void 0:ge.filename)||W,Q=Ae.indexOf(re),ue=Ae.indexOf(W);if(Q<0||ue<0){F(new Set([W])),ie(W);return}const[ve,Re]=Q<ue?[Q,ue]:[ue,Q];F(new Set(Ae.slice(ve,Re+1)));return}if(I){F(re=>{const Q=new Set(re);return Q.has(W)?Q.delete(W):Q.add(W),Q}),ie(W);return}F(new Set),ie(W);const V=t.find(re=>re.filename===W);V&&!V.isActive&&s(W)},[S,G,ge==null?void 0:ge.filename,Ae,s,t]);y.useEffect(()=>{if(P.size===0)return;const T=W=>{W.key==="Escape"&&Xe()};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[P.size,Xe]);const tt=y.useCallback(()=>{for(const T of P)o.handleDelete(T);F(new Set),ie(null)},[P,o]),We=y.useCallback(T=>{T.length!==0&&fetch("/api/documents/sort-request",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filenames:T})}).then(()=>o.fetchDocs()).catch(()=>{})},[o]),Ue=y.useCallback(T=>{fetch("/api/documents/sort-reject",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:T})}).then(()=>o.fetchDocs()).catch(()=>{})},[o]),st=y.useCallback(T=>{fetch("/api/documents/sort-accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:T})}).then(()=>o.fetchDocs()).catch(()=>{})},[o]);if(g!==null)return l.jsx(rf,{results:g,query:m,onSwitchDocument:s,actions:o});const mt=T=>l.jsx("input",{className:"sidebar-rename-input",value:U.value,onChange:W=>X(ae=>ae?{...ae,value:W.target.value}:null),onBlur:T,onKeyDown:W=>{W.key==="Enter"&&T(),W.key==="Escape"&&X(null)},autoFocus:!0,onClick:W=>W.stopPropagation()}),Nt=(T,W,ae,I,V,re=!1)=>l.jsxs("div",{className:`files-row${T.isActive?" active":""}${T.docId&&(ne==null?void 0:ne.masterDocId)===T.docId&&k.has(`variants-${T.docId}`)?" active-within":""}${P.has(T.filename)?" selected":""} ${_(T.filename)?"dragging":""} ${M(T.filename)}${T.masterDocId?" is-variant":""}`,style:{paddingLeft:W,...L(T.filename)},"data-drag-id":T.filename,"data-drag-type":"doc","data-drag-ws":ae||"__docs__","data-drag-container":I||"",onPointerDown:Q=>j(Q,{type:"doc",file:T.filename,sourceWs:ae||null},T.title),onClick:Q=>Qe(Q,T.filename),onDoubleClick:()=>Fe("doc",T.filename,T.title),onContextMenu:Q=>ht(Q,T),children:[l.jsx("span",{className:"files-row-icon",children:l.jsx(Y$,{type:T.contentType})}),(U==null?void 0:U.type)==="doc"&&U.key===T.filename?mt(Y):l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"files-row-label",children:T.title}),T.variantType&&l.jsx("span",{className:"files-badge-variant",children:T.variantType}),(T.autoAccept===!0||T.autoAccept!==!1&&re)&&l.jsx("span",{className:"sidebar-auto-accept-dot",title:T.autoAccept===!0?"Auto-accept on":"Auto-accept inherited"}),r.filenames.includes(T.filename)&&!pt.has(T.filename)&&l.jsx("span",{className:"files-badge-pending"}),T.sortRequest&&(T.sortRequest.proposal?l.jsx("span",{className:"files-badge-sort-proposal",title:"Sort proposal ready — right-click to review"}):l.jsx("span",{className:"files-badge-sort-pending",title:"Sort requested"})),o.getDocTags(T.filename).includes("✓")&&l.jsx("span",{className:"files-badge-approved",children:l.jsx(Lk,{})}),T.lastSent&&l.jsx("span",{className:"files-badge-sent",children:l.jsx(Lk,{})}),V&&l.jsx("span",{className:`files-row-chevron${k.has(`variants-${T.docId}`)?" collapsed":""}`,onClick:Q=>{Q.stopPropagation(),ct(`variants-${T.docId}`)},children:l.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"6 9 12 15 18 9"})})})]})]},T.filename),Mt=(T,W,ae,I,V=!1)=>{const re=T.docId?$.get(T.docId):void 0,Q=!!(re&&re.length>0),ue=d&&(f==null?void 0:f.parentDocId)&&f.parentDocId===T.docId,ve=Q||ue,Re=!k.has(`variants-${T.docId}`);return ve?l.jsxs("div",{className:"files-variant-group",children:[Nt(T,W,ae,I,Q,V),Re&&(re==null?void 0:re.map(xe=>Nt(xe,W+16,ae,I,!1,V))),ue&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:W+16},children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:d})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]})]},`vg-${T.filename}`):Nt(T,W,ae,I,!1,V)},Jt=(T,W,ae,I,V=!1)=>{const re=12+W*16;if(T.type==="doc"){const Et=t.find(dn=>dn.filename===T.file);return!Et||B.has(Et.filename)?null:Mt(Et,re,ae,I,V)}const Q=T,ue=`container-${Q.id}`,ve=k.has(ue),Re=Fu(Q.items),xe=Q.autoAccept===!0,Dt=xe||V;return l.jsxs("div",{className:`${M(Q.id)} ${R(Q.id)?"files-drop-inside":""}`,children:[l.jsxs("div",{className:`files-row is-container${ve&&(ne!=null&&ne.containerKeys.has(ue))?" active-within":""} ${_(Q.id)?"dragging":""} ${M(Q.id)}`,style:{paddingLeft:re,...L(Q.id)},"data-drag-id":Q.id,"data-drag-type":"container-header","data-drag-ws":ae,"data-drag-parent":I||"","data-section-key":ue,onPointerDown:Et=>j(Et,{type:"container",id:Q.id,sourceWs:ae},Q.name),onClick:()=>!S&&ct(ue),onDoubleClick:Et=>{Et.stopPropagation(),Fe("container",Q.id,Q.name,ae)},onContextMenu:Et=>{Et.preventDefault(),Et.stopPropagation(),qe({x:Et.clientX,y:Et.clientY,type:"container",wsFilename:ae,containerId:Q.id,title:Q.name,nodes:Q.items,autoAccept:xe})},children:[l.jsx("span",{className:"files-row-icon",children:l.jsx(z$,{})}),(U==null?void 0:U.type)==="container"&&U.key===Q.id?mt(Y):l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"files-row-label",children:Q.name}),Dt&&l.jsx("span",{className:"sidebar-auto-accept-dot",title:xe?"Auto-accept on for this container":"Auto-accept inherited from workspace"}),l.jsx("span",{className:"files-row-count",children:Re})]})]}),l.jsxs("div",{className:`files-children${ve?" collapsed":""}`,"data-drop-ws":ae,"data-drop-container":Q.id,children:[d&&!(f!=null&&f.parentDocId)&&(f==null?void 0:f.wsFilename)===ae&&f.containerId===Q.id&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:12+(W+1)*16},children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:d})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),Q.items.filter(Et=>Et.type!=="doc"||!x(Et.file)).map(Et=>Jt(Et,W+1,ae,Q.id,Dt))]})]},Q.id)};return l.jsxs("div",{className:"files-scroll",ref:c,children:[l.jsxs("div",{className:"files-section",children:[l.jsxs("div",{className:`files-row is-section${k.has("docs")&&ne!==null&&ne.wsFilename===null?" active-within":""}`,"data-section-key":"docs",onClick:()=>ct("docs"),children:[l.jsx("span",{className:`files-row-chevron leading${k.has("docs")?" collapsed":""}`,children:l.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"6 9 12 15 18 9"})})}),l.jsx("span",{className:"files-row-label",children:"Documents"}),l.jsx("button",{className:"files-section-btn",onClick:T=>{T.stopPropagation(),Ve({anchor:T.target.getBoundingClientRect()})},title:"New document",children:"+"})]}),l.jsxs("div",{className:`files-section-list files-children${k.has("docs")?" collapsed":""}`,"data-drop-ws":"__docs__",children:[d&&!(f!=null&&f.parentDocId)&&(!f||!e.some(T=>T.filename===(f==null?void 0:f.wsFilename)))&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:28},children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:d})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),ze.map(T=>Mt(T,28))]})]}),e.map(T=>{var re,Q,ue;const W=((re=T.workspace)==null?void 0:re.root)||[],ae=k.has(T.filename),I=Fu(W),V=((Q=T.workspace)==null?void 0:Q.autoAccept)===!0||T.autoAccept===!0;return l.jsxs("div",{className:`files-section ${_(T.filename)?"dragging":""} ${(N==null?void 0:N.itemId)===T.filename?N.position==="before"?"files-ws-drop-before":"files-ws-drop-after":""}`,children:[l.jsx("div",{className:`files-row is-section${ae&&(ne==null?void 0:ne.wsFilename)===T.filename?" active-within":""}${(N==null?void 0:N.itemId)==="__section__"&&N.wsFilename===T.filename&&N.position==="inside"?" files-ws-drop-target":""}`,"data-section-key":T.filename,"data-ws-drag":T.filename,onPointerDown:ve=>j(ve,{type:"workspace",filename:T.filename},T.title),onClick:()=>!S&&ct(T.filename),onDoubleClick:ve=>{ve.stopPropagation(),Fe("workspace",T.filename,T.title)},onContextMenu:ve=>{var Re;ve.preventDefault(),ve.stopPropagation(),qe({x:ve.clientX,y:ve.clientY,type:"workspace",wsFilename:T.filename,title:T.title,nodes:W,autoAccept:((Re=T.workspace)==null?void 0:Re.autoAccept)===!0||T.autoAccept===!0})},children:(U==null?void 0:U.type)==="workspace"&&U.key===T.filename?l.jsxs(l.Fragment,{children:[l.jsx("span",{className:`files-row-chevron leading${ae?" collapsed":""}`,children:l.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"6 9 12 15 18 9"})})}),mt(Y)]}):l.jsxs(l.Fragment,{children:[l.jsx("span",{className:`files-row-chevron leading${ae?" collapsed":""}`,children:l.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"6 9 12 15 18 9"})})}),l.jsx("span",{className:"files-row-label",children:T.title}),(((ue=T.workspace)==null?void 0:ue.autoAccept)===!0||T.autoAccept===!0)&&l.jsx("span",{className:"sidebar-auto-accept-dot",title:"Auto-accept on for this workspace"}),l.jsx("span",{className:"files-row-count",children:I}),l.jsxs("div",{className:"files-section-actions",children:[l.jsx("button",{className:"files-section-btn",onClick:ve=>{ve.stopPropagation(),Ve({anchor:ve.target.getBoundingClientRect(),wsFilename:T.filename,containerId:null})},title:"New document",children:"+"}),l.jsx("button",{className:"files-section-btn",onClick:ve=>{ve.stopPropagation(),o.handleCreateContainer(T.filename,null)},title:"New container",children:"☐"})]})]})}),l.jsxs("div",{className:`files-section-list files-children${ae?" collapsed":""}`,"data-drop-ws":T.filename,children:[d&&!(f!=null&&f.parentDocId)&&(f==null?void 0:f.wsFilename)===T.filename&&f.containerId===null&&l.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:28},children:[l.jsxs("div",{className:"sidebar-item-title",children:[l.jsx("span",{className:"sidebar-writing-spinner"}),l.jsx("span",{className:"sidebar-item-title-text",children:d})]}),l.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),W.filter(ve=>ve.type!=="doc"||!x(ve.file)).map(ve=>Jt(ve,1,T.filename,null,V))]})]},T.filename)}),l.jsx("div",{className:"files-new-ws",children:l.jsx("button",{onClick:o.handleCreateWorkspace,children:"+ New Workspace"})}),Te&&l.jsx(Bd,{x:Te.x,y:Te.y,filename:Te.wsFilename,title:Te.title,onClose:()=>qe(null),onDuplicate:()=>{},onRename:()=>{Te.type==="workspace"?Fe("workspace",Te.wsFilename,Te.title):Te.containerId&&Fe("container",Te.containerId,Te.title,Te.wsFilename),qe(null)},onArchive:()=>{},onDelete:()=>{Te.type==="workspace"?o.handleDeleteWorkspace(Te.wsFilename):Te.containerId&&o.handleDeleteContainer(Te.wsFilename,Te.containerId,!1)},folderDocCount:Te.type==="container"?Fu(Te.nodes):0,onDeleteWithDocs:Te.type==="container"&&Te.containerId?()=>{o.handleDeleteContainer(Te.wsFilename,Te.containerId,!0)}:void 0,onPluginAction:(T,W)=>At(T,W,Te.nodes),pluginItems:K.filter(T=>T.folderCapable),folderMode:!0,onNewDoc:T=>{Ve({anchor:T.target.getBoundingClientRect(),wsFilename:Te.wsFilename,containerId:Te.type==="container"?Te.containerId:null}),qe(null)},onNewContainer:()=>{o.handleCreateContainer(Te.wsFilename,Te.type==="container"?Te.containerId:null),qe(null)},onAcceptAll:()=>{const T=Eu(Te.nodes);T.length&&Ye(T,"accept"),qe(null)},onRejectAll:()=>{const T=Eu(Te.nodes);T.length&&Ye(T,"reject"),qe(null)},folderAutoAccept:Te.autoAccept,folderAutoAcceptLabel:Te.type==="workspace"?"for workspace":"for container",onToggleFolderAutoAccept:()=>{fetch("/api/auto-accept/inherit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wsFile:Te.wsFilename,...Te.type==="container"?{containerId:Te.containerId}:{},enabled:!Te.autoAccept})}).catch(()=>{})},onRequestSortAll:()=>{const T=Eu(Te.nodes);T.length&&We(T)}}),z&&l.jsx(Bd,{x:z.x,y:z.y,filename:z.filename,title:z.title,bulkCount:z.bulkCount,onBulkDelete:tt,onBulkRequestSort:z.bulkCount?()=>We([...P]):void 0,onClose:()=>ee(null),onDuplicate:()=>xt(z.filename),onCreateVariant:z.docId?T=>{fetch("/api/documents/variant",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:z.filename,masterDocId:z.docId,variantType:T})}).catch(()=>{})}:void 0,onRename:()=>{Fe("doc",z.filename,z.title),ee(null)},onArchive:()=>o.handleArchive(z.filename),onDelete:()=>o.handleDelete(z.filename),onPluginAction:(T,W)=>St(T,W,z.filename,z.title),pluginItems:K,onSchedulePost:J?()=>{ye({filename:z.filename,title:z.title}),ee(null)}:void 0,onPostNow:z.contentType==="blog"?()=>{const T=(ge==null?void 0:ge.filename)===z.filename;Se({filename:z.filename,title:z.title,isActive:T}),ee(null)}:void 0,isAlreadyPublished:z.contentType==="blog"&&!!z.postedUrl,onViewAnalytics:z.docId&&z.lastSent&&(z.postedUrl||z.isNewsletter)?()=>{z.isNewsletter?Le({docId:z.docId,title:z.title}):z.postedUrl&&window.open(z.postedUrl,"_blank"),ee(null)}:void 0,viewAnalyticsLabel:z.isNewsletter?"View Analytics":z.contentType==="blog"&&z.postedUrl?"View Post":z.postedUrl?"View on X":"View Analytics",isApproved:o.getDocTags(z.filename).includes("✓"),onToggleApprove:()=>{o.getDocTags(z.filename).includes("✓")?o.handleRemoveTag(z.filename,"✓"):(o.handleAddTag(z.filename,"✓"),setTimeout(()=>window.dispatchEvent(new CustomEvent("ow-accept-all")),50))},isAutoAccept:(()=>{var W;const T=(W=t.find(ae=>ae.filename===z.filename))==null?void 0:W.autoAccept;return T===!0?!0:T===!1?!1:Pd(e,z.filename)})(),onToggleAutoAccept:()=>{var ae;const T=(ae=t.find(I=>I.filename===z.filename))==null?void 0:ae.autoAccept,W=T===!0?!0:T===!1?!1:Pd(e,z.filename);fetch("/api/auto-accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:z.filename,enabled:!W})}).then(()=>o.fetchDocs()).catch(()=>{})},isAlreadySent:!!z.lastSent,onMarkSent:()=>{const T=z.filename;o.getDocTags(T).includes("✓")&&o.handleRemoveTag(T,"✓"),s(T),setTimeout(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualPost:{postedAt:new Date().toISOString()}})}).then(()=>o.fetchDocs()).catch(()=>{})},100),ee(null)},sortState:z.bulkCount?void 0:(nn=z.sortRequest)!=null&&nn.proposal?"proposal":z.sortRequest?"pending":"none",sortProposalLabel:(()=>{var re;const T=(re=z.sortRequest)==null?void 0:re.proposal;if(!T)return;const W=e.find(Q=>Q.filename===T.wsFilename),ae=(W==null?void 0:W.title)||T.wsFilename;if(!T.containerId)return ae;const I=Q=>{for(const ue of Q){if(ue.type==="container"&&ue.id===T.containerId)return ue.name;if(ue.type==="container"){const ve=I(ue.items);if(ve)return ve}}return null},V=W!=null&&W.workspace?I(W.workspace.root):null;return V?`${ae} / ${V}`:ae})(),sortProposalReasoning:(Ht=(at=z.sortRequest)==null?void 0:at.proposal)==null?void 0:Ht.reasoning,onRequestSort:z.bulkCount?void 0:()=>We([z.filename]),onCancelSort:()=>Ue(z.filename),onAcceptSortProposal:()=>st(z.filename),onRejectSortProposal:()=>Ue(z.filename)}),D&&l.jsx(FT,{actionLabel:D.label,docTitle:D.title,onClose:()=>q(null),onConfirm:T=>{const W=K.find(ae=>ae.action===D.action);W&&St(D.action,W,D.filename,D.title,T),q(null)}}),Ee&&l.jsx(zT,{docId:Ee.docId,title:Ee.title,onClose:()=>Le(null)}),le&&l.jsx(Vl,{filename:le.filename,title:le.title,onClose:()=>ye(null)}),oe&&l.jsx(HT,{filename:oe.filename,title:oe.title,isActive:oe.isActive,onSwitchDocument:s,onClose:()=>Se(null)}),Ie&&l.jsx(UT,{anchorRect:Ie.anchor,onClose:()=>Ve(null),onSelect:T=>{Ve(null),Ie.wsFilename?o.handleCreateInWorkspace(Ie.wsFilename,Ie.containerId??null,T):T?fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:T})}).catch(()=>{}):i()}})]})}const Z$=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],e8=[{value:"any",label:"Any"},{value:"content_type",label:"Content Type"},{value:"connection",label:"Connection"}],VT=["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Anchorage","Pacific/Honolulu","America/Phoenix","America/Toronto","America/Vancouver","America/Sao_Paulo","America/Mexico_City","Europe/London","Europe/Paris","Europe/Berlin","Europe/Amsterdam","Europe/Rome","Europe/Madrid","Europe/Moscow","Asia/Tokyo","Asia/Shanghai","Asia/Kolkata","Asia/Dubai","Asia/Singapore","Asia/Seoul","Australia/Sydney","Australia/Melbourne","Pacific/Auckland"];function Dk(t){var e;try{const n=new Date,i=((e=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"short"}).formatToParts(n).find(c=>c.type==="timeZoneName"))==null?void 0:e.value)||"";return`${t.split("/").pop().replace(/_/g," ")} (${i})`}catch{return t}}function t8(t){if(t.length>0)return t[0].timezone;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;if(VT.includes(e))return e}catch{}return"America/New_York"}function n8({slots:t,onBack:e}){const[n,r]=y.useState(t),[s,i]=y.useState(()=>t8(t)),[o,c]=y.useState(!1),[d,f]=y.useState("09:00"),[h,m]=y.useState(["default"]),[g,v]=y.useState("any"),[x,k]=y.useState(!1),w=y.useRef(null);y.useEffect(()=>{if(!o)return;function _(R){w.current&&!w.current.contains(R.target)&&c(!1)}return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[o]);async function S(_){i(_);const R=[];for(const L of n){const $=await fetch(`/api/scheduler/slots/${L.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({timezone:_})});if($.ok){const B=await $.json();R.push(B.slot)}else R.push(L)}R.length>0&&r(R)}async function N(){const _=await fetch("/api/scheduler/slots",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({time:d,days:h.includes("default")?["default"]:h,filter_type:g,timezone:s})});if(_.ok){const R=await _.json();r(L=>[...L,R.slot]),k(!1),f("09:00"),m(["default"]),v("any")}}async function j(_){(await fetch(`/api/scheduler/slots/${_}`,{method:"DELETE"})).ok&&r(L=>L.filter($=>$.id!==_))}function M(_){m(R=>{if(_==="default")return["default"];const L=R.filter($=>$!=="default");if(L.includes(_)){const $=L.filter(B=>B!==_);return $.length===0?["default"]:$}return[...L,_]})}return l.jsxs("div",{className:"sidebar-schedule",children:[l.jsxs("div",{className:"sidebar-schedule-header",children:[l.jsx("button",{className:"sidebar-schedule-btn",onClick:e,title:"Back",children:l.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"m15 18-6-6 6-6"})})}),l.jsx("h3",{children:"Slot Settings"}),l.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>k(!x),children:x?"Cancel":"+ Add"})]}),l.jsxs("div",{className:"slot-tz",ref:w,children:[l.jsx("label",{className:"slot-tz-label",children:"Timezone"}),l.jsxs("button",{className:"slot-tz-trigger",onClick:()=>c(!o),children:[l.jsx("span",{children:Dk(s)}),l.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:`slot-tz-chevron ${o?"slot-tz-chevron--open":""}`,children:l.jsx("path",{d:"m6 9 6 6 6-6"})})]}),o&&l.jsx("div",{className:"slot-tz-dropdown",children:VT.map(_=>l.jsx("div",{className:`slot-tz-option ${_===s?"active":""}`,onClick:()=>{S(_),c(!1)},children:Dk(_)},_))})]}),x&&l.jsxs("div",{className:"slot-add-form",children:[l.jsxs("div",{className:"slot-add-row",children:[l.jsx("input",{type:"time",className:"slot-input",value:d,onChange:_=>f(_.target.value)}),l.jsx("select",{className:"slot-input",value:g,onChange:_=>v(_.target.value),children:e8.map(_=>l.jsx("option",{value:_.value,children:_.label},_.value))})]}),l.jsxs("div",{className:"slot-add-days",children:[l.jsx("button",{className:`sidebar-schedule-btn slot-day-btn ${h.includes("default")?"sidebar-schedule-btn--active":""}`,onClick:()=>M("default"),children:"Every day"}),Z$.map(_=>l.jsx("button",{className:`sidebar-schedule-btn slot-day-btn ${h.includes(_.toLowerCase())?"sidebar-schedule-btn--active":""}`,onClick:()=>M(_.toLowerCase()),children:_},_))]}),l.jsx("button",{className:"sidebar-schedule-btn sidebar-schedule-btn--active slot-create-btn",onClick:N,children:"Create Slot"})]}),l.jsx("div",{className:"slot-list",children:n.length===0?l.jsxs("div",{className:"schedule-empty",children:[l.jsx("div",{className:"schedule-empty-title",children:"No slots"}),l.jsx("div",{className:"schedule-empty-desc",children:"Create time slots to define your posting schedule."})]}):n.map(_=>l.jsxs("div",{className:"schedule-item slot-item",children:[l.jsx("div",{className:"schedule-item-time slot-item-time",children:r8(_.time)}),l.jsxs("div",{className:"schedule-item-content",children:[l.jsx("div",{className:"schedule-item-text",children:_.days.includes("default")?"Every day":_.days.join(", ")}),l.jsxs("div",{className:"schedule-item-meta",children:[l.jsxs("span",{children:["Filter: ",_.filter_type]}),_.filter_value&&l.jsxs("span",{children:["(",_.filter_value,")"]})]})]}),l.jsx("button",{className:"schedule-item-action schedule-item-action--danger slot-delete-btn",onClick:()=>j(_.id),title:"Delete slot",children:"×"})]},_.id))})]})}function r8(t){const[e,n]=t.split(":").map(Number),r=e>=12?"PM":"AM";return`${e%12||12}:${String(n).padStart(2,"0")} ${r}`}function s8({onBack:t}){const[e,n]=y.useState([]),[r,s]=y.useState([]),[i,o]=y.useState(null),[c,d]=y.useState(!1),[f,h]=y.useState(!0),m=y.useCallback(async()=>{try{const[S,N]=await Promise.all([fetch("/api/scheduler/autoplugs/goals"),fetch("/api/scheduler/autoplugs/tracking")]);if(S.ok){const j=await S.json();n(j.goals||[])}if(N.ok){const j=await N.json();s(j.tracking||[])}}catch{}h(!1)},[]);y.useEffect(()=>{m()},[m]);const g=async S=>{(await fetch(`/api/scheduler/autoplugs/goals/${S.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!S.enabled})})).ok&&n(j=>j.map(M=>M.id===S.id?{...M,enabled:!M.enabled}:M))},v=async S=>{(await fetch(`/api/scheduler/autoplugs/goals/${S}`,{method:"DELETE"})).ok&&(n(j=>j.filter(M=>M.id!==S)),o(null))},x=async S=>{(await fetch(`/api/scheduler/autoplugs/tracking/${S}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({skipped:!0})})).ok&&s(j=>j.map(M=>M.id===S?{...M,skipped:!0}:M))},k=e.reduce((S,N)=>N.rule&&N.enabled?Math.min(S,N.rule.threshold):S,1/0),w=k===1/0?50:k;return l.jsxs("div",{className:"sidebar-schedule",children:[l.jsxs("div",{className:"sidebar-schedule-header",children:[l.jsx("button",{className:"sidebar-schedule-back",onClick:t,title:"Back",children:l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"m15 18-6-6 6-6"})})}),l.jsx("h3",{children:"Autoplugs"}),l.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>d(!c),children:c?"Cancel":"+ Add"})]}),c&&l.jsx(o8,{onCreated:S=>{n(N=>[...N,S]),d(!1)}}),f?null:l.jsxs(l.Fragment,{children:[e.length===0?l.jsxs("div",{className:"schedule-empty",children:[l.jsx("div",{className:"schedule-empty-title",children:"No goals"}),l.jsx("div",{className:"schedule-empty-desc",children:"Create a goal to start autoplugging your tweets."})]}):e.map(S=>l.jsxs("div",{children:[l.jsxs("div",{className:"schedule-item",onClick:()=>o(i===S.id?null:S.id),children:[l.jsxs("div",{className:"schedule-item-content",children:[l.jsx("div",{className:"schedule-item-text",children:S.name}),l.jsx("div",{className:"schedule-item-meta",children:i8(S).map((N,j)=>l.jsx("span",{children:N},j))})]}),l.jsx("button",{className:`autoplug-toggle ${S.enabled?"autoplug-toggle--on":"autoplug-toggle--off"}`,onClick:N=>{N.stopPropagation(),g(S)},title:S.enabled?"Disable":"Enable"})]}),i===S.id&&l.jsx(a8,{goal:S,onSaved:N=>{n(j=>j.map(M=>M.id===N.id?N:M))},onDeleted:()=>v(S.id),onRefresh:m})]},S.id)),l.jsx("div",{className:"schedule-day-header",children:"Tracking"}),r.length===0?l.jsxs("div",{className:"schedule-empty",children:[l.jsx("div",{className:"schedule-empty-title",children:"No tracked tweets"}),l.jsx("div",{className:"schedule-empty-desc",children:"Tweets will appear here after posting."})]}):r.map(S=>l.jsxs("div",{className:"schedule-item",children:[l.jsxs("div",{className:"schedule-item-content",children:[l.jsx("div",{className:"schedule-item-text",children:S.original_text||`Tweet ${S.tweet_id}`}),l.jsxs("div",{className:"schedule-item-meta",children:[l.jsx("span",{children:l8(S.posted_at)}),l.jsxs("span",{children:[S.likes," likes"]}),l.jsxs("span",{children:[S.retweets," RTs"]}),S.views>0&&l.jsxs("span",{children:[c8(S.views)," views"]})]}),S.triggered?l.jsxs("div",{className:"autoplug-tracking-triggered",children:[l.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Autoplugged ",S.goal_name?`→ ${S.goal_name}`:""]}):S.skipped?l.jsx("div",{className:"autoplug-tracking-skipped",children:"Skipped"}):l.jsx("div",{className:"autoplug-tracking-bar",children:l.jsx("div",{className:"autoplug-tracking-bar-fill",style:{width:`${Math.min(100,S.likes/w*100)}%`}})})]}),!S.triggered&&!S.skipped&&l.jsx("button",{className:"autoplug-tracking-skip",onClick:()=>x(S.id),title:"Skip autoplug for this tweet",children:"×"})]},S.id))]})]})}function i8(t){const e=[];return t.rule&&(e.push(`${t.rule.threshold}+ ${t.rule.metric}`),e.push(t.rule.mode.charAt(0).toUpperCase()+t.rule.mode.slice(1)),t.rule.delay_minutes>0&&e.push(`${t.rule.delay_minutes}m delay`)),e.push(`${t.pool_count} msg${t.pool_count!==1?"s":""}`),e}function o8({onCreated:t}){const[e,n]=y.useState(""),[r,s]=y.useState(""),[i,o]=y.useState(""),[c,d]=y.useState("likes"),[f,h]=y.useState(50),[m,g]=y.useState(30),[v,x]=y.useState("static"),[k,w]=y.useState(!1),S=async()=>{if(e.trim()){w(!0);try{const N=await fetch("/api/scheduler/autoplugs/goals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e.trim(),link:r.trim()||null,description:i.trim()||null})});if(!N.ok){w(!1);return}const{goal:j}=await N.json();await fetch("/api/scheduler/autoplugs/rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({goal_id:j.id,metric:c,threshold:f,delay_minutes:m,mode:v})});const M=await fetch("/api/scheduler/autoplugs/goals");if(M.ok){const R=((await M.json()).goals||[]).find(L=>L.id===j.id);if(R){t(R);return}}t({...j,rule_count:1,pool_count:0,rule:{metric:c,threshold:f,delay_minutes:m,mode:v,id:""}})}finally{w(!1)}}};return l.jsxs("div",{className:"autoplug-editor",children:[l.jsxs("label",{children:["Name",l.jsx("input",{value:e,onChange:N=>n(N.target.value),placeholder:"Newsletter, Course..."})]}),l.jsxs("label",{children:["Link",l.jsx("input",{value:r,onChange:N=>s(N.target.value),placeholder:"https://..."})]}),l.jsxs("label",{children:["Description (context for LLM)",l.jsx("textarea",{value:i,onChange:N=>o(N.target.value),placeholder:"Weekly engineering insights...",rows:2})]}),l.jsxs("div",{className:"autoplug-editor-row",children:[l.jsx("input",{type:"number",value:f,onChange:N=>h(Number(N.target.value)),min:1}),l.jsxs("select",{value:c,onChange:N=>d(N.target.value),children:[l.jsx("option",{value:"likes",children:"likes"}),l.jsx("option",{value:"retweets",children:"retweets"}),l.jsx("option",{value:"views",children:"views"})]}),l.jsx("span",{className:"autoplug-editor-row-label",children:"wait"}),l.jsx("input",{type:"number",value:m,onChange:N=>g(Number(N.target.value)),min:0,className:"autoplug-delay-input"}),l.jsx("span",{className:"autoplug-editor-row-label",children:"min"})]}),l.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map(N=>l.jsx("button",{className:v===N?"active":"",onClick:()=>x(N),children:N==="llm"?"LLM":N.charAt(0).toUpperCase()+N.slice(1)},N))}),l.jsx("button",{className:"sidebar-schedule-btn sidebar-schedule-btn--active autoplug-create-btn",onClick:S,disabled:k||!e.trim(),children:k?"Creating...":"Create Goal"})]})}function a8({goal:t,onSaved:e,onDeleted:n,onRefresh:r}){var X,z,ee,P;const[s,i]=y.useState(t.name),[o,c]=y.useState(t.link||""),[d,f]=y.useState(t.description||""),[h,m]=y.useState(((X=t.rule)==null?void 0:X.metric)||"likes"),[g,v]=y.useState(((z=t.rule)==null?void 0:z.threshold)||50),[x,k]=y.useState(((ee=t.rule)==null?void 0:ee.delay_minutes)||30),[w,S]=y.useState(((P=t.rule)==null?void 0:P.mode)||"static"),[N,j]=y.useState([]),[M,_]=y.useState(""),[R,L]=y.useState(!1);y.useEffect(()=>{fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`).then(F=>F.json()).then(F=>j(F.pool||[])).catch(()=>{})},[t.id]);const $=async()=>{var F;L(!0);try{await fetch(`/api/scheduler/autoplugs/goals/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s,link:o||null,description:d||null})}),(F=t.rule)!=null&&F.id?await fetch(`/api/scheduler/autoplugs/rules/${t.rule.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({metric:h,threshold:g,delay_minutes:x,mode:w})}):await fetch("/api/scheduler/autoplugs/rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({goal_id:t.id,metric:h,threshold:g,delay_minutes:x,mode:w})}),r()}finally{L(!1)}},B=async()=>{if(!M.trim())return;const F=await fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:M.trim()})});if(F.ok){const G=await F.json();j(ie=>[...ie,G.message]),_("")}},U=async F=>{(await fetch(`/api/scheduler/autoplugs/pool/${F}`,{method:"DELETE"})).ok&&j(ie=>ie.filter(K=>K.id!==F))};return l.jsxs("div",{className:"autoplug-editor",children:[l.jsxs("label",{children:["Name",l.jsx("input",{value:s,onChange:F=>i(F.target.value)})]}),l.jsxs("label",{children:["Link",l.jsx("input",{value:o,onChange:F=>c(F.target.value),placeholder:"https://..."})]}),l.jsxs("label",{children:["Description",l.jsx("textarea",{value:d,onChange:F=>f(F.target.value),rows:2})]}),l.jsx("div",{className:"autoplug-editor-section-label",children:"Trigger"}),l.jsxs("div",{className:"autoplug-editor-row",children:[l.jsx("input",{type:"number",value:g,onChange:F=>v(Number(F.target.value)),min:1}),l.jsxs("select",{value:h,onChange:F=>m(F.target.value),children:[l.jsx("option",{value:"likes",children:"likes"}),l.jsx("option",{value:"retweets",children:"retweets"}),l.jsx("option",{value:"views",children:"views"})]}),l.jsx("span",{className:"autoplug-editor-row-label",children:"wait"}),l.jsx("input",{type:"number",value:x,onChange:F=>k(Number(F.target.value)),min:0,className:"autoplug-delay-input"}),l.jsx("span",{className:"autoplug-editor-row-label",children:"min"})]}),l.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map(F=>l.jsx("button",{className:w===F?"active":"",onClick:()=>S(F),children:F==="llm"?"LLM":F.charAt(0).toUpperCase()+F.slice(1)},F))}),l.jsxs("div",{className:"autoplug-pool-section",children:[l.jsx("div",{className:"autoplug-editor-section-label",children:"Static Pool"}),N.map(F=>l.jsxs("div",{className:"autoplug-pool-item",children:[l.jsx("span",{children:F.content}),l.jsx("button",{onClick:()=>U(F.id),title:"Remove",children:"×"})]},F.id)),l.jsxs("div",{className:"autoplug-pool-add",children:[l.jsx("input",{value:M,onChange:F=>_(F.target.value),placeholder:"Add message... (use {{link}} for link)",onKeyDown:F=>F.key==="Enter"&&B()}),l.jsx("button",{onClick:B,children:"+"})]})]}),(w==="llm"||w==="hybrid")&&l.jsx("div",{className:"autoplug-llm-hint",children:"LLM mode uses Author's Voice to generate contextual replies referencing the original tweet."}),l.jsxs("div",{className:"autoplug-editor-actions",children:[l.jsx("button",{className:"schedule-item-action",onClick:$,disabled:R,children:R?"Saving...":"Save"}),l.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:n,children:"Delete"})]})]})}function l8(t){const e=Date.now()-new Date(t).getTime(),n=Math.floor(e/6e4);if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function c8(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function u8({onBack:t}){const[e,n]=y.useState([]),[r,s]=y.useState([]),[i,o]=y.useState(!1),[c,d]=y.useState(!1),[f,h]=y.useState(null),[m,g]=y.useState(!0),v=y.useCallback(async()=>{try{const[w,S]=await Promise.all([fetch("/api/scheduler/queue"),fetch("/api/scheduler/slots"),fetch("/api/scheduler/sync",{method:"POST"})]);if(w.ok){const N=await w.json();n(N.items||[])}if(S.ok){const N=await S.json();s(N.slots||[])}}catch{}g(!1)},[]);y.useEffect(()=>{v()},[v]);const x=async w=>{(await fetch(`/api/scheduler/queue/${w}`,{method:"DELETE"})).ok&&(n(N=>N.filter(j=>j.id!==w)),h(null))};if(c)return l.jsx(s8,{onBack:()=>{d(!1),v()}});if(i)return l.jsx(n8,{slots:r,onBack:()=>{o(!1),v()}});const k=d8(r,e);return l.jsxs("div",{className:"sidebar-schedule",children:[l.jsxs("div",{className:"sidebar-schedule-header",children:[l.jsx("button",{className:"sidebar-schedule-back",onClick:t,title:"Back to documents",children:l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"m15 18-6-6 6-6"})})}),l.jsx("h3",{children:"Schedule"}),l.jsxs("div",{className:"sidebar-schedule-actions",children:[l.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>d(!0),title:"Autoplugs",children:l.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}),l.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>o(!0),title:"Manage slots",children:l.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),l.jsx("circle",{cx:"12",cy:"12",r:"3"})]})})]})]}),m?null:r.length===0?l.jsxs("div",{className:"schedule-empty",children:[l.jsx("div",{className:"schedule-empty-title",children:"No time slots"}),l.jsx("div",{className:"schedule-empty-desc",children:"Create time slots to define your posting schedule."})]}):k.map(({label:w,entries:S})=>l.jsxs("div",{className:"schedule-day",children:[l.jsx("div",{className:"schedule-day-header",children:w}),S.map((N,j)=>{var M,_,R,L,$;return N.type==="empty"?l.jsxs("div",{className:"schedule-slot-empty",children:[l.jsx("div",{className:"schedule-item-time",children:Bk(N.time)}),l.jsx("div",{className:"schedule-slot-empty-label",children:((M=N.slot)==null?void 0:M.filter_type)==="any"?"Open slot":`${(_=N.slot)==null?void 0:_.filter_type}: ${((R=N.slot)==null?void 0:R.filter_value)||"any"}`})]},`empty-${j}`):l.jsxs("div",{children:[l.jsxs("div",{className:"schedule-item",onClick:()=>h(f===N.item.id?null:N.item.id),children:[l.jsx("div",{className:"schedule-item-time",children:Bk(N.time)}),l.jsxs("div",{className:"schedule-item-content",children:[l.jsx("div",{className:"schedule-item-text",children:((L=N.item.content)==null?void 0:L.text)||JSON.stringify(N.item.content)}),l.jsxs("div",{className:"schedule-item-meta",children:[l.jsx("span",{className:`schedule-item-status schedule-item-status--${N.item.status}`}),l.jsx("span",{children:N.item.status}),N.item.connection_name&&l.jsx("span",{children:N.item.connection_name}),N.item.provider&&l.jsx("span",{children:N.item.provider})]})]})]}),f===N.item.id&&l.jsxs("div",{className:"schedule-item-expanded",children:[l.jsx("div",{className:"schedule-item-full-text",children:(($=N.item.content)==null?void 0:$.text)||JSON.stringify(N.item.content,null,2)}),l.jsx("div",{className:"schedule-item-actions",children:l.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:()=>x(N.item.id),children:"Cancel"})})]})]},N.item.id)})]},w))]})}function d8(t,e){const n=new Date,r=[];for(let c=0;c<7;c++){const d=new Date(n);d.setDate(d.getDate()+c),d.setHours(0,0,0,0);let f;c===0?f="Today":c===1?f="Tomorrow":f=d.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}),r.push({label:f,date:d})}const s=new Map;for(const c of e){const d=new Date(c.scheduled_at),f=`${d.getFullYear()}-${d.getMonth()}-${d.getDate()}-${d.getHours()}-${d.getMinutes()}`;s.set(f,c)}const i=new Set,o=[];for(const{label:c,date:d}of r){const f=[],h=d.getDay(),g=["sun","mon","tue","wed","thu","fri","sat"][h];for(const v of t){if(!(v.days.includes("default")||v.days.includes(g)))continue;const[k,w]=v.time.split(":").map(Number),S=new Date(d);if(S.setHours(k,w,0,0),Pk(d,n)&&S<n)continue;const N=`${S.getFullYear()}-${S.getMonth()}-${S.getDate()}-${k}-${w}`,j=s.get(N);j?(f.push({type:"filled",time:S,item:j,slot:v}),i.add(j.id)):f.push({type:"empty",time:S,slot:v})}for(const v of e){if(i.has(v.id))continue;const x=new Date(v.scheduled_at);Pk(x,d)&&(f.push({type:"filled",time:x,item:v}),i.add(v.id))}f.sort((v,x)=>v.time.getTime()-x.time.getTime()),f.length>0&&o.push({label:c,entries:f})}return o}function Pk(t,e){return t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate()}function Bk(t){return t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function f8({onBack:t}){const[e,n]=y.useState([]),[r,s]=y.useState(""),[i,o]=y.useState(null),[c,d]=y.useState(!1),f=y.useRef(null),h=y.useCallback(async()=>{try{const w=await fetch("/api/tasks");if(w.ok){const S=await w.json();n(S.tasks||[])}}catch{}},[]);y.useEffect(()=>{h()},[h]);const m=async()=>{const w=r.trim();if(w){s("");try{const S=await fetch("/api/tasks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:w})});if(S.ok){const N=await S.json();n(j=>[...j,N.task])}}catch{}}},g=w=>{o(w),fetch(`/api/tasks/${w}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({completed:!0})}).catch(()=>{}),setTimeout(()=>{n(S=>S.filter(N=>N.id!==w)),o(null)},400)},v=async w=>{try{(await fetch(`/api/tasks/${w}`,{method:"DELETE"})).ok&&n(N=>N.filter(j=>j.id!==w))}catch{}},x=()=>{d(!0),setTimeout(()=>{var w;return(w=f.current)==null?void 0:w.focus()},0)},k=e.filter(w=>!w.completed);return l.jsxs("div",{className:"sidebar-tasks",children:[l.jsxs("div",{className:"sidebar-tasks-header",children:[l.jsx("button",{className:"sidebar-tasks-back",onClick:t,title:"Back to documents",children:l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"m15 18-6-6 6-6"})})}),l.jsx("h3",{children:"Tasks"}),l.jsx("button",{className:"sidebar-tasks-add-btn",onClick:x,title:"Add task",children:"+"})]}),k.length===0&&!c?l.jsxs("div",{className:"sidebar-tasks-empty",children:[l.jsx("div",{className:"sidebar-tasks-empty-title",children:"No tasks"}),l.jsx("div",{className:"sidebar-tasks-empty-desc",children:"Add tasks to track your checklist."})]}):l.jsx("div",{className:"sidebar-tasks-list",children:k.map(w=>l.jsxs("div",{className:`sidebar-tasks-item${i===w.id?" completing":""}`,children:[l.jsx("input",{type:"checkbox",className:"sidebar-tasks-checkbox",checked:i===w.id,onChange:()=>g(w.id)}),l.jsx("span",{className:`sidebar-tasks-text${i===w.id?" completed":""}`,children:w.text}),l.jsx("button",{className:"sidebar-tasks-delete",onClick:()=>v(w.id),title:"Remove",children:"×"})]},w.id))}),c&&l.jsx("div",{className:"sidebar-tasks-add",children:l.jsx("input",{ref:f,type:"text",placeholder:"New task...",value:r,onChange:w=>s(w.target.value),onKeyDown:w=>{w.key==="Enter"&&m(),w.key==="Escape"&&(d(!1),s(""))},onBlur:()=>{r.trim()||d(!1)}})})]})}function h8({profiles:t,activeProfile:e,trashedProfiles:n,onSwitch:r,onCreate:s,onDelete:i,onRestore:o}){const[c,d]=y.useState(!1),[f,h]=y.useState(!1),[m,g]=y.useState(""),[v,x]=y.useState(null),k=y.useRef(null),w=y.useRef(null);y.useEffect(()=>{if(!c)return;const N=j=>{k.current&&!k.current.contains(j.target)&&(d(!1),h(!1),g(""),x(null))};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[c]),y.useEffect(()=>{f&&w.current&&w.current.focus()},[f]);const S=()=>{const N=m.trim();N&&(s(N),g(""),h(!1))};return l.jsxs("div",{className:"sidebar-profile-wrapper",ref:k,children:[l.jsx("button",{className:"sidebar-collapse-btn",onClick:()=>d(!c),title:`Profile: ${e}`,children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("circle",{cx:"12",cy:"8",r:"4"}),l.jsx("path",{d:"M5.5 21a8.38 8.38 0 0 1 13 0"})]})}),c&&l.jsxs("div",{className:"sidebar-profile-dropdown",children:[t.map(N=>l.jsxs("div",{className:"sidebar-profile-row",children:[v===N?l.jsxs("div",{className:"sidebar-profile-confirm",children:[l.jsx("span",{children:"Delete?"}),l.jsxs("div",{className:"sidebar-inline-confirm",children:[l.jsx("button",{onClick:()=>{i(N),x(null)},children:"Yes"}),l.jsx("button",{onClick:()=>x(null),children:"No"})]})]}):l.jsx(l.Fragment,{children:l.jsxs("button",{className:`sidebar-profile-option ${N===e?"active":""}`,onClick:()=>{N!==e&&r(N),d(!1)},children:[l.jsx("span",{className:"sidebar-profile-check",children:N===e?"✓":""}),l.jsx("span",{children:N})]})}),N!=="Default"&&N!==e&&v!==N&&l.jsx("button",{className:"sidebar-profile-delete-btn",onClick:j=>{j.stopPropagation(),x(N)},title:"Delete profile",children:"×"})]},N)),n.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"sidebar-profile-divider"}),l.jsx("div",{className:"sidebar-profile-trash-label",children:"Trash"}),n.map(N=>l.jsxs("div",{className:"sidebar-profile-row sidebar-profile-trashed",children:[l.jsx("span",{className:"sidebar-profile-trash-name",children:N}),l.jsx("button",{className:"sidebar-profile-restore-btn",onClick:()=>o(N),children:"Restore"})]},N))]}),l.jsx("div",{className:"sidebar-profile-divider"}),f?l.jsx("div",{className:"sidebar-profile-add-input",children:l.jsx("input",{ref:w,type:"text",value:m,onChange:N=>g(N.target.value),onKeyDown:N=>{N.key==="Enter"&&S(),N.key==="Escape"&&(h(!1),g(""))},placeholder:"Profile name..."})}):l.jsxs("button",{className:"sidebar-profile-option sidebar-profile-add",onClick:()=>h(!0),children:[l.jsx("span",{className:"sidebar-profile-check",children:"+"}),l.jsx("span",{children:"New Profile"})]})]})]})}const qT=200,KT=600,nv=260;function $k({open:t,onSwitchDocument:e,onCreateDocument:n,refreshKey:r,docTagsRefreshKey:s,workspacesRefreshKey:i,pendingDocs:o,writingTitle:c,writingTarget:d,pendingWriteFilenames:f,activeFilename:h,onClose:m,width:g,onWidthChange:v,floating:x}){const{docs:k,setDocs:w,workspaces:S,setWorkspaces:N,assignedFiles:j,fetchDocs:M,fetchWorkspaces:_,scrollRef:R,markPendingDelete:L}=j$(r,i),$=M$(M,_,w,N,k,L),B=$d(),U=y.useRef(!1),X=y.useCallback(Ye=>{Ye.preventDefault(),U.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";let ct=g;const Fe=ge=>{U.current&&(ct=Math.min(KT,Math.max(qT,ge.clientX)),v(ct))},Y=()=>{U.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("pointermove",Fe),window.removeEventListener("pointerup",Y);try{localStorage.setItem("ow-sidebar-width",String(ct))}catch{}};window.addEventListener("pointermove",Fe),window.addEventListener("pointerup",Y)},[g,v]),z=y.useCallback(Ye=>{w(ct=>ct.map(Fe=>({...Fe,isActive:Fe.filename===Ye}))),e(Ye)},[w,e]);y.useEffect(()=>{h&&w(Ye=>Ye.some(ct=>ct.filename===h?!ct.isActive:ct.isActive)?Ye.map(ct=>({...ct,isActive:ct.filename===h})):Ye)},[h,w,r]);const[ee,P]=y.useState(!1),[F,G]=y.useState(!1),[ie,K]=y.useState([]),[ce,J]=y.useState("Default"),A=y.useCallback(async()=>{try{const Ye=await fetch("/api/profiles");if(Ye.ok){const ct=await Ye.json();K(ct.profiles),J(ct.active)}}catch{}},[]);y.useEffect(()=>{A()},[A]);const D=y.useCallback(async Ye=>{try{(await fetch("/api/profiles/switch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Ye})})).ok&&(J(Ye),A())}catch{}},[A]),q=y.useCallback(async Ye=>{try{(await fetch("/api/profiles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Ye})})).ok&&A()}catch{}},[A]),[le,ye]=y.useState([]),oe=y.useCallback(async()=>{try{const Ye=await fetch("/api/profiles/trash");if(Ye.ok){const ct=await Ye.json();ye(ct.profiles)}}catch{}},[]);y.useEffect(()=>{oe()},[oe]);const Se=y.useCallback(async Ye=>{try{(await fetch(`/api/profiles/${encodeURIComponent(Ye)}`,{method:"DELETE"})).ok&&(A(),oe())}catch{}},[A,oe]),Ee=y.useCallback(async Ye=>{try{(await fetch("/api/profiles/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Ye})})).ok&&(A(),oe())}catch{}},[A,oe]),[Le,Ie]=y.useState(""),[Ve,Te]=y.useState(null),qe=y.useRef(),pt=y.useRef(null),ut=y.useCallback(Ye=>{if(Ie(Ye),qe.current&&clearTimeout(qe.current),!Ye.trim()){Te(null);return}qe.current=setTimeout(async()=>{try{const ct=await fetch(`/api/documents/search?q=${encodeURIComponent(Ye.trim())}&archived=true`);ct.ok&&Te(await ct.json())}catch{}},250)},[]);y.useEffect(()=>()=>{qe.current&&clearTimeout(qe.current)},[]);const be={docs:k,archivedDocs:[],workspaces:S,assignedFiles:j,pendingDocs:o,writingTitle:c,writingTarget:d,pendingWriteFilenames:f,onSwitchDocument:z,onCreateDocument:n,actions:$,scrollRef:R,searchQuery:Le,searchResults:Ve,onSearchChange:ut},ht=()=>{switch(B){case"files":return l.jsx(Q$,{...be});case"timeline":return l.jsx(B$,{...be});case"board":return l.jsx($$,{...be});case"shelf":return l.jsx(F$,{...be});default:return l.jsx(P$,{...be})}},xt=l.jsxs("div",{className:"sidebar-search",children:[l.jsxs("svg",{className:"sidebar-search-icon",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("circle",{cx:"10.5",cy:"10.5",r:"7"}),l.jsx("path",{d:"m20 20-4.5-4.5"})]}),l.jsx("input",{ref:pt,className:"sidebar-search-input",type:"text",placeholder:"Search...",value:Le,onChange:Ye=>ut(Ye.target.value)}),Le&&l.jsx("button",{className:"sidebar-search-clear",onClick:()=>ut(""),title:"Clear search",children:"×"})]}),St=t?{width:`${g}px`,minWidth:`${g}px`}:void 0,At=t&&!x?l.jsx("div",{className:"sidebar-resize-handle",onPointerDown:X,onDoubleClick:()=>{v(nv);try{localStorage.setItem("ow-sidebar-width",String(nv))}catch{}},title:"Drag to resize · double-click to reset"}):null;return B==="board"?l.jsxs("div",{className:`sidebar sidebar-board-mode ${t?"open":""}`,style:St,children:[ht(),At]}):l.jsxs("div",{className:`sidebar ${t?"open":""}`,style:St,children:[l.jsxs("div",{className:"sidebar-topbar",children:[l.jsxs("div",{className:"sidebar-logo",children:[l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[l.jsx("path",{d:"M17 3a2.83 2.83 0 0 1 4 4L7.5 20.5 2 22l1.5-5.5Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),l.jsx("path",{d:"M15 5l4 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),l.jsx("span",{className:"sidebar-logo-text",children:"OpenWriter"})]}),l.jsxs("div",{className:"sidebar-topbar-actions",children:[l.jsx(h8,{profiles:ie,activeProfile:ce,trashedProfiles:le,onSwitch:D,onCreate:q,onDelete:Se,onRestore:Ee}),l.jsx("button",{className:`sidebar-collapse-btn${ee?" sidebar-collapse-btn--active":""}`,onClick:()=>{P(!ee),G(!1)},title:"Schedule",children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),l.jsx("line",{x1:"16",x2:"16",y1:"1",y2:"5"}),l.jsx("line",{x1:"8",x2:"8",y1:"1",y2:"5"}),l.jsx("line",{x1:"3",x2:"21",y1:"9",y2:"9"})]})}),l.jsx("button",{className:`sidebar-collapse-btn${F?" sidebar-collapse-btn--active":""}`,onClick:()=>{G(!F),P(!1)},title:"Tasks",children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),l.jsx("path",{d:"m9 12 2 2 4-4"})]})}),m&&l.jsx("button",{className:"sidebar-collapse-btn",onClick:m,title:"Close sidebar",children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[l.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",stroke:"currentColor",strokeWidth:"2"}),l.jsx("path",{d:"M9 3v18",stroke:"currentColor",strokeWidth:"2"}),l.jsx("path",{d:"M15 10l-2 2 2 2",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})]}),F?l.jsx(f8,{onBack:()=>G(!1)}):ee?l.jsx(u8,{onBack:()=>P(!1)}):l.jsxs(l.Fragment,{children:[xt,ht()]}),At]})}function db(t,e,n){let r=t.resolve(e);for(;r.depth>0;){const s=r.node(r.depth),i=r.before(r.depth),o=i+s.nodeSize;if(s.childCount===1)e=i,n=o,r=t.resolve(e);else break}return{from:e,to:n}}function p8(t,e){const n=Wn(t,e);if(!n)return!1;const{node:r,pos:s}=n;return t.chain().command(({tr:i})=>(i.setNodeMarkup(s,void 0,{...r.attrs,pendingStatus:null}),!0)).run(),!0}function m8(t,e){const n=Wn(t,e);if(!n)return!1;const{node:r,pos:s}=n;return t.chain().command(({tr:i})=>(i.setNodeMarkup(s,void 0,{...r.attrs,pendingStatus:null,pendingOriginalContent:null,pendingSelectionFrom:null,pendingSelectionTo:null,pendingOriginalFrom:null,pendingOriginalTo:null}),!0)).run(),!0}function g8(t,e){var o;const n=Wn(t,e);if(!n)return!1;const{node:r,pos:s}=n;if(((o=r.attrs)==null?void 0:o.pendingStatus)!=="delete")return!0;const i=db(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function v8(t,e){var o;const n=Wn(t,e);if(!n)return!0;const{node:r,pos:s}=n;if(((o=r.attrs)==null?void 0:o.pendingStatus)!=="insert")return!0;const i=db(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function b8(t,e){var o,c;const n=Wn(t,e);if(!n)return!1;const{node:r,pos:s}=n;if(((o=r.attrs)==null?void 0:o.pendingStatus)!=="rewrite")return!0;const i=(c=r.attrs)==null?void 0:c.pendingOriginalContent;if(i)t.chain().deleteRange({from:s,to:s+r.nodeSize}).insertContentAt(s,i).run();else{const d=db(t.state.doc,s,s+r.nodeSize);t.chain().deleteRange(d).run()}return!0}function y8(t,e){var i;const n=Wn(t,e);if(!n)return!1;const{node:r,pos:s}=n;return((i=r.attrs)==null?void 0:i.pendingStatus)!=="delete"||t.chain().command(({tr:o})=>(o.setNodeMarkup(s,void 0,{...r.attrs,pendingStatus:null}),!0)).run(),!0}function x8(t,e){const n=nf(t,e);if(n.length===0)return!1;for(const r of[...n].reverse()){const s=Wn(t,r.nodeId);s&&t.chain().command(({tr:i})=>(i.setNodeMarkup(s.pos,void 0,{...s.node.attrs,pendingStatus:null,pendingOriginalContent:null,pendingGroupId:null,pendingSelectionFrom:null,pendingSelectionTo:null,pendingOriginalFrom:null,pendingOriginalTo:null}),!0)).run()}return!0}function w8(t,e){var c;const n=nf(t,e);if(n.length===0)return!1;const r=(c=n[0].node.attrs)==null?void 0:c.pendingOriginalContent,s=n[0].pos,i=n[n.length-1],o=i.pos+i.node.nodeSize;try{return r&&Array.isArray(r)&&r.length>0?t.chain().deleteRange({from:s,to:o}).insertContentAt(s,r).run():t.chain().deleteRange({from:s,to:o}).run(),!0}catch{return!1}}function GT(t,e){var i,o;const n=Wn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return x8(t,r);switch((o=n.node.attrs)==null?void 0:o.pendingStatus){case"insert":return p8(t,e);case"rewrite":return m8(t,e);case"delete":return g8(t,e);default:return!1}}function JT(t,e){var i,o;const n=Wn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return w8(t,r);switch((o=n.node.attrs)==null?void 0:o.pendingStatus){case"insert":return v8(t,e);case"rewrite":return b8(t,e);case"delete":return y8(t,e);default:return!1}}function k8(t){const e=YT(t).reverse();for(const n of e)GT(t,n);t.view&&lb(t.view)}function S8(t){const e=YT(t).reverse();for(const n of e)JT(t,n);t.view&&lb(t.view)}function fb(t){const e=[],n=new Set;return t.state.doc.descendants((r,s)=>{var o,c,d;const i=(o=r.attrs)==null?void 0:o.pendingStatus;if(i&&((c=r.attrs)!=null&&c.id)){const f=(d=r.attrs)==null?void 0:d.pendingGroupId;if(f){if(n.has(f))return!0;n.add(f)}e.push({nodeId:r.attrs.id,pos:s,pendingStatus:i,groupId:f,editor:t})}return!0}),e}function Pp(t){const e=[];for(const n of t)n&&!n.isDestroyed&&e.push(...fb(n));return e}function YT(t){return fb(t).map(e=>e.nodeId)}function E8(t){let e=0,n=0,r=0;for(const s of t)s.pendingStatus==="insert"?e++:s.pendingStatus==="rewrite"?n++:s.pendingStatus==="delete"&&r++;return{insert:e,rewrite:n,delete:r,total:t.length}}function rl(t,e){if(t.isDestroyed)return;let n=-1;if(t.state.doc.descendants((i,o)=>{var c;return((c=i.attrs)==null?void 0:c.id)===e?(n=o,!1):!0}),n===-1)return;const r=t.view.nodeDOM(n),s=r instanceof HTMLElement?r:r==null?void 0:r.parentElement;if(s){s.scrollIntoView({behavior:"smooth",block:"center"});return}try{const i=t.view.coordsAtPos(n),o=t.view.dom.closest(".editor-container");if(o){const c=o.getBoundingClientRect(),d=i.top-c.top+o.scrollTop-o.clientHeight/2;o.scrollTo({top:d,behavior:"smooth"})}}catch{}}function N8(t){const[e,n]=y.useState([]),[r,s]=y.useState(0),i=y.useRef(),o=y.useRef(new Set),c=y.useCallback(()=>{const S=t.filter(R=>R&&!R.isDestroyed);if(S.length===0){n([]),o.current=new Set;return}const N=Pp(S);n(N);const j=o.current,M=new Set(N.map(R=>R.nodeId));let _=-1;if(j.size>0){for(let R=0;R<N.length;R++)if(!j.has(N[R].nodeId)){_=R;break}}o.current=M,_>=0?(s(_),rl(N[_].editor,N[_].nodeId)):N.length===0?s(0):s(R=>Math.min(R,N.length-1))},[t]);y.useEffect(()=>{const S=t.filter(M=>M&&!M.isDestroyed);if(S.length===0)return;const N=()=>{clearTimeout(i.current),i.current=setTimeout(c,50)};for(const M of S)M.on("transaction",N);c();const j=setTimeout(()=>{const M=Pp(S.filter(_=>!_.isDestroyed));M.length>0&&rl(M[0].editor,M[0].nodeId)},150);return()=>{for(const M of S)M.isDestroyed||M.off("transaction",N);clearTimeout(i.current),clearTimeout(j)}},[t,c]),y.useEffect(()=>{const S=e[r]??null;return lk((S==null?void 0:S.nodeId)??null,(S==null?void 0:S.groupId)??null),S!=null&&S.editor&&!S.editor.isDestroyed&&S.editor.view&&lb(S.editor.view),()=>{lk(null)}},[r,e]);const d=E8(e),f=e[r]??null,h=y.useCallback(()=>{if(e.length===0)return;const S=(r+1)%e.length;s(S),e[S]&&rl(e[S].editor,e[S].nodeId)},[e,r]),m=y.useCallback(()=>{if(e.length===0)return;const S=(r-1+e.length)%e.length;s(S),e[S]&&rl(e[S].editor,e[S].nodeId)},[e,r]),g=y.useCallback(()=>{const S=t.filter(M=>M&&!M.isDestroyed),N=Pp(S);if(N.length===0)return;const j=Math.min(r,N.length-1);rl(N[j].editor,N[j].nodeId)},[t,r]),v=y.useCallback(()=>{f&&(GT(f.editor,f.nodeId),c(),g())},[f,c,g]),x=y.useCallback(()=>{f&&(JT(f.editor,f.nodeId),c(),g())},[f,c,g]),k=y.useCallback(()=>{const S=t.filter(N=>N&&!N.isDestroyed);for(const N of S)k8(N);c()},[t,c]),w=y.useCallback(()=>{const S=t.filter(N=>N&&!N.isDestroyed);for(const N of S)S8(N);c()},[t,c]);return{pendingNodes:e,counts:d,currentNode:f,currentIndex:r,hasPending:d.total>0,goToNext:h,goToPrevious:m,acceptCurrent:v,rejectCurrent:x,acceptAll:k,rejectAll:w,refresh:c}}const C8=[{fmt:"epub",label:"EPUB"},{fmt:"html",label:"HTML"},{fmt:"docx",label:"DOCX"},{fmt:"md",label:"MD"}];function Fk({contentType:t,docId:e,manuscriptStyle:n,onSwitchDocument:r}){const[s,i]=y.useState([]),[o,c]=y.useState("manifest"),d=t==="manuscript",f=n==="indented"?"indented":"spaced",[h,m]=y.useState(null),g=h??f;y.useEffect(()=>{m(null)},[n,e]);const v=S=>{S!==g&&(m(S),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manuscriptContext:{paragraphStyle:S}})}).then(()=>{window.dispatchEvent(new CustomEvent("ow-manuscript-restyle"))}).catch(()=>m(null)))};y.useEffect(()=>{let S=!1;const N=()=>{fetch("/api/manuscripts").then(j=>j.json()).then(j=>{S||i(j.manuscripts||[])}).catch(()=>{})};return N(),window.addEventListener("ow-documents-changed",N),()=>{S=!0,window.removeEventListener("ow-documents-changed",N)}},[]),y.useEffect(()=>{c("manifest")},[e]);const x=S=>{c(S),window.dispatchEvent(new CustomEvent(S==="preview"?"ow-manuscript-preview":"ow-manuscript-manifest"))},k=S=>`/api/manuscript/export?docId=${encodeURIComponent(e||"")}&format=${S}`,w=S=>`review-panel__toggle-btn${S?" review-panel__toggle-btn--active":""}`;return l.jsxs(l.Fragment,{children:[d&&e&&l.jsxs("div",{className:"review-tab__section",children:[l.jsx("div",{className:"review-tab__section-label",children:"This Manuscript"}),l.jsxs("div",{className:"review-tab__toggle",role:"tablist","aria-label":"Manuscript view",children:[l.jsx("button",{type:"button",className:w(o==="manifest"),onClick:()=>x("manifest"),children:"Manifest"}),l.jsx("button",{type:"button",className:w(o==="preview"),onClick:()=>x("preview"),title:o==="preview"?"Re-render":"Preview the compiled book",children:"Preview"})]}),l.jsx("div",{className:"ms-style-label",children:"Paragraph style"}),l.jsxs("div",{className:"review-tab__toggle",role:"tablist","aria-label":"Paragraph style",children:[l.jsx("button",{type:"button",className:w(g==="spaced"),onClick:()=>v("spaced"),title:"Blank line between paragraphs, no indent",children:"Spaced"}),l.jsx("button",{type:"button",className:w(g==="indented"),onClick:()=>v("indented"),title:"First-line indent, no gap — traditional print",children:"Indented"})]}),l.jsx("div",{className:"ms-dl-row",children:C8.map(S=>l.jsx("a",{className:"ms-dl-btn",href:k(S.fmt),download:!0,children:S.label},S.fmt))})]}),l.jsxs("div",{className:"review-tab__section",children:[l.jsx("div",{className:"review-tab__section-label",children:"Manuscripts"}),s.length===0?l.jsx("div",{className:"ms-empty",children:"None yet — create one from the “+” menu."}):l.jsx("ul",{className:"ms-list",children:s.map(S=>l.jsx("li",{children:l.jsx("button",{type:"button",className:S.docId===e?"ms-item ms-item--active":"ms-item",onClick:()=>r(S.filename),title:S.title,children:S.title})},S.docId))})]})]})}const XT="ow-review-scope";function _8(){try{return localStorage.getItem(XT)==="workspace"?"workspace":"all"}catch{return"all"}}function T8(t){try{localStorage.setItem(XT,t)}catch{}}function QT(t){if(!t)return[];const e=[];for(const n of t)n.type==="doc"&&n.file&&e.push(n.file),n.type==="container"&&n.items&&e.push(...QT(n.items));return e}function ZT(t,e){if(!t)return!1;for(const n of t)if(n.type==="doc"&&n.file===e||n.type==="container"&&n.items&&ZT(n.items,e))return!0;return!1}const Di={strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},j8=()=>l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:l.jsx("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",...Di})}),M8=()=>l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:l.jsx("path",{d:"M6 3l5 5-5 5",stroke:"currentColor",...Di})}),A8=()=>l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:l.jsx("path",{d:"M3 10l5-5 5 5",stroke:"currentColor",...Di})}),R8=()=>l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:l.jsx("path",{d:"M3 6l5 5 5-5",stroke:"currentColor",...Di})}),O8=()=>l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:l.jsx("path",{d:"M3 8.5l3.5 3.5L13 5",stroke:"currentColor",...Di})}),I8=()=>l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[l.jsx("path",{d:"M1 8.5l3.5 3.5L11 5",stroke:"currentColor",...Di}),l.jsx("path",{d:"M8 12l.5.5L15 6",stroke:"currentColor",...Di})]}),zk=()=>l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:l.jsx("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor",...Di})});function e2(t,e,n){const r=Wn(t,e);if(!r)return!1;const{pos:s,node:i}=r,o={type:n.type||i.type.name,attrs:{...n.attrs||{},id:i.attrs.id,pendingStatus:i.attrs.pendingStatus,pendingOriginalContent:i.attrs.pendingOriginalContent,pendingSelectionFrom:i.attrs.pendingSelectionFrom,pendingSelectionTo:i.attrs.pendingSelectionTo,pendingOriginalFrom:i.attrs.pendingOriginalFrom,pendingOriginalTo:i.attrs.pendingOriginalTo},content:n.content};try{return t.chain().command(({tr:c})=>(c.setMeta("addToHistory",!1),!0)).deleteRange({from:s,to:s+i.nodeSize}).insertContentAt(s,o).run(),!0}catch{return!1}}function t2(t,e,n){const r=nf(t,e);if(r.length===0)return!1;const s=r[0].pos,i=r[r.length-1].pos+r[r.length-1].node.nodeSize;try{return t.chain().command(({tr:o})=>(o.setMeta("addToHistory",!1),!0)).deleteRange({from:s,to:i}).insertContentAt(s,n).run(),!0}catch{return!1}}function Nu(t,e){if(!ab()||!e)return!1;const n=M5();return j5()&&n&&Array.isArray(n)?t2(t,e,n):n&&e2(t,e,n),ul(!1),!0}function L8(t,e){return t.indexOf(e)}function D8({editors:t,pendingDocs:e,currentFilename:n,docId:r,contentType:s,manuscriptStyle:i,pendingTitle:o,onSwitchDocument:c,sendMessage:d,getDocument:f,docVersionRef:h}){const{counts:m,currentNode:g,currentIndex:v,hasPending:x,goToNext:k,goToPrevious:w,acceptCurrent:S,rejectCurrent:N,acceptAll:j,rejectAll:M}=N8(t),[_,R]=y.useState(o?"title":"body");y.useEffect(()=>{o&&_!=="title"&&m.total===0?R("title"):!o&&_==="title"&&R("body")},[o,m.total,_]);const L=!!o,$=m.total+(L?1:0),B=_==="title"?0:(L?1:0)+v,[U,X]=y.useState(!1);y.useEffect(()=>{_!=="title"&&X(!1)},[_]),y.useEffect(()=>{const Y=!!o&&_==="title",ge={docId:r,titleFocused:Y,titleShowOriginal:Y&&U};return window.dispatchEvent(new CustomEvent("ow-pending-review-cursor",{detail:ge})),()=>{window.dispatchEvent(new CustomEvent("ow-pending-review-cursor",{detail:{docId:r,titleFocused:!1,titleShowOriginal:!1}}))}},[r,o,_,U]);const z=y.useCallback(()=>{r&&d({type:"accept-pending-title",docId:r})},[r,d]),ee=y.useCallback(()=>{r&&d({type:"reject-pending-title",docId:r})},[r,d]),P=y.useRef(null),F=y.useRef(null),[G,ie]=y.useState(()=>_8()),[K,ce]=y.useState([]);y.useEffect(()=>{let Y=!1;async function ge(){try{const me=await(await fetch("/api/workspaces")).json();if(!Array.isArray(me))return;const ze=await Promise.all(me.map(async Ae=>{try{const Qe=await(await fetch(`/api/workspaces/${encodeURIComponent(Ae.filename)}`)).json();return{...Ae,workspace:Qe}}catch{return Ae}}));Y||ce(ze)}catch{}}ge();const ne=()=>ge();return window.addEventListener("ow-workspaces-changed",ne),()=>{Y=!0,window.removeEventListener("ow-workspaces-changed",ne)}},[]);const J=y.useMemo(()=>{var ge;if(K.length===0||!n)return null;const Y=K.find(ne=>{var he;return ZT((he=ne.workspace)==null?void 0:he.root,n)});return Y?new Set(QT((ge=Y.workspace)==null?void 0:ge.root)):null},[K,n]),A=y.useMemo(()=>G==="all"||!J?e.filenames:e.filenames.filter(Y=>J.has(Y)),[G,e.filenames,J]),D=y.useCallback(Y=>{ie(Y),T8(Y)},[]),q=A.length,le=L8(A,n),ye=(g==null?void 0:g.pendingStatus)==="rewrite",oe=!!(g!=null&&g.groupId),Se=ye,Ee=y.useCallback(()=>{var ge,ne;const Y=g==null?void 0:g.editor;if(!(!Y||!g||g.pendingStatus!=="rewrite"))if(U)F.current&&Nu(F.current,P.current),P.current=null,F.current=null,X(!1);else if(oe&&g.groupId){const he=nf(Y,g.groupId);if(he.length===0)return;const me=(ge=he[0].node.attrs)==null?void 0:ge.pendingOriginalContent;if(!me||!Array.isArray(me))return;const ze=he.map(Qe=>Qe.node.toJSON()),Ae=me.map((Qe,tt)=>({...Qe,attrs:{...Qe.attrs||{},pendingStatus:"rewrite",pendingGroupId:g.groupId,...tt===0?{pendingOriginalContent:me}:{}}}));if(ul(!0,g.nodeId,ze,g.groupId),!t2(Y,g.groupId,Ae)){ul(!1);return}P.current=g.nodeId,F.current=Y,X(!0)}else{const he=Wn(Y,g.nodeId);if(!he)return;const{node:me}=he,ze=(ne=me.attrs)==null?void 0:ne.pendingOriginalContent;if(!ze)return;const Ae=me.toJSON();if(ul(!0,g.nodeId,Ae),!e2(Y,g.nodeId,ze)){ul(!1);return}P.current=g.nodeId,F.current=Y,X(!0)}},[g,U,oe]);y.useEffect(()=>{if(!U)return;const Y=P.current,ge=F.current;Y&&ge&&(g==null?void 0:g.nodeId)!==Y&&(Nu(ge,Y),P.current=null,F.current=null,X(!1))},[g==null?void 0:g.nodeId,U]),y.useEffect(()=>{if(t.length!==0)return()=>{ab()&&P.current&&F.current&&(Nu(F.current,P.current),P.current=null,F.current=null)}},[t]);const Le=y.useCallback(Y=>{if(!n)return;if(!t.some(ne=>!ne||ne.isDestroyed?!1:fb(ne).length>0)){const ne=f==null?void 0:f();ne&&d({type:"doc-update",document:ne,filename:n,version:(h==null?void 0:h.current)??0}),d({type:"pending-resolved",filename:n,action:Y})}},[t,n,d,f,h]),Ie=y.useCallback(()=>{F.current&&U&&P.current&&(Nu(F.current,P.current),P.current=null,F.current=null,X(!1))},[U]),Ve=y.useCallback(()=>{if(_==="title"&&o){z(),m.total>0&&R("body");return}Ie(),S(),Le("accept")},[_,o,z,m.total,Ie,S,Le]),Te=y.useCallback(()=>{if(_==="title"&&o){ee(),m.total>0&&R("body");return}Ie(),N(),Le("reject")},[_,o,ee,m.total,Ie,N,Le]),qe=y.useCallback(()=>{Ie(),o&&z(),j(),Le("accept")},[Ie,o,z,j,Le]);y.useEffect(()=>{const Y=()=>qe();return window.addEventListener("ow-accept-all",Y),()=>window.removeEventListener("ow-accept-all",Y)},[qe]);const pt=y.useCallback(()=>{Ie(),o&&ee(),M(),Le("reject")},[Ie,o,ee,M,Le]),ut=y.useCallback(()=>{if(!($<=1)){if(_==="title"){R("body");return}if(L&&v>=m.total-1){k(),R("title");return}k()}},[$,_,L,v,m.total,k]),be=y.useCallback(()=>{if(!($<=1)){if(_==="title"){w(),R("body");return}if(L&&v===0){R("title");return}w()}},[$,_,L,v,w]),ht=y.useCallback(()=>{if(q===0||q===1&&le===0)return;const Y=le<=0?q-1:le-1;c(A[Y])},[q,le,A,c]),xt=y.useCallback(()=>{if(q===0||q===1&&le===0)return;const Y=le>=q-1?0:le+1;c(A[Y])},[q,le,A,c]);y.useEffect(()=>{if(!x&&!o)return;const Y=ge=>{if(!(ge.target instanceof HTMLInputElement||ge.target instanceof HTMLTextAreaElement)&&!(ge.target instanceof HTMLElement&&ge.target.closest("[contenteditable]")))switch(ge.key){case"j":case"ArrowDown":!ge.metaKey&&!ge.ctrlKey&&(ge.preventDefault(),ut());break;case"k":case"ArrowUp":!ge.metaKey&&!ge.ctrlKey&&(ge.preventDefault(),be());break;case"h":case"ArrowLeft":!ge.metaKey&&!ge.ctrlKey&&!ge.altKey&&(ge.preventDefault(),ht());break;case"l":case"ArrowRight":!ge.metaKey&&!ge.ctrlKey&&!ge.altKey&&(ge.preventDefault(),xt());break;case"a":!ge.metaKey&&!ge.ctrlKey&&!ge.shiftKey&&(ge.preventDefault(),Ve());break;case"r":!ge.metaKey&&!ge.ctrlKey&&(ge.preventDefault(),Te());break;case"A":ge.shiftKey&&!ge.metaKey&&!ge.ctrlKey&&(ge.preventDefault(),qe());break;case"R":ge.shiftKey&&!ge.metaKey&&!ge.ctrlKey&&(ge.preventDefault(),pt());break;case"o":!ge.metaKey&&!ge.ctrlKey&&!ge.shiftKey&&(ge.preventDefault(),_==="title"?X(ne=>!ne):Ee());break}};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[x,o,ut,be,ht,xt,Ve,Te,qe,pt,Ee]);const St=le>=0?`${le+1} / ${q}`:`— / ${q}`,At=e.filenames.length,Ye=!J,Fe=At>0?l.jsxs("div",{className:"review-tab__section",children:[l.jsx("div",{className:"review-tab__section-label",children:"Scope"}),l.jsxs("div",{className:"review-tab__toggle",children:[l.jsx("button",{type:"button",className:`review-panel__toggle-btn${G==="all"?" review-panel__toggle-btn--active":""}`,onClick:()=>D("all"),title:"Cycle every pending doc in the profile",children:"All"}),l.jsx("button",{type:"button",className:`review-panel__toggle-btn${G==="workspace"?" review-panel__toggle-btn--active":""}`,onClick:()=>!Ye&&D("workspace"),disabled:Ye,title:Ye?"Current doc is not in a workspace":"Only cycle pending docs in this workspace",children:"Workspace"})]})]}):null;return!x&&!o?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"review-tab__empty",children:[l.jsx("div",{className:"review-tab__empty-title",children:"All caught up"}),l.jsx("div",{className:"review-tab__empty-note",children:"No pending agent changes. New writes from agents will land here for review."})]}),l.jsx("div",{className:"review-tab",children:l.jsx(Fk,{contentType:s,docId:r,manuscriptStyle:i,onSwitchDocument:c})})]}):l.jsxs("div",{className:"review-tab",children:[Fe,q>1&&l.jsxs("div",{className:"review-tab__section",children:[l.jsx("div",{className:"review-tab__section-label",children:"Document"}),l.jsxs("div",{className:"review-tab__row",children:[l.jsx("button",{className:"review-panel__btn",onClick:ht,title:"Previous doc (h)",children:l.jsx(j8,{})}),l.jsx("button",{className:"review-panel__btn",onClick:xt,title:"Next doc (l)",children:l.jsx(M8,{})}),l.jsx("span",{className:"review-panel__counter",children:St})]})]}),l.jsx("div",{className:"review-tab__section review-tab__section--actions",children:l.jsxs("div",{className:"review-tab__toggle",children:[l.jsx("button",{className:`review-panel__toggle-btn${(Se||_==="title")&&!U?" review-panel__toggle-btn--active":""}`,onClick:()=>{_==="title"?U&&X(!1):Se&&U&&Ee()},disabled:!Se&&_!=="title",title:"Show modified (o)",children:"Modified"}),l.jsx("button",{className:`review-panel__toggle-btn${(Se||_==="title")&&U?" review-panel__toggle-btn--active":""}`,onClick:()=>{_==="title"?U||X(!0):Se&&!U&&Ee()},disabled:!Se&&_!=="title",title:"Show original (o)",children:"Original"})]})}),l.jsxs("div",{className:"review-tab__section",children:[l.jsx("div",{className:"review-tab__section-label",children:_==="title"?"Title":"Change"}),l.jsxs("div",{className:"review-tab__row",children:[l.jsx("button",{className:"review-panel__btn",onClick:be,disabled:$<=1,title:"Previous (k)",children:l.jsx(A8,{})}),l.jsx("button",{className:"review-panel__btn",onClick:ut,disabled:$<=1,title:"Next (j)",children:l.jsx(R8,{})}),l.jsxs("span",{className:"review-panel__counter",children:[B+1," / ",$]})]})]}),l.jsx("div",{className:"review-tab__section",children:l.jsxs("div",{className:"review-tab__row",children:[l.jsxs("button",{className:"review-tab__judge-btn review-tab__judge-btn--accept",onClick:Ve,title:"Accept (a)",children:[l.jsx(O8,{}),l.jsx("span",{children:"Accept"})]}),l.jsxs("button",{className:"review-tab__judge-btn review-tab__judge-btn--reject",onClick:Te,title:"Reject (r)",children:[l.jsx(zk,{}),l.jsx("span",{children:"Reject"})]})]})}),l.jsx("div",{className:"review-tab__section",children:l.jsxs("div",{className:"review-tab__row",children:[l.jsxs("button",{className:"review-tab__bulk-btn review-tab__bulk-btn--accept",onClick:qe,title:"Accept all (Shift+A)",children:[l.jsx(I8,{}),l.jsx("span",{children:"Accept all"})]}),l.jsxs("button",{className:"review-tab__bulk-btn review-tab__bulk-btn--reject",onClick:pt,title:"Reject all (Shift+R)",children:[l.jsx(zk,{}),l.jsx("span",{children:"Reject all"})]})]})}),l.jsx(Fk,{contentType:s,docId:r,manuscriptStyle:i,onSwitchDocument:c})]})}const P8={"agent-finished":"Agent finished",accept:"Accepted",manual:"Saved"};function B8(t){const e=Date.now()-t,n=Math.floor(e/1e3);if(n<60)return"Just now";const r=Math.floor(n/60);if(r<60)return`${r}m ago`;const s=Math.floor(r/60);if(s<24)return`${s}h ago`;const i=Math.floor(s/24);return i<7?`${i}d ago`:new Date(t).toLocaleDateString()}function Uk(t){return t==="human"?"you":t}function $8({docId:t}){const[e,n]=y.useState([]),[r,s]=y.useState(null),[i,o]=y.useState(!1),c=y.useCallback(()=>{if(!t){n([]);return}fetch(`/api/commits/${t}`).then(h=>h.ok?h.json():{commits:[]}).then(h=>n(Array.isArray(h.commits)?h.commits:[])).catch(()=>n([]))},[t]);y.useEffect(()=>{c()},[c]);const d=y.useCallback(async()=>{if(!t||i)return;const h=window.prompt('Save version — optional note (e.g. "first full draft"):')??void 0;o(!0);try{(await(await fetch("/api/commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({docId:t,note:h||void 0})})).json().catch(()=>({}))).committed||window.setTimeout(()=>{},0),c()}catch{}o(!1)},[t,i,c]),f=y.useCallback(async h=>{if(!i){o(!0);try{(await fetch(`/api/versions/${h}/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:"full"})})).ok&&c()}catch{}o(!1)}},[i,c]);return l.jsxs("div",{className:"versions-tab",children:[l.jsx("div",{className:"versions-tab__actions",children:l.jsx("button",{className:"versions-tab__save-btn",disabled:!t||i,onClick:d,children:"+ Save version"})}),l.jsx("div",{className:"versions-tab__list",children:e.length===0?l.jsx("div",{className:"versions-tab__empty",children:'No versions yet. A version is committed when an agent finishes writing, when you accept changes, or when you hit "Save version."'}):e.map(h=>l.jsxs("div",{className:`commit-row${r===h.ts?" commit-row--expanded":""}`,onClick:()=>s(r===h.ts?null:h.ts),children:[l.jsxs("div",{className:"commit-row__head",children:[l.jsx("span",{className:"commit-row__time",children:B8(h.ts)}),l.jsx("span",{className:"commit-row__authors",children:h.actors.map(m=>l.jsx("span",{className:`commit-badge commit-badge--${m}`,children:Uk(m)},m))})]}),l.jsx("div",{className:"commit-row__label",children:h.label}),h.note&&l.jsxs("div",{className:"commit-row__note",children:["“",h.note,"”"]}),r===h.ts&&l.jsxs("div",{className:"commit-row__detail",onClick:m=>m.stopPropagation(),children:[l.jsx("div",{className:"commit-row__trigger",children:P8[h.trigger]??h.trigger}),l.jsx("ul",{className:"commit-row__breakdown",children:Object.keys(h.summary.byActor).map(m=>{const g=h.summary.byActor[m];return l.jsxs("li",{children:[l.jsx("span",{className:`commit-badge commit-badge--${m}`,children:Uk(m)}),g.added>0&&l.jsxs("span",{children:[" ",g.added," added"]}),g.edited>0&&l.jsxs("span",{children:[" ",g.edited," edited"]}),g.removed>0&&l.jsxs("span",{children:[" ",g.removed," removed"]})]},m)})}),l.jsx("button",{className:"commit-row__restore",disabled:i||!h.restorable,title:h.restorable?"Restore the document to this version":"Snapshot pruned — cannot restore",onClick:()=>f(h.snapshotTs),children:"Restore this version"})]})]},h.ts))})]})}function F8({docId:t,currentFilename:e,onSwitchDocument:n}){const[r,s]=y.useState(new Map),[i,o]=y.useState([]),[c,d]=y.useState([]),[f,h]=y.useState(!0),[m,g]=y.useState(!1);y.useEffect(()=>{let w=!1;const S=async()=>{try{const M=await(await fetch("/api/documents")).json();if(w)return;const _=new Map;if(Array.isArray(M))for(const R of M)R!=null&&R.docId&&_.set(R.docId,{docId:R.docId,filename:R.filename,title:R.title||R.filename});s(_)}catch{}finally{w||h(!1)}};S();const N=()=>S();return window.addEventListener("ow-documents-changed",N),()=>{w=!0,window.removeEventListener("ow-documents-changed",N)}},[]),y.useEffect(()=>{if(!t){o([]);return}let w=!1;const S=()=>{g(!0),fetch(`/api/backlinks/${t}`).then(j=>j.ok?j.json():[]).then(j=>{w||o(Array.isArray(j)?j:[])}).catch(()=>{w||o([])}).finally(()=>{w||g(!1)})};S();const N=()=>S();return window.addEventListener("ow-metadata-changed",N),()=>{w=!0,window.removeEventListener("ow-metadata-changed",N)}},[t]),y.useEffect(()=>{let w=!1;const S=()=>{fetch("/api/document").then(j=>j.json()).then(j=>{var _;if(w)return;const M=(_=j==null?void 0:j.metadata)==null?void 0:_.references;d(Array.isArray(M)?M:[])}).catch(()=>{w||d([])})};S();const N=()=>S();return window.addEventListener("ow-metadata-changed",N),()=>{w=!0,window.removeEventListener("ow-metadata-changed",N)}},[e,t]);const v=y.useMemo(()=>i.map(w=>{const S=r.get(w.from_doc);return S?{docId:w.from_doc,title:S.title,filename:S.filename,snippet:w.text}:null}).filter(w=>w!==null),[i,r]),x=y.useMemo(()=>c.map(w=>{const S=r.get(w);return S?{docId:w,title:S.title,filename:S.filename}:null}).filter(w=>w!==null),[c,r]);if(!t)return l.jsxs("div",{className:"backlinks-tab__empty",children:[l.jsx("div",{className:"backlinks-tab__empty-title",children:"No document open"}),l.jsx("div",{className:"backlinks-tab__empty-note",children:"Open a doc to see what links to it and what it links out to."})]});const k=f||m;return l.jsxs("div",{className:"backlinks-tab",children:[l.jsxs("div",{className:"backlinks-tab__group",children:[l.jsxs("div",{className:"backlinks-tab__group-label",children:["Inbound ",l.jsx("span",{className:"backlinks-tab__count",children:v.length})]}),k&&v.length===0?l.jsx("div",{className:"backlinks-tab__empty-note backlinks-tab__inline-note",children:"Loading…"}):v.length===0?l.jsx("div",{className:"backlinks-tab__empty-note backlinks-tab__inline-note",children:"No docs link to this one yet."}):v.map(w=>l.jsxs("button",{type:"button",className:"backlinks-tab__entry",onClick:()=>n(w.filename),children:[l.jsx("div",{className:"backlinks-tab__entry-title",children:w.title}),w.snippet&&l.jsx("div",{className:"backlinks-tab__entry-snippet",children:w.snippet})]},w.docId))]}),l.jsxs("div",{className:"backlinks-tab__group",children:[l.jsxs("div",{className:"backlinks-tab__group-label",children:["Outbound ",l.jsx("span",{className:"backlinks-tab__count",children:x.length})]}),x.length===0?l.jsx("div",{className:"backlinks-tab__empty-note backlinks-tab__inline-note",children:"This doc doesn’t reference others yet."}):x.map(w=>l.jsx("button",{type:"button",className:"backlinks-tab__entry",onClick:()=>n(w.filename),children:l.jsx("div",{className:"backlinks-tab__entry-title",children:w.title})},w.docId))]})]})}const z8=[{key:"md",label:"Markdown",desc:"Plain .md file",icon:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),l.jsx("path",{d:"M14 2v6h6"})]})},{key:"html",label:"HTML",desc:"Styled web page",icon:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("polyline",{points:"16 18 22 12 16 6"}),l.jsx("polyline",{points:"8 6 2 12 8 18"})]})},{key:"docx",label:"Word",desc:"Microsoft Word .docx",icon:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),l.jsx("path",{d:"M14 2v6h6"}),l.jsx("path",{d:"M16 13H8"}),l.jsx("path",{d:"M16 17H8"}),l.jsx("path",{d:"M10 9H8"})]})},{key:"txt",label:"Plain Text",desc:"Unformatted .txt file",icon:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M17 6.1H3"}),l.jsx("path",{d:"M21 12.1H3"}),l.jsx("path",{d:"M15.1 18H3"})]})},{key:"pdf",label:"PDF",desc:"Print preview for save as PDF",icon:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("polyline",{points:"6 9 6 2 18 2 18 9"}),l.jsx("path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"}),l.jsx("rect",{x:"6",y:"14",width:"12",height:"8"})]})}];function U8(t){const e=n=>{if(n==="pdf"){window.open("/api/export?format=pdf","_blank");return}const r=document.createElement("a");r.href=`/api/export?format=${n}`,r.download="",document.body.appendChild(r),r.click(),document.body.removeChild(r)};return l.jsx("div",{className:"exports-tab",children:l.jsx("div",{className:"exports-tab__list",children:z8.map(n=>l.jsxs("button",{type:"button",className:"exports-tab__item",onClick:()=>e(n.key),children:[l.jsx("span",{className:"exports-tab__item-icon",children:n.icon}),l.jsxs("span",{className:"exports-tab__item-text",children:[l.jsx("span",{className:"exports-tab__item-label",children:n.label}),l.jsx("span",{className:"exports-tab__item-desc",children:n.desc})]})]},n.key))})})}const H8=3e4,W8=500;let Ei={entries:[],freshKeys:new Set};const rv=new Set;function n2(t){return`${t.ts}:${t.kind}:${t.headline}`}function V8(){for(const t of rv)t(Ei)}function sv(t){Ei=t,V8()}function q8(t){return rv.add(t),()=>{rv.delete(t)}}function K8(){return Ei}function G8(t){const e=t.detail;e!=null&&e.entries&&sv({entries:e.entries,freshKeys:new Set})}function J8(t){const e=t.detail;if(!(e!=null&&e.event))return;const n=e.event,r=n2(n),s={entries:[n,...Ei.entries].slice(0,W8),freshKeys:new Set([...Ei.freshKeys,r])};sv(s),window.setTimeout(()=>{if(Ei.freshKeys.has(r)){const i=new Set(Ei.freshKeys);i.delete(r),sv({...Ei,freshKeys:i})}},H8)}typeof window<"u"&&(window.addEventListener("ow-activity-seed",G8),window.addEventListener("ow-activity-event",J8));function Y8(){const[t,e]=y.useState(K8);return y.useEffect(()=>q8(e),[]),t}function X8(){const[t,e]=y.useState(()=>({byDocId:new Map,filenameSet:new Set}));return y.useEffect(()=>{let n=!1;const r=()=>{fetch("/api/documents").then(s=>s.json()).then(s=>{if(n||!Array.isArray(s))return;const i=new Map,o=new Set;for(const c of s)c.filename&&o.add(c.filename),c.docId&&c.filename&&i.set(c.docId,c.filename);e({byDocId:i,filenameSet:o})}).catch(()=>{})};return r(),window.addEventListener("ow-documents-changed",r),()=>{n=!0,window.removeEventListener("ow-documents-changed",r)}},[]),t}function Q8(t,e){return t.docId?e.byDocId.get(t.docId)??null:t.filename&&e.filenameSet.has(t.filename)?t.filename:null}function Z8(t,e){const n=Math.max(0,e-t),r=Math.floor(n/1e3);if(r<45)return"just now";const s=Math.floor(r/60);if(s<60)return`${s}m ago`;const i=Math.floor(s/60);if(i<24)return`${i}h ago`;const o=Math.floor(i/24);return o<7?`${o}d ago`:new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function eF({onSwitchDocument:t}){const{entries:e,freshKeys:n}=Y8(),r=X8(),[s,i]=y.useState(()=>Date.now());y.useEffect(()=>{const c=setInterval(()=>i(Date.now()),3e4);return()=>clearInterval(c)},[]);const o=y.useMemo(()=>tF(e,s),[e,s]);return e.length===0?l.jsxs("div",{className:"activity-tab__empty",children:[l.jsx("div",{className:"activity-tab__empty-title",children:"No activity yet"}),l.jsx("div",{className:"activity-tab__empty-note",children:"Agent actions — writes, enrichment, backlink propagation — will appear here as they happen."})]}):l.jsx("div",{className:"activity-tab",children:o.map(c=>l.jsxs("div",{className:"activity-tab__group",children:[l.jsx("div",{className:"activity-tab__group-label",children:c.label}),c.entries.map(d=>{const f=n2(d),h=n.has(f),m=d.kind==="doc-deleted"?null:Q8(d,r),g=m!==null,v=!g,x=v&&d.kind!=="doc-deleted"?"Doc no longer available":void 0,k=()=>{m&&t(m)};return l.jsxs("div",{className:`activity-tab__entry${h?" activity-tab__entry--fresh":""}${g?" activity-tab__entry--clickable":""}${v?" activity-tab__entry--muted":""}`,role:g?"button":void 0,tabIndex:g?0:void 0,title:x,onClick:k,onKeyDown:w=>{g&&(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),k())},children:[l.jsx("span",{className:`activity-tab__kind-dot activity-tab__kind-dot--${d.kind}`,"aria-hidden":"true"}),l.jsxs("div",{className:"activity-tab__entry-body",children:[l.jsx("div",{className:"activity-tab__headline",children:d.headline}),d.detail&&l.jsx("div",{className:"activity-tab__detail",children:d.detail})]}),l.jsx("div",{className:"activity-tab__ts",title:new Date(d.ts).toLocaleString(),children:Z8(d.ts,s)})]},f)})]},c.label))})}function tF(t,e){if(t.length===0)return[];const n=Hk(e),r=n-1440*60*1e3,s=[];let i=null;for(const o of t){const c=Hk(o.ts);let d;c===n?d="Today":c===r?d="Yesterday":d=new Date(o.ts).toLocaleDateString(void 0,{weekday:"long",month:"short",day:"numeric"}),(!i||i.label!==d)&&(i={label:d,entries:[]},s.push(i)),i.entries.push(o)}return s}function Hk(t){const e=new Date(t);return e.setHours(0,0,0,0),e.getTime()}async function Cu(t,e={}){var s,i;const r=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:t,arguments:e})})).json();if((i=(s=r==null?void 0:r.content)==null?void 0:s[0])!=null&&i.text)try{return JSON.parse(r.content[0].text)}catch{return r.content[0].text}return r}function nF(){const[t,e]=y.useState([]),[n,r]=y.useState(!0),[s,i]=y.useState("closed"),[o,c]=y.useState(""),[d,f]=y.useState(!1),[h,m]=y.useState(null),[g,v]=y.useState(null),[x,k]=y.useState(null),w=y.useCallback(async()=>{r(!0);try{const _=await Cu("list_blog_sites");e((_==null?void 0:_.sites)||[])}finally{r(!1)}},[]);y.useEffect(()=>{w()},[w]);const S=()=>{i("closed"),c(""),m(null),v(null),k(null)},N=async()=>{if(o.trim()){f(!0),m(null);try{const _=await Cu("inspect_blog_repo",{repo_url:o.trim()});if(_.error){m(_.error);return}v({..._,label:_.repo,branch:"main",site_url:_.site_url||"",blog_url_pattern:_.blog_url_pattern||"/blog/{slug}/"}),i("review")}catch(_){m((_==null?void 0:_.message)||"Inspection failed")}finally{f(!1)}}},j=async()=>{if(g){i("saving"),k(null);try{const _=await Cu("add_blog_site",{label:g.label,owner:g.owner,repo:g.repo,branch:g.branch||"main",content_dir:g.content_dir,image_dir:g.image_dir,image_public_prefix:g.image_public_prefix,framework:g.framework,frontmatter_defaults:g.frontmatter_defaults||{},frontmatter_field_map:g.frontmatter_field_map||{},frontmatter_schema:g.frontmatter_schema||[],site_url:g.site_url||"",blog_url_pattern:g.blog_url_pattern||"/blog/{slug}/"});if(_!=null&&_.error){k(_.error),i("review");return}S(),await w()}catch(_){k((_==null?void 0:_.message)||"Save failed"),i("review")}}},M=async _=>{if(!window.confirm(`Remove "${_.label}" (${_.owner}/${_.repo})?
209
209
 
210
210
  This only removes the OpenWriter registration. Your GitHub repo is untouched.`))return;const L=await Cu("remove_blog_site",{id:_.id});if(L!=null&&L.error){alert(`Remove failed: ${L.error}`);return}await w()};return l.jsxs("div",{className:"github-plugin-settings",children:[l.jsxs("div",{className:"github-plugin-settings__header",children:[l.jsx("span",{className:"github-plugin-settings__title",children:"Blog repos"}),s==="closed"&&l.jsx("button",{className:"github-plugin-settings__add-btn",onClick:()=>i("url"),children:"+ Add"})]}),n?l.jsx("div",{className:"github-plugin-settings__loading",children:"Loading…"}):t.length===0&&s==="closed"?l.jsxs("div",{className:"github-plugin-settings__empty",children:["Connect a GitHub repo to publish blog posts via local git — no PATs, no Workers. Uses your existing ",l.jsx("code",{children:"gh auth login"}),"."]}):l.jsx("div",{className:"github-plugin-settings__list",children:t.map(_=>l.jsxs("div",{className:"github-plugin-settings__site",children:[l.jsxs("div",{className:"github-plugin-settings__site-info",children:[l.jsxs("div",{className:"github-plugin-settings__site-row1",children:[l.jsx("span",{className:"github-plugin-settings__site-label",children:_.label}),l.jsx("span",{className:`github-plugin-settings__site-framework github-plugin-settings__site-framework--${_.framework}`,children:_.framework})]}),l.jsxs("div",{className:"github-plugin-settings__site-repo",children:[_.owner,"/",_.repo,"@",_.branch]}),l.jsxs("div",{className:"github-plugin-settings__site-dirs",children:[l.jsx("span",{title:"content_dir",children:_.content_dir}),l.jsx("span",{className:"github-plugin-settings__site-sep",children:"·"}),l.jsx("span",{title:"image_public_prefix",children:_.image_public_prefix})]})]}),l.jsx("button",{className:"github-plugin-settings__remove-btn",onClick:()=>M(_),title:"Remove",children:"×"})]},_.id))}),s==="url"&&l.jsxs("div",{className:"github-plugin-settings__form",children:[l.jsx("label",{className:"github-plugin-settings__label",children:"GitHub repo"}),l.jsx("input",{className:"github-plugin-settings__input",type:"text",placeholder:"owner/repo or https://github.com/owner/repo",value:o,onChange:_=>c(_.target.value),onKeyDown:_=>{_.key==="Enter"&&!d&&N()},autoFocus:!0}),h&&l.jsx("div",{className:"github-plugin-settings__error",children:h}),l.jsxs("div",{className:"github-plugin-settings__form-buttons",children:[l.jsx("button",{className:"github-plugin-settings__btn github-plugin-settings__btn--primary",onClick:N,disabled:d||!o.trim(),children:d?"Inspecting…":"Inspect"}),l.jsx("button",{className:"github-plugin-settings__btn",onClick:S,disabled:d,children:"Cancel"})]})]}),(s==="review"||s==="saving")&&g&&l.jsxs("div",{className:"github-plugin-settings__form",children:[l.jsxs("div",{className:"github-plugin-settings__form-meta",children:[l.jsxs("span",{children:["Detected: ",g.framework]}),l.jsx("span",{children:"·"}),l.jsxs("span",{children:[g.markdown_files_found," posts"]}),l.jsx("span",{children:"·"}),l.jsxs("span",{className:`github-plugin-settings__confidence github-plugin-settings__confidence--${g.confidence}`,children:[g.confidence," confidence"]})]}),l.jsx("label",{className:"github-plugin-settings__label",children:"Label"}),l.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.label,onChange:_=>v({...g,label:_.target.value})}),l.jsx("label",{className:"github-plugin-settings__label",children:"Branch"}),l.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.branch,onChange:_=>v({...g,branch:_.target.value})}),l.jsx("label",{className:"github-plugin-settings__label",children:"Content directory"}),l.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.content_dir,onChange:_=>v({...g,content_dir:_.target.value})}),l.jsx("label",{className:"github-plugin-settings__label",children:"Image directory"}),l.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.image_dir,onChange:_=>v({...g,image_dir:_.target.value})}),l.jsx("label",{className:"github-plugin-settings__label",children:"Image public prefix"}),l.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.image_public_prefix,onChange:_=>v({...g,image_public_prefix:_.target.value})}),l.jsxs("label",{className:"github-plugin-settings__label",children:["Site URL ",l.jsx("span",{className:"github-plugin-settings__hint",children:"— optional, used for the live link after publish"})]}),l.jsx("input",{className:"github-plugin-settings__input",type:"text",placeholder:"https://example.com",value:g.site_url||"",onChange:_=>v({...g,site_url:_.target.value})}),l.jsxs("label",{className:"github-plugin-settings__label",children:["Blog URL pattern ",l.jsxs("span",{className:"github-plugin-settings__hint",children:["— uses ","{slug}"," placeholder"]})]}),l.jsx("input",{className:"github-plugin-settings__input",type:"text",placeholder:"/blog/{slug}/",value:g.blog_url_pattern||"",onChange:_=>v({...g,blog_url_pattern:_.target.value})}),l.jsx("label",{className:"github-plugin-settings__label",children:"Framework"}),l.jsxs("select",{className:"github-plugin-settings__input",value:g.framework,onChange:_=>v({...g,framework:_.target.value}),children:[l.jsx("option",{value:"astro",children:"Astro"}),l.jsx("option",{value:"next",children:"Next"}),l.jsx("option",{value:"jekyll",children:"Jekyll"}),l.jsx("option",{value:"hugo",children:"Hugo"}),l.jsx("option",{value:"unknown",children:"Unknown"})]}),g.frontmatter_schema.length>0&&l.jsxs("div",{className:"github-plugin-settings__schema",children:[l.jsxs("span",{className:"github-plugin-settings__label",children:["Frontmatter keys detected (",g.samples_analyzed," ",g.samples_analyzed===1?"sample":"samples",")"]}),l.jsx("code",{children:g.frontmatter_schema.join(", ")})]}),Object.keys(g.frontmatter_defaults||{}).length>0&&l.jsxs("div",{className:"github-plugin-settings__schema",children:[l.jsx("span",{className:"github-plugin-settings__label",children:"Frontmatter defaults (constants applied to every post)"}),l.jsx("code",{children:Object.entries(g.frontmatter_defaults).map(([_,R])=>l.jsxs("div",{children:[_,": ",typeof R=="string"?R:JSON.stringify(R)]},_))})]}),Object.keys(g.frontmatter_field_map||{}).length>0&&l.jsxs("div",{className:"github-plugin-settings__schema",children:[l.jsx("span",{className:"github-plugin-settings__label",children:"Field name mapping (openwriter → site)"}),l.jsx("code",{children:Object.entries(g.frontmatter_field_map).map(([_,R])=>l.jsxs("div",{children:[_," → ",R]},_))})]}),x&&l.jsx("div",{className:"github-plugin-settings__error",children:x}),l.jsxs("div",{className:"github-plugin-settings__form-buttons",children:[l.jsx("button",{className:"github-plugin-settings__btn github-plugin-settings__btn--primary",onClick:j,disabled:s==="saving"||!g.label.trim(),children:s==="saving"?"Saving…":"Add site"}),l.jsx("button",{className:"github-plugin-settings__btn",onClick:S,disabled:s==="saving",children:"Cancel"})]})]})]})}const rF={none:"No Plan",free:"No Plan",creator:"Publish — $19/mo",growth:"Publish+Email — $49/mo"},sF=[{plan:"creator",label:"Publish $19/mo"},{plan:"growth",label:"Publish+Email $49/mo"}];function iF(){var d,f;const[t,e]=y.useState(null),[n,r]=y.useState(!0);y.useEffect(()=>{fetch("/api/billing").then(h=>h.json()).then(h=>e(h)).catch(()=>{}).finally(()=>r(!1))},[]);const s=y.useCallback(async h=>{const m=await fetch("/api/billing/checkout",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({plan:h})});if(m.ok){const g=await m.json();g.url&&window.open(g.url,"_blank")}},[]),i=y.useCallback(async()=>{const h=await fetch("/api/billing/portal",{method:"POST",headers:{"Content-Type":"application/json"}});if(h.ok){const m=await h.json();m.url&&window.open(m.url,"_blank")}},[]);if(n)return l.jsx("div",{className:"billing-section",children:l.jsx("div",{className:"billing-loading",children:"Loading..."})});if(!(t!=null&&t.authenticated))return null;const o=t.plan||"free",c=sF.filter(h=>{const m=["free","creator","growth"];return m.indexOf(h.plan)>m.indexOf(o)});return l.jsxs("div",{className:"billing-section",children:[l.jsxs("div",{className:"billing-plan",children:[l.jsx("span",{className:"billing-plan-label",children:"Plan"}),l.jsx("span",{className:`billing-plan-badge billing-plan-badge--${o}`,children:rF[o]||o})]}),((d=t.billing)==null?void 0:d.paymentFailed)&&l.jsx("div",{className:"billing-warning",children:"Payment failed — update card to keep your plan."}),c.length>0&&l.jsx("div",{className:"billing-upgrades",children:c.map(h=>l.jsxs("button",{className:"billing-upgrade-btn",onClick:()=>s(h.plan),children:["Upgrade to ",h.label]},h.plan))}),((f=t.billing)==null?void 0:f.hasPaymentMethod)&&l.jsx("button",{className:"billing-manage-btn",onClick:i,children:"Manage Billing"})]})}const oF=[{label:"Fast",cost:"free"},{label:"Fast+",cost:"$"},{label:"Sonnet",cost:"$$"},{label:"Opus",cost:"$$$"}];function aF(){const[t,e]=y.useState(null),[n,r]=y.useState([]),[s,i]=y.useState(!0),[o,c]=y.useState(!1),d=y.useCallback(()=>{Promise.all([x$(),w$()]).then(([f,h])=>{f!=null&&f.wallet&&e(f.wallet.balanceCents),r(h)}).finally(()=>i(!1))},[]);return y.useEffect(()=>{d()},[d]),y.useEffect(()=>{const f=()=>{document.visibilityState==="visible"&&d()};return document.addEventListener("visibilitychange",f),()=>document.removeEventListener("visibilitychange",f)},[d]),s?l.jsx("div",{className:"billing-section",children:l.jsx("div",{className:"billing-loading",children:"Loading…"})}):t===null&&n.length===0?null:l.jsxs("div",{className:"billing-section",children:[l.jsxs("div",{className:"billing-plan",children:[l.jsx("span",{className:"billing-plan-label",children:"Balance"}),l.jsx("span",{className:"av-credits-balance",children:t===null?"—":y$(t)})]}),l.jsx("div",{className:"av-credits-legend",children:oF.map(f=>l.jsxs("span",{className:"av-credits-legend-item",children:[l.jsx("span",{className:"av-credits-model",children:f.label}),l.jsx("span",{className:"av-credits-cost",children:f.cost})]},f.label))}),n.length>0&&l.jsxs(l.Fragment,{children:[l.jsxs("button",{className:"av-credits-topup-toggle",onClick:()=>c(f=>!f),children:[l.jsx("svg",{className:`plugin-config-chevron${o?" plugin-config-chevron--open":""}`,width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"9 18 15 12 9 6"})}),"Add balance"]}),o&&l.jsx("div",{className:"billing-upgrades",children:n.map(f=>l.jsxs("button",{className:"billing-upgrade-btn",onClick:()=>IT(f.amountDollars),children:["Add $",f.amountDollars]},f.priceId))})]})]})}function Wk(t){return t.replace(/^@openwriter\/plugin-/,"").replace(/-/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function lF({status:t}){return t==="saving"?l.jsx("span",{className:"plugin-config-status plugin-config-status--saving",children:"Saving…"}):t==="saved"?l.jsxs("span",{className:"plugin-config-status plugin-config-status--saved",children:[l.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#22c55e",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Saved"]}):t==="error"?l.jsxs("span",{className:"plugin-config-status plugin-config-status--error",children:[l.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),l.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),"Failed"]}):null}function cF(t){const[e,n]=y.useState([]),[r,s]=y.useState(null),[i,o]=y.useState(new Set),[c,d]=y.useState({}),f=y.useCallback(()=>{fetch("/api/available-plugins").then(g=>g.json()).then(g=>n(g.plugins||[])).catch(()=>{})},[]);y.useEffect(()=>{f()},[f]),y.useEffect(()=>{const g=()=>f();return window.addEventListener("ow-plugins-changed",g),()=>window.removeEventListener("ow-plugins-changed",g)},[f]);const h=y.useCallback(async(g,v)=>{s(g);try{(await fetch(v?"/api/plugins/disable":"/api/plugins/enable",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:g})})).ok&&f()}catch{}finally{s(null)}},[f]),m=y.useCallback(async(g,v,x)=>{const k=`${g}:${v}`;d(w=>({...w,[k]:"saving"}));try{const w=await fetch("/api/plugins/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:g,config:{[v]:x}})});if(!w.ok)throw new Error(`save failed (${w.status})`);d(S=>({...S,[k]:"saved"})),setTimeout(()=>{d(S=>S[k]==="saved"?{...S,[k]:"idle"}:S)},2e3)}catch{d(w=>({...w,[k]:"error"}))}},[]);return l.jsx("div",{className:"plugins-tab",children:e.length===0?l.jsx("div",{className:"plugin-empty",children:"No plugins found"}):e.map(g=>l.jsxs("div",{className:"plugin-item",children:[l.jsxs("div",{className:"plugin-item-header",children:[l.jsxs("div",{className:"plugin-item-info",children:[l.jsxs("div",{className:"plugin-item-name",children:[Wk(g.name),l.jsxs("span",{className:"plugin-item-version",children:["v",g.version]})]}),g.description&&l.jsx("div",{className:"plugin-item-desc",children:g.description})]}),l.jsxs("label",{className:`plugin-toggle${r===g.name?" loading":""}`,children:[l.jsx("input",{type:"checkbox",checked:g.enabled,disabled:r===g.name,onChange:()=>h(g.name,g.enabled)}),l.jsx("span",{className:"plugin-toggle-track"}),l.jsx("span",{className:"plugin-toggle-thumb"})]})]}),g.enabled&&(()=>{const v=Object.entries(g.configSchema||{}),x=v.filter(([,j])=>j.type==="select"),k=v.filter(([,j])=>j.type!=="select"),w=v.some(([j,M])=>M.required&&!g.config[j]),S=g.name==="@openwriter/plugin-authors-voice"?l.jsx(aF,{}):g.name==="@openwriter/plugin-publish"?l.jsx(iF,{}):g.name==="@openwriter/plugin-github"?l.jsx(nF,{}):null,N=(j,M)=>{const _=c[`${g.name}:${j}`]||"idle";return l.jsxs("div",{className:"plugin-config-field",children:[l.jsxs("label",{className:"plugin-config-label",children:[M.description||j,l.jsx(lF,{status:_})]}),M.options?l.jsxs("select",{className:"plugin-config-input",defaultValue:g.config[j]||"",onChange:R=>m(g.name,j,R.target.value),children:[!M.required&&!M.options.some(R=>R.value==="")&&l.jsx("option",{value:"",children:"—"}),M.options.map(R=>l.jsx("option",{value:R.value,children:R.label},R.value))]}):l.jsx("input",{className:"plugin-config-input",type:j.toLowerCase().includes("key")||j.toLowerCase().includes("secret")||j.toLowerCase().includes("token")?"password":"text",defaultValue:g.config[j]||"",placeholder:M.env?`$${M.env}`:"",onBlur:R=>m(g.name,j,R.target.value)})]},j)};return v.length===0&&!S?null:l.jsxs("div",{className:"plugin-config-section",children:[w&&l.jsxs("div",{className:"plugin-setup-hint",children:["Ask your agent: “set up ",Wk(g.name),"”"]}),x.length>0&&l.jsx("div",{className:"plugin-config",children:x.map(([j,M])=>N(j,M))}),S,k.length>0&&l.jsxs(l.Fragment,{children:[l.jsxs("button",{className:"plugin-config-toggle",onClick:()=>o(j=>{const M=new Set(j);return M.has(g.name)?M.delete(g.name):M.add(g.name),M}),children:[l.jsx("svg",{className:`plugin-config-chevron${i.has(g.name)?" plugin-config-chevron--open":""}`,width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"9 18 15 12 9 6"})}),"Settings"]}),i.has(g.name)&&l.jsx("div",{className:"plugin-config",children:k.map(([j,M])=>N(j,M))})]})]})})()]},g.name))})}function uF({existingConnection:t,onClose:e,onSaved:n}){const[r,s]=y.useState("form"),[i,o]=y.useState(null),[c,d]=y.useState((t==null?void 0:t.domain)||""),[f,h]=y.useState(""),[m,g]=y.useState((t==null?void 0:t.from_name)||""),[v,x]=y.useState(""),[k,w]=y.useState((t==null?void 0:t.id)||""),[S,N]=y.useState({dns_verified:!1,sender_verified:!1}),j=y.useRef(null),M=y.useRef(null);y.useEffect(()=>{const X=z=>{r!=="submitting"&&r!=="verifying"&&M.current&&!M.current.contains(z.target)&&e()};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[e,r]),y.useEffect(()=>{const X=z=>{z.key==="Escape"&&r!=="submitting"&&r!=="verifying"&&e()};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[e,r]),y.useEffect(()=>()=>{j.current&&clearInterval(j.current)},[]);async function _(){var X,z;s("submitting"),o(null);try{const P=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"setup_custom_domain",arguments:{domain:c,from_email:f,from_name:m||void 0,physical_address:v}})})).json(),F=(z=(X=P.content)==null?void 0:X[0])!=null&&z.text?JSON.parse(P.content[0].text):P;if(F.error){o(F.error),s("error");return}const G=F.connectionId||F.connection_id||k;G&&w(G),L(G)}catch(ee){o(ee.message),s("error")}}async function R(){var X,z;s("submitting"),o(null);try{const P=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"setup_custom_domain",arguments:{domain:c,from_email:f||void 0,from_name:m||void 0,physical_address:v||void 0}})})).json(),F=(z=(X=P.content)==null?void 0:X[0])!=null&&z.text?JSON.parse(P.content[0].text):P;if(F.error){o(F.error),s("error");return}s("done")}catch(ee){o(ee.message),s("error")}}function L(X){s("verifying"),j.current=setInterval(async()=>{var z,ee;try{const F=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"check_domain_status",arguments:{connectionId:X}})})).json(),G=(ee=(z=F.content)==null?void 0:z[0])!=null&&ee.text?JSON.parse(F.content[0].text):F,ie=!!G.dns_verified,K=!!G.sender_verified;N({dns_verified:ie,sender_verified:K}),ie&&K&&(j.current&&clearInterval(j.current),j.current=null,s("done"))}catch{}},5e3)}function $(){k&&fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"resend_domain_verification",arguments:{connectionId:k}})}).catch(()=>{})}const B=!!t,U=c.trim()&&f.trim()&&v.trim();return l.jsx("div",{className:"newsletter-modal-overlay",children:l.jsxs("div",{className:"newsletter-modal newsletter-modal--setup",ref:M,children:[l.jsxs("div",{className:"newsletter-modal__header",children:[l.jsx("h3",{children:B?"Newsletter Settings":"Set Up Newsletter"}),l.jsx("button",{className:"newsletter-modal__close",onClick:e,children:"×"})]}),l.jsxs("div",{className:"newsletter-modal__body",children:[r==="form"&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"newsletter-modal__field",children:[l.jsx("label",{className:"newsletter-modal__label",children:"Domain"}),l.jsx("input",{className:"newsletter-modal__input",type:"text",placeholder:"yourdomain.com",value:c,onChange:X=>d(X.target.value),disabled:B,autoComplete:"off"})]}),l.jsxs("div",{className:"newsletter-modal__field",children:[l.jsx("label",{className:"newsletter-modal__label",children:"From Email"}),l.jsx("input",{className:"newsletter-modal__input",type:"email",placeholder:"newsletter@yourdomain.com",value:f,onChange:X=>h(X.target.value),autoComplete:"off"})]}),l.jsxs("div",{className:"newsletter-modal__field",children:[l.jsxs("label",{className:"newsletter-modal__label",children:["From Name ",l.jsx("span",{className:"newsletter-modal__optional",children:"(optional)"})]}),l.jsx("input",{className:"newsletter-modal__input",type:"text",placeholder:"Your Name or Brand",value:m,onChange:X=>g(X.target.value),autoComplete:"off"})]}),l.jsxs("div",{className:"newsletter-modal__field",children:[l.jsxs("label",{className:"newsletter-modal__label",children:["Physical Address ",l.jsx("span",{className:"newsletter-modal__required",children:"*"})]}),l.jsx("textarea",{className:"newsletter-modal__input newsletter-modal__textarea",rows:2,placeholder:"123 Main St, City, State 12345",value:v,onChange:X=>x(X.target.value)}),l.jsx("span",{className:"newsletter-modal__hint",children:"Required by CAN-SPAM. Included in email footer."})]}),l.jsxs("div",{className:"newsletter-modal__actions",children:[l.jsx("button",{className:"newsletter-modal__btn",onClick:e,children:"Cancel"}),l.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:B?R:_,disabled:!U,children:B?"Save":"Set Up Domain"})]})]}),r==="submitting"&&l.jsxs("div",{className:"newsletter-modal__status",children:[l.jsx("div",{className:"newsletter-modal__spinner"}),l.jsx("span",{children:B?"Saving...":"Setting up domain..."})]}),r==="verifying"&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"newsletter-modal__verify",children:[l.jsx("p",{className:"newsletter-modal__verify-title",children:"Verifying domain setup..."}),l.jsxs("div",{className:"newsletter-modal__verify-checks",children:[l.jsxs("div",{className:`newsletter-modal__verify-item${S.dns_verified?" newsletter-modal__verify-item--done":""}`,children:[S.dns_verified?"✓":l.jsx("span",{className:"newsletter-modal__spinner newsletter-modal__spinner--sm"}),l.jsx("span",{children:"DNS records"})]}),l.jsxs("div",{className:`newsletter-modal__verify-item${S.sender_verified?" newsletter-modal__verify-item--done":""}`,children:[S.sender_verified?"✓":l.jsx("span",{className:"newsletter-modal__spinner newsletter-modal__spinner--sm"}),l.jsx("span",{children:"Sender verification"})]})]}),l.jsx("p",{className:"newsletter-modal__hint",children:"This may take a few minutes. You can close and check back later."})]}),l.jsxs("div",{className:"newsletter-modal__actions",children:[l.jsx("button",{className:"newsletter-modal__btn",onClick:$,children:"Resend Verification"}),l.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>{n(),e()},children:"Close"})]})]}),r==="done"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"newsletter-modal__status newsletter-modal__status--success",children:B?"Settings saved!":"Newsletter domain configured!"}),l.jsx("div",{className:"newsletter-modal__actions",children:l.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>{n(),e()},children:"Done"})})]}),r==="error"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"newsletter-modal__error",children:i}),l.jsxs("div",{className:"newsletter-modal__actions",children:[l.jsx("button",{className:"newsletter-modal__btn",onClick:e,children:"Cancel"}),l.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>s("form"),children:"Try Again"})]})]})]})]})})}const dF={x:[],linkedin:[]};function fF({connectionId:t,provider:e,displayName:n,onClose:r,onSaved:s}){const[i,o]=y.useState("loading"),[c,d]=y.useState({}),[f,h]=y.useState(null),m=y.useRef(null),g=dF[e]||[];y.useEffect(()=>{fetch(`/api/connections/${t}/config`).then(k=>k.json()).then(k=>{d(k.config||{}),o("form")}).catch(k=>{h(k.message),o("error")})},[t]),y.useEffect(()=>{const k=w=>{i!=="saving"&&m.current&&!m.current.contains(w.target)&&r()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[r,i]),y.useEffect(()=>{const k=w=>{w.key==="Escape"&&i!=="saving"&&r()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[r,i]);async function v(){o("saving"),h(null);try{const k=await fetch(`/api/connections/${t}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),w=await k.json();if(!k.ok)throw new Error(w.error||"Failed to save");o("saved"),s(),setTimeout(r,800)}catch(k){h(k.message),o("error")}}function x(k){switch(k){case"x":return"X (Twitter)";case"linkedin":return"LinkedIn";default:return k}}return l.jsx("div",{className:"conn-config-overlay",children:l.jsxs("div",{className:"conn-config-modal",ref:m,children:[l.jsxs("div",{className:"conn-config-modal__header",children:[l.jsxs("div",{className:"conn-config-modal__title",children:[x(e)," Settings"]}),l.jsx("div",{className:"conn-config-modal__subtitle",children:n})]}),i==="loading"&&l.jsxs("div",{className:"conn-config-modal__body conn-config-modal__center",children:[l.jsx("div",{className:"conn-config-spinner"}),l.jsx("span",{children:"Loading configuration..."})]}),(i==="form"||i==="error")&&g.length>0&&l.jsxs("div",{className:"conn-config-modal__body",children:[g.map(k=>l.jsxs("div",{className:"conn-config-field",children:[l.jsxs("label",{className:"conn-config-field__label",children:[k.label,k.readonly&&l.jsx("span",{className:"conn-config-field__badge",children:"read-only"})]}),l.jsx("input",{className:"conn-config-field__input",value:c[k.key]||"",placeholder:k.placeholder,readOnly:k.readonly,onChange:w=>d(S=>({...S,[k.key]:w.target.value}))})]},k.key)),f&&l.jsx("div",{className:"conn-config-modal__error",children:f})]}),(i==="form"||i==="error")&&g.length===0&&l.jsx("div",{className:"conn-config-modal__body conn-config-modal__center",children:l.jsxs("span",{className:"conn-config-modal__empty",children:["No configuration needed for ",x(e),"."]})}),i==="saving"&&l.jsxs("div",{className:"conn-config-modal__body conn-config-modal__center",children:[l.jsx("div",{className:"conn-config-spinner"}),l.jsx("span",{children:"Saving..."})]}),i==="saved"&&l.jsxs("div",{className:"conn-config-modal__body conn-config-modal__center",children:[l.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#22c55e",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("polyline",{points:"20 6 9 17 4 12"})}),l.jsx("span",{children:"Saved"})]}),l.jsxs("div",{className:"conn-config-modal__footer",children:[l.jsx("button",{className:"conn-config-btn conn-config-btn--secondary",onClick:r,children:i==="saved"?"Close":"Cancel"}),g.length>0&&(i==="form"||i==="error")&&l.jsx("button",{className:"conn-config-btn conn-config-btn--primary",onClick:v,children:"Save"})]})]})})}const hF=[{id:"x",label:"X (Twitter)",oauth:!0},{id:"linkedin",label:"LinkedIn",oauth:!0},{id:"newsletter",label:"Newsletter",oauth:!1}];function Bp(t){switch(t){case"x":return l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:l.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"})});case"linkedin":return l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:l.jsx("path",{d:"M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"})});case"newsletter":return l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),l.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]});default:return l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("circle",{cx:"12",cy:"12",r:"10"})})}}function pF(t){return t==="active"?"connections-status--active":t==="expired"?"connections-status--expired":t==="revoked"?"connections-status--revoked":"connections-status--pending"}function mF(t){const[e,n]=y.useState([]),[r,s]=y.useState(null),[i,o]=y.useState(null),[c,d]=y.useState(null),[f,h]=y.useState(null),[m,g]=y.useState(null),v=y.useRef(null);async function x(){try{const R=await(await fetch("/api/connections")).json();s(R.authenticated!==!1);const L=(R.connections||[]).filter($=>$&&$.id&&$.provider);return n(L),L}catch{return[]}}y.useEffect(()=>{x()},[]),y.useEffect(()=>()=>{v.current&&clearInterval(v.current)},[]);async function k(_){d(_);try{const R=await fetch(`/api/connections/oauth/${_}/start`,{method:"POST"}),L=await R.json();if(!R.ok||!L.url){d(null);return}window.open(L.url,"_blank","width=600,height=700"),v.current=setInterval(async()=>{try{const B=await(await fetch(`/api/connections/oauth/${_}/status/${L.state}`)).json();if(B.status==="completed"){v.current&&clearInterval(v.current),v.current=null,d(null);const U=await x();if(_==="x"){const X=U.find(z=>z.provider==="x"&&z.status==="active");if(X!=null&&X.display_name){const z=X.display_name.replace("@","");localStorage.setItem("ow-x-handle",z),window.dispatchEvent(new StorageEvent("storage",{key:"ow-x-handle",newValue:z}))}}}else B.status==="failed"&&(v.current&&clearInterval(v.current),v.current=null,d(null))}catch{}},2e3)}catch{d(null)}}async function w(_){try{const R=await fetch(`/api/connections/${_}`,{method:"DELETE"});if(!R.ok){const L=await R.json().catch(()=>({error:"Delete failed"}));console.error("[Connections] Delete failed:",L.error)}}catch(R){console.error("[Connections] Delete error:",R)}o(null),await x()}const S=new Map,N=new Map;for(const _ of e){S.has(_.provider)||S.set(_.provider,_);const R=N.get(_.provider)||[];R.push(_),N.set(_.provider,R)}const j=new Set,M=r===!1;return l.jsxs("div",{className:"connections-tab",children:[m&&l.jsx(fF,{connectionId:m.id,provider:m.provider,displayName:m.display_name,onClose:()=>g(null),onSaved:()=>x()}),f&&l.jsx(uF,{existingConnection:f==="edit"?S.get("newsletter"):null,onClose:()=>h(null),onSaved:()=>x()}),M?l.jsxs("div",{className:"connections-dropdown__upsell",children:[l.jsx("p",{children:"Connect your X, LinkedIn, and other accounts to publish directly from OpenWriter."}),l.jsxs("p",{children:["Set up the ",l.jsx("strong",{children:"Publish"})," plugin to get started."]})]}):l.jsx("div",{className:"connections-dropdown__list",children:hF.flatMap(_=>{const R=j.has(_.id),L=N.get(_.id)||[],$=U=>i===U.id?l.jsxs("div",{className:"connections-dropdown__confirm",children:[l.jsxs("span",{children:["Disconnect ",U.display_name||_.label,"?"]}),l.jsxs("div",{className:"connections-dropdown__confirm-btns",children:[l.jsx("button",{onClick:()=>w(U.id),children:"Yes"}),l.jsx("button",{onClick:()=>o(null),children:"No"})]})]},U.id):l.jsxs("div",{className:"connections-dropdown__item",children:[l.jsx("div",{className:"connections-dropdown__icon",children:Bp(_.id)}),l.jsxs("div",{className:"connections-dropdown__info",children:[l.jsx("div",{className:"connections-dropdown__name",children:U.display_name||U.domain||_.label}),l.jsxs("div",{className:"connections-dropdown__type",children:[l.jsx("span",{className:`connections-status ${pF(U.status)}`}),"Connected"]})]}),l.jsxs("div",{className:"connections-dropdown__actions",children:[l.jsx("button",{className:"connections-dropdown__action-btn",onClick:()=>{_.id==="newsletter"?h("edit"):g({id:U.id,provider:_.id,display_name:U.display_name||_.label})},title:"Settings",children:l.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),l.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),l.jsx("button",{className:"connections-dropdown__action-btn connections-dropdown__action-btn--delete",onClick:()=>o(U.id),title:"Disconnect",children:"×"})]})]},U.id),B=L.map($);return R?(B.push(l.jsx("div",{className:"connections-dropdown__add-row",children:l.jsx("button",{className:"connections-dropdown__add-btn",onClick:()=>k(_.id),disabled:c!==null,children:c===_.id?"Connecting…":`+ Add ${_.label} repo`})},`${_.id}__add`)),B):L.length>0?B:_.oauth?[l.jsxs("div",{className:"connections-dropdown__item connections-dropdown__item--disconnected",children:[l.jsx("div",{className:"connections-dropdown__icon",children:Bp(_.id)}),l.jsxs("div",{className:"connections-dropdown__info",children:[l.jsx("div",{className:"connections-dropdown__name",children:_.label}),l.jsx("div",{className:"connections-dropdown__type",children:"Not connected"})]}),l.jsx("button",{className:"connections-dropdown__connect-inline-btn",onClick:()=>k(_.id),disabled:c!==null,children:c===_.id?"Connecting…":"Connect"})]},_.id)]:[l.jsxs("div",{className:"connections-dropdown__item connections-dropdown__item--disconnected",children:[l.jsx("div",{className:"connections-dropdown__icon",children:Bp(_.id)}),l.jsxs("div",{className:"connections-dropdown__info",children:[l.jsx("div",{className:"connections-dropdown__name",children:_.label}),l.jsx("div",{className:"connections-dropdown__type",children:"Built-in · Not configured"})]}),l.jsx("button",{className:"connections-dropdown__connect-inline-btn",onClick:()=>h("new"),children:"Configure"})]},_.id)]})})]})}const gF={tree:l.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"M3 3h7v7H3zM14 3h7v4h-7zM14 10h7v4h-7zM3 13h7v8H3z"})}),files:l.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),l.jsx("polyline",{points:"14 2 14 8 20 8"})]}),timeline:l.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("line",{x1:"12",y1:"2",x2:"12",y2:"22"}),l.jsx("circle",{cx:"12",cy:"6",r:"2"}),l.jsx("circle",{cx:"12",cy:"12",r:"2"}),l.jsx("circle",{cx:"12",cy:"18",r:"2"}),l.jsx("line",{x1:"14",y1:"6",x2:"20",y2:"6"}),l.jsx("line",{x1:"14",y1:"12",x2:"20",y2:"12"}),l.jsx("line",{x1:"14",y1:"18",x2:"20",y2:"18"})]}),board:l.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("rect",{x:"3",y:"3",width:"5",height:"18",rx:"1"}),l.jsx("rect",{x:"10",y:"3",width:"5",height:"12",rx:"1"}),l.jsx("rect",{x:"17",y:"3",width:"5",height:"15",rx:"1"})]}),shelf:l.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M4 19V5"}),l.jsx("path",{d:"M8 19V7"}),l.jsx("path",{d:"M12 19V4"}),l.jsx("path",{d:"M16 19V8"}),l.jsx("path",{d:"M20 19V6"}),l.jsx("line",{x1:"2",y1:"20",x2:"22",y2:"20"})]})};function vF(t){const[e,n]=y.useState(LE),[r,s]=y.useState(DE),[i,o]=y.useState($d),c=PE(),[d,f]=y.useState($E),[h,m]=y.useState(FE),g=(N=e,j=r,M=i,_=c,R=d,L=h)=>{zE(N,j,M,_,R,L)},v=N=>{n(N),g(N)},x=()=>{const N=r==="light"?"dark":"light";s(N),g(void 0,N)},k=N=>{o(N),g(void 0,void 0,N),window.dispatchEvent(new CustomEvent("ow-sidebar-mode-change",{detail:N}))},w=N=>{f(N),g(void 0,void 0,void 0,void 0,N)},S=N=>{m(N),g(void 0,void 0,void 0,void 0,void 0,N)};return l.jsxs("div",{className:"appearance-tab",children:[l.jsx("div",{className:"appearance-section",children:l.jsxs("div",{className:"appearance-section-header",children:[l.jsx("span",{className:"appearance-section-title",children:"Mode"}),l.jsxs("button",{className:"appearance-mode-btn",onClick:x,title:r==="light"?"Switch to dark":"Switch to light",children:[r==="light"?l.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("circle",{cx:"12",cy:"12",r:"5"}),l.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),l.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),l.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),l.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),l.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),l.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),l.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),l.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]}):l.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:l.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})}),l.jsx("span",{children:r==="light"?"Light":"Dark"})]})]})}),l.jsxs("div",{className:"appearance-section",children:[l.jsx("div",{className:"appearance-section-header",children:l.jsx("span",{className:"appearance-section-title",children:"Typography"})}),l.jsx("div",{className:"appearance-typeface-grid",children:AE.map(N=>l.jsx("button",{className:`appearance-style-option ${e===N.id?"active":""}`,onClick:()=>v(N.id),title:N.description,children:N.label},N.id))})]}),l.jsxs("div",{className:"appearance-section",children:[l.jsx("div",{className:"appearance-section-header",children:l.jsx("span",{className:"appearance-section-title",children:"Spacing"})}),l.jsx("div",{className:"appearance-typography-grid",children:IE.map(N=>l.jsx("button",{className:`appearance-style-option ${d===N.id?"active":""}`,onClick:()=>w(N.id),children:N.label},N.id))})]}),l.jsxs("div",{className:"appearance-section",children:[l.jsx("div",{className:"appearance-section-header",children:l.jsx("span",{className:"appearance-section-title",children:"Canvas"})}),l.jsx("div",{className:"appearance-style-grid",children:OE.map(N=>l.jsx("button",{className:`appearance-style-option ${h===N.id?"active":""}`,onClick:()=>S(N.id),children:N.label},N.id))})]}),l.jsxs("div",{className:"appearance-section",children:[l.jsx("div",{className:"appearance-section-header",children:l.jsx("span",{className:"appearance-section-title",children:"Layout"})}),l.jsx("div",{className:"appearance-mode-grid",children:RE.map(N=>l.jsxs("button",{className:`appearance-mode-option ${i===N.id?"active":""}`,onClick:()=>k(N.id),children:[gF[N.icon],l.jsx("span",{children:N.label})]},N.id))})]})]})}const r2=[{id:"review",label:"Review",scope:"doc",icon:l.jsx(X5,{}),Component:D8},{id:"activity",label:"Activity",scope:"workspace",icon:l.jsx(n$,{}),Component:eF},{id:"backlinks",label:"Backlinks",scope:"doc",icon:l.jsx(e$,{}),Component:F8},{id:"exports",label:"Export",scope:"doc",icon:l.jsx(t$,{}),Component:U8},{id:"versions",label:"Versions",scope:"doc",icon:l.jsx(Q5,{}),Component:$8},{id:"plugins",label:"Plugins",scope:"settings",icon:l.jsx(r$,{}),Component:cF},{id:"connections",label:"Connections",scope:"settings",icon:l.jsx(s$,{}),Component:mF},{id:"appearance",label:"Appearance",scope:"settings",icon:l.jsx(i$,{}),Component:vF}];function bF(t){return t?r2.find(e=>e.id===t)??null:null}let Vk=0;function yF({pendingDocs:t}){const{visible:e,activeTab:n,openTab:r}=Bl(),[s,i]=y.useState(!1),[o,c]=y.useState(!1);return y.useEffect(()=>{const d=t.filenames.length,f=Vk;Vk=d,f===0&&d>0&&r("review")},[t.filenames.length,r]),y.useEffect(()=>{const d=()=>r("review");return window.addEventListener("ow-pending-write-applied",d),()=>window.removeEventListener("ow-pending-write-applied",d)},[r]),y.useEffect(()=>{const d=()=>{if(!(e&&n==="activity")){i(!0),window.setTimeout(()=>i(!1),500);try{localStorage.getItem("ow-bell-hint-seen")||(c(!0),localStorage.setItem("ow-bell-hint-seen","1"),window.setTimeout(()=>c(!1),6e3))}catch{}}};return window.addEventListener("ow-activity-event",d),()=>window.removeEventListener("ow-activity-event",d)},[e,n]),l.jsx("div",{className:"rail-icon-strip",role:"tablist","aria-label":"Right rail tabs",children:r2.map(d=>{const f=e&&n===d.id,h=d.id==="activity";return l.jsxs("button",{type:"button",role:"tab","aria-selected":f,className:["rail-icon-btn",f?"rail-icon-btn--active":"",`rail-icon-btn--scope-${d.scope}`,h&&s?"rail-icon-btn--pulsing":""].filter(Boolean).join(" "),onClick:()=>r(d.id),title:d.label,"aria-label":d.label,children:[d.icon,h&&o&&l.jsxs("div",{className:"rail-icon-hint",role:"tooltip",children:[l.jsx("span",{children:"Agent activity lives here."}),l.jsx("button",{type:"button",className:"rail-icon-hint-close",onClick:m=>{m.stopPropagation(),c(!1)},"aria-label":"Dismiss",children:"×"})]})]},d.id)})})}function xF(t){const{activeTab:e}=Bl(),n=bF(e);return l.jsx("div",{className:"rail-body",role:"tabpanel",children:n?l.jsx(n.Component,{...t}):null})}const wF=()=>l.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:l.jsx("path",{d:"M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),kF=()=>l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[l.jsx("path",{d:"M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),l.jsx("path",{d:"M9 14l2 2 4-4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),SF=()=>l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[l.jsx("path",{d:"M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),l.jsx("path",{d:"M12 16v-5M9.5 13.5L12 11l2.5 2.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),EF=()=>l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[l.jsx("path",{d:"M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),l.jsx("path",{d:"M14 14l-4 4M10 14l4 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]});function NF({syncStatus:t,onSync:e}){const[n,r]=y.useState(!1),[s,i]=y.useState([]),[o,c]=y.useState(!1),d=y.useRef(null),f=y.useCallback(()=>{if(n){r(!1);return}r(!0),c(!0),fetch("/api/sync/pending").then(h=>h.json()).then(h=>i(h)).catch(()=>i([])).finally(()=>c(!1))},[n]);return y.useEffect(()=>{t.state!=="pending"&&r(!1)},[t.state]),y.useEffect(()=>{if(!n)return;const h=m=>{d.current&&!d.current.contains(m.target)&&r(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[n]),l.jsxs("div",{className:"sync-btn-group",ref:d,children:[l.jsxs("button",{className:`titlebar-btn sync-btn-state sync-${t.state}`,onClick:e,disabled:t.state==="syncing",title:t.lastSyncTime?`Last synced: ${new Date(t.lastSyncTime).toLocaleString()}`:"Sync to GitHub",children:[t.state==="unconfigured"&&l.jsxs(l.Fragment,{children:[l.jsx(wF,{})," Sync"]}),t.state==="synced"&&l.jsxs(l.Fragment,{children:[l.jsx(kF,{})," Synced"]}),t.state==="pending"&&l.jsxs(l.Fragment,{children:[l.jsx(SF,{})," Sync",t.pendingFiles?` (${t.pendingFiles})`:""]}),t.state==="syncing"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"sync-btn-spinner"})," Syncing..."]}),t.state==="error"&&l.jsxs(l.Fragment,{children:[l.jsx(EF,{})," Retry"]})]}),t.state==="pending"&&t.pendingFiles&&t.pendingFiles>0&&l.jsx("button",{className:"sync-details-btn",onClick:f,title:"View pending changes",children:l.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:l.jsx("path",{d:n?"M3 7.5L6 4.5L9 7.5":"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n&&l.jsxs("div",{className:"sync-pending-dropdown",children:[l.jsx("div",{className:"sync-pending-header",children:"Changes to push"}),o?l.jsx("div",{className:"sync-pending-loading",children:"Loading..."}):s.length===0?l.jsx("div",{className:"sync-pending-loading",children:"No changes"}):l.jsx("div",{className:"sync-pending-list",children:s.map((h,m)=>l.jsxs("div",{className:`sync-pending-item sync-file-${h.status}`,children:[l.jsx("span",{className:"sync-file-badge",children:h.status[0].toUpperCase()}),l.jsx("span",{className:"sync-file-name",children:h.file})]},m))})]})]})}function CF(t){const{syncStatus:e,onSync:n,onToggleToolbar:r,toolbarOpen:s,focusMode:i,onToggleFocusMode:o,heatmapOn:c,onToggleHeatmap:d,heatmapAvailable:f,heatmapTitle:h,...m}=t,{open:g,visible:v,overlay:x,activeTab:k,width:w,setWidth:S,closeRail:N,openTab:j}=Bl(),M=y.useRef(null),_=y.useRef(null),R=y.useRef(i);y.useEffect(()=>{if(i!==R.current)if(R.current=i,i)_.current={open:g,activeTab:k},g&&N();else{const B=_.current;_.current=null,!x&&(B!=null&&B.open)&&B.activeTab&&j(B.activeTab)}},[i]);const L=y.useCallback(B=>{B.preventDefault();const U=B.clientX,X=w,z=P=>{const F=U-P.clientX;S(X+F)},ee=()=>{window.removeEventListener("pointermove",z),window.removeEventListener("pointerup",ee)};window.addEventListener("pointermove",z),window.addEventListener("pointerup",ee)},[w,S]);y.useEffect(()=>{if(!g)return;const B=U=>{U.key==="Escape"&&M.current&&M.current.contains(document.activeElement)&&(U.preventDefault(),N())};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[g,N]);const $=!v;return l.jsxs("aside",{ref:M,className:`right-rail-column${$?"":" open"}`,style:$?void 0:{width:w,minWidth:w},"aria-label":"Right rail",children:[!x&&!$&&l.jsx("div",{className:"right-rail-resize-handle",onPointerDown:L,"aria-hidden":"true"}),l.jsxs("div",{className:"right-rail-topbar",children:[l.jsxs("div",{className:"right-rail-topbar-actions right-rail-topbar-actions--start",children:[l.jsx("button",{type:"button",className:"right-rail-topbar-btn",onClick:N,title:"Hide rail","aria-label":"Hide rail",children:l.jsx(o$,{})}),l.jsx("button",{type:"button",className:`right-rail-topbar-btn${i?" right-rail-topbar-btn--active":""}`,onClick:o,title:"Focus mode","aria-label":"Focus mode","aria-pressed":i,children:l.jsx(RT,{})}),l.jsx("button",{type:"button",className:`right-rail-topbar-btn${s?" right-rail-topbar-btn--active":""}`,onClick:r,title:"Toggle format toolbar","aria-label":"Toggle format toolbar","aria-pressed":s,children:l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[l.jsx("path",{d:"M4 20h16"}),l.jsx("path",{d:"m6 16 6-12 6 12"}),l.jsx("path",{d:"M8 12h8"})]})}),f&&l.jsx("button",{type:"button",className:`right-rail-topbar-btn${c?" right-rail-topbar-btn--active":""}`,onClick:d,title:h,"aria-label":"Voice heatmap (human vs agent)","aria-pressed":c,children:l.jsx(Z5,{})})]}),l.jsx("div",{className:"right-rail-topbar-actions right-rail-topbar-actions--end",children:l.jsx(NF,{syncStatus:e,onSync:n})})]}),l.jsx(yF,{pendingDocs:m.pendingDocs}),l.jsx(xF,{...m})]})}function _F({onClose:t,onSetupComplete:e}){const[n,r]=y.useState("detecting"),[s,i]=y.useState(null),[o,c]=y.useState("gh"),[d,f]=y.useState("openwriter-docs"),[h,m]=y.useState(!0),[g,v]=y.useState(""),[x,k]=y.useState(""),[w,S]=y.useState(""),[N,j]=y.useState("");y.useEffect(()=>{fetch("/api/sync/capabilities").then(_=>_.json()).then(_=>{i(_),_.ghAuthenticated?c("gh"):(_.gitInstalled,c("pat")),r("setup")}).catch(()=>{S("Failed to detect git capabilities"),r("error")})},[]);const M=y.useCallback(async()=>{r("progress"),j(o==="connect"?"Connecting to repository...":"Creating repository and syncing...");try{const _={method:o,repoName:d,isPrivate:h};o==="pat"&&(_.pat=g),o==="connect"&&(_.remoteUrl=x,_.pat=g||void 0);const R=await fetch("/api/sync/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)});if(!R.ok){const L=await R.json().catch(()=>({}));throw new Error(L.error||`Setup failed (${R.status})`)}r("done"),e()}catch(_){S(_.message),r("error")}},[o,d,h,g,x,e]);return l.jsx("div",{className:"sync-modal-overlay",onClick:t,children:l.jsxs("div",{className:"sync-modal",onClick:_=>_.stopPropagation(),children:[l.jsxs("div",{className:"sync-modal-header",children:[l.jsx("h2",{children:"Sync to GitHub"}),l.jsx("button",{className:"sync-modal-close",onClick:t,children:"×"})]}),n==="detecting"&&l.jsxs("div",{className:"sync-modal-body",children:[l.jsx("div",{className:"sync-spinner"}),l.jsx("p",{children:"Detecting git configuration..."})]}),n==="setup"&&s&&l.jsxs("div",{className:"sync-modal-body",children:[!s.gitInstalled&&l.jsxs("div",{className:"sync-warning",children:["Git is not installed. Please ",l.jsx("a",{href:"https://git-scm.com/downloads",target:"_blank",rel:"noreferrer",children:"install git"})," first."]}),s.gitInstalled&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"sync-tabs",children:[s.ghAuthenticated&&l.jsx("button",{className:`sync-tab${o==="gh"?" active":""}`,onClick:()=>c("gh"),children:"GitHub CLI"}),l.jsx("button",{className:`sync-tab${o==="pat"?" active":""}`,onClick:()=>c("pat"),children:"Personal Access Token"}),l.jsx("button",{className:`sync-tab${o==="connect"?" active":""}`,onClick:()=>c("connect"),children:"Connect Existing"})]}),o==="gh"&&l.jsxs("div",{className:"sync-form",children:[l.jsxs("label",{children:["Repository name",l.jsx("input",{type:"text",value:d,onChange:_=>f(_.target.value),placeholder:"openwriter-docs"})]}),l.jsxs("label",{className:"sync-checkbox",children:[l.jsx("input",{type:"checkbox",checked:h,onChange:_=>m(_.target.checked)}),"Private repository"]})]}),o==="pat"&&l.jsxs("div",{className:"sync-form",children:[!s.ghAuthenticated&&!s.ghInstalled&&l.jsxs("p",{className:"sync-hint",children:["Create a ",l.jsx("a",{href:"https://github.com/settings/tokens/new?scopes=repo&description=OpenWriter",target:"_blank",rel:"noreferrer",children:"Personal Access Token"})," with ",l.jsx("code",{children:"repo"})," scope."]}),l.jsxs("label",{children:["Personal Access Token",l.jsx("input",{type:"password",value:g,onChange:_=>v(_.target.value),placeholder:"ghp_..."})]}),l.jsxs("label",{children:["Repository name",l.jsx("input",{type:"text",value:d,onChange:_=>f(_.target.value),placeholder:"openwriter-docs"})]}),l.jsxs("label",{className:"sync-checkbox",children:[l.jsx("input",{type:"checkbox",checked:h,onChange:_=>m(_.target.checked)}),"Private repository"]})]}),o==="connect"&&l.jsxs("div",{className:"sync-form",children:[l.jsxs("label",{children:["Remote URL",l.jsx("input",{type:"text",value:x,onChange:_=>k(_.target.value),placeholder:"https://github.com/user/repo.git"})]}),l.jsxs("label",{children:["PAT (optional, for private repos)",l.jsx("input",{type:"password",value:g,onChange:_=>v(_.target.value),placeholder:"ghp_..."})]})]}),l.jsxs("div",{className:"sync-modal-actions",children:[l.jsx("button",{className:"sync-btn secondary",onClick:t,children:"Cancel"}),l.jsx("button",{className:"sync-btn primary",onClick:M,disabled:o==="pat"&&!g||o==="connect"&&!x||o!=="connect"&&!d,children:o==="connect"?"Connect & Sync":"Create & Sync"})]})]})]}),n==="progress"&&l.jsxs("div",{className:"sync-modal-body",children:[l.jsx("div",{className:"sync-spinner"}),l.jsx("p",{children:N})]}),n==="done"&&l.jsxs("div",{className:"sync-modal-body",children:[l.jsx("div",{className:"sync-success-icon",children:"✓"}),l.jsx("p",{children:"Successfully synced to GitHub!"}),l.jsx("div",{className:"sync-modal-actions",children:l.jsx("button",{className:"sync-btn primary",onClick:t,children:"Done"})})]}),n==="error"&&l.jsxs("div",{className:"sync-modal-body",children:[l.jsx("div",{className:"sync-error-msg",children:w}),l.jsxs("div",{className:"sync-modal-actions",children:[l.jsx("button",{className:"sync-btn secondary",onClick:()=>r("setup"),children:"Back"}),l.jsx("button",{className:"sync-btn secondary",onClick:t,children:"Close"})]})]})]})})}function TF({onNodeChanges:t,onAgentStatus:e,onDocumentSwitched:n,onDocumentReloaded:r,onDocumentsChanged:s,onWorkspacesChanged:i,onTitleChanged:o,onPendingDocsChanged:c,onMetadataChanged:d,onSyncStatus:f,onWritingStarted:h,onWritingFinished:m,onIdRewrites:g,onPendingFilenamesChanged:v,getEditorState:x}){const k=y.useRef(null),[w,S]=y.useState(!1),N=y.useRef(0),j=y.useRef(new Set),M=()=>{var A;return(A=ie.current)==null?void 0:A.call(ie,new Set(j.current))},_=y.useRef(t),R=y.useRef(e),L=y.useRef(n),$=y.useRef(s),B=y.useRef(i),U=y.useRef(o),X=y.useRef(c),z=y.useRef(f),ee=y.useRef(d),P=y.useRef(h),F=y.useRef(m),G=y.useRef(g),ie=y.useRef(v),K=y.useRef(r),ce=y.useRef(x);_.current=t,R.current=e,L.current=n,$.current=s,B.current=i,U.current=o,X.current=c,ee.current=d,z.current=f,P.current=h,F.current=m,G.current=g,ie.current=v,K.current=r,ce.current=x,y.useEffect(()=>{const D=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;let q,le=!1,ye=1e3;function oe(){const Ee=new WebSocket(D);k.current=Ee,Ee.onopen=()=>{S(!0),ye=1e3,le&&Ee.send(JSON.stringify({type:"request-document"})),le=!0},Ee.onmessage=Le=>{var Ie,Ve,Te,qe,pt,ut,be,ht,xt,St,At,Ye,ct,Fe;try{const Y=JSON.parse(Le.data);if(Y.type==="node-changes"&&Y.changes&&((Ie=_.current)==null||Ie.call(_,Y.changes),typeof Y.version=="number"&&(N.current=Y.version)),Y.type==="id-rewrites"&&Array.isArray(Y.rewrites)&&((Ve=G.current)==null||Ve.call(G,Y.rewrites)),Y.type==="agent-status"&&((Te=R.current)==null||Te.call(R,!!Y.agentConnected)),Y.type==="document-switched"&&(N.current=typeof Y.version=="number"?Y.version:0,(qe=L.current)==null||qe.call(L,{document:Y.document,title:Y.title,filename:Y.filename,docId:Y.docId,metadata:Y.metadata,pendingMetadata:Y.pendingMetadata??null}),window.dispatchEvent(new CustomEvent("ow-pending-metadata-changed",{detail:{docId:Y.docId,pendingMetadata:Y.pendingMetadata??null}}))),Y.type==="pending-metadata-changed"&&window.dispatchEvent(new CustomEvent("ow-pending-metadata-changed",{detail:{docId:Y.docId,pendingMetadata:Y.pendingMetadata??null}})),Y.type==="document-reloaded"&&(typeof Y.version=="number"&&(N.current=Y.version),(pt=K.current)==null||pt.call(K,{document:Y.document,title:Y.title,filename:Y.filename,docId:Y.docId,metadata:Y.metadata,orphanCount:typeof Y.orphanCount=="number"?Y.orphanCount:0,staleBaselineCount:typeof Y.staleBaselineCount=="number"?Y.staleBaselineCount:0})),Y.type==="metadata-changed"&&Y.metadata&&((ut=ee.current)==null||ut.call(ee,Y.metadata)),Y.type==="documents-changed"&&((be=$.current)==null||be.call($)),Y.type==="workspaces-changed"&&((ht=B.current)==null||ht.call(B)),Y.type==="title-changed"&&Y.title&&((xt=U.current)==null||xt.call(U,Y.title)),Y.type==="pending-docs-changed"&&Y.pendingDocs&&((St=X.current)==null||St.call(X,Y.pendingDocs)),Y.type==="sync-status"&&((At=z.current)==null||At.call(z,{state:Y.state,lastSyncTime:Y.lastSyncTime,pendingFiles:Y.pendingFiles,error:Y.error})),Y.type==="writing-started"&&Y.title&&(typeof Y.key=="string"&&(j.current.add(Y.key),M()),(Ye=P.current)==null||Ye.call(P,Y.title,Y.target||null)),Y.type==="writing-finished"&&(typeof Y.key=="string"&&Y.key?j.current.delete(Y.key):j.current.clear(),M(),(ct=F.current)==null||ct.call(F)),Y.type==="pending-writes-sync"&&Array.isArray(Y.writes)&&(j.current=new Set(Y.writes.map(ge=>ge.key).filter(Boolean)),M(),Y.writes.length>0)){const ge=Y.writes.reduce((ne,he)=>ne.startedAt>he.startedAt?ne:he);ge!=null&&ge.title&&((Fe=P.current)==null||Fe.call(P,ge.title,ge.target||null))}if(Y.type==="plugins-changed"&&window.dispatchEvent(new CustomEvent("ow-plugins-changed")),Y.type==="comments-changed"&&Y.filename&&window.dispatchEvent(new CustomEvent("ow-comments-changed",{detail:{filename:Y.filename}})),Y.type==="documents-changed"&&window.dispatchEvent(new CustomEvent("ow-documents-changed")),Y.type==="metadata-changed"&&window.dispatchEvent(new CustomEvent("ow-metadata-changed",{detail:{metadata:Y.metadata}})),Y.type==="activity-log"&&Array.isArray(Y.entries)&&window.dispatchEvent(new CustomEvent("ow-activity-seed",{detail:{entries:Y.entries}})),Y.type==="activity-event"&&Y.event&&window.dispatchEvent(new CustomEvent("ow-activity-event",{detail:{event:Y.event}})),Y.type==="toast"&&typeof Y.message=="string"){const ge=Y.kind==="error"?"error":"info";Ai(Y.message,ge,typeof Y.durationMs=="number"?Y.durationMs:ge==="error"?9e3:3500)}}catch{}},Ee.onclose=()=>{S(!1),q=setTimeout(oe,ye),ye=Math.min(ye*1.5,8e3)},Ee.onerror=()=>{Ee.close()}}oe();function Se(){var Ee;document.visibilityState==="visible"&&((Ee=k.current)==null?void 0:Ee.readyState)!==WebSocket.OPEN&&(clearTimeout(q),ye=1e3,oe())}return document.addEventListener("visibilitychange",Se),()=>{clearTimeout(q),document.removeEventListener("visibilitychange",Se),k.current&&(k.current.onclose=null,k.current.close())}},[]);const J=y.useCallback(A=>{var D;((D=k.current)==null?void 0:D.readyState)===WebSocket.OPEN&&k.current.send(JSON.stringify(A))},[]);return{connected:w,sendMessage:J,docVersionRef:N}}function jF(t){const[e,n]=y.useState(null),[r,s]=y.useState(!1),[i,o]=y.useState(null),c=y.useRef(void 0);return y.useEffect(()=>{if(!t){n(null),s(!1),o(null),c.current=void 0;return}t!==c.current&&(c.current=t,s(!0),o(null),fetch(`/api/tweet-embed?url=${encodeURIComponent(t)}`).then(d=>d.ok?d.json():d.json().then(f=>Promise.reject(new Error(f.error||`HTTP ${d.status}`)))).then(d=>{n(d),s(!1)}).catch(d=>{o(d.message),s(!1)}))},[t]),{tweet:e,loading:r,error:i}}function MF(t){var r;const e=t.view.dom,n=[];for(const s of e.children){const i=(r=s.innerText)==null?void 0:r.trim();i&&n.push(i)}return n.join(`
211
211