openwriter 0.36.0 → 0.36.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.
|
@@ -207,9 +207,9 @@ Run: ${T.updateCommand}`,children:["v",T.latestVersion]})]}),c.jsxs("div",{class
|
|
|
207
207
|
`);Ve.trim()&&fetch("/api/comments",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:n,text:Ve,note:J.trim(),nodeId:Oe[Oe.length-1],nodeIds:Oe})}).then(()=>{s(!1),F(!1),$("")}).catch(et=>{console.error("[ContextMenu] Comment create failed:",et)})},[t,n,J,W]),Lt=x.useCallback(()=>{ne&&(q({id:ne.id,text:ne.text}),$(ne.note),F(!0),V(null))},[ne]),at=x.useCallback(()=>{ne&&fetch("/api/comments/resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[ne.id]})}).then(()=>{s(!1),V(null)}).catch(Q=>{console.error("[ContextMenu] Comment resolve failed:",Q)})},[ne]),De=x.useCallback(()=>{ne&&fetch("/api/comments",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[ne.id]})}).then(()=>{s(!1),V(null)}).catch(Q=>{console.error("[ContextMenu] Comment delete failed:",Q)})},[ne]),ve=x.useCallback((Q,he)=>{const me=$e.current||t.current;if(me){const Ue=Q.docId?Ap({docId:Q.docId,nodeId:he==null?void 0:he.nodeId,quote:he==null?void 0:he.quote}):Ap({filename:Q.filename});me.chain().focus().setLink({href:Ue}).run()}fetch("/api/auto-tag-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetFile:Q.filename})}).catch(()=>{}),s(!1),w(!1),re(null)},[t]),Z=x.useCallback(Q=>{if(!Q.docId){ve(Q);return}re({docId:Q.docId,filename:Q.filename,title:Q.title,paragraphs:[],loading:!0}),fetch(`/api/documents/by-doc-id/${Q.docId}/paragraphs`).then(he=>he.json()).then(he=>{re(me=>me&&me.docId===Q.docId?{...me,paragraphs:Array.isArray(he.paragraphs)?he.paragraphs:[],loading:!1}:me)}).catch(()=>{re(he=>he&&he.docId===Q.docId?{...he,paragraphs:[],loading:!1}:he)})},[ve]),je=x.useCallback(()=>{const Q=I.trim();if(!Q)return;const he=$e.current||t.current;he&&(fetch("/api/create-link-doc",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:Q})}).then(me=>me.json()).then(me=>{if(me.filename){const Ue=Ap(me.docId?{docId:me.docId}:{filename:me.filename});he.chain().focus().setLink({href:Ue}).run()}}).catch(()=>{}),s(!1),w(!1),R(!1),P(""))},[t,I]);return r?c.jsx("div",{ref:we,className:"context-menu",style:{left:i.x,top:i.y},children:l?c.jsx("div",{className:"context-menu-loading",children:"Applying..."}):K?c.jsxs("div",{className:"context-menu-comment-editor",children:[(()=>{const Q=(W==null?void 0:W.text)??(()=>{const he=$e.current||t.current,me=Ee.current;return!he||!me||me.from===me.to?"":he.state.doc.textBetween(me.from,me.to,`
|
|
208
208
|
`)})();return Q?c.jsx("div",{className:"context-menu-comment-quote",children:Q}):null})(),c.jsx("textarea",{autoFocus:!0,className:"context-menu-comment-textarea",value:J,onChange:Q=>$(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"&&(Q.metaKey||Q.ctrlKey)&&(Q.preventDefault(),_t()),Q.key==="Escape"&&(s(!1),F(!1),$(""),q(null))},placeholder:"Note for agent (optional)...",rows:4}),c.jsxs("div",{className:"context-menu-comment-actions",children:[c.jsx("span",{className:"context-menu-comment-hint",children:"⌘↵ to save · Esc to cancel"}),c.jsx("button",{onClick:_t,children:W?"Save":"Comment"})]})]}):ne?c.jsxs(c.Fragment,{children:[c.jsx("button",{className:"context-menu-item",onClick:Lt,children:c.jsx("span",{children:"Edit comment"})}),c.jsx("button",{className:"context-menu-item",onClick:at,children:c.jsx("span",{children:"Resolve comment"})}),c.jsx("button",{className:"context-menu-item",onClick:De,children:c.jsx("span",{children:"Delete comment"})})]}):m?c.jsxs("div",{className:"context-menu-custom",children:[c.jsx("input",{autoFocus:!0,value:f,onChange:Q=>h(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"&&Ct(),Q.key==="Escape"&&s(!1)},placeholder:"Custom instruction..."}),c.jsx("button",{onClick:Ct,children:"Apply"})]}):be?c.jsxs("div",{className:"context-menu-link-picker",children:[c.jsxs("div",{className:"context-menu-link-header",children:[c.jsx("button",{className:"context-menu-link-back",onClick:()=>re(null),title:"Back to doc list",children:"←"}),c.jsxs("span",{children:['Pick paragraph in "',be.title,'"']})]}),c.jsx("button",{className:"context-menu-item context-menu-new-link",onClick:()=>ve({filename:be.filename,docId:be.docId}),children:c.jsx("span",{children:"Link whole doc"})}),c.jsx("div",{className:"context-menu-link-list",children:be.loading?c.jsx("div",{className:"context-menu-loading",children:"Loading…"}):be.paragraphs.length===0?c.jsx("div",{className:"context-menu-loading",children:"No paragraphs"}):be.paragraphs.map(Q=>{const he=Q.preview.replace(/…$/,"").slice(0,50),me=Q.type==="heading"?Math.max(0,(Q.level||1)-1)*12:12;return c.jsx("button",{className:`context-menu-item context-menu-paragraph-row context-menu-paragraph-row--${Q.type}`,style:{paddingLeft:8+me},onClick:()=>ve({filename:be.filename,docId:be.docId},{nodeId:Q.nodeId,quote:he}),children:c.jsx("span",{children:Q.preview})},Q.nodeId)})})]}):A&&oe?c.jsxs("div",{className:"context-menu-link-picker",children:[c.jsxs("div",{className:"context-menu-link-header",children:["Linked from ",oe.entries.length," ",oe.entries.length===1?"place":"places"]}),c.jsx("div",{className:"context-menu-link-list",children:oe.entries.map((Q,he)=>{const me=S.find(Oe=>Oe.docId===Q.from_doc),Ue=(me==null?void 0:me.title)||Q.from_doc;return c.jsxs("button",{className:"context-menu-item",onClick:()=>{window.dispatchEvent(new CustomEvent("ow-navigate-to-link",{detail:{docId:Q.from_doc,nodeId:Q.from_node,filename:null,quote:null}})),s(!1),L(!1)},children:[c.jsx("span",{children:Ue}),c.jsxs("span",{className:"context-menu-shortcut",children:['"',Q.text,'"']})]},`${Q.from_doc}-${Q.from_node}-${he}`)})})]}):k?c.jsxs("div",{className:"context-menu-link-picker",children:[c.jsx("div",{className:"context-menu-link-header",children:"Link to document"}),_?c.jsxs("div",{className:"context-menu-custom",children:[c.jsx("input",{autoFocus:!0,value:I,onChange:Q=>P(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"&&je(),Q.key==="Escape"&&R(!1)},placeholder:"New document title..."}),c.jsx("button",{onClick:je,children:"Create"})]}):c.jsx("button",{className:"context-menu-item context-menu-new-link",onClick:()=>R(!0),children:c.jsx("span",{children:"+ New link doc"})}),c.jsxs("div",{className:"context-menu-link-list",children:[T.length>0&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"context-menu-section-header",children:"Linked in this doc"}),S.filter(Q=>kk(Q,T)).map(Q=>c.jsxs("div",{className:"context-menu-link-row",children:[c.jsx("button",{className:"context-menu-item context-menu-link-row__main",onClick:()=>ve(Q),children:c.jsx("span",{children:Q.title})}),Q.docId&&c.jsx("button",{className:"context-menu-link-row__drill",title:"Pick a paragraph in this doc",onClick:()=>Z(Q),children:"▸"})]},`linked-${Q.filename}`))]}),c.jsx("div",{className:"context-menu-section-header",children:"All documents"}),S.filter(Q=>!kk(Q,T)).map(Q=>c.jsxs("div",{className:"context-menu-link-row",children:[c.jsx("button",{className:"context-menu-item context-menu-link-row__main",onClick:()=>ve(Q),children:c.jsx("span",{children:Q.title})}),Q.docId&&c.jsx("button",{className:"context-menu-link-row__drill",title:"Pick a paragraph in this doc",onClick:()=>Z(Q),children:"▸"})]},Q.filename)),S.length===0&&c.jsx("div",{className:"context-menu-loading",children:"No documents"})]})]}):(()=>{const Q=gt();let he;return Q.map((me,Ue)=>{const Oe=me.isPlugin&&me.pluginDisplayName&&me.pluginDisplayName!==he,Ve=he!==void 0;me.isPlugin?he=me.pluginDisplayName:he=void 0;const et=!me.isPlugin&&Ve;return c.jsxs("span",{children:[Oe&&c.jsx("div",{className:"context-menu-section-header",children:me.pluginDisplayName}),et&&c.jsx("div",{className:"context-menu-divider"}),c.jsxs("button",{className:"context-menu-item",onClick:()=>yt(me),children:[c.jsx("span",{children:me.label}),me.shortcut&&c.jsx("span",{className:"context-menu-shortcut",children:me.shortcut})]})]},me.action)})})()}):null}const d$=80,Op=8,Jo=8,f$=400;function Sk(t){return t.nodeIds&&t.nodeIds.length>0?t.nodeIds:[t.nodeId]}function Ek(t,e){const n=new Set(e);return t.every(r=>n.has(r))}function h$(t,e){const n=e.find(s=>s.id===t);if(!n)return[];const r=Sk(n);return e.filter(s=>{if(s.id===n.id)return!0;const i=Sk(s);return Ek(i,r)||Ek(r,i)}).sort((s,i)=>(s.createdAt||"").localeCompare(i.createdAt||""))}function p$({documentId:t}){const[e,n]=x.useState(null),[r,s]=x.useState({kind:"view"}),[i,o]=x.useState(""),[l,d]=x.useState(0),[f,h]=x.useState({left:0,top:0,placement:"above"}),m=x.useRef(null),g=x.useRef(null),v=x.useRef(null),b=x.useRef(null),k=x.useRef({kind:"view"});x.useEffect(()=>{b.current=e},[e]),x.useEffect(()=>{k.current=r},[r]),x.useEffect(()=>{const J=()=>d($=>$+1);return window.addEventListener("ow-comments-changed",J),()=>window.removeEventListener("ow-comments-changed",J)},[]);const w=x.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},[]),S=x.useCallback(()=>{w(),v.current=window.setTimeout(()=>{k.current.kind==="view"&&n(null)},d$)},[w]),N=x.useCallback(()=>{w(),n(null),s({kind:"view"}),o("")},[w]),T=x.useMemo(()=>e?h$(e.commentId,$u()):[],[e,l]);x.useEffect(()=>{e&&T.length===0&&N()},[e,T.length,N]),x.useLayoutEffect(()=>{if(!e)return;const J=m.current;if(!J)return;const $=J.getBoundingClientRect(),{rect:W}=e,q=W.top,ne=window.innerHeight-W.bottom,V=q>=$.height+Op||q>=ne?"above":"below",oe=V==="above"?Math.max(Jo,W.top-$.height-Op):Math.min(window.innerHeight-$.height-Jo,W.bottom+Op);let Y=W.left;Y+$.width>window.innerWidth-Jo&&(Y=window.innerWidth-$.width-Jo),Y<Jo&&(Y=Jo),h({left:Y,top:oe,placement:V})},[e,r,T.length,l]),x.useEffect(()=>{const J=ne=>{var Y,A,L;const V=ne.target,oe=(Y=V==null?void 0:V.closest)==null?void 0:Y.call(V,"[data-comment-id]");if(oe){const ee=oe.getAttribute("data-comment-id");if(!ee)return;if(((A=b.current)==null?void 0:A.commentId)===ee){w();return}w(),s({kind:"view"}),o(""),n({commentId:ee,rect:oe.getBoundingClientRect()});return}if((L=m.current)!=null&&L.contains(V)){w();return}b.current&&S()},$=ne=>{var oe,Y;const V=ne.relatedTarget;if(V&&((oe=m.current)!=null&&oe.contains(V))){w();return}V&&((Y=V.closest)!=null&&Y.call(V,"[data-comment-id]"))||b.current&&S()},W=ne=>{if(ne.key==="Escape"&&b.current){if(ne.preventDefault(),k.current.kind!=="view"){s({kind:"view"}),o("");return}N()}},q=ne=>{var V;b.current&&k.current.kind==="view"&&((V=m.current)!=null&&V.contains(ne.target)||N())};return document.addEventListener("mouseover",J),document.addEventListener("mouseout",$),document.addEventListener("keydown",W),document.addEventListener("scroll",q,!0),()=>{document.removeEventListener("mouseover",J),document.removeEventListener("mouseout",$),document.removeEventListener("keydown",W),document.removeEventListener("scroll",q,!0),w()}},[w,S,N]),x.useEffect(()=>{var J;r.kind!=="view"&&((J=g.current)==null||J.focus())},[r]);const M=x.useCallback(J=>{const $=$u().find(W=>W.id===J);$&&(o($.note||""),s({kind:"edit",commentId:J}))},[]),_=x.useCallback(J=>{o(""),s({kind:"compose",parentCommentId:J})},[]),R=x.useCallback(()=>{s({kind:"view"}),o("")},[]),I=x.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(J=>console.error("[CommentPopover] Save failed:",J))},[r,t,i]),P=x.useCallback(()=>{if(r.kind!=="compose"||!t)return;const J=$u().find($=>$.id===r.parentCommentId);J&&fetch("/api/comments",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:t,text:J.text,note:i.trim(),nodeId:J.nodeId,nodeIds:J.nodeIds})}).then(()=>{s({kind:"view"}),o("")}).catch($=>console.error("[CommentPopover] Create failed:",$))},[r,t,i]),B=x.useCallback(J=>{fetch("/api/comments/resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[J]})}).catch($=>console.error("[CommentPopover] Resolve failed:",$))},[]),z=x.useCallback(J=>{fetch("/api/comments",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[J]})}).catch($=>console.error("[CommentPopover] Delete failed:",$))},[]);if(!e||T.length===0)return null;const K=r.kind!=="view",F=r.kind==="compose"?"Adding a new comment on the same range":null;return c.jsx("div",{ref:m,className:`ow-comment-popover ow-comment-popover-${f.placement}`,style:{left:f.left,top:f.top,maxHeight:f$},onMouseEnter:w,onMouseLeave:S,children:K?c.jsxs(c.Fragment,{children:[F&&c.jsx("div",{className:"ow-comment-popover-empty",children:F}),c.jsx("textarea",{ref:g,className:"ow-comment-popover-textarea",value:i,onChange:J=>o(J.target.value),onKeyDown:J=>{J.key==="Enter"&&(J.metaKey||J.ctrlKey)&&(J.preventDefault(),r.kind==="edit"?I():r.kind==="compose"&&P()),J.key==="Escape"&&(J.preventDefault(),R())},rows:4,placeholder:"Note for agent (optional)..."}),c.jsxs("div",{className:"ow-comment-popover-actions",children:[c.jsx("span",{className:"ow-comment-popover-hint",children:"⌘↵ to save · Esc to cancel"}),c.jsx("button",{className:"ow-icon-btn",onClick:r.kind==="edit"?I:P,title:"Save",children:c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M20 6 9 17l-5-5"})})})]})]}):c.jsx("div",{className:"ow-comment-popover-stack",children:T.map((J,$)=>c.jsxs("div",{className:`ow-comment-popover-card${$>0?" ow-comment-popover-card-divider":""}`,children:[J.note?c.jsx("div",{className:"ow-comment-popover-text",children:J.note}):c.jsx("div",{className:"ow-comment-popover-empty",children:"No note"}),c.jsxs("div",{className:"ow-comment-popover-actions",children:[c.jsx("button",{className:"ow-icon-btn",onClick:()=>M(J.id),title:"Edit comment",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M12 20h9"}),c.jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"})]})}),c.jsx("button",{className:"ow-icon-btn",onClick:()=>_(J.id),title:"Add another comment on this range",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M12 5v14"}),c.jsx("path",{d:"M5 12h14"})]})}),c.jsx("button",{className:"ow-icon-btn",onClick:()=>B(J.id),title:"Resolve (mark addressed)",children:c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M20 6 9 17l-5-5"})})}),c.jsx("button",{className:"ow-icon-btn ow-icon-btn-danger",onClick:()=>z(J.id),title:"Delete (remove permanently)",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6 6 18"}),c.jsx("path",{d:"m6 6 12 12"})]})})]})]},J.id))})})}function ku(t){return t.type==="doc"?t.file:t.id}function Rl(t,e){for(const n of t)n.type==="doc"?e.add(n.file):n.type==="container"&&Rl(n.items,e)}function _T(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=_T(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(_T(r.root,e,s,!1)===!0)return!0}return!1}function pa(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 Fs(t){return/^[A-Z]:[/\\]|^\//.test(t)}function TT(t){const e=t.replace(/\\/g,"/").split("/");return e.length>=2?e[e.length-2]:""}function m$(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 g$(t,e){const[n,r]=x.useState([]),[s,i]=x.useState([]),o=x.useRef(null),l=x.useRef(new Set),d=x.useCallback(g=>{l.current.add(g)},[]),f=x.useMemo(()=>{const g=new Set;for(const v of s)v.workspace&&Rl(v.workspace.root,g);return g},[s]),h=x.useCallback(()=>{fetch("/api/documents").then(g=>g.json()).then(g=>{if(!Array.isArray(g))return;const v=l.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 b=v.size>0?g.filter(k=>!v.has(k.filename)):g;r(b)}).catch(()=>{})},[]),m=x.useCallback(()=>{fetch("/api/workspaces").then(g=>g.json()).then(async g=>{if(!Array.isArray(g))return;const v=await Promise.all(g.map(async b=>{try{const w=await(await fetch(`/api/workspaces/${encodeURIComponent(b.filename)}`)).json();return{...b,workspace:w}}catch{return b}}));i(v)}).catch(()=>{})},[]);return x.useEffect(()=>{h()},[h,t]),x.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 jT(t,e,n){return t.map(r=>r.type==="container"&&r.id===e?{...r,name:n}:r.type==="container"?{...r,items:jT(r.items,e,n)}:r)}function v$(t,e,n,r,s,i){const o=x.useCallback(_=>{n(R=>R.filter(I=>I.filename!==_)),i==null||i(_),fetch(`/api/documents/${encodeURIComponent(_)}`,{method:"DELETE"}).catch(()=>t())},[n,t]),l=x.useCallback(_=>{n(R=>R.filter(I=>I.filename!==_)),fetch(`/api/documents/${encodeURIComponent(_)}/archive`,{method:"POST"}).catch(()=>t())},[n,t]),d=x.useCallback(_=>{n(R=>R.filter(I=>I.filename!==_)),fetch(`/api/documents/${encodeURIComponent(_)}/unarchive`,{method:"POST"}).catch(()=>t())},[n,t]),f=x.useCallback((_,R,I)=>{!I.trim()||I.trim()===R||(n(P=>P.map(B=>B.filename===_?{...B,title:I.trim()}:B)),fetch(`/api/documents/${encodeURIComponent(_)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:I.trim()})}).catch(()=>t()))},[n,t]),h=x.useCallback(_=>{r(R=>R.filter(I=>I.filename!==_)),fetch(`/api/workspaces/${encodeURIComponent(_)}`,{method:"DELETE"}).catch(()=>e())},[r,e]),m=x.useCallback((_,R)=>{R.trim()&&(r(I=>I.map(P=>P.filename===_?{...P,title:R.trim()}:P)),fetch(`/api/workspaces/${encodeURIComponent(_)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:R.trim()})}).catch(()=>e()))},[r,e]),g=x.useCallback((_,R)=>{r(I=>I.map(P=>P.filename!==_||!P.workspace?P:{...P,docCount:Math.max(0,P.docCount-1),workspace:{...P.workspace,root:Zg(P.workspace.root,B=>B.type==="doc"&&B.file===R)}})),fetch(`/api/workspaces/${encodeURIComponent(_)}/docs/${encodeURIComponent(R)}`,{method:"DELETE"}).catch(()=>e())},[r,e]),v=x.useCallback((_,R,I=!1)=>{r(B=>B.map(z=>z.filename!==_||!z.workspace?z:{...z,workspace:{...z.workspace,root:Zg(z.workspace.root,K=>K.type==="container"&&K.id===R)}}));const P=`/api/workspaces/${encodeURIComponent(_)}/containers/${encodeURIComponent(R)}${I?"?cascade=true":""}`;fetch(P,{method:"DELETE"}).then(()=>{I&&t()}).catch(()=>e())},[r,e,t]),b=x.useCallback((_,R,I)=>{I.trim()&&(r(P=>P.map(B=>B.filename!==_||!B.workspace?B:{...B,workspace:{...B.workspace,root:jT(B.workspace.root,R,I.trim())}})),fetch(`/api/workspaces/${encodeURIComponent(_)}/containers/${encodeURIComponent(R)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:I.trim()})}).catch(()=>e()))},[r,e]),k=x.useCallback(()=>{fetch("/api/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:"Untitled Workspace"})}).catch(()=>{})},[]),w=x.useCallback((_,R,I)=>{fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I?{metadata:I}:{})}).then(P=>P.json()).then(P=>{if(P.filename)return fetch(`/api/workspaces/${encodeURIComponent(_)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:P.filename,title:P.title||"Untitled",containerId:R})})}).catch(()=>{})},[]),S=x.useCallback((_,R)=>{fetch(`/api/workspaces/${encodeURIComponent(_)}/containers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:"Untitled",parentContainerId:R})}).catch(()=>{})},[]),N=x.useCallback(_=>{const R=s.find(I=>I.filename===_);return(R==null?void 0:R.tags)??[]},[s]),T=x.useCallback((_,R)=>{const I=R.trim();I&&(n(P=>P.map(B=>{if(B.filename!==_)return B;const z=B.tags??[];return z.includes(I)?B:{...B,tags:[...z,I]}})),fetch(`/api/doc-tags/${encodeURIComponent(_)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag:I})}).catch(()=>{}))},[n]),M=x.useCallback((_,R)=>{n(I=>I.map(P=>{if(P.filename!==_)return P;const B=P.tags??[],z=B.filter(K=>K!==R);return z.length===B.length?P:z.length>0?{...P,tags:z}:{...P,tags:void 0}})),fetch(`/api/doc-tags/${encodeURIComponent(_)}/${encodeURIComponent(R)}`,{method:"DELETE"}).catch(()=>{})},[n]);return{fetchDocs:t,handleDelete:o,handleArchive:l,handleUnarchive:d,handleRename:f,handleCreateWorkspace:k,handleDeleteWorkspace:h,handleCreateInWorkspace:w,handleRemoveFromWorkspace:g,handleCreateContainer:S,handleDeleteContainer:v,handleRenameContainer:b,handleRenameWorkspace:m,getDocTags:N,handleAddTag:T,handleRemoveTag:M}}function MT({docs:t,workspaces:e,assignedFiles:n,scrollRef:r,setCollapsedSections:s}){const[i,o]=x.useState(null),[l,d]=x.useState(null),f=x.useRef(null),h=x.useRef(null),m=x.useRef(null),g=x.useRef(null),v=x.useRef(null),b=5,k=(z,K,F)=>F==="before"?K>0?ku(z[K-1]):null:ku(z[K]),w=x.useCallback((z,K)=>{if(K===null){const $=t.filter(q=>!n.has(q.filename)).map(q=>({type:"doc",file:q.filename,title:q.title})),W=$.findIndex(q=>ku(q)===z);return W>=0?{siblings:$,index:W,containerId:null}:null}const F=e.find($=>$.filename===K);if(!(F!=null&&F.workspace))return null;const J=($,W)=>{for(let q=0;q<$.length;q++){if(ku($[q])===z)return{siblings:$,index:q,containerId:W};if($[q].type==="container"){const ne=J($[q].items,$[q].id);if(ne)return ne}}return null};return J(F.workspace.root,null)},[t,n,e]),S=x.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=x.useCallback((z,K)=>{if(!z||!K)return;if(z.type==="workspace"){const V=K.itemId;if(V===z.filename)return;const oe=e.map(L=>L.filename),Y=oe.indexOf(z.filename);if(Y<0)return;oe.splice(Y,1);let A=oe.indexOf(V);if(A<0)return;K.position==="after"&&(A+=1),oe.splice(A,0,z.filename),fetch("/api/workspaces/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:oe})}).catch(()=>{});return}const{wsFilename:F,containerId:J,afterId:$}=K,W=z.type==="doc"?z.file:z.id,q=z.sourceWs;if(K.itemId===W)return;if(z.type==="container"){if(F===null&&J===null&&K.itemId!=="__section__"){const V=K.itemId,oe=K.position==="after"?V:(()=>{const Y=e.findIndex(A=>A.filename===V);return Y>0?e[Y-1].filename:null})();fetch("/api/workspaces/promote-container",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:q,containerId:W,afterWorkspaceFilename:oe})}).catch(()=>{});return}if(q!==F&&F){fetch(`/api/workspaces/${encodeURIComponent(F)}/containers/${encodeURIComponent(W)}/cross-move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:q,targetContainerId:J??null,afterIdentifier:$})}).catch(()=>{});return}if(!F)return;fetch(`/api/workspaces/${encodeURIComponent(F)}/docs/${encodeURIComponent(W)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:J??null,afterFile:$})}).catch(()=>{});return}const ne=z.file;if(q===null&&F===null){const V=t.filter(ee=>!n.has(ee.filename)).map(ee=>ee.filename),oe=V.indexOf(ne);if(oe<0)return;V.splice(oe,1);let Y=$?V.indexOf($):-1;Y>=0?Y+=1:Y=0,V.splice(Y,0,ne);const A=[];let L=0;for(const ee of t)n.has(ee.filename)?A.push(ee.filename):A.push(V[L++]);fetch("/api/documents/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:A})}).catch(()=>{});return}if(q===null&&F!==null){fetch(`/api/workspaces/${encodeURIComponent(F)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:ne,title:ne.replace(/\.md$/,""),containerId:J??null,afterFile:$})}).catch(()=>{});return}if(q!==null&&F===null){fetch(`/api/workspaces/${encodeURIComponent(q)}/docs/${encodeURIComponent(ne)}`,{method:"DELETE"}).catch(()=>{});return}if(q===F&&F!==null){fetch(`/api/workspaces/${encodeURIComponent(F)}/docs/${encodeURIComponent(ne)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:J??null,afterFile:$})}).catch(()=>{});return}q!==null&&F!==null&&fetch(`/api/workspaces/${encodeURIComponent(F)}/docs/${encodeURIComponent(ne)}/cross-move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:q,containerId:J??null,afterFile:$,title:ne.replace(/\.md$/,"")})}).catch(()=>{})},[e,t,n]),T=x.useCallback((z,K)=>{const F=m.current;F&&(F.style.display="none");const J=document.elementFromPoint(z,K);if(F&&(F.style.display=""),!J)return null;if((i==null?void 0:i.type)==="workspace"||(i==null?void 0:i.type)==="container"){const ee=J.closest("[data-ws-drag]");if(ee){const ue=ee.dataset.wsDrag,be=ee.getBoundingClientRect(),re=(K-be.top)/be.height;return{itemId:ue,position:re<.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 ee=J.closest("[data-ws-drag]");if(ee)return{itemId:"__section__",position:"inside",wsFilename:ee.dataset.wsDrag,containerId:null,afterId:null}}const $=J.closest("[data-drag-id]");if(!$){const ee=J.closest("[data-drop-ws]");return ee?{itemId:"__section__",position:"inside",wsFilename:ee.dataset.dropWs==="__docs__"?null:ee.dataset.dropWs,containerId:ee.dataset.dropContainer||null,afterId:null}:null}const W=$.dataset.dragId,q=$.dataset.dragType,ne=$.dataset.dragWs==="__docs__"?null:$.dataset.dragWs,V=$.getBoundingClientRect(),oe=(K-V.top)/V.height;if(q==="container-header"){const ee=W,ue=$.dataset.dragParent||null,be=w(ee,ne);if(!be)return null;const re=(i==null?void 0:i.type)==="container"?.33:.25;return oe<re?{itemId:ee,position:"before",wsFilename:ne,containerId:ue,afterId:k(be.siblings,be.index,"before")}:oe>1-re?{itemId:ee,position:"after",wsFilename:ne,containerId:ue,afterId:k(be.siblings,be.index,"after")}:{itemId:ee,position:"inside",wsFilename:ne,containerId:ee,afterId:null}}const Y=$.dataset.dragContainer||null,A=w(W,ne);if(!A)return null;const L=oe<.5?"before":"after";return{itemId:W,position:L,wsFilename:ne,containerId:Y,afterId:k(A.siblings,A.index,L)}},[w,i]),M=x.useCallback(z=>{const K=r.current;if(!K)return;const F=K.getBoundingClientRect(),J=80,$=18;let W=0;if(z<F.top+J?W=-$*Math.max(0,1-(z-F.top)/J):z>F.bottom-J&&(W=$*Math.max(0,1-(F.bottom-z)/J)),h.current&&(cancelAnimationFrame(h.current),h.current=null),W!==0){const q=()=>{K.scrollTop+=W,h.current=requestAnimationFrame(q)};h.current=requestAnimationFrame(q)}},[r]),_=x.useCallback((z,K)=>{const F=m.current;F&&(F.style.display="none");const J=document.elementFromPoint(z,K);F&&(F.style.display="");const $=J==null?void 0:J.closest("[data-section-key]");if(!$){f.current&&(clearTimeout(f.current),f.current=null);return}const W=$.dataset.sectionKey;f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{s(q=>{if(!q.has(W))return q;const ne=new Set(q);return ne.delete(W),ne})},500)},[s]);x.useEffect(()=>{if(!i)return;const z=F=>{m.current&&(m.current.style.left=`${F.clientX+12}px`,m.current.style.top=`${F.clientY-8}px`),d(T(F.clientX,F.clientY)),M(F.clientY),_(F.clientX,F.clientY)},K=F=>{N(i,T(F.clientX,F.clientY)),S()};return window.addEventListener("pointermove",z),window.addEventListener("pointerup",K),()=>{window.removeEventListener("pointermove",z),window.removeEventListener("pointerup",K)}},[i,T,N,S,M,_]);const R=x.useCallback((z,K,F)=>{if(z.button!==0||z.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:z.clientX,y:z.clientY},v.current=K;const $=q=>{if(!g.current||!v.current)return;const ne=q.clientX-g.current.x,V=q.clientY-g.current.y;if(Math.abs(ne)+Math.abs(V)>=b){document.body.style.userSelect="none",window.removeEventListener("pointermove",$),window.removeEventListener("pointerup",W),o(v.current),v.current=null;const oe=document.createElement("div");oe.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);",oe.textContent=F,document.body.appendChild(oe),m.current=oe,oe.style.left=`${q.clientX+12}px`,oe.style.top=`${q.clientY-8}px`}},W=()=>{window.removeEventListener("pointermove",$),window.removeEventListener("pointerup",W),g.current=null,v.current=null,document.body.style.userSelect=""};window.addEventListener("pointermove",$),window.addEventListener("pointerup",W)},[]);return{draggedItem:i,dropIndicator:l,handlePointerDown:R,dropClass:z=>!l||l.itemId!==z?"":l.position==="before"?"drop-before":l.position==="after"?"drop-after":l.position==="inside"?"drop-inside":"",isDragging:z=>i?i.type==="doc"?i.file===z:i.type==="workspace"?i.filename===z:i.id===z:!1,isContainerDropTarget:z=>!l||!i?!1:l.containerId===z}}function zl(t,e,n,r){var h;const s=x.useRef(e);s.current=e;const i=x.useRef(r);i.current=r;const o=x.useRef(null),l=x.useRef(null),d=x.useCallback(m=>{var v,b;const g=m||((v=s.current.find(k=>k.isActive))==null?void 0:v.filename);g&&((b=i.current)==null||b.call(i,g),l.current&&clearTimeout(l.current),l.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(),T=k.getBoundingClientRect(),M=N.top<T.top||N.bottom>T.bottom;if(S||M){const _=N.top-T.top-(T.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;x.useEffect(()=>{d(f)},[f,n,d]),x.useEffect(()=>{const m=g=>{var b,k;const v=((b=g.detail)==null?void 0:b.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]),x.useEffect(()=>()=>{l.current&&clearTimeout(l.current)},[])}const y$=[{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 b$({onPick:t}){const[e,n]=x.useState(!1),r=x.useRef(null),s=x.useRef(null),[i,o]=x.useState({});return x.useLayoutEffect(()=>{if(!e||!r.current||!s.current)return;const l=s.current.getBoundingClientRect(),d=r.current.getBoundingClientRect(),f=8;let h=l.right-4,m=l.top-4;h+d.width+f>window.innerWidth&&(h=l.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]),c.jsxs("span",{onMouseLeave:()=>n(!1),children:[c.jsx("div",{className:"context-menu-divider"}),c.jsxs("button",{ref:s,className:"context-menu-item context-menu-submenu-trigger",onMouseEnter:()=>n(!0),onClick:()=>n(l=>!l),children:[c.jsx("span",{children:"Create variant"}),c.jsx("span",{className:"context-menu-submenu-arrow",children:"▸"})]}),e&&c.jsx("div",{ref:r,className:"context-menu context-menu-submenu",style:i,children:y$.map(l=>c.jsx("button",{className:"context-menu-item",onClick:()=>t(l.key),children:c.jsx("span",{children:l.label})},l.key))})]})}function Nk({items:t,onAction:e}){const[n,r]=x.useState(null),s=x.useRef(null),i=x.useRef({}),o=x.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]),[l,d]=x.useState({});x.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 b=m.right-4,k=m.top-4;b+g.width+v>window.innerWidth&&(b=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:b,top:k})},[n]);const f=[];for(const[h,m]of o)if(h!=="_ungrouped"&&m.length>=3)f.push(c.jsxs("span",{children:[c.jsx("div",{className:"context-menu-divider"}),c.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:[c.jsx("span",{children:"Transform"}),c.jsx("span",{className:"context-menu-submenu-arrow",children:"▸"})]}),n===h&&c.jsx("div",{ref:s,className:"context-menu context-menu-submenu",style:l,onMouseLeave:()=>r(null),children:m.map(g=>c.jsx("button",{className:"context-menu-item",onClick:()=>e(g),children:c.jsx("span",{children:g.label})},g.action))})]},`sub-${h}`));else{let g=!0;for(const v of m){const b=g&&h!=="_ungrouped";g=!1,f.push(c.jsxs("span",{children:[b&&c.jsx("div",{className:"context-menu-divider"}),b&&c.jsx("div",{className:"context-menu-section-header",children:h}),c.jsx("button",{className:"context-menu-item",onClick:()=>e(v),children:c.jsx("span",{children:v.label})})]},v.action))}}return c.jsx(c.Fragment,{children:f})}function Bd({x:t,y:e,filename:n,title:r,onClose:s,onDuplicate:i,onCreateVariant:o,onRename:l,onArchive:d,onDelete:f,onPluginAction:h,pluginItems:m,onSchedulePost:g,onPostNow:v,isAlreadyPublished:b,onViewAnalytics:k,viewAnalyticsLabel:w,onMarkSent:S,isAlreadySent:N,isApproved:T,onToggleApprove:M,isAutoAccept:_,onToggleAutoAccept:R,sortState:I,sortProposalLabel:P,sortProposalReasoning:B,onRequestSort:z,onCancelSort:K,onAcceptSortProposal:F,onRejectSortProposal:J,folderMode:$,onNewDoc:W,onNewContainer:q,onAcceptAll:ne,onRejectAll:V,folderAutoAccept:oe,onToggleFolderAutoAccept:Y,folderAutoAcceptLabel:A,onRequestSortAll:L,folderDocCount:ee,onDeleteWithDocs:ue,bulkCount:be,onBulkDelete:re,onBulkRequestSort:we}){const Ee=x.useRef(null),[$e,Fe]=x.useState(!1),[Ze,Re]=x.useState(!1),[tt,gt]=x.useState({left:t,top:e});x.useLayoutEffect(()=>{const ge=Ee.current;if(!ge)return;const yt=ge.getBoundingClientRect(),Ct=8;let _t=t,Lt=e;e+yt.height+Ct>window.innerHeight&&(Lt=e-yt.height),t+yt.width+Ct>window.innerWidth&&(_t=t-yt.width),Lt<Ct&&(Lt=Ct),_t<Ct&&(_t=Ct),gt({left:_t,top:Lt})},[t,e]),x.useEffect(()=>{const ge=yt=>{Ee.current&&!Ee.current.contains(yt.target)&&s()};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[s]),x.useEffect(()=>{const ge=yt=>{yt.key==="Escape"&&s()};return document.addEventListener("keydown",ge),()=>document.removeEventListener("keydown",ge)},[s]);const ut=x.useCallback(ge=>{h(ge.action,ge),s()},[h,s]);return be&&be>1&&re?c.jsxs("div",{ref:Ee,className:"context-menu",style:{left:tt.left,top:tt.top},children:[c.jsxs("div",{className:"context-menu-section-header",children:[be," selected"]}),we&&c.jsx("button",{className:"context-menu-item",onClick:()=>{we(),s()},children:c.jsxs("span",{children:["Request sort (",be,")"]})}),$e?c.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:ge=>ge.stopPropagation(),children:[c.jsxs("span",{children:["Delete ",be,"?"]}),c.jsx("button",{onClick:()=>{re(),s()},children:"Yes"}),c.jsx("button",{onClick:()=>Fe(!1),children:"No"})]}):c.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>Fe(!0),children:c.jsxs("span",{children:["Delete (",be,")"]})})]}):$?c.jsxs("div",{ref:Ee,className:"context-menu",style:{left:tt.left,top:tt.top},children:[c.jsx("button",{className:"context-menu-item",onClick:()=>{l(),s()},children:c.jsx("span",{children:"Rename"})}),W&&c.jsx("button",{className:"context-menu-item",onClick:ge=>{W(ge),s()},children:c.jsx("span",{children:"New Document"})}),q&&c.jsx("button",{className:"context-menu-item",onClick:()=>{q(),s()},children:c.jsx("span",{children:"New Container"})}),(ne||V)&&c.jsx("div",{className:"context-menu-divider"}),ne&&c.jsx("button",{className:"context-menu-item",onClick:()=>{ne(),s()},children:c.jsx("span",{children:"Accept All Changes"})}),V&&c.jsx("button",{className:"context-menu-item",onClick:()=>{V(),s()},children:c.jsx("span",{children:"Reject All Changes"})}),Y&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"context-menu-divider"}),c.jsx("button",{className:"context-menu-item",onClick:()=>{Y(),s()},children:c.jsx("span",{children:oe?`Turn off auto-accept${A?" "+A:""}`:`Turn on auto-accept${A?" "+A:""}`})})]}),L&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"context-menu-divider"}),c.jsx("button",{className:"context-menu-item",onClick:()=>{L(),s()},children:c.jsx("span",{children:"Request sort all"})})]}),m.length>0&&c.jsx(Nk,{items:m,onAction:ut}),c.jsx("div",{className:"context-menu-divider"}),$e?ee&&ee>0&&ue?c.jsxs("div",{className:"sidebar-ctx-folder-delete",onClick:ge=>ge.stopPropagation(),children:[c.jsx("div",{className:"sidebar-ctx-folder-delete-prompt",children:"Delete this folder?"}),c.jsxs("button",{className:"context-menu-item sidebar-ctx-delete-option",onClick:()=>{f(),s()},children:[c.jsx("span",{children:"Folder only"}),c.jsxs("span",{className:"sidebar-ctx-delete-hint",children:[ee," doc",ee===1?"":"s"," → Documents"]})]}),c.jsxs("button",{className:"context-menu-item sidebar-ctx-delete-option sidebar-ctx-delete",onClick:()=>{ue(),s()},children:[c.jsxs("span",{children:["Folder + ",ee," doc",ee===1?"":"s"]}),c.jsx("span",{className:"sidebar-ctx-delete-hint",children:"permanently deletes files"})]}),c.jsx("button",{className:"context-menu-item sidebar-ctx-delete-cancel",onClick:()=>Fe(!1),children:c.jsx("span",{children:"Cancel"})})]}):c.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:ge=>ge.stopPropagation(),children:[c.jsx("span",{children:"Delete?"}),c.jsx("button",{onClick:()=>{f(),s()},children:"Yes"}),c.jsx("button",{onClick:()=>Fe(!1),children:"No"})]}):c.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>Fe(!0),children:c.jsx("span",{children:"Delete"})})]}):c.jsxs("div",{ref:Ee,className:"context-menu",style:{left:tt.left,top:tt.top},children:[c.jsx("button",{className:"context-menu-item",onClick:()=>{i(),s()},children:c.jsx("span",{children:"Duplicate"})}),o&&c.jsx(b$,{onPick:ge=>{o(ge),s()}}),c.jsx("button",{className:"context-menu-item",onClick:()=>{l(),s()},children:c.jsx("span",{children:"Rename"})}),Ze?c.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:ge=>ge.stopPropagation(),children:[c.jsx("span",{children:"Archive?"}),c.jsx("button",{onClick:()=>{d(),s()},children:"Yes"}),c.jsx("button",{onClick:()=>Re(!1),children:"No"})]}):c.jsx("button",{className:"context-menu-item",onClick:()=>Re(!0),children:c.jsx("span",{children:"Archive"})}),$e?c.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:ge=>ge.stopPropagation(),children:[c.jsx("span",{children:Fs(n)?"Remove?":"Delete?"}),c.jsx("button",{onClick:()=>{f(),s()},children:"Yes"}),c.jsx("button",{onClick:()=>Fe(!1),children:"No"})]}):c.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>Fe(!0),children:c.jsx("span",{children:Fs(n)?"Remove":"Delete"})}),M&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"context-menu-divider"}),c.jsx("button",{className:"context-menu-item",onClick:()=>{M(),s()},children:c.jsx("span",{children:T?"Remove Approval":"Approve"})})]}),R&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"context-menu-divider"}),c.jsx("button",{className:"context-menu-item",onClick:()=>{R(),s()},children:c.jsx("span",{children:_?"Turn off auto-accept":"Turn on auto-accept"})})]}),I==="proposal"&&F&&J&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"context-menu-divider"}),c.jsxs("div",{className:"sidebar-ctx-sort-proposal",onClick:ge=>ge.stopPropagation(),children:[c.jsxs("div",{className:"sidebar-ctx-sort-proposal-label",children:["Sort to ",P]}),B&&c.jsx("div",{className:"sidebar-ctx-sort-proposal-reason",children:B}),c.jsxs("div",{className:"sidebar-ctx-sort-proposal-actions",children:[c.jsx("button",{onClick:()=>{F(),s()},children:"Accept"}),c.jsx("button",{onClick:()=>{J(),s()},children:"Reject"})]})]})]}),I==="pending"&&K&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"context-menu-divider"}),c.jsxs("div",{className:"sidebar-ctx-sort-pending",onClick:ge=>ge.stopPropagation(),children:[c.jsx("span",{className:"sidebar-ctx-sort-pending-label",children:"Sort requested"}),c.jsx("button",{onClick:()=>{K(),s()},children:"Cancel"})]})]}),I==="none"&&z&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"context-menu-divider"}),c.jsx("button",{className:"context-menu-item",onClick:()=>{z(),s()},children:c.jsx("span",{children:"Request sort"})})]}),g&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"context-menu-divider"}),c.jsx("button",{className:"context-menu-item",onClick:()=>{g(),s()},children:c.jsx("span",{children:"Schedule Post"})})]}),v&&c.jsx("button",{className:"context-menu-item",onClick:()=>{v(),s()},children:c.jsx("span",{children:b?"Republish to Blog":"Post to Blog Now"})}),S&&!N&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"context-menu-divider"}),c.jsx("button",{className:"context-menu-item",onClick:()=>{S(),s()},children:c.jsx("span",{children:"Mark as Sent"})})]}),k&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"context-menu-divider"}),c.jsx("button",{className:"context-menu-item",onClick:()=>{k(),s()},children:c.jsx("span",{children:w||"View Analytics"})})]}),m.length>0&&c.jsx(Nk,{items:m,onAction:ut})]})}const Ck=5e3;function AT(t,e){return!t.promptForFocus||!e?!1:e.wordCount>Ck?(_i(`Document too large to transform: ${e.wordCount.toLocaleString()} words (max ${Ck.toLocaleString()}). Trim it down first.`,"error"),!0):!1}function RT({actionLabel:t,docTitle:e,onConfirm:n,onClose:r}){const[s,i]=x.useState(""),o=x.useRef(null);x.useEffect(()=>{var d;(d=o.current)==null||d.focus()},[]),x.useEffect(()=>{const d=f=>{f.key==="Escape"&&r()};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const l=x.useCallback(()=>{n(s.trim())},[s,n]);return c.jsx("div",{className:"focus-modal-overlay",onClick:r,children:c.jsxs("div",{className:"focus-modal",onClick:d=>d.stopPropagation(),children:[c.jsxs("div",{className:"focus-modal-header",children:[c.jsx("h2",{children:t}),c.jsx("button",{className:"focus-modal-close",onClick:r,children:"×"})]}),c.jsxs("div",{className:"focus-modal-body",children:[c.jsxs("label",{children:['Focus instructions for "',e,'"',c.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)&&l()}})]}),c.jsxs("div",{className:"focus-modal-hint",children:[s.length,"/500"]}),c.jsxs("div",{className:"focus-modal-actions",children:[c.jsx("button",{className:"focus-modal-btn secondary",onClick:r,children:"Cancel"}),c.jsx("button",{className:"focus-modal-btn primary",onClick:l,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(c.jsx("mark",{children:t.slice(o,o+e.length)},o)),i=o+e.length}return n}function _k({r:t,query:e,onClick:n}){return c.jsxs("div",{className:`sidebar-item search-result-item ${t.isActive?"active":""} ${t.isArchived?"search-result-archived":""}`,onClick:n,children:[c.jsxs("div",{className:"sidebar-item-title",children:[c.jsx("span",{className:"sidebar-item-title-text",children:t.matchType==="title"?Ip(t.title,e):t.title}),t.isArchived&&c.jsx("span",{className:"search-archived-badge",children:"archived"})]}),t.matchType==="tag"&&t.matchedTag&&c.jsxs("div",{className:"search-result-tag",children:["Tag: ",Ip(t.matchedTag,e)]}),t.matchType==="content"&&t.snippet&&c.jsx("div",{className:"search-result-snippet",children:Ip(t.snippet,e)}),c.jsxs("div",{className:"sidebar-item-meta",children:[t.wordCount.toLocaleString()," words · ",pa(t.lastModified)]})]})}function rf({results:t,query:e,onSwitchDocument:n,actions:r}){if(t.length===0)return c.jsx("div",{className:"sidebar-scroll",children:c.jsxs("div",{className:"search-empty",children:['No results for "',e,'"']})});const s=t.filter(o=>!o.isArchived),i=t.filter(o=>o.isArchived);return c.jsx("div",{className:"sidebar-scroll",children:c.jsxs("div",{className:"search-results",children:[s.map(o=>c.jsx(_k,{r:o,query:e,onClick:()=>n(o.filename)},o.filename)),i.length>0&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"search-archived-divider",children:c.jsx("span",{children:"Archived"})}),i.map(o=>c.jsx(_k,{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 Tk(t){return new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function jk(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 OT({docId:t,title:e,onClose:n}){const[r,s]=x.useState("loading"),[i,o]=x.useState([]),[l,d]=x.useState(""),[f,h]=x.useState(null),[m,g]=x.useState(null),[v,b]=x.useState("links"),[k,w]=x.useState("all"),[S,N]=x.useState(!1),[T,M]=x.useState(!1),[_,R]=x.useState(""),[I,P]=x.useState(!1),[B,z]=x.useState(null),K=x.useRef(null);x.useEffect(()=>{let re=!1;return(async()=>{try{const we=await Lp("list_newsletter_issues",{limit:20});if(re)return;if(!we.issues||we.issues.length===0){s("no-data");return}o(we.issues);const Ee=we.issues[0].id;d(Ee)}catch(we){re||(g(we.message),s("error"))}})(),()=>{re=!0}},[]),x.useEffect(()=>{if(!l)return;let re=!1;return N(!0),M(!1),z(null),R(""),(async()=>{try{const we=await Lp("get_newsletter_analytics",{issue_id:l});if(re)return;if(we.error){g(we.error),s("error");return}h(we),s("loaded")}catch(we){re||(g(we.message),s("error"))}finally{re||N(!1)}})(),()=>{re=!0}},[l]),x.useEffect(()=>{const re=we=>{K.current&&!K.current.contains(we.target)&&n()};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[n]),x.useEffect(()=>{const re=we=>{we.key==="Escape"&&n()};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[n]);const F=f?w$(f.subscriber_events):[],J=(f==null?void 0:f.issue.recipient_count)??0,$=f?f.stats.delivered||J-f.stats.bounces:0,W=f?new Set(f.subscriber_events.filter(re=>{var we;return re.event_type==="click"&&((we=re.url)==null?void 0:we.includes("/newsletter/unsubscribe/"))}).map(re=>re.email)).size:0,q=f?f.stats.unsubscribes||W:0,ne=f?f.subscriber_events.filter(re=>re.event_type==="dropped").length:0,V=f?Math.max(0,J-f.stats.unique_opens):0,oe=f!=null&&f.issue.sent_at?Date.now()-new Date(f.issue.sent_at).getTime():0,Y=Math.floor(oe/36e5),A=!!(f!=null&&f.issue.resent_at||B),L=re=>{const we=Math.floor(re/36e5);return we<1?"just now":we<24?`${we}h ago`:`${Math.floor(we/24)}d ${we%24}h ago`},ee=async()=>{if(!(!_.trim()||I)){P(!0);try{const re=await Lp("resend_to_unopened",{issue_id:l,subject:_});re.error?(g(re.error),s("error")):(z({sent:re.sent,failed:re.failed}),M(!1))}catch(re){g(re.message),s("error")}finally{P(!1)}}},ue=re=>{var we;return re.event_type==="unsubscribe"||re.event_type==="click"&&!!((we=re.url)!=null&&we.includes("/newsletter/unsubscribe/"))},be=f?x$(f.subscriber_events.filter(re=>k==="all"?!0:k==="unsubscribe"?ue(re):re.event_type===k)):[];return c.jsx("div",{className:"newsletter-modal-overlay",children:c.jsxs("div",{className:"na-modal",ref:K,children:[c.jsxs("div",{className:"na-header",children:[c.jsx("h3",{children:"Newsletter Analytics"}),c.jsx("button",{className:"newsletter-modal__close",onClick:n,children:"×"})]}),r==="loading"&&!f&&c.jsx("div",{className:"na-body",children:c.jsxs("div",{className:"newsletter-modal__status",children:[c.jsx("div",{className:"newsletter-modal__spinner"}),c.jsx("span",{children:"Loading analytics..."})]})}),r==="no-data"&&c.jsxs("div",{className:"na-body",children:[c.jsx("div",{className:"newsletter-modal__status",children:c.jsx("span",{children:"No newsletter sends found yet."})}),c.jsx("div",{className:"newsletter-modal__actions",children:c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:n,children:"Done"})})]}),r==="error"&&c.jsxs("div",{className:"na-body",children:[c.jsx("div",{className:"newsletter-modal__error",children:m}),c.jsx("div",{className:"newsletter-modal__actions",children:c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:n,children:"Done"})})]}),r==="loaded"&&f&&c.jsxs("div",{className:"na-body",children:[i.length>1&&c.jsx("select",{className:"newsletter-modal__select na-issue-select",value:l,onChange:re=>d(re.target.value),children:i.map(re=>c.jsxs("option",{value:re.id,children:[re.subject," — ",Tk(re.sent_at)]},re.id))}),S?c.jsxs("div",{className:"newsletter-modal__status",children:[c.jsx("div",{className:"newsletter-modal__spinner"}),c.jsx("span",{children:"Loading..."})]}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"na-kpi-row",children:[c.jsxs("div",{className:"na-kpi",children:[c.jsx("div",{className:"na-kpi__value",children:$.toLocaleString()}),c.jsx("div",{className:"na-kpi__label",children:"Delivered"}),c.jsxs("div",{className:"na-kpi__sub",children:[J.toLocaleString()," sent"]})]}),c.jsxs("div",{className:"na-kpi",children:[c.jsx("div",{className:"na-kpi__value",children:Dp(f.stats.unique_opens,$)}),c.jsx("div",{className:"na-kpi__label",children:"Open rate"}),c.jsxs("div",{className:"na-kpi__sub",children:[f.stats.unique_opens.toLocaleString()," opens"]})]}),c.jsxs("div",{className:"na-kpi",children:[c.jsx("div",{className:"na-kpi__value",children:Dp(f.stats.unique_clicks,$)}),c.jsx("div",{className:"na-kpi__label",children:"Click rate"}),c.jsxs("div",{className:"na-kpi__sub",children:[f.stats.unique_clicks.toLocaleString()," clicks"]})]})]}),c.jsxs("div",{className:"na-kpi-row na-kpi-row--secondary",children:[c.jsxs("div",{className:"na-kpi na-kpi--sm",children:[c.jsx("span",{className:"na-kpi__value--sm",children:f.stats.bounces}),c.jsx("span",{className:"na-kpi__label--sm",children:"Bounces"})]}),c.jsxs("div",{className:"na-kpi na-kpi--sm",children:[c.jsx("span",{className:"na-kpi__value--sm",children:q}),c.jsx("span",{className:"na-kpi__label--sm",children:"Unsubs"})]}),c.jsxs("div",{className:"na-kpi na-kpi--sm",children:[c.jsx("span",{className:"na-kpi__value--sm",children:ne}),c.jsx("span",{className:"na-kpi__label--sm",children:"Dropped"})]}),f.stats.complaints>0&&c.jsxs("div",{className:"na-kpi na-kpi--sm",children:[c.jsx("span",{className:"na-kpi__value--sm",children:f.stats.complaints}),c.jsx("span",{className:"na-kpi__label--sm",children:"Spam"})]})]}),V>0&&!A&&c.jsx("div",{className:"na-resend",children:T?c.jsxs("div",{className:"na-resend-panel",children:[c.jsxs("div",{className:"na-resend-label-row",children:[c.jsx("span",{className:"na-resend-label",children:"New subject line"}),c.jsxs("span",{className:"na-resend-meta",children:["sent ",L(oe),Y<48?" · consider waiting 48h":""]})]}),c.jsx("input",{className:"na-resend-input",type:"text",value:_,onChange:re=>R(re.target.value),placeholder:"Try a different angle"}),c.jsxs("div",{className:"na-resend-actions",children:[c.jsx("button",{className:"na-resend-cancel",onClick:()=>M(!1),children:"Cancel"}),c.jsx("button",{className:"na-resend-send",onClick:ee,disabled:I||!_.trim(),children:I?"Sending...":`Send to ${V.toLocaleString()}`})]})]}):c.jsxs("button",{className:"na-resend-toggle",onClick:()=>{M(!0),R(f.issue.subject)},children:["Resend to ",V.toLocaleString()," non-openers ",c.jsx("span",{style:{float:"right"},children:"›"})]})}),A&&c.jsxs("div",{className:"na-resend-done",children:["Resent ",f.issue.resent_at?L(Date.now()-new Date(f.issue.resent_at).getTime()):"just now",B?` — ${B.sent} sent`:"",f.issue.resend_subject?` — "${f.issue.resend_subject}"`:""]}),c.jsxs("div",{className:"na-tabs",children:[c.jsxs("button",{className:`na-tab${v==="links"?" active":""}`,onClick:()=>b("links"),children:["Links (",F.length,")"]}),c.jsxs("button",{className:`na-tab${v==="activity"?" active":""}`,onClick:()=>b("activity"),children:["Activity (",f.subscriber_events.length,")"]})]}),v==="links"&&c.jsx("div",{className:"na-table-wrap",children:F.length===0?c.jsx("div",{className:"na-empty",children:"No link clicks recorded yet."}):c.jsxs("table",{className:"na-table",children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Link"}),c.jsx("th",{children:"Unique"}),c.jsx("th",{children:"Total"}),c.jsx("th",{children:"CTR"})]})}),c.jsx("tbody",{children:F.map(re=>c.jsxs("tr",{children:[c.jsx("td",{className:"na-table__url",title:re.url,children:c.jsx("a",{href:re.url,target:"_blank",rel:"noopener noreferrer",children:jk(re.url)})}),c.jsx("td",{children:re.uniqueClicks}),c.jsx("td",{children:re.totalClicks}),c.jsx("td",{children:Dp(re.uniqueClicks,$)})]},re.url))})]})}),v==="activity"&&c.jsxs("div",{className:"na-activity",children:[c.jsx("div",{className:"na-filter-row",children:["all","open","click","bounce","dropped","unsubscribe"].map(re=>c.jsx("button",{className:`na-filter-btn${k===re?" active":""}`,onClick:()=>w(re),children:re==="all"?"All":re.charAt(0).toUpperCase()+re.slice(1)+"s"},re))}),c.jsxs("div",{className:"na-table-wrap",children:[be.length===0?c.jsxs("div",{className:"na-empty",children:["No ",k==="all"?"":k+" ","events recorded."]}):c.jsxs("table",{className:"na-table",children:[c.jsx("thead",{children:c.jsxs("tr",{children:[c.jsx("th",{children:"Email"}),c.jsx("th",{children:"Event"}),c.jsx("th",{children:"Detail"}),c.jsx("th",{children:"Time"})]})}),c.jsx("tbody",{children:be.slice(0,100).map(re=>c.jsxs("tr",{children:[c.jsx("td",{className:"na-table__email",children:re.email}),c.jsxs("td",{children:[c.jsx("span",{className:`na-badge na-badge--${re.event_type}`,children:re.event_type}),re.count>1&&c.jsxs("span",{className:"na-count",children:[re.count,"x"]})]}),c.jsx("td",{className:"na-table__url",children:re.url?c.jsx("a",{href:re.url,target:"_blank",rel:"noopener noreferrer",children:jk(re.url,35)}):"—"}),c.jsx("td",{className:"na-table__time",children:Tk(re.latestTimestamp)})]},re.key))})]}),be.length>100&&c.jsxs("div",{className:"na-truncated",children:["Showing 100 of ",be.length," events"]})]})]})]})]})]})})}function x$(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 w$(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 k$(t){return t.tweetContext?"tweet":t.articleContext?"article":t.linkedinContext?"linkedin":t.newsletterContext?"newsletter":t.blogContext?"blog":"tweet"}function Ul({filename:t,title:e,onClose:n}){const[r,s]=x.useState("queue"),[i,o]=x.useState(null),[l,d]=x.useState(null),[f,h]=x.useState(""),[m,g]=x.useState(!1),[v,b]=x.useState(null),[k,w]=x.useState(null);x.useEffect(()=>{fetch(`/api/documents/${encodeURIComponent(t)}/text`).then(T=>{if(!T.ok)throw new Error("Failed to load document");return T.json()}).then(T=>{d(T.text||""),o(k$(T.meta||{}))}).catch(T=>w(T.message))},[t]);const S=async()=>{var T;if(!(!l||!i)){g(!0);try{const M={content:l,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 I=(T=R.item)!=null&&T.scheduled_at?new Date(R.item.scheduled_at).toLocaleString():"now";b({success:!0,message:`Scheduled for ${I}`})}else b({success:!1,message:R.error||"Failed to schedule"})}catch(M){b({success:!1,message:M.message})}finally{g(!1)}}},N=i===null&&!k;return c.jsx("div",{className:"schedule-post-overlay",onClick:n,children:c.jsxs("div",{className:"schedule-post-modal",onClick:T=>T.stopPropagation(),children:[c.jsxs("div",{className:"schedule-post-modal-header",children:[c.jsx("h3",{children:"Schedule Post"}),c.jsx("button",{className:"schedule-post-modal-close",onClick:n,children:"×"})]}),c.jsx("div",{className:"schedule-post-modal-doc",children:e}),k?c.jsxs("div",{className:"schedule-post-modal-result error",children:[k,c.jsx("button",{className:"schedule-post-modal-done",onClick:n,children:"Done"})]}):v?c.jsxs("div",{className:`schedule-post-modal-result ${v.success?"success":"error"}`,children:[v.message,c.jsx("button",{className:"schedule-post-modal-done",onClick:n,children:"Done"})]}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"schedule-post-modal-field",children:[c.jsx("label",{children:"Content Type"}),c.jsx("div",{className:"schedule-post-modal-type",children:N?"...":i})]}),c.jsxs("div",{className:"schedule-post-modal-field",children:[c.jsx("label",{children:"Mode"}),c.jsxs("div",{className:"schedule-post-modal-modes",children:[c.jsx("button",{className:`schedule-post-mode ${r==="queue"?"active":""}`,onClick:()=>s("queue"),children:"Queue Next"}),c.jsx("button",{className:`schedule-post-mode ${r==="now"?"active":""}`,onClick:()=>s("now"),children:"Post Now"}),c.jsx("button",{className:`schedule-post-mode ${r==="custom"?"active":""}`,onClick:()=>s("custom"),children:"Custom Time"})]})]}),r==="custom"&&c.jsxs("div",{className:"schedule-post-modal-field",children:[c.jsx("label",{children:"Date & Time"}),c.jsx("input",{type:"datetime-local",value:f,onChange:T=>h(T.target.value)})]}),c.jsxs("div",{className:"schedule-post-modal-actions",children:[c.jsx("button",{className:"schedule-post-modal-cancel",onClick:n,children:"Cancel"}),c.jsx("button",{className:"schedule-post-modal-submit",onClick:S,disabled:m||N||r==="custom"&&!f,children:m?"Scheduling...":r==="now"?"Post Now":"Schedule"})]})]})]})})}const Mk=[{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}}}];function IT({anchorRect:t,onSelect:e,onClose:n}){const r=x.useRef(null),[s,i]=x.useState(null),[o,l]=x.useState(""),d=x.useRef(null),[f,h]=x.useState({left:t.left,top:t.bottom+4});x.useLayoutEffect(()=>{const b=r.current;if(!b)return;const k=b.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]),x.useEffect(()=>{const b=k=>{r.current&&!r.current.contains(k.target)&&n()};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[n]),x.useEffect(()=>{const b=k=>{k.key==="Escape"&&n()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[n]),x.useEffect(()=>{s&&setTimeout(()=>{var b;return(b=d.current)==null?void 0:b.focus()},0)},[s]);const m=b=>{if(b.needsUrl){i(b.key),l("");return}e(b.metadata)},g=()=>{if(!s||!o.trim())return;const b=o.trim();if(!b.includes("x.com")&&!b.includes("twitter.com"))return;const k=Mk.find(S=>S.key===s);if(!(k!=null&&k.metadata))return;const w=JSON.parse(JSON.stringify(k.metadata));w.tweetContext&&(w.tweetContext.url=b),e(w)},v=o.trim().includes("x.com")||o.trim().includes("twitter.com");return c.jsx("div",{ref:r,className:"create-doc-dropdown",style:{left:f.left,top:f.top},children:Mk.map(b=>c.jsxs("div",{children:[c.jsx("button",{className:`create-doc-dropdown-item${s===b.key?" active":""}`,onClick:()=>m(b),children:b.label}),s===b.key&&c.jsxs("div",{className:"create-doc-dropdown-url",children:[c.jsx("input",{ref:d,type:"text",placeholder:b.urlPlaceholder,value:o,onChange:k=>l(k.target.value),onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),g()),k.key==="Escape"&&(i(null),l(""))}}),c.jsx("button",{onClick:g,disabled:!v,children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})})]})]},b.key))})}const S$=[{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 E$({docs:t,archivedDocs:e,workspaces:n,assignedFiles:r,pendingDocs:s,onSwitchDocument:i,onCreateDocument:o,actions:l,scrollRef:d,writingTitle:f,writingTarget:h,pendingWriteFilenames:m,searchQuery:g,searchResults:v,onSearchChange:b}){const k=D=>!!m&&m.has(D),[w,S]=x.useState(null),[N,T]=x.useState(""),[M,_]=x.useState(null),[R,I]=x.useState(()=>{try{const D=localStorage.getItem("ow-collapsed-sections");return D?new Set(JSON.parse(D)):new Set}catch{return new Set}}),[P,B]=x.useState(null),[z,K]=x.useState(null),[F,J]=x.useState(""),[$,W]=x.useState(null),[q,ne]=x.useState(""),[V,oe]=x.useState(null),[Y,A]=x.useState(""),[L,ee]=x.useState(null),[ue,be]=x.useState(null),[re,we]=x.useState([]),[Ee,$e]=x.useState(!1),[Fe,Ze]=x.useState(null),[Re,tt]=x.useState(null),[gt,ut]=x.useState(null),[ge,yt]=x.useState(null),[Ct,_t]=x.useState(null),[Lt,at]=x.useState(RE),De=x.useRef(null);x.useEffect(()=>{if(!Ct)return;const D=le=>{De.current&&!De.current.contains(le.target)&&_t(null)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[Ct]);const ve=D=>{at(D),CM(D),_t(null)},Z=D=>{D.preventDefault(),_t({x:D.clientX,y:D.clientY})},je=x.useCallback((D,le)=>{fetch("/api/documents/batch-resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filenames:D,action:le})}).catch(()=>{})},[]),{draggedItem:Q,dropIndicator:he,handlePointerDown:me,dropClass:Ue,isDragging:Oe,isContainerDropTarget:Ve}=MT({docs:t,workspaces:n,assignedFiles:r,scrollRef:d,setCollapsedSections:I}),et=x.useCallback(()=>{fetch("/api/plugins").then(D=>D.json()).then(D=>{const le=[];let fe=!1;for(const se of D.plugins||[]){const pe=se.displayName||void 0;for(const ye of se.sidebarMenuItems||[])le.push({...ye,pluginDisplayName:pe});se.name==="@openwriter/plugin-publish"&&se.enabled&&(fe=!0)}we(le),$e(fe)}).catch(()=>{})},[]);x.useEffect(()=>{et()},[et]),x.useEffect(()=>{const D=()=>et();return window.addEventListener("ow-plugins-changed",D),()=>window.removeEventListener("ow-plugins-changed",D)},[et]);const{variantsByMaster:ft,variantFilenames:We}=x.useMemo(()=>{const D=new Map,le=new Set;for(const fe of t)if(fe.masterDocId){const se=D.get(fe.masterDocId)||[];se.push(fe),D.set(fe.masterDocId,se),le.add(fe.filename)}return{variantsByMaster:D,variantFilenames:le}},[t]),Ge=x.useCallback((D,le)=>{D.preventDefault(),D.stopPropagation(),ee({x:D.clientX,y:D.clientY,filename:le.filename,title:le.title,docId:le.docId,lastSent:le.lastSent,postedUrl:le.postedUrl,isNewsletter:le.isNewsletter})},[]),vt=x.useCallback(D=>{fetch("/api/documents/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:D})}).catch(()=>{})},[]),Et=x.useCallback((D,le,fe)=>{fetch("/api/documents/variant",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:D,masterDocId:le,variantType:fe})}).catch(()=>{})},[]),_e=x.useCallback((D,le,fe,se,pe)=>{if(!AT(le,t.find(ye=>ye.filename===fe))){if(le.promptForFocus&&pe===void 0){Ze({action:D,label:le.label,filename:fe,title:se});return}fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:D,filename:fe,title:se,instructions:pe||"",label:le.label})}).catch(()=>{})}},[t]),Ne=D=>{I(le=>{const fe=new Set(le);return fe.has(D)?fe.delete(D):fe.add(D),localStorage.setItem("ow-collapsed-sections",JSON.stringify([...fe])),fe})},Ke=x.useRef(n);Ke.current=n;const st=x.useCallback(D=>{var le;for(const fe of Ke.current){const se=ev(((le=fe.workspace)==null?void 0:le.root)||[],D);if(se){I(pe=>{const ye=[fe.filename,...se.map(Se=>`container-${Se}`)];if(ye.every(Se=>!pe.has(Se)))return pe;const Pe=new Set(pe);for(const Se of ye)Pe.delete(Se);return localStorage.setItem("ow-collapsed-sections",JSON.stringify([...Pe])),Pe});break}}},[]);zl(d,t,n.length,st);const Ye=x.useMemo(()=>{var se;const D=t.find(pe=>pe.isActive);if(!D)return null;const le=D.masterDocId?t.find(pe=>pe.docId===D.masterDocId):void 0,fe=(le==null?void 0:le.filename)??D.filename;for(const pe of n){const ye=ev(((se=pe.workspace)==null?void 0:se.root)||[],fe);if(ye)return{wsFilename:pe.filename,containerKeys:new Set(ye.map(Pe=>`container-${Pe}`)),masterDocId:(le==null?void 0:le.docId)??null}}return{wsFilename:null,containerKeys:new Set,masterDocId:(le==null?void 0:le.docId)??null}},[t,n]);if(v!==null)return c.jsx(rf,{results:v,query:g,onSwitchDocument:i,actions:l});const jt=t.filter(D=>!r.has(D.filename)&&!We.has(D.filename)),j=(D,le,fe,se,pe,ye=!1)=>c.jsxs("div",{className:`sidebar-item ${D.isActive?"active":""} ${Oe(D.filename)?"dragging":""} ${Ue(D.filename)}`,"data-drag-id":D.filename,"data-drag-type":"doc","data-drag-ws":le||"__docs__","data-drag-container":fe||"",onPointerDown:Pe=>me(Pe,{type:"doc",file:D.filename,sourceWs:le||null},D.title),onClick:()=>!D.isActive&&!Q&&i(D.filename),onDoubleClick:()=>{S(D.filename),T(D.title)},onContextMenu:Pe=>Ge(Pe,D),children:[w===D.filename?c.jsx("input",{className:"sidebar-rename-input",value:N,onChange:Pe=>T(Pe.target.value),onBlur:()=>{l.handleRename(D.filename,D.title,N),S(null)},onKeyDown:Pe=>{Pe.key==="Enter"&&(l.handleRename(D.filename,D.title,N),S(null)),Pe.key==="Escape"&&S(null)},autoFocus:!0,onClick:Pe=>Pe.stopPropagation()}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"sidebar-item-title",children:[c.jsx("span",{className:"sidebar-item-title-text",children:D.title}),D.variantType&&c.jsx("span",{className:"files-badge-variant",children:D.variantType}),l.getDocTags(D.filename).includes("✓")&&c.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:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),D.lastSent&&c.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:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),(D.autoAccept===!0||D.autoAccept!==!1&&ye)&&c.jsx("span",{className:"sidebar-auto-accept-dot",title:D.autoAccept===!0?"Auto-accept on":"Auto-accept inherited"}),s.filenames.includes(D.filename)&&c.jsx("span",{className:"sidebar-pending-dot"})]}),Fs(D.filename)&&c.jsx("div",{className:"sidebar-item-context",children:TT(D.filename)}),c.jsxs("div",{className:"sidebar-item-meta",children:[D.wordCount.toLocaleString()," words · ",pa(D.lastModified)]}),c.jsxs("div",{className:"sidebar-tags",children:[l.getDocTags(D.filename).filter(Pe=>Pe!=="✓").map(Pe=>c.jsxs("span",{className:"sidebar-tag",onClick:Se=>Se.stopPropagation(),children:[Pe,c.jsx("span",{className:"sidebar-tag-remove",onClick:Se=>{Se.stopPropagation(),l.handleRemoveTag(D.filename,Pe)},children:"×"})]},Pe)),V===D.filename?c.jsx("input",{className:"sidebar-tag-input",value:Y,onChange:Pe=>A(Pe.target.value),onBlur:()=>{Y.trim()&&l.handleAddTag(D.filename,Y),oe(null)},onKeyDown:Pe=>{Pe.key==="Enter"&&(l.handleAddTag(D.filename,Y),oe(null),A("")),Pe.key==="Escape"&&(oe(null),A(""))},autoFocus:!0,onClick:Pe=>Pe.stopPropagation(),placeholder:"tag..."}):c.jsx("button",{className:"sidebar-tag-add",onClick:Pe=>{Pe.stopPropagation(),oe(D.filename),A("")},children:"+"})]})]}),M===D.filename?c.jsxs("div",{className:"sidebar-confirm-delete",onClick:Pe=>Pe.stopPropagation(),children:[c.jsx("span",{children:Fs(D.filename)?"Remove?":"Delete?"}),c.jsx("button",{onClick:()=>{l.handleDelete(D.filename),_(null)},children:"Yes"}),c.jsx("button",{onClick:()=>_(null),children:"No"})]}):c.jsx("button",{className:"sidebar-delete-btn",onClick:Pe=>{Pe.stopPropagation(),_(D.filename)},title:Fs(D.filename)?"Remove document":"Delete document",children:"×"})]},D.filename),U=(D,le,fe,se,pe,ye=!1)=>{const Pe=D.docId?ft.get(D.docId):void 0,Se=f&&(h==null?void 0:h.parentDocId)&&h.parentDocId===D.docId;if(!(Pe&&Pe.length>0||Se))return j(D,le,fe,se,pe,ye);const It=`variants-${D.docId}`,Sn=!R.has(It);return c.jsxs("div",{className:"sidebar-variant-group",children:[c.jsxs("div",{className:`sidebar-variant-master${!Sn&&(Ye==null?void 0:Ye.masterDocId)===D.docId?" active-within":""}`,onClick:yn=>{yn.target.closest(".sidebar-variant-chevron")&&(yn.stopPropagation(),Ne(It))},children:[j(D,le,fe,se,pe,ye),c.jsx("span",{className:`sidebar-variant-chevron${Sn?"":" collapsed"}`,children:c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})})]}),Sn&&c.jsxs("div",{className:"sidebar-variant-children",children:[Pe==null?void 0:Pe.map((yn,En)=>j(yn,le,fe,se,En,ye)),Se&&c.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[c.jsxs("div",{className:"sidebar-item-title",children:[c.jsx("span",{className:"sidebar-writing-spinner"}),c.jsx("span",{className:"sidebar-item-title-text",children:f})]}),c.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]})]})]},`vg-${D.filename}`)},ie=(D,le,fe,se,pe,ye,Pe=!1)=>{if(D.type==="doc"){const qe=t.find(Nt=>Nt.filename===D.file);return qe?We.has(qe.filename)?c.jsx(c.Fragment,{}):U(qe,fe,se,pe,ye,Pe):Fs(D.file)?c.jsx("div",{className:"sidebar-item sidebar-unavailable",children:c.jsxs("div",{className:"sidebar-item-title",children:[D.title||D.file," (unavailable)"]})},D.file):c.jsxs("div",{className:"sidebar-item sidebar-missing",children:[c.jsxs("div",{className:"sidebar-item-title",children:[D.title||D.file," (missing)"]}),c.jsx("button",{className:"sidebar-delete-btn",onClick:()=>l.handleRemoveFromWorkspace(fe,D.file),title:"Remove",children:"×"})]},D.file)}const Se=D,Vt=`container-${Se.id}`,It=R.has(Vt),Sn=le<=2?`depth-${le}`:"depth-2",yn=Se.autoAccept===!0,En=yn||Pe;return c.jsxs("div",{className:`sidebar-container ${Sn} ${It?"collapsed":""} ${Ue(Se.id)} ${Ve(Se.id)?"drop-inside":""}`,children:[c.jsxs("div",{className:`sidebar-container-header${It&&(Ye!=null&&Ye.containerKeys.has(Vt))?" active-within":""} ${(he==null?void 0:he.itemId)===Se.id&&he.position==="inside"?"drop-inside":""}`,"data-drag-id":Se.id,"data-drag-type":"container-header","data-drag-ws":fe,"data-drag-parent":se||"","data-section-key":Vt,onPointerDown:qe=>me(qe,{type:"container",id:Se.id,sourceWs:fe},Se.name),onClick:()=>!Q&&Ne(Vt),onContextMenu:qe=>{qe.preventDefault(),qe.stopPropagation(),yt({x:qe.clientX,y:qe.clientY,type:"container",wsFilename:fe,containerId:Se.id,title:Se.name,nodes:Se.items,autoAccept:yn})},children:[c.jsx("span",{className:`sidebar-chevron ${It?"collapsed":""}`,children:"▾"}),z===Se.id?c.jsx("input",{className:"sidebar-rename-input",value:F,onChange:qe=>J(qe.target.value),onBlur:()=>{l.handleRenameContainer(fe,Se.id,F),K(null)},onKeyDown:qe=>{qe.key==="Enter"&&(l.handleRenameContainer(fe,Se.id,F),K(null)),qe.key==="Escape"&&K(null)},autoFocus:!0,onClick:qe=>qe.stopPropagation()}):c.jsx("span",{className:"sidebar-container-name",onDoubleClick:qe=>{qe.stopPropagation(),K(Se.id),J(Se.name)},children:Se.name}),En&&c.jsx("span",{className:"sidebar-auto-accept-dot",title:yn?"Auto-accept on for this container":"Auto-accept inherited from workspace"}),c.jsxs("div",{className:"sidebar-container-actions",children:[c.jsx("button",{className:"sidebar-new-btn",onClick:qe=>{qe.stopPropagation(),ut({anchor:qe.target.getBoundingClientRect(),wsFilename:fe,containerId:Se.id})},title:"New doc",children:"+"}),le<2&&c.jsx("button",{className:"sidebar-new-btn",onClick:qe=>{qe.stopPropagation(),l.handleCreateContainer(fe,Se.id)},title:"New sub-container",children:"☐"}),c.jsx("button",{className:"sidebar-new-btn sidebar-container-delete",onClick:qe=>{qe.stopPropagation(),l.handleDeleteContainer(fe,Se.id)},title:"Delete container",children:"×"})]})]}),!It&&c.jsxs("div",{className:"sidebar-container-list","data-drop-ws":fe,"data-drop-container":Se.id,children:[f&&!(h!=null&&h.parentDocId)&&(h==null?void 0:h.wsFilename)===fe&&h.containerId===Se.id&&c.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[c.jsxs("div",{className:"sidebar-item-title",children:[c.jsx("span",{className:"sidebar-writing-spinner"}),c.jsx("span",{className:"sidebar-item-title-text",children:f})]}),c.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),Se.items.filter(qe=>qe.type!=="doc"?!0:!(k(qe.file)||f&&(h==null?void 0:h.wsFilename)===fe&&h.containerId===Se.id&&qe.title===f)).map((qe,Nt)=>ie(qe,le+1,fe,Se.id,Se.items,Nt,En)),Se.items.length===0&&!f&&c.jsx("div",{className:"sidebar-empty",children:Q?"Drop here":"Empty"})]})]},Se.id)};return c.jsxs("div",{className:"sidebar-scroll",ref:d,children:[c.jsxs("div",{className:`sidebar-section sidebar-docs-section ${R.has("docs")?"docs-collapsed":""}`,children:[c.jsxs("div",{className:`sidebar-section-header${R.has("docs")&&Ye!==null&&Ye.wsFilename===null?" active-within":""}`,"data-section-key":"docs",onClick:()=>Ne("docs"),onContextMenu:Z,children:[c.jsx("span",{className:`sidebar-chevron ${R.has("docs")?"collapsed":""}`,children:"▾"}),c.jsx("span",{className:"sidebar-label",children:"Documents"}),c.jsx("button",{className:"sidebar-new-btn",onClick:D=>{D.stopPropagation(),ut({anchor:D.target.getBoundingClientRect()})},title:"New document",children:"+"})]}),!R.has("docs")&&c.jsxs("div",{className:"sidebar-section-list","data-drop-ws":"__docs__",children:[f&&!(h!=null&&h.parentDocId)&&(!h||!n.some(D=>D.filename===(h==null?void 0:h.wsFilename)))&&c.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[c.jsxs("div",{className:"sidebar-item-title",children:[c.jsx("span",{className:"sidebar-writing-spinner"}),c.jsx("span",{className:"sidebar-item-title-text",children:f})]}),c.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),jt.filter(D=>!k(D.filename)&&(!f||D.title!==f)).map((D,le)=>{const fe=jt.map(se=>({type:"doc",file:se.filename,title:se.title}));return U(D,void 0,null,fe,le)}),jt.length===0&&c.jsx("div",{className:"sidebar-empty",children:Q?"Drop here to unassign":"No unassigned documents"})]})]}),n.map(D=>{var pe,ye,Pe;const le=((pe=D.workspace)==null?void 0:pe.root)||[],fe=R.has(D.filename),se=((ye=D.workspace)==null?void 0:ye.autoAccept)===!0||D.autoAccept===!0;return c.jsxs("div",{className:`sidebar-section sidebar-workspace-section ${fe?"ws-collapsed":""} ${Oe(D.filename)?"dragging":""} ${(he==null?void 0:he.itemId)===D.filename?he.position==="before"?"drop-before":"drop-after":""}`,children:[c.jsxs("div",{className:`sidebar-section-header${fe&&(Ye==null?void 0:Ye.wsFilename)===D.filename?" active-within":""}`,"data-section-key":D.filename,"data-ws-drag":D.filename,onPointerDown:Se=>me(Se,{type:"workspace",filename:D.filename},D.title),onClick:()=>!Q&&Ne(D.filename),onContextMenu:Se=>{var Vt;Se.preventDefault(),Se.stopPropagation(),yt({x:Se.clientX,y:Se.clientY,type:"workspace",wsFilename:D.filename,title:D.title,nodes:le,autoAccept:((Vt=D.workspace)==null?void 0:Vt.autoAccept)===!0||D.autoAccept===!0})},children:[c.jsx("span",{className:`sidebar-chevron ${fe?"collapsed":""}`,children:"▾"}),$===D.filename?c.jsx("input",{className:"sidebar-rename-input",value:q,onChange:Se=>ne(Se.target.value),onBlur:()=>{l.handleRenameWorkspace(D.filename,q),W(null)},onKeyDown:Se=>{Se.key==="Enter"&&(l.handleRenameWorkspace(D.filename,q),W(null)),Se.key==="Escape"&&W(null)},autoFocus:!0,onClick:Se=>Se.stopPropagation()}):c.jsx("span",{className:"sidebar-label sidebar-workspace-label",onDoubleClick:Se=>{Se.stopPropagation(),W(D.filename),ne(D.title)},children:D.title}),(((Pe=D.workspace)==null?void 0:Pe.autoAccept)===!0||D.autoAccept===!0)&&c.jsx("span",{className:"sidebar-auto-accept-dot",title:"Auto-accept on for this workspace"}),c.jsxs("div",{className:"sidebar-workspace-actions",children:[c.jsx("button",{className:"sidebar-new-btn",onClick:Se=>{Se.stopPropagation(),ut({anchor:Se.target.getBoundingClientRect(),wsFilename:D.filename,containerId:null})},title:"New document",children:"+"}),c.jsx("button",{className:"sidebar-new-btn",onClick:Se=>{Se.stopPropagation(),l.handleCreateContainer(D.filename,null)},title:"New container",children:"☐"}),P===D.filename?c.jsxs("span",{className:"sidebar-inline-confirm",onClick:Se=>Se.stopPropagation(),children:[c.jsx("button",{onClick:()=>{l.handleDeleteWorkspace(D.filename),B(null)},children:"Yes"}),c.jsx("button",{onClick:()=>B(null),children:"No"})]}):c.jsx("button",{className:"sidebar-new-btn sidebar-workspace-delete",onClick:Se=>{Se.stopPropagation(),B(D.filename)},title:"Delete workspace",children:"×"})]})]}),!fe&&c.jsxs("div",{className:"sidebar-section-list","data-drop-ws":D.filename,children:[f&&!(h!=null&&h.parentDocId)&&(h==null?void 0:h.wsFilename)===D.filename&&h.containerId===null&&c.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[c.jsxs("div",{className:"sidebar-item-title",children:[c.jsx("span",{className:"sidebar-writing-spinner"}),c.jsx("span",{className:"sidebar-item-title-text",children:f})]}),c.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),le.filter(Se=>Se.type!=="doc"?!0:!(k(Se.file)||f&&(h==null?void 0:h.wsFilename)===D.filename&&h.containerId===null&&Se.title===f)).map((Se,Vt)=>ie(Se,0,D.filename,null,le,Vt,se)),le.length===0&&!f&&c.jsx("div",{className:"sidebar-empty",children:Q?"Drop here to add":"Empty workspace"})]})]},D.filename)}),c.jsx("div",{className:"sidebar-new-workspace",children:c.jsx("button",{onClick:l.handleCreateWorkspace,children:"+ New Workspace"})}),ge&&c.jsx(Bd,{x:ge.x,y:ge.y,filename:ge.wsFilename,title:ge.title,onClose:()=>yt(null),onDuplicate:()=>{},onRename:()=>{ge.type==="workspace"?(W(ge.wsFilename),ne(ge.title)):ge.containerId&&(K(ge.containerId),J(ge.title)),yt(null)},onArchive:()=>{},onDelete:()=>{ge.type==="workspace"?l.handleDeleteWorkspace(ge.wsFilename):ge.containerId&&l.handleDeleteContainer(ge.wsFilename,ge.containerId)},onPluginAction:()=>{},pluginItems:[],folderMode:!0,onNewDoc:D=>{ut({anchor:D.target.getBoundingClientRect(),wsFilename:ge.wsFilename,containerId:ge.type==="container"?ge.containerId:null}),yt(null)},onNewContainer:()=>{l.handleCreateContainer(ge.wsFilename,ge.type==="container"?ge.containerId:null),yt(null)},onAcceptAll:()=>{const D=new Set;Rl(ge.nodes,D),D.size&&je([...D],"accept"),yt(null)},onRejectAll:()=>{const D=new Set;Rl(ge.nodes,D),D.size&&je([...D],"reject"),yt(null)},folderAutoAccept:ge.autoAccept,folderAutoAcceptLabel:ge.type==="workspace"?"for workspace":"for container",onToggleFolderAutoAccept:()=>{fetch("/api/auto-accept/inherit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wsFile:ge.wsFilename,...ge.type==="container"?{containerId:ge.containerId}:{},enabled:!ge.autoAccept})}).catch(()=>{})}}),L&&c.jsx(Bd,{x:L.x,y:L.y,filename:L.filename,title:L.title,onClose:()=>ee(null),onDuplicate:()=>vt(L.filename),onCreateVariant:L.docId?D=>Et(L.filename,L.docId,D):void 0,onRename:()=>{S(L.filename),T(L.title)},onArchive:()=>l.handleArchive(L.filename),onDelete:()=>l.handleDelete(L.filename),onPluginAction:(D,le)=>_e(D,le,L.filename,L.title),pluginItems:re,onSchedulePost:Ee?()=>{tt({filename:L.filename,title:L.title}),ee(null)}:void 0,onViewAnalytics:L.docId&&L.lastSent&&(L.postedUrl||L.isNewsletter)?()=>{L.isNewsletter?be({docId:L.docId,title:L.title}):L.postedUrl&&window.open(L.postedUrl,"_blank"),ee(null)}:void 0,viewAnalyticsLabel:L.isNewsletter?"View Analytics":L.postedUrl?"View on X":"View Analytics",isApproved:l.getDocTags(L.filename).includes("✓"),onToggleApprove:()=>{l.getDocTags(L.filename).includes("✓")?l.handleRemoveTag(L.filename,"✓"):(l.handleAddTag(L.filename,"✓"),setTimeout(()=>window.dispatchEvent(new CustomEvent("ow-accept-all")),50))},isAutoAccept:(()=>{var le;const D=(le=t.find(fe=>fe.filename===L.filename))==null?void 0:le.autoAccept;return D===!0?!0:D===!1?!1:Pd(n,L.filename)})(),onToggleAutoAccept:()=>{var fe;const D=(fe=t.find(se=>se.filename===L.filename))==null?void 0:fe.autoAccept,le=D===!0?!0:D===!1?!1:Pd(n,L.filename);fetch("/api/auto-accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:L.filename,enabled:!le})}).then(()=>l.fetchDocs()).catch(()=>{})},isAlreadySent:!!L.lastSent,onMarkSent:()=>{const D=L.filename;l.getDocTags(D).includes("✓")&&l.handleRemoveTag(D,"✓"),i(D),setTimeout(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualPost:{postedAt:new Date().toISOString()}})}).then(()=>l.fetchDocs()).catch(()=>{})},100),ee(null)}}),Fe&&c.jsx(RT,{actionLabel:Fe.label,docTitle:Fe.title,onClose:()=>Ze(null),onConfirm:D=>{const le=re.find(fe=>fe.action===Fe.action);le&&_e(Fe.action,le,Fe.filename,Fe.title,D),Ze(null)}}),ue&&c.jsx(OT,{docId:ue.docId,title:ue.title,onClose:()=>be(null)}),Re&&c.jsx(Ul,{filename:Re.filename,title:Re.title,onClose:()=>tt(null)}),gt&&c.jsx(IT,{anchorRect:gt.anchor,onClose:()=>ut(null),onSelect:D=>{ut(null),gt.wsFilename?l.handleCreateInWorkspace(gt.wsFilename,gt.containerId??null,D):D?fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:D})}).catch(()=>{}):o()}}),Ct&&c.jsx("div",{ref:De,className:"sidebar-density-dropdown",style:{position:"fixed",left:Ct.x,top:Ct.y,zIndex:200},children:S$.map(D=>c.jsx("button",{className:`sidebar-density-option ${Lt===D.id?"active":""}`,onClick:()=>ve(D.id),children:D.label},D.id))})]})}function N$({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,onCreateDocument:i,actions:o,scrollRef:l,searchQuery:d,searchResults:f}){const[h,m]=x.useState(null);if(zl(l,t,e.length),f!==null)return c.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 b="";for(const w of g){const S=m$(w.lastModified);S!==b&&(v.push({label:S,docs:[]}),b=S),v[v.length-1].docs.push(w)}const k=w=>{for(const S of e){if(!S.workspace)continue;const N=T=>{for(const M of T)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 c.jsxs("div",{className:"sidebar-scroll tl-scroll",ref:l,children:[c.jsxs("div",{className:"tl-header",children:[c.jsx("span",{className:"tl-title",children:"Timeline"}),c.jsx("button",{className:"sidebar-new-btn",onClick:i,title:"New document",children:"+"})]}),v.map(w=>c.jsxs("div",{className:"tl-group",children:[c.jsx("div",{className:"tl-date",children:w.label}),w.docs.map(S=>{const N=k(S.filename);return c.jsxs("div",{className:`tl-item ${S.isActive?"active":""}`,onClick:()=>!S.isActive&&s(S.filename),children:[c.jsx("div",{className:"tl-dot"}),c.jsxs("div",{className:"tl-content",children:[c.jsxs("div",{className:"tl-item-title",children:[c.jsx("span",{children:S.title}),r.filenames.includes(S.filename)&&c.jsx("span",{className:"sidebar-pending-dot"})]}),Fs(S.filename)&&c.jsx("div",{className:"tl-item-context",children:TT(S.filename)}),c.jsxs("div",{className:"tl-item-meta",children:[S.wordCount.toLocaleString()," words · ",pa(S.lastModified)]}),N&&c.jsx("div",{className:"tl-badge",children:N})]}),h===S.filename?c.jsxs("div",{className:"sidebar-confirm-delete",onClick:T=>T.stopPropagation(),children:[c.jsx("span",{children:Fs(S.filename)?"Remove?":"Delete?"}),c.jsx("button",{onClick:()=>{o.handleDelete(S.filename),m(null)},children:"Yes"}),c.jsx("button",{onClick:()=>m(null),children:"No"})]}):c.jsx("button",{className:"sidebar-delete-btn",onClick:T=>{T.stopPropagation(),m(S.filename)},title:Fs(S.filename)?"Remove":"Delete",children:"×"})]},S.filename)})]},w.label)),t.length===0&&c.jsx("div",{className:"sidebar-empty",children:"No documents yet"})]})}function C$({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:o,searchQuery:l,searchResults:d,onSearchChange:f}){const[h,m]=x.useState([]),[g,v]=x.useState(null);zl(o,t,e.length);const[b,k]=x.useState(null),w=x.useRef(null);x.useEffect(()=>{if(!g)return;const A=L=>{w.current&&!w.current.contains(L.target)&&v(null)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[g]);const S=(A,L)=>{for(const ee of A)if(ee.type==="container"){if(ee.id===L)return ee;const ue=S(ee.items,L);if(ue)return ue}return null},N=A=>{let L=0;for(const ee of A)ee.type==="doc"?L++:ee.type==="container"&&(L+=N(ee.items));return L},T=A=>{const L=[];for(const ee of A)ee.type==="doc"?L.push(ee.file):ee.type==="container"&&L.push(...T(ee.items));return L},M=x.useMemo(()=>{if(h.length===0)return[];const A=h[h.length-1],L=e.find(ue=>ue.filename===A.wsFilename);if(!(L!=null&&L.workspace))return[];if(A.type==="workspace")return L.workspace.root;const ee=S(L.workspace.root,A.key);return ee?ee.items:[]},[h,e]),_=M.filter(A=>A.type==="container"),R=x.useMemo(()=>{const A=M.filter(L=>L.type==="doc").map(L=>L.file);return t.filter(L=>A.includes(L.filename))},[M,t]),I=A=>{const L=T(A.items);return t.filter(ee=>L.includes(ee.filename))},P=A=>{const L=e.find(ue=>ue.filename===A);if(!(L!=null&&L.workspace))return[];const ee=T(L.workspace.root);return t.filter(ue=>ee.includes(ue.filename))},B=x.useMemo(()=>t.filter(A=>!n.has(A.filename)),[t,n]),z=A=>{m(L=>[...L,A]),v(null)},K=()=>{m(A=>A.slice(0,-1)),v(null)},F=(A,L)=>{if(g===A){v(null);return}const ue=L.currentTarget.getBoundingClientRect();k({top:ue.bottom+4,left:ue.left}),v(A)},J=A=>{s(A),v(null)},$=h.length>1?h[h.length-2].title:"All",W=x.useRef(null),q=x.useRef(null),[ne,V]=x.useState(null),oe=x.useCallback(A=>{const ee=A.currentTarget.getBoundingClientRect();V({top:ee.bottom+4,left:ee.left})},[]);x.useEffect(()=>{if(!d)return;const A=L=>{q.current&&!q.current.contains(L.target)&&W.current&&!W.current.contains(L.target)&&f("")};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[d,f]);const Y=()=>{if(!g)return[];if(g==="__unassigned__")return B;if(g==="__level-docs__")return R;const A=e.find(L=>L.filename===g);if(A)return P(A.filename);for(const L of e){if(!L.workspace)continue;const ee=S(L.workspace.root,g);if(ee)return I(ee)}return[]};return c.jsxs("div",{className:"board-scroll",ref:o,children:[c.jsxs("div",{className:"board-search-pill",children:[c.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:[c.jsx("circle",{cx:"11",cy:"11",r:"8"}),c.jsx("path",{d:"m21 21-4.3-4.3"})]}),c.jsx("input",{ref:W,className:"board-search-input",type:"text",placeholder:"Search...",value:l,onChange:A=>f(A.target.value),onFocus:oe}),l&&c.jsx("button",{className:"board-search-clear",onClick:()=>f(""),children:"×"})]}),h.length===0?c.jsx("button",{className:"board-back board-back--static",tabIndex:-1,children:"All"}):c.jsxs("button",{className:"board-back",onClick:K,title:`Back to ${$}`,children:["← ",$]}),h.length===0&&c.jsxs(c.Fragment,{children:[B.length>0&&c.jsxs("button",{className:`board-chip ${g==="__unassigned__"?"open":""}`,onClick:A=>F("__unassigned__",A),children:["Documents ",c.jsx("span",{className:"board-chip-count",children:B.length})]}),e.map(A=>{var ee;const L=(ee=A.workspace)==null?void 0:ee.root.some(ue=>ue.type==="container");return c.jsxs("button",{className:`board-chip ${g===A.filename?"open":""}`,onClick:ue=>L?z({type:"workspace",key:A.filename,title:A.title,wsFilename:A.filename}):F(A.filename,ue),children:[A.title," ",c.jsx("span",{className:"board-chip-count",children:A.docCount}),L&&c.jsx("span",{className:"board-chip-arrow",children:"›"})]},A.filename)}),c.jsx("button",{className:"board-chip board-chip-add",onClick:i.handleCreateWorkspace,title:"New workspace",children:"+"})]}),h.length>0&&c.jsxs(c.Fragment,{children:[R.length>0&&c.jsxs("button",{className:`board-chip board-chip-docs ${g==="__level-docs__"?"open":""}`,onClick:A=>F("__level-docs__",A),children:["Docs ",c.jsx("span",{className:"board-chip-count",children:R.length})]}),_.map(A=>{const L=A.items.some(ee=>ee.type==="container");return c.jsxs("button",{className:`board-chip ${g===A.id?"open":""}`,onClick:ee=>L?z({type:"container",key:A.id,title:A.name,wsFilename:h[h.length-1].wsFilename}):F(A.id,ee),children:[A.name," ",c.jsx("span",{className:"board-chip-count",children:N(A.items)}),L&&c.jsx("span",{className:"board-chip-arrow",children:"›"})]},A.id)})]}),g&&b&&(()=>{const A=Y();return c.jsxs("div",{className:"board-dropdown",ref:w,style:{position:"fixed",top:b.top,left:b.left},children:[A.map(L=>c.jsxs("div",{className:`board-dropdown-item ${L.isActive?"active":""}`,onClick:()=>J(L.filename),children:[c.jsxs("span",{className:"board-dropdown-title",children:[L.title,r.filenames.includes(L.filename)&&c.jsx("span",{className:"board-pending-dot"})]}),c.jsxs("span",{className:"board-dropdown-meta",children:[L.wordCount.toLocaleString()," words · ",pa(L.lastModified)]})]},L.filename)),A.length===0&&c.jsx("div",{className:"board-dropdown-empty",children:"No documents"})]})})(),d&&ne&&c.jsxs("div",{className:"board-dropdown board-search-dropdown",ref:q,style:{position:"fixed",top:ne.top,left:ne.left},children:[d.map(A=>c.jsxs("div",{className:`board-dropdown-item ${A.isActive?"active":""}`,onClick:()=>{s(A.filename),f("")},children:[c.jsx("span",{className:"board-dropdown-title",children:A.title}),A.matchType==="tag"&&A.matchedTag&&c.jsxs("span",{className:"board-dropdown-meta",children:["Tag: ",A.matchedTag]}),A.matchType==="content"&&A.snippet&&c.jsx("span",{className:"board-dropdown-meta board-search-snippet",children:A.snippet}),c.jsxs("span",{className:"board-dropdown-meta",children:[A.wordCount.toLocaleString()," words · ",pa(A.lastModified)]})]},A.filename)),d.length===0&&c.jsx("div",{className:"board-dropdown-empty",children:"No results"})]})]})}function _$({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:o,searchQuery:l,searchResults:d}){const[f,h]=x.useState([]);if(zl(o,t,e.length),d!==null)return c.jsx(rf,{results:d,query:l,onSwitchDocument:s});const m=(M,_)=>{for(const R of M)if(R.type==="container"){if(R.id===_)return R;const I=m(R.items,_);if(I)return I}return null},g=M=>{let _=0;for(const R of M)R.type==="doc"?_++:R.type==="container"&&(_+=g(R.items));return _},v=x.useMemo(()=>{if(f.length===0)return[];const M=f[f.length-1],_=e.find(I=>I.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]),b=v.filter(M=>M.type==="container"),k=x.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",T=f.length>0?f[f.length-1].title:"Documents";return c.jsxs("div",{className:"shelf-wrapper",children:[c.jsxs("div",{className:"shelf-spines",ref:o,children:[f.length>0&&c.jsxs("button",{className:"shelf-back",onClick:S,title:`Back to ${N}`,children:[c.jsx("span",{className:"shelf-back-arrow",children:"←"}),c.jsx("span",{className:"shelf-back-label",children:N})]}),f.length===0&&c.jsxs(c.Fragment,{children:[e.map(M=>c.jsxs("div",{className:"shelf-section-spine",onClick:()=>w({type:"workspace",key:M.filename,title:M.title,wsFilename:M.filename}),title:M.title,children:[c.jsx("span",{className:"shelf-section-title",children:M.title}),c.jsx("span",{className:"shelf-section-count",children:M.docCount})]},M.filename)),c.jsx("button",{className:"shelf-add",onClick:i.handleCreateWorkspace,title:"New workspace",children:"+"})]}),f.length>0&&b.map(M=>c.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:[c.jsx("span",{className:"shelf-section-title",children:M.name}),c.jsx("span",{className:"shelf-section-count",children:g(M.items)})]},M.id))]}),c.jsxs("div",{className:"shelf-docs",children:[c.jsx("div",{className:"shelf-docs-header",children:T}),c.jsxs("div",{className:"shelf-docs-list",children:[k.map(M=>c.jsxs("div",{className:`shelf-doc-item ${M.isActive?"active":""}`,onClick:()=>s(M.filename),children:[c.jsxs("div",{className:"shelf-doc-title",children:[c.jsx("span",{children:M.title}),r.filenames.includes(M.filename)&&c.jsx("span",{className:"shelf-pending-dot"})]}),c.jsxs("div",{className:"shelf-doc-meta",children:[M.wordCount.toLocaleString()," words · ",pa(M.lastModified)]})]},M.filename)),k.length===0&&c.jsx("div",{className:"shelf-docs-empty",children:"No documents"})]})]})]})}async function Ak(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 LT({filename:t,title:e,isActive:n,onSwitchDocument:r,onClose:s}){const[i,o]=x.useState("loading"),[l,d]=x.useState([]),[f,h]=x.useState(null),[m,g]=x.useState(null),[v,b]=x.useState(null);x.useEffect(()=>{Ak("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=l.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 Ak("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;b({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 c.jsx("div",{className:"post-blog-overlay",onClick:()=>{i!=="posting"&&s()},children:c.jsxs("div",{className:"post-blog-modal",onClick:S=>S.stopPropagation(),children:[c.jsxs("div",{className:"post-blog-modal-header",children:[c.jsx("h3",{children:"Post to Blog"}),c.jsx("button",{className:"post-blog-modal-close",onClick:s,disabled:i==="posting",children:"×"})]}),c.jsx("div",{className:"post-blog-modal-doc",children:e}),i==="loading"&&c.jsx("div",{className:"post-blog-modal-loading",children:"Loading blog sites…"}),i==="pick"&&l.length===0&&c.jsxs("div",{className:"post-blog-modal-empty",children:["No blog sites registered. Add one in ",c.jsx("strong",{children:"Settings → Plugins → GitHub"})," first.",c.jsx("button",{className:"post-blog-modal-done",onClick:s,children:"Close"})]}),i==="pick"&&l.length>0&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"post-blog-modal-label",children:"Choose a destination"}),c.jsx("div",{className:"post-blog-modal-sites",children:l.map(S=>c.jsxs("button",{className:`post-blog-modal-site${f===S.id?" post-blog-modal-site--selected":""}`,onClick:()=>{h(S.id),o("confirm")},children:[c.jsx("div",{className:"post-blog-modal-site-label",children:S.label}),c.jsxs("div",{className:"post-blog-modal-site-repo",children:[S.owner,"/",S.repo,"@",S.branch]})]},S.id))})]}),i==="confirm"&&k&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"post-blog-modal-confirm",children:["Publish to ",c.jsxs("strong",{children:[k.owner,"/",k.repo,"@",k.branch]}),"?",c.jsxs("div",{className:"post-blog-modal-target-dir",children:["→ ",k.content_dir]})]}),c.jsxs("div",{className:"post-blog-modal-actions",children:[c.jsx("button",{className:"post-blog-modal-btn post-blog-modal-btn--primary",onClick:w,children:"Publish now"}),l.length>1&&c.jsx("button",{className:"post-blog-modal-btn",onClick:()=>o("pick"),children:"Back"}),c.jsx("button",{className:"post-blog-modal-btn",onClick:s,children:"Cancel"})]})]}),i==="posting"&&c.jsx("div",{className:"post-blog-modal-loading",children:"Publishing…"}),i==="done"&&v&&c.jsxs("div",{className:"post-blog-modal-result post-blog-modal-result--success",children:[c.jsx("div",{children:v.message||"Published"}),v.file&&c.jsx("div",{className:"post-blog-modal-meta",children:v.file}),typeof v.images_committed=="number"&&v.images_committed>0&&c.jsxs("div",{className:"post-blog-modal-meta",children:[v.images_committed," image",v.images_committed===1?"":"s"," committed"]}),v.warning&&c.jsx("div",{className:"post-blog-modal-warning",children:v.warning}),c.jsxs("div",{className:"post-blog-modal-actions",children:[v.liveUrl?c.jsx("button",{className:"post-blog-modal-btn post-blog-modal-btn--primary",onClick:()=>window.open(v.liveUrl,"_blank"),children:"View Post"}):v.commitUrl?c.jsx("button",{className:"post-blog-modal-btn post-blog-modal-btn--primary",onClick:()=>window.open(v.commitUrl,"_blank"),children:"View commit"}):null,c.jsx("button",{className:"post-blog-modal-btn",onClick:s,children:"Done"})]}),v.liveUrl&&v.commitUrl&&c.jsx("button",{className:"post-blog-modal-commit-link",onClick:()=>window.open(v.commitUrl,"_blank"),children:"View commit"})]}),i==="error"&&c.jsxs("div",{className:"post-blog-modal-result post-blog-modal-result--error",children:[c.jsx("div",{children:m||"Publish failed"}),c.jsx("div",{className:"post-blog-modal-actions",children:c.jsx("button",{className:"post-blog-modal-btn",onClick:s,children:"Close"})})]})]})})}const T$=()=>c.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[c.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"}),c.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14",opacity:"0.5"})]}),j$=()=>c.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),c.jsx("polyline",{points:"14 2 14 8 20 8"}),c.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),c.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]}),M$=()=>c.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:c.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"})}),A$=()=>c.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[c.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"}),c.jsx("path",{d:"M7 15l-4-3.5L7 8",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),R$=()=>c.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[c.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"}),c.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"})]}),O$=()=>c.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[c.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"}),c.jsx("rect",{x:"2",y:"16",width:"8",height:"7",rx:"1.5",fill:"none",stroke:"currentColor",strokeWidth:"1.5"}),c.jsx("line",{x1:"4",y1:"18.5",x2:"8",y2:"18.5",stroke:"currentColor",strokeWidth:"1",opacity:"0.7"}),c.jsx("line",{x1:"4",y1:"20.5",x2:"7",y2:"20.5",stroke:"currentColor",strokeWidth:"1",opacity:"0.7"})]}),I$=()=>c.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:c.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"})}),L$=()=>c.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),c.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),D$=()=>c.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("path",{d:"M2 12h20"}),c.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"})]}),Rk=()=>c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})});function P$({type:t}){switch(t){case"tweet":return c.jsx(M$,{});case"reply":return c.jsx(A$,{});case"quote":return c.jsx(R$,{});case"article":return c.jsx(O$,{});case"linkedin":return c.jsx(I$,{});case"newsletter":return c.jsx(L$,{});case"blog":return c.jsx(D$,{});default:return c.jsx(j$,{})}}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 Su(t){const e=new Set;return Rl(t,e),[...e]}function DT(t,e,n=0){for(const r of t)if(r.type==="container"){if(r.id===e)return n;const s=DT(r.items,e,n+1);if(s>=0)return s}return-1}function B$(t,e){if(!e)return 12;for(const n of t){if(!n.workspace)continue;const r=DT(n.workspace.root,e);if(r>=0)return 12+(r+1)*16}return 12}function $$({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,onCreateDocument:i,actions:o,scrollRef:l,writingTitle:d,writingTarget:f,pendingWriteFilenames:h,searchQuery:m,searchResults:g,onSearchChange:v}){var st,Ye,jt;const b=j=>!!h&&h.has(j),[k,w]=x.useState(()=>{try{const j=localStorage.getItem("ow-files-collapsed");return j?new Set(JSON.parse(j)):new Set}catch{return new Set}}),{draggedItem:S,dropIndicator:N,handlePointerDown:T,dropClass:M,isDragging:_,isContainerDropTarget:R}=MT({docs:t,workspaces:e,assignedFiles:n,scrollRef:l,setCollapsedSections:w}),I=j=>!N||N.itemId!==j||N.position==="inside"?void 0:{"--drop-indent":`${B$(e,N.containerId)}px`},{variantsByMaster:P,variantFilenames:B}=x.useMemo(()=>{const j=new Map,U=new Set;for(const ie of t)if(ie.masterDocId){const D=j.get(ie.masterDocId)||[];D.push(ie),j.set(ie.masterDocId,D),U.add(ie.filename)}return{variantsByMaster:j,variantFilenames:U}},[t]),[z,K]=x.useState(null),[F,J]=x.useState(null),[$,W]=x.useState(new Set),[q,ne]=x.useState(null),[V,oe]=x.useState([]),[Y,A]=x.useState(!1),[L,ee]=x.useState(null),[ue,be]=x.useState(null),[re,we]=x.useState(null),[Ee,$e]=x.useState(null),[Fe,Ze]=x.useState(null),[Re,tt]=x.useState(null),[gt,ut]=x.useState(new Set);x.useEffect(()=>{ut(new Set)},[r]);const ge=x.useCallback(()=>{fetch("/api/plugins").then(j=>j.json()).then(j=>{const U=[];let ie=!1;for(const D of j.plugins||[]){const le=D.displayName||void 0;for(const fe of D.sidebarMenuItems||[])U.push({...fe,pluginDisplayName:le});D.name==="@openwriter/plugin-publish"&&D.enabled&&(ie=!0)}oe(U),A(ie)}).catch(()=>{})},[]);x.useEffect(()=>{ge()},[ge]),x.useEffect(()=>{const j=()=>ge();return window.addEventListener("ow-plugins-changed",j),()=>window.removeEventListener("ow-plugins-changed",j)},[ge]);const yt=x.useCallback((j,U)=>{if(j.preventDefault(),j.stopPropagation(),$.has(U.filename)&&$.size>1){J({x:j.clientX,y:j.clientY,filename:U.filename,title:U.title,bulkCount:$.size});return}$.size>0&&!$.has(U.filename)&&W(new Set),J({x:j.clientX,y:j.clientY,filename:U.filename,title:U.title,docId:U.docId,lastSent:U.lastSent,postedUrl:U.postedUrl,isNewsletter:U.isNewsletter,contentType:U.contentType,sortRequest:U.sortRequest})},[$]),Ct=x.useCallback(j=>{fetch("/api/documents/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:j})}).catch(()=>{})},[]),_t=x.useCallback((j,U,ie,D,le)=>{if(!AT(U,t.find(fe=>fe.filename===ie))){if(U.promptForFocus&&le===void 0){ee({action:j,label:U.label,filename:ie,title:D});return}fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:j,filename:ie,title:D,instructions:le||"",label:U.label})}).catch(()=>{})}},[t]),Lt=x.useCallback((j,U,ie)=>{for(const D of Su(ie)){const le=t.find(fe=>fe.filename===D);fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:j,filename:D,title:(le==null?void 0:le.title)||D,instructions:"",label:U.label})}).catch(()=>{})}},[t]),at=x.useCallback((j,U)=>{ut(ie=>{const D=new Set(ie);for(const le of j)D.add(le);return D}),fetch("/api/documents/batch-resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filenames:j,action:U})}).catch(()=>{})},[]),De=j=>{w(U=>{const ie=new Set(U);return ie.has(j)?ie.delete(j):ie.add(j),localStorage.setItem("ow-files-collapsed",JSON.stringify([...ie])),ie})},ve=(j,U,ie,D)=>{K({type:j,key:U,value:ie,wsFilename:D})},Z=()=>{if(!z)return;const{type:j,key:U,value:ie,wsFilename:D}=z;j==="doc"?o.handleRename(U,"",ie):j==="workspace"?o.handleRenameWorkspace(U,ie):j==="container"&&D&&o.handleRenameContainer(D,U,ie),K(null)},je=t.find(j=>j.isActive),Q=x.useMemo(()=>{var D;const j=t.find(le=>le.isActive);if(!j)return null;const U=j.masterDocId?t.find(le=>le.docId===j.masterDocId):void 0,ie=(U==null?void 0:U.filename)??j.filename;for(const le of e){const fe=tv(((D=le.workspace)==null?void 0:D.root)||[],ie);if(fe)return{wsFilename:le.filename,containerKeys:new Set(fe.map(se=>`container-${se}`)),masterDocId:(U==null?void 0:U.docId)??null}}return{wsFilename:null,containerKeys:new Set,masterDocId:(U==null?void 0:U.docId)??null}},[t,e]),he=x.useRef(e);he.current=e;const me=x.useCallback(j=>{var U;for(const ie of he.current){const D=tv(((U=ie.workspace)==null?void 0:U.root)||[],j);if(D){w(le=>{const fe=[ie.filename,...D.map(pe=>`container-${pe}`)];if(fe.every(pe=>!le.has(pe)))return le;const se=new Set(le);for(const pe of fe)se.delete(pe);return localStorage.setItem("ow-files-collapsed",JSON.stringify([...se])),se});break}}},[]);zl(l,t,e.length,me);const Ue=x.useMemo(()=>t.filter(j=>!n.has(j.filename)&&!B.has(j.filename)&&!b(j.filename)),[t,n,B,h]),Oe=x.useMemo(()=>{var D;const j=[],U=le=>{j.push(le.filename);const fe=le.docId?P.get(le.docId):void 0,se=le.docId&&!k.has(`variants-${le.docId}`);if(fe&&se)for(const pe of fe)j.push(pe.filename)},ie=le=>{for(const fe of le)if(fe.type==="doc"){const se=t.find(pe=>pe.filename===fe.file);se&&!B.has(se.filename)&&U(se)}else k.has(`container-${fe.id}`)||ie(fe.items)};k.has("docs")||Ue.forEach(U);for(const le of e)k.has(le.filename)||ie(((D=le.workspace)==null?void 0:D.root)||[]);return j},[t,e,Ue,B,P,k]),Ve=x.useCallback(()=>{W(new Set)},[]),et=x.useCallback((j,U)=>{if(S)return;const ie=j.shiftKey,D=j.ctrlKey||j.metaKey;if(ie){const fe=q||(je==null?void 0:je.filename)||U,se=Oe.indexOf(fe),pe=Oe.indexOf(U);if(se<0||pe<0){W(new Set([U])),ne(U);return}const[ye,Pe]=se<pe?[se,pe]:[pe,se];W(new Set(Oe.slice(ye,Pe+1)));return}if(D){W(fe=>{const se=new Set(fe);return se.has(U)?se.delete(U):se.add(U),se}),ne(U);return}W(new Set),ne(U);const le=t.find(fe=>fe.filename===U);le&&!le.isActive&&s(U)},[S,q,je==null?void 0:je.filename,Oe,s,t]);x.useEffect(()=>{if($.size===0)return;const j=U=>{U.key==="Escape"&&Ve()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[$.size,Ve]);const ft=x.useCallback(()=>{for(const j of $)o.handleDelete(j);W(new Set),ne(null)},[$,o]),We=x.useCallback(j=>{j.length!==0&&fetch("/api/documents/sort-request",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filenames:j})}).then(()=>o.fetchDocs()).catch(()=>{})},[o]),Ge=x.useCallback(j=>{fetch("/api/documents/sort-reject",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:j})}).then(()=>o.fetchDocs()).catch(()=>{})},[o]),vt=x.useCallback(j=>{fetch("/api/documents/sort-accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:j})}).then(()=>o.fetchDocs()).catch(()=>{})},[o]);if(g!==null)return c.jsx(rf,{results:g,query:m,onSwitchDocument:s,actions:o});const Et=j=>c.jsx("input",{className:"sidebar-rename-input",value:z.value,onChange:U=>K(ie=>ie?{...ie,value:U.target.value}:null),onBlur:j,onKeyDown:U=>{U.key==="Enter"&&j(),U.key==="Escape"&&K(null)},autoFocus:!0,onClick:U=>U.stopPropagation()}),_e=(j,U,ie,D,le,fe=!1)=>c.jsxs("div",{className:`files-row${j.isActive?" active":""}${j.docId&&(Q==null?void 0:Q.masterDocId)===j.docId&&k.has(`variants-${j.docId}`)?" active-within":""}${$.has(j.filename)?" selected":""} ${_(j.filename)?"dragging":""} ${M(j.filename)}${j.masterDocId?" is-variant":""}`,style:{paddingLeft:U,...I(j.filename)},"data-drag-id":j.filename,"data-drag-type":"doc","data-drag-ws":ie||"__docs__","data-drag-container":D||"",onPointerDown:se=>T(se,{type:"doc",file:j.filename,sourceWs:ie||null},j.title),onClick:se=>et(se,j.filename),onDoubleClick:()=>ve("doc",j.filename,j.title),onContextMenu:se=>yt(se,j),children:[c.jsx("span",{className:"files-row-icon",children:c.jsx(P$,{type:j.contentType})}),(z==null?void 0:z.type)==="doc"&&z.key===j.filename?Et(Z):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"files-row-label",children:j.title}),j.variantType&&c.jsx("span",{className:"files-badge-variant",children:j.variantType}),(j.autoAccept===!0||j.autoAccept!==!1&&fe)&&c.jsx("span",{className:"sidebar-auto-accept-dot",title:j.autoAccept===!0?"Auto-accept on":"Auto-accept inherited"}),r.filenames.includes(j.filename)&&!gt.has(j.filename)&&c.jsx("span",{className:"files-badge-pending"}),j.sortRequest&&(j.sortRequest.proposal?c.jsx("span",{className:"files-badge-sort-proposal",title:"Sort proposal ready — right-click to review"}):c.jsx("span",{className:"files-badge-sort-pending",title:"Sort requested"})),o.getDocTags(j.filename).includes("✓")&&c.jsx("span",{className:"files-badge-approved",children:c.jsx(Rk,{})}),j.lastSent&&c.jsx("span",{className:"files-badge-sent",children:c.jsx(Rk,{})}),le&&c.jsx("span",{className:`files-row-chevron${k.has(`variants-${j.docId}`)?" collapsed":""}`,onClick:se=>{se.stopPropagation(),De(`variants-${j.docId}`)},children:c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})})]})]},j.filename),Ne=(j,U,ie,D,le=!1)=>{const fe=j.docId?P.get(j.docId):void 0,se=!!(fe&&fe.length>0),pe=d&&(f==null?void 0:f.parentDocId)&&f.parentDocId===j.docId,ye=se||pe,Pe=!k.has(`variants-${j.docId}`);return ye?c.jsxs("div",{className:"files-variant-group",children:[_e(j,U,ie,D,se,le),Pe&&(fe==null?void 0:fe.map(Se=>_e(Se,U+16,ie,D,!1,le))),pe&&c.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:U+16},children:[c.jsxs("div",{className:"sidebar-item-title",children:[c.jsx("span",{className:"sidebar-writing-spinner"}),c.jsx("span",{className:"sidebar-item-title-text",children:d})]}),c.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]})]},`vg-${j.filename}`):_e(j,U,ie,D,!1,le)},Ke=(j,U,ie,D,le=!1)=>{const fe=12+U*16;if(j.type==="doc"){const It=t.find(Sn=>Sn.filename===j.file);return!It||B.has(It.filename)?null:Ne(It,fe,ie,D,le)}const se=j,pe=`container-${se.id}`,ye=k.has(pe),Pe=Fu(se.items),Se=se.autoAccept===!0,Vt=Se||le;return c.jsxs("div",{className:`${M(se.id)} ${R(se.id)?"files-drop-inside":""}`,children:[c.jsxs("div",{className:`files-row is-container${ye&&(Q!=null&&Q.containerKeys.has(pe))?" active-within":""} ${_(se.id)?"dragging":""} ${M(se.id)}`,style:{paddingLeft:fe,...I(se.id)},"data-drag-id":se.id,"data-drag-type":"container-header","data-drag-ws":ie,"data-drag-parent":D||"","data-section-key":pe,onPointerDown:It=>T(It,{type:"container",id:se.id,sourceWs:ie},se.name),onClick:()=>!S&&De(pe),onDoubleClick:It=>{It.stopPropagation(),ve("container",se.id,se.name,ie)},onContextMenu:It=>{It.preventDefault(),It.stopPropagation(),tt({x:It.clientX,y:It.clientY,type:"container",wsFilename:ie,containerId:se.id,title:se.name,nodes:se.items,autoAccept:Se})},children:[c.jsx("span",{className:"files-row-icon",children:c.jsx(T$,{})}),(z==null?void 0:z.type)==="container"&&z.key===se.id?Et(Z):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"files-row-label",children:se.name}),Vt&&c.jsx("span",{className:"sidebar-auto-accept-dot",title:Se?"Auto-accept on for this container":"Auto-accept inherited from workspace"}),c.jsx("span",{className:"files-row-count",children:Pe})]})]}),c.jsxs("div",{className:`files-children${ye?" collapsed":""}`,"data-drop-ws":ie,"data-drop-container":se.id,children:[d&&!(f!=null&&f.parentDocId)&&(f==null?void 0:f.wsFilename)===ie&&f.containerId===se.id&&c.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:12+(U+1)*16},children:[c.jsxs("div",{className:"sidebar-item-title",children:[c.jsx("span",{className:"sidebar-writing-spinner"}),c.jsx("span",{className:"sidebar-item-title-text",children:d})]}),c.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),se.items.filter(It=>It.type!=="doc"||!b(It.file)).map(It=>Ke(It,U+1,ie,se.id,Vt))]})]},se.id)};return c.jsxs("div",{className:"files-scroll",ref:l,children:[c.jsxs("div",{className:"files-section",children:[c.jsxs("div",{className:`files-row is-section${k.has("docs")&&Q!==null&&Q.wsFilename===null?" active-within":""}`,"data-section-key":"docs",onClick:()=>De("docs"),children:[c.jsx("span",{className:`files-row-chevron leading${k.has("docs")?" collapsed":""}`,children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})}),c.jsx("span",{className:"files-row-label",children:"Documents"}),c.jsx("button",{className:"files-section-btn",onClick:j=>{j.stopPropagation(),Ze({anchor:j.target.getBoundingClientRect()})},title:"New document",children:"+"})]}),c.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(j=>j.filename===(f==null?void 0:f.wsFilename)))&&c.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:28},children:[c.jsxs("div",{className:"sidebar-item-title",children:[c.jsx("span",{className:"sidebar-writing-spinner"}),c.jsx("span",{className:"sidebar-item-title-text",children:d})]}),c.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),Ue.map(j=>Ne(j,28))]})]}),e.map(j=>{var fe,se,pe;const U=((fe=j.workspace)==null?void 0:fe.root)||[],ie=k.has(j.filename),D=Fu(U),le=((se=j.workspace)==null?void 0:se.autoAccept)===!0||j.autoAccept===!0;return c.jsxs("div",{className:`files-section ${_(j.filename)?"dragging":""} ${(N==null?void 0:N.itemId)===j.filename?N.position==="before"?"files-ws-drop-before":"files-ws-drop-after":""}`,children:[c.jsx("div",{className:`files-row is-section${ie&&(Q==null?void 0:Q.wsFilename)===j.filename?" active-within":""}${(N==null?void 0:N.itemId)==="__section__"&&N.wsFilename===j.filename&&N.position==="inside"?" files-ws-drop-target":""}`,"data-section-key":j.filename,"data-ws-drag":j.filename,onPointerDown:ye=>T(ye,{type:"workspace",filename:j.filename},j.title),onClick:()=>!S&&De(j.filename),onDoubleClick:ye=>{ye.stopPropagation(),ve("workspace",j.filename,j.title)},onContextMenu:ye=>{var Pe;ye.preventDefault(),ye.stopPropagation(),tt({x:ye.clientX,y:ye.clientY,type:"workspace",wsFilename:j.filename,title:j.title,nodes:U,autoAccept:((Pe=j.workspace)==null?void 0:Pe.autoAccept)===!0||j.autoAccept===!0})},children:(z==null?void 0:z.type)==="workspace"&&z.key===j.filename?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:`files-row-chevron leading${ie?" collapsed":""}`,children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})}),Et(Z)]}):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:`files-row-chevron leading${ie?" collapsed":""}`,children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})}),c.jsx("span",{className:"files-row-label",children:j.title}),(((pe=j.workspace)==null?void 0:pe.autoAccept)===!0||j.autoAccept===!0)&&c.jsx("span",{className:"sidebar-auto-accept-dot",title:"Auto-accept on for this workspace"}),c.jsx("span",{className:"files-row-count",children:D}),c.jsxs("div",{className:"files-section-actions",children:[c.jsx("button",{className:"files-section-btn",onClick:ye=>{ye.stopPropagation(),Ze({anchor:ye.target.getBoundingClientRect(),wsFilename:j.filename,containerId:null})},title:"New document",children:"+"}),c.jsx("button",{className:"files-section-btn",onClick:ye=>{ye.stopPropagation(),o.handleCreateContainer(j.filename,null)},title:"New container",children:"☐"})]})]})}),c.jsxs("div",{className:`files-section-list files-children${ie?" collapsed":""}`,"data-drop-ws":j.filename,children:[d&&!(f!=null&&f.parentDocId)&&(f==null?void 0:f.wsFilename)===j.filename&&f.containerId===null&&c.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:28},children:[c.jsxs("div",{className:"sidebar-item-title",children:[c.jsx("span",{className:"sidebar-writing-spinner"}),c.jsx("span",{className:"sidebar-item-title-text",children:d})]}),c.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),U.filter(ye=>ye.type!=="doc"||!b(ye.file)).map(ye=>Ke(ye,1,j.filename,null,le))]})]},j.filename)}),c.jsx("div",{className:"files-new-ws",children:c.jsx("button",{onClick:o.handleCreateWorkspace,children:"+ New Workspace"})}),Re&&c.jsx(Bd,{x:Re.x,y:Re.y,filename:Re.wsFilename,title:Re.title,onClose:()=>tt(null),onDuplicate:()=>{},onRename:()=>{Re.type==="workspace"?ve("workspace",Re.wsFilename,Re.title):Re.containerId&&ve("container",Re.containerId,Re.title,Re.wsFilename),tt(null)},onArchive:()=>{},onDelete:()=>{Re.type==="workspace"?o.handleDeleteWorkspace(Re.wsFilename):Re.containerId&&o.handleDeleteContainer(Re.wsFilename,Re.containerId,!1)},folderDocCount:Re.type==="container"?Fu(Re.nodes):0,onDeleteWithDocs:Re.type==="container"&&Re.containerId?()=>{o.handleDeleteContainer(Re.wsFilename,Re.containerId,!0)}:void 0,onPluginAction:(j,U)=>Lt(j,U,Re.nodes),pluginItems:V.filter(j=>j.folderCapable),folderMode:!0,onNewDoc:j=>{Ze({anchor:j.target.getBoundingClientRect(),wsFilename:Re.wsFilename,containerId:Re.type==="container"?Re.containerId:null}),tt(null)},onNewContainer:()=>{o.handleCreateContainer(Re.wsFilename,Re.type==="container"?Re.containerId:null),tt(null)},onAcceptAll:()=>{const j=Su(Re.nodes);j.length&&at(j,"accept"),tt(null)},onRejectAll:()=>{const j=Su(Re.nodes);j.length&&at(j,"reject"),tt(null)},folderAutoAccept:Re.autoAccept,folderAutoAcceptLabel:Re.type==="workspace"?"for workspace":"for container",onToggleFolderAutoAccept:()=>{fetch("/api/auto-accept/inherit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wsFile:Re.wsFilename,...Re.type==="container"?{containerId:Re.containerId}:{},enabled:!Re.autoAccept})}).catch(()=>{})},onRequestSortAll:()=>{const j=Su(Re.nodes);j.length&&We(j)}}),F&&c.jsx(Bd,{x:F.x,y:F.y,filename:F.filename,title:F.title,bulkCount:F.bulkCount,onBulkDelete:ft,onBulkRequestSort:F.bulkCount?()=>We([...$]):void 0,onClose:()=>J(null),onDuplicate:()=>Ct(F.filename),onCreateVariant:F.docId?j=>{fetch("/api/documents/variant",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:F.filename,masterDocId:F.docId,variantType:j})}).catch(()=>{})}:void 0,onRename:()=>{ve("doc",F.filename,F.title),J(null)},onArchive:()=>o.handleArchive(F.filename),onDelete:()=>o.handleDelete(F.filename),onPluginAction:(j,U)=>_t(j,U,F.filename,F.title),pluginItems:V,onSchedulePost:Y?()=>{be({filename:F.filename,title:F.title}),J(null)}:void 0,onPostNow:F.contentType==="blog"?()=>{const j=(je==null?void 0:je.filename)===F.filename;we({filename:F.filename,title:F.title,isActive:j}),J(null)}:void 0,isAlreadyPublished:F.contentType==="blog"&&!!F.postedUrl,onViewAnalytics:F.docId&&F.lastSent&&(F.postedUrl||F.isNewsletter)?()=>{F.isNewsletter?$e({docId:F.docId,title:F.title}):F.postedUrl&&window.open(F.postedUrl,"_blank"),J(null)}:void 0,viewAnalyticsLabel:F.isNewsletter?"View Analytics":F.contentType==="blog"&&F.postedUrl?"View Post":F.postedUrl?"View on X":"View Analytics",isApproved:o.getDocTags(F.filename).includes("✓"),onToggleApprove:()=>{o.getDocTags(F.filename).includes("✓")?o.handleRemoveTag(F.filename,"✓"):(o.handleAddTag(F.filename,"✓"),setTimeout(()=>window.dispatchEvent(new CustomEvent("ow-accept-all")),50))},isAutoAccept:(()=>{var U;const j=(U=t.find(ie=>ie.filename===F.filename))==null?void 0:U.autoAccept;return j===!0?!0:j===!1?!1:Pd(e,F.filename)})(),onToggleAutoAccept:()=>{var ie;const j=(ie=t.find(D=>D.filename===F.filename))==null?void 0:ie.autoAccept,U=j===!0?!0:j===!1?!1:Pd(e,F.filename);fetch("/api/auto-accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:F.filename,enabled:!U})}).then(()=>o.fetchDocs()).catch(()=>{})},isAlreadySent:!!F.lastSent,onMarkSent:()=>{const j=F.filename;o.getDocTags(j).includes("✓")&&o.handleRemoveTag(j,"✓"),s(j),setTimeout(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualPost:{postedAt:new Date().toISOString()}})}).then(()=>o.fetchDocs()).catch(()=>{})},100),J(null)},sortState:F.bulkCount?void 0:(st=F.sortRequest)!=null&&st.proposal?"proposal":F.sortRequest?"pending":"none",sortProposalLabel:(()=>{var fe;const j=(fe=F.sortRequest)==null?void 0:fe.proposal;if(!j)return;const U=e.find(se=>se.filename===j.wsFilename),ie=(U==null?void 0:U.title)||j.wsFilename;if(!j.containerId)return ie;const D=se=>{for(const pe of se){if(pe.type==="container"&&pe.id===j.containerId)return pe.name;if(pe.type==="container"){const ye=D(pe.items);if(ye)return ye}}return null},le=U!=null&&U.workspace?D(U.workspace.root):null;return le?`${ie} / ${le}`:ie})(),sortProposalReasoning:(jt=(Ye=F.sortRequest)==null?void 0:Ye.proposal)==null?void 0:jt.reasoning,onRequestSort:F.bulkCount?void 0:()=>We([F.filename]),onCancelSort:()=>Ge(F.filename),onAcceptSortProposal:()=>vt(F.filename),onRejectSortProposal:()=>Ge(F.filename)}),L&&c.jsx(RT,{actionLabel:L.label,docTitle:L.title,onClose:()=>ee(null),onConfirm:j=>{const U=V.find(ie=>ie.action===L.action);U&&_t(L.action,U,L.filename,L.title,j),ee(null)}}),Ee&&c.jsx(OT,{docId:Ee.docId,title:Ee.title,onClose:()=>$e(null)}),ue&&c.jsx(Ul,{filename:ue.filename,title:ue.title,onClose:()=>be(null)}),re&&c.jsx(LT,{filename:re.filename,title:re.title,isActive:re.isActive,onSwitchDocument:s,onClose:()=>we(null)}),Fe&&c.jsx(IT,{anchorRect:Fe.anchor,onClose:()=>Ze(null),onSelect:j=>{Ze(null),Fe.wsFilename?o.handleCreateInWorkspace(Fe.wsFilename,Fe.containerId??null,j):j?fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:j})}).catch(()=>{}):i()}})]})}const F$=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],z$=[{value:"any",label:"Any"},{value:"content_type",label:"Content Type"},{value:"connection",label:"Connection"}],PT=["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 Ok(t){var e;try{const n=new Date,i=((e=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"short"}).formatToParts(n).find(l=>l.type==="timeZoneName"))==null?void 0:e.value)||"";return`${t.split("/").pop().replace(/_/g," ")} (${i})`}catch{return t}}function U$(t){if(t.length>0)return t[0].timezone;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;if(PT.includes(e))return e}catch{}return"America/New_York"}function H$({slots:t,onBack:e}){const[n,r]=x.useState(t),[s,i]=x.useState(()=>U$(t)),[o,l]=x.useState(!1),[d,f]=x.useState("09:00"),[h,m]=x.useState(["default"]),[g,v]=x.useState("any"),[b,k]=x.useState(!1),w=x.useRef(null);x.useEffect(()=>{if(!o)return;function _(R){w.current&&!w.current.contains(R.target)&&l(!1)}return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[o]);async function S(_){i(_);const R=[];for(const I of n){const P=await fetch(`/api/scheduler/slots/${I.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({timezone:_})});if(P.ok){const B=await P.json();R.push(B.slot)}else R.push(I)}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(I=>[...I,R.slot]),k(!1),f("09:00"),m(["default"]),v("any")}}async function T(_){(await fetch(`/api/scheduler/slots/${_}`,{method:"DELETE"})).ok&&r(I=>I.filter(P=>P.id!==_))}function M(_){m(R=>{if(_==="default")return["default"];const I=R.filter(P=>P!=="default");if(I.includes(_)){const P=I.filter(B=>B!==_);return P.length===0?["default"]:P}return[...I,_]})}return c.jsxs("div",{className:"sidebar-schedule",children:[c.jsxs("div",{className:"sidebar-schedule-header",children:[c.jsx("button",{className:"sidebar-schedule-btn",onClick:e,title:"Back",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"m15 18-6-6 6-6"})})}),c.jsx("h3",{children:"Slot Settings"}),c.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>k(!b),children:b?"Cancel":"+ Add"})]}),c.jsxs("div",{className:"slot-tz",ref:w,children:[c.jsx("label",{className:"slot-tz-label",children:"Timezone"}),c.jsxs("button",{className:"slot-tz-trigger",onClick:()=>l(!o),children:[c.jsx("span",{children:Ok(s)}),c.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:c.jsx("path",{d:"m6 9 6 6 6-6"})})]}),o&&c.jsx("div",{className:"slot-tz-dropdown",children:PT.map(_=>c.jsx("div",{className:`slot-tz-option ${_===s?"active":""}`,onClick:()=>{S(_),l(!1)},children:Ok(_)},_))})]}),b&&c.jsxs("div",{className:"slot-add-form",children:[c.jsxs("div",{className:"slot-add-row",children:[c.jsx("input",{type:"time",className:"slot-input",value:d,onChange:_=>f(_.target.value)}),c.jsx("select",{className:"slot-input",value:g,onChange:_=>v(_.target.value),children:z$.map(_=>c.jsx("option",{value:_.value,children:_.label},_.value))})]}),c.jsxs("div",{className:"slot-add-days",children:[c.jsx("button",{className:`sidebar-schedule-btn slot-day-btn ${h.includes("default")?"sidebar-schedule-btn--active":""}`,onClick:()=>M("default"),children:"Every day"}),F$.map(_=>c.jsx("button",{className:`sidebar-schedule-btn slot-day-btn ${h.includes(_.toLowerCase())?"sidebar-schedule-btn--active":""}`,onClick:()=>M(_.toLowerCase()),children:_},_))]}),c.jsx("button",{className:"sidebar-schedule-btn sidebar-schedule-btn--active slot-create-btn",onClick:N,children:"Create Slot"})]}),c.jsx("div",{className:"slot-list",children:n.length===0?c.jsxs("div",{className:"schedule-empty",children:[c.jsx("div",{className:"schedule-empty-title",children:"No slots"}),c.jsx("div",{className:"schedule-empty-desc",children:"Create time slots to define your posting schedule."})]}):n.map(_=>c.jsxs("div",{className:"schedule-item slot-item",children:[c.jsx("div",{className:"schedule-item-time slot-item-time",children:W$(_.time)}),c.jsxs("div",{className:"schedule-item-content",children:[c.jsx("div",{className:"schedule-item-text",children:_.days.includes("default")?"Every day":_.days.join(", ")}),c.jsxs("div",{className:"schedule-item-meta",children:[c.jsxs("span",{children:["Filter: ",_.filter_type]}),_.filter_value&&c.jsxs("span",{children:["(",_.filter_value,")"]})]})]}),c.jsx("button",{className:"schedule-item-action schedule-item-action--danger slot-delete-btn",onClick:()=>T(_.id),title:"Delete slot",children:"×"})]},_.id))})]})}function W$(t){const[e,n]=t.split(":").map(Number),r=e>=12?"PM":"AM";return`${e%12||12}:${String(n).padStart(2,"0")} ${r}`}function V$({onBack:t}){const[e,n]=x.useState([]),[r,s]=x.useState([]),[i,o]=x.useState(null),[l,d]=x.useState(!1),[f,h]=x.useState(!0),m=x.useCallback(async()=>{try{const[S,N]=await Promise.all([fetch("/api/scheduler/autoplugs/goals"),fetch("/api/scheduler/autoplugs/tracking")]);if(S.ok){const T=await S.json();n(T.goals||[])}if(N.ok){const T=await N.json();s(T.tracking||[])}}catch{}h(!1)},[]);x.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(T=>T.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(T=>T.filter(M=>M.id!==S)),o(null))},b=async S=>{(await fetch(`/api/scheduler/autoplugs/tracking/${S}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({skipped:!0})})).ok&&s(T=>T.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 c.jsxs("div",{className:"sidebar-schedule",children:[c.jsxs("div",{className:"sidebar-schedule-header",children:[c.jsx("button",{className:"sidebar-schedule-back",onClick:t,title:"Back",children:c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"m15 18-6-6 6-6"})})}),c.jsx("h3",{children:"Autoplugs"}),c.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>d(!l),children:l?"Cancel":"+ Add"})]}),l&&c.jsx(K$,{onCreated:S=>{n(N=>[...N,S]),d(!1)}}),f?null:c.jsxs(c.Fragment,{children:[e.length===0?c.jsxs("div",{className:"schedule-empty",children:[c.jsx("div",{className:"schedule-empty-title",children:"No goals"}),c.jsx("div",{className:"schedule-empty-desc",children:"Create a goal to start autoplugging your tweets."})]}):e.map(S=>c.jsxs("div",{children:[c.jsxs("div",{className:"schedule-item",onClick:()=>o(i===S.id?null:S.id),children:[c.jsxs("div",{className:"schedule-item-content",children:[c.jsx("div",{className:"schedule-item-text",children:S.name}),c.jsx("div",{className:"schedule-item-meta",children:q$(S).map((N,T)=>c.jsx("span",{children:N},T))})]}),c.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&&c.jsx(G$,{goal:S,onSaved:N=>{n(T=>T.map(M=>M.id===N.id?N:M))},onDeleted:()=>v(S.id),onRefresh:m})]},S.id)),c.jsx("div",{className:"schedule-day-header",children:"Tracking"}),r.length===0?c.jsxs("div",{className:"schedule-empty",children:[c.jsx("div",{className:"schedule-empty-title",children:"No tracked tweets"}),c.jsx("div",{className:"schedule-empty-desc",children:"Tweets will appear here after posting."})]}):r.map(S=>c.jsxs("div",{className:"schedule-item",children:[c.jsxs("div",{className:"schedule-item-content",children:[c.jsx("div",{className:"schedule-item-text",children:S.original_text||`Tweet ${S.tweet_id}`}),c.jsxs("div",{className:"schedule-item-meta",children:[c.jsx("span",{children:J$(S.posted_at)}),c.jsxs("span",{children:[S.likes," likes"]}),c.jsxs("span",{children:[S.retweets," RTs"]}),S.views>0&&c.jsxs("span",{children:[Y$(S.views)," views"]})]}),S.triggered?c.jsxs("div",{className:"autoplug-tracking-triggered",children:[c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Autoplugged ",S.goal_name?`→ ${S.goal_name}`:""]}):S.skipped?c.jsx("div",{className:"autoplug-tracking-skipped",children:"Skipped"}):c.jsx("div",{className:"autoplug-tracking-bar",children:c.jsx("div",{className:"autoplug-tracking-bar-fill",style:{width:`${Math.min(100,S.likes/w*100)}%`}})})]}),!S.triggered&&!S.skipped&&c.jsx("button",{className:"autoplug-tracking-skip",onClick:()=>b(S.id),title:"Skip autoplug for this tweet",children:"×"})]},S.id))]})]})}function q$(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 K$({onCreated:t}){const[e,n]=x.useState(""),[r,s]=x.useState(""),[i,o]=x.useState(""),[l,d]=x.useState("likes"),[f,h]=x.useState(50),[m,g]=x.useState(30),[v,b]=x.useState("static"),[k,w]=x.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:T}=await N.json();await fetch("/api/scheduler/autoplugs/rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({goal_id:T.id,metric:l,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(I=>I.id===T.id);if(R){t(R);return}}t({...T,rule_count:1,pool_count:0,rule:{metric:l,threshold:f,delay_minutes:m,mode:v,id:""}})}finally{w(!1)}}};return c.jsxs("div",{className:"autoplug-editor",children:[c.jsxs("label",{children:["Name",c.jsx("input",{value:e,onChange:N=>n(N.target.value),placeholder:"Newsletter, Course..."})]}),c.jsxs("label",{children:["Link",c.jsx("input",{value:r,onChange:N=>s(N.target.value),placeholder:"https://..."})]}),c.jsxs("label",{children:["Description (context for LLM)",c.jsx("textarea",{value:i,onChange:N=>o(N.target.value),placeholder:"Weekly engineering insights...",rows:2})]}),c.jsxs("div",{className:"autoplug-editor-row",children:[c.jsx("input",{type:"number",value:f,onChange:N=>h(Number(N.target.value)),min:1}),c.jsxs("select",{value:l,onChange:N=>d(N.target.value),children:[c.jsx("option",{value:"likes",children:"likes"}),c.jsx("option",{value:"retweets",children:"retweets"}),c.jsx("option",{value:"views",children:"views"})]}),c.jsx("span",{className:"autoplug-editor-row-label",children:"wait"}),c.jsx("input",{type:"number",value:m,onChange:N=>g(Number(N.target.value)),min:0,className:"autoplug-delay-input"}),c.jsx("span",{className:"autoplug-editor-row-label",children:"min"})]}),c.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map(N=>c.jsx("button",{className:v===N?"active":"",onClick:()=>b(N),children:N==="llm"?"LLM":N.charAt(0).toUpperCase()+N.slice(1)},N))}),c.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 G$({goal:t,onSaved:e,onDeleted:n,onRefresh:r}){var K,F,J,$;const[s,i]=x.useState(t.name),[o,l]=x.useState(t.link||""),[d,f]=x.useState(t.description||""),[h,m]=x.useState(((K=t.rule)==null?void 0:K.metric)||"likes"),[g,v]=x.useState(((F=t.rule)==null?void 0:F.threshold)||50),[b,k]=x.useState(((J=t.rule)==null?void 0:J.delay_minutes)||30),[w,S]=x.useState((($=t.rule)==null?void 0:$.mode)||"static"),[N,T]=x.useState([]),[M,_]=x.useState(""),[R,I]=x.useState(!1);x.useEffect(()=>{fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`).then(W=>W.json()).then(W=>T(W.pool||[])).catch(()=>{})},[t.id]);const P=async()=>{var W;I(!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})}),(W=t.rule)!=null&&W.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:b,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:b,mode:w})}),r()}finally{I(!1)}},B=async()=>{if(!M.trim())return;const W=await fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:M.trim()})});if(W.ok){const q=await W.json();T(ne=>[...ne,q.message]),_("")}},z=async W=>{(await fetch(`/api/scheduler/autoplugs/pool/${W}`,{method:"DELETE"})).ok&&T(ne=>ne.filter(V=>V.id!==W))};return c.jsxs("div",{className:"autoplug-editor",children:[c.jsxs("label",{children:["Name",c.jsx("input",{value:s,onChange:W=>i(W.target.value)})]}),c.jsxs("label",{children:["Link",c.jsx("input",{value:o,onChange:W=>l(W.target.value),placeholder:"https://..."})]}),c.jsxs("label",{children:["Description",c.jsx("textarea",{value:d,onChange:W=>f(W.target.value),rows:2})]}),c.jsx("div",{className:"autoplug-editor-section-label",children:"Trigger"}),c.jsxs("div",{className:"autoplug-editor-row",children:[c.jsx("input",{type:"number",value:g,onChange:W=>v(Number(W.target.value)),min:1}),c.jsxs("select",{value:h,onChange:W=>m(W.target.value),children:[c.jsx("option",{value:"likes",children:"likes"}),c.jsx("option",{value:"retweets",children:"retweets"}),c.jsx("option",{value:"views",children:"views"})]}),c.jsx("span",{className:"autoplug-editor-row-label",children:"wait"}),c.jsx("input",{type:"number",value:b,onChange:W=>k(Number(W.target.value)),min:0,className:"autoplug-delay-input"}),c.jsx("span",{className:"autoplug-editor-row-label",children:"min"})]}),c.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map(W=>c.jsx("button",{className:w===W?"active":"",onClick:()=>S(W),children:W==="llm"?"LLM":W.charAt(0).toUpperCase()+W.slice(1)},W))}),c.jsxs("div",{className:"autoplug-pool-section",children:[c.jsx("div",{className:"autoplug-editor-section-label",children:"Static Pool"}),N.map(W=>c.jsxs("div",{className:"autoplug-pool-item",children:[c.jsx("span",{children:W.content}),c.jsx("button",{onClick:()=>z(W.id),title:"Remove",children:"×"})]},W.id)),c.jsxs("div",{className:"autoplug-pool-add",children:[c.jsx("input",{value:M,onChange:W=>_(W.target.value),placeholder:"Add message... (use {{link}} for link)",onKeyDown:W=>W.key==="Enter"&&B()}),c.jsx("button",{onClick:B,children:"+"})]})]}),(w==="llm"||w==="hybrid")&&c.jsx("div",{className:"autoplug-llm-hint",children:"LLM mode uses Author's Voice to generate contextual replies referencing the original tweet."}),c.jsxs("div",{className:"autoplug-editor-actions",children:[c.jsx("button",{className:"schedule-item-action",onClick:P,disabled:R,children:R?"Saving...":"Save"}),c.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:n,children:"Delete"})]})]})}function J$(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 Y$(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function X$({onBack:t}){const[e,n]=x.useState([]),[r,s]=x.useState([]),[i,o]=x.useState(!1),[l,d]=x.useState(!1),[f,h]=x.useState(null),[m,g]=x.useState(!0),v=x.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)},[]);x.useEffect(()=>{v()},[v]);const b=async w=>{(await fetch(`/api/scheduler/queue/${w}`,{method:"DELETE"})).ok&&(n(N=>N.filter(T=>T.id!==w)),h(null))};if(l)return c.jsx(V$,{onBack:()=>{d(!1),v()}});if(i)return c.jsx(H$,{slots:r,onBack:()=>{o(!1),v()}});const k=Q$(r,e);return c.jsxs("div",{className:"sidebar-schedule",children:[c.jsxs("div",{className:"sidebar-schedule-header",children:[c.jsx("button",{className:"sidebar-schedule-back",onClick:t,title:"Back to documents",children:c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"m15 18-6-6 6-6"})})}),c.jsx("h3",{children:"Schedule"}),c.jsxs("div",{className:"sidebar-schedule-actions",children:[c.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>d(!0),title:"Autoplugs",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}),c.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>o(!0),title:"Manage slots",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.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"}),c.jsx("circle",{cx:"12",cy:"12",r:"3"})]})})]})]}),m?null:r.length===0?c.jsxs("div",{className:"schedule-empty",children:[c.jsx("div",{className:"schedule-empty-title",children:"No time slots"}),c.jsx("div",{className:"schedule-empty-desc",children:"Create time slots to define your posting schedule."})]}):k.map(({label:w,entries:S})=>c.jsxs("div",{className:"schedule-day",children:[c.jsx("div",{className:"schedule-day-header",children:w}),S.map((N,T)=>{var M,_,R,I,P;return N.type==="empty"?c.jsxs("div",{className:"schedule-slot-empty",children:[c.jsx("div",{className:"schedule-item-time",children:Lk(N.time)}),c.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-${T}`):c.jsxs("div",{children:[c.jsxs("div",{className:"schedule-item",onClick:()=>h(f===N.item.id?null:N.item.id),children:[c.jsx("div",{className:"schedule-item-time",children:Lk(N.time)}),c.jsxs("div",{className:"schedule-item-content",children:[c.jsx("div",{className:"schedule-item-text",children:((I=N.item.content)==null?void 0:I.text)||JSON.stringify(N.item.content)}),c.jsxs("div",{className:"schedule-item-meta",children:[c.jsx("span",{className:`schedule-item-status schedule-item-status--${N.item.status}`}),c.jsx("span",{children:N.item.status}),N.item.connection_name&&c.jsx("span",{children:N.item.connection_name}),N.item.provider&&c.jsx("span",{children:N.item.provider})]})]})]}),f===N.item.id&&c.jsxs("div",{className:"schedule-item-expanded",children:[c.jsx("div",{className:"schedule-item-full-text",children:((P=N.item.content)==null?void 0:P.text)||JSON.stringify(N.item.content,null,2)}),c.jsx("div",{className:"schedule-item-actions",children:c.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:()=>b(N.item.id),children:"Cancel"})})]})]},N.item.id)})]},w))]})}function Q$(t,e){const n=new Date,r=[];for(let l=0;l<7;l++){const d=new Date(n);d.setDate(d.getDate()+l),d.setHours(0,0,0,0);let f;l===0?f="Today":l===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 l of e){const d=new Date(l.scheduled_at),f=`${d.getFullYear()}-${d.getMonth()}-${d.getDate()}-${d.getHours()}-${d.getMinutes()}`;s.set(f,l)}const i=new Set,o=[];for(const{label:l,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),Ik(d,n)&&S<n)continue;const N=`${S.getFullYear()}-${S.getMonth()}-${S.getDate()}-${k}-${w}`,T=s.get(N);T?(f.push({type:"filled",time:S,item:T,slot:v}),i.add(T.id)):f.push({type:"empty",time:S,slot:v})}for(const v of e){if(i.has(v.id))continue;const b=new Date(v.scheduled_at);Ik(b,d)&&(f.push({type:"filled",time:b,item:v}),i.add(v.id))}f.sort((v,b)=>v.time.getTime()-b.time.getTime()),f.length>0&&o.push({label:l,entries:f})}return o}function Ik(t,e){return t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate()}function Lk(t){return t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Z$({onBack:t}){const[e,n]=x.useState([]),[r,s]=x.useState(""),[i,o]=x.useState(null),[l,d]=x.useState(!1),f=x.useRef(null),h=x.useCallback(async()=>{try{const w=await fetch("/api/tasks");if(w.ok){const S=await w.json();n(S.tasks||[])}}catch{}},[]);x.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(T=>[...T,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(T=>T.id!==w))}catch{}},b=()=>{d(!0),setTimeout(()=>{var w;return(w=f.current)==null?void 0:w.focus()},0)},k=e.filter(w=>!w.completed);return c.jsxs("div",{className:"sidebar-tasks",children:[c.jsxs("div",{className:"sidebar-tasks-header",children:[c.jsx("button",{className:"sidebar-tasks-back",onClick:t,title:"Back to documents",children:c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"m15 18-6-6 6-6"})})}),c.jsx("h3",{children:"Tasks"}),c.jsx("button",{className:"sidebar-tasks-add-btn",onClick:b,title:"Add task",children:"+"})]}),k.length===0&&!l?c.jsxs("div",{className:"sidebar-tasks-empty",children:[c.jsx("div",{className:"sidebar-tasks-empty-title",children:"No tasks"}),c.jsx("div",{className:"sidebar-tasks-empty-desc",children:"Add tasks to track your checklist."})]}):c.jsx("div",{className:"sidebar-tasks-list",children:k.map(w=>c.jsxs("div",{className:`sidebar-tasks-item${i===w.id?" completing":""}`,children:[c.jsx("input",{type:"checkbox",className:"sidebar-tasks-checkbox",checked:i===w.id,onChange:()=>g(w.id)}),c.jsx("span",{className:`sidebar-tasks-text${i===w.id?" completed":""}`,children:w.text}),c.jsx("button",{className:"sidebar-tasks-delete",onClick:()=>v(w.id),title:"Remove",children:"×"})]},w.id))}),l&&c.jsx("div",{className:"sidebar-tasks-add",children:c.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 e8({profiles:t,activeProfile:e,trashedProfiles:n,onSwitch:r,onCreate:s,onDelete:i,onRestore:o}){const[l,d]=x.useState(!1),[f,h]=x.useState(!1),[m,g]=x.useState(""),[v,b]=x.useState(null),k=x.useRef(null),w=x.useRef(null);x.useEffect(()=>{if(!l)return;const N=T=>{k.current&&!k.current.contains(T.target)&&(d(!1),h(!1),g(""),b(null))};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[l]),x.useEffect(()=>{f&&w.current&&w.current.focus()},[f]);const S=()=>{const N=m.trim();N&&(s(N),g(""),h(!1))};return c.jsxs("div",{className:"sidebar-profile-wrapper",ref:k,children:[c.jsx("button",{className:"sidebar-collapse-btn",onClick:()=>d(!l),title:`Profile: ${e}`,children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"8",r:"4"}),c.jsx("path",{d:"M5.5 21a8.38 8.38 0 0 1 13 0"})]})}),l&&c.jsxs("div",{className:"sidebar-profile-dropdown",children:[t.map(N=>c.jsxs("div",{className:"sidebar-profile-row",children:[v===N?c.jsxs("div",{className:"sidebar-profile-confirm",children:[c.jsx("span",{children:"Delete?"}),c.jsxs("div",{className:"sidebar-inline-confirm",children:[c.jsx("button",{onClick:()=>{i(N),b(null)},children:"Yes"}),c.jsx("button",{onClick:()=>b(null),children:"No"})]})]}):c.jsx(c.Fragment,{children:c.jsxs("button",{className:`sidebar-profile-option ${N===e?"active":""}`,onClick:()=>{N!==e&&r(N),d(!1)},children:[c.jsx("span",{className:"sidebar-profile-check",children:N===e?"✓":""}),c.jsx("span",{children:N})]})}),N!=="Default"&&N!==e&&v!==N&&c.jsx("button",{className:"sidebar-profile-delete-btn",onClick:T=>{T.stopPropagation(),b(N)},title:"Delete profile",children:"×"})]},N)),n.length>0&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"sidebar-profile-divider"}),c.jsx("div",{className:"sidebar-profile-trash-label",children:"Trash"}),n.map(N=>c.jsxs("div",{className:"sidebar-profile-row sidebar-profile-trashed",children:[c.jsx("span",{className:"sidebar-profile-trash-name",children:N}),c.jsx("button",{className:"sidebar-profile-restore-btn",onClick:()=>o(N),children:"Restore"})]},N))]}),c.jsx("div",{className:"sidebar-profile-divider"}),f?c.jsx("div",{className:"sidebar-profile-add-input",children:c.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..."})}):c.jsxs("button",{className:"sidebar-profile-option sidebar-profile-add",onClick:()=>h(!0),children:[c.jsx("span",{className:"sidebar-profile-check",children:"+"}),c.jsx("span",{children:"New Profile"})]})]})]})}const BT=200,$T=600,nv=260;function Dk({open:t,onSwitchDocument:e,onCreateDocument:n,refreshKey:r,docTagsRefreshKey:s,workspacesRefreshKey:i,pendingDocs:o,writingTitle:l,writingTarget:d,pendingWriteFilenames:f,activeFilename:h,onClose:m,width:g,onWidthChange:v,floating:b}){const{docs:k,setDocs:w,workspaces:S,setWorkspaces:N,assignedFiles:T,fetchDocs:M,fetchWorkspaces:_,scrollRef:R,markPendingDelete:I}=g$(r,i),P=v$(M,_,w,N,k,I),B=$d(),z=x.useRef(!1),K=x.useCallback(at=>{at.preventDefault(),z.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";let De=g;const ve=je=>{z.current&&(De=Math.min($T,Math.max(BT,je.clientX)),v(De))},Z=()=>{z.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("pointermove",ve),window.removeEventListener("pointerup",Z);try{localStorage.setItem("ow-sidebar-width",String(De))}catch{}};window.addEventListener("pointermove",ve),window.addEventListener("pointerup",Z)},[g,v]),F=x.useCallback(at=>{w(De=>De.map(ve=>({...ve,isActive:ve.filename===at}))),e(at)},[w,e]);x.useEffect(()=>{h&&w(at=>at.some(De=>De.filename===h?!De.isActive:De.isActive)?at.map(De=>({...De,isActive:De.filename===h})):at)},[h,w,r]);const[J,$]=x.useState(!1),[W,q]=x.useState(!1),[ne,V]=x.useState([]),[oe,Y]=x.useState("Default"),A=x.useCallback(async()=>{try{const at=await fetch("/api/profiles");if(at.ok){const De=await at.json();V(De.profiles),Y(De.active)}}catch{}},[]);x.useEffect(()=>{A()},[A]);const L=x.useCallback(async at=>{try{(await fetch("/api/profiles/switch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:at})})).ok&&(Y(at),A())}catch{}},[A]),ee=x.useCallback(async at=>{try{(await fetch("/api/profiles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:at})})).ok&&A()}catch{}},[A]),[ue,be]=x.useState([]),re=x.useCallback(async()=>{try{const at=await fetch("/api/profiles/trash");if(at.ok){const De=await at.json();be(De.profiles)}}catch{}},[]);x.useEffect(()=>{re()},[re]);const we=x.useCallback(async at=>{try{(await fetch(`/api/profiles/${encodeURIComponent(at)}`,{method:"DELETE"})).ok&&(A(),re())}catch{}},[A,re]),Ee=x.useCallback(async at=>{try{(await fetch("/api/profiles/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:at})})).ok&&(A(),re())}catch{}},[A,re]),[$e,Fe]=x.useState(""),[Ze,Re]=x.useState(null),tt=x.useRef(),gt=x.useRef(null),ut=x.useCallback(at=>{if(Fe(at),tt.current&&clearTimeout(tt.current),!at.trim()){Re(null);return}tt.current=setTimeout(async()=>{try{const De=await fetch(`/api/documents/search?q=${encodeURIComponent(at.trim())}&archived=true`);De.ok&&Re(await De.json())}catch{}},250)},[]);x.useEffect(()=>()=>{tt.current&&clearTimeout(tt.current)},[]);const ge={docs:k,archivedDocs:[],workspaces:S,assignedFiles:T,pendingDocs:o,writingTitle:l,writingTarget:d,pendingWriteFilenames:f,onSwitchDocument:F,onCreateDocument:n,actions:P,scrollRef:R,searchQuery:$e,searchResults:Ze,onSearchChange:ut},yt=()=>{switch(B){case"files":return c.jsx($$,{...ge});case"timeline":return c.jsx(N$,{...ge});case"board":return c.jsx(C$,{...ge});case"shelf":return c.jsx(_$,{...ge});default:return c.jsx(E$,{...ge})}},Ct=c.jsxs("div",{className:"sidebar-search",children:[c.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:[c.jsx("circle",{cx:"10.5",cy:"10.5",r:"7"}),c.jsx("path",{d:"m20 20-4.5-4.5"})]}),c.jsx("input",{ref:gt,className:"sidebar-search-input",type:"text",placeholder:"Search...",value:$e,onChange:at=>ut(at.target.value)}),$e&&c.jsx("button",{className:"sidebar-search-clear",onClick:()=>ut(""),title:"Clear search",children:"×"})]}),_t=t?{width:`${g}px`,minWidth:`${g}px`}:void 0,Lt=t&&!b?c.jsx("div",{className:"sidebar-resize-handle",onPointerDown:K,onDoubleClick:()=>{v(nv);try{localStorage.setItem("ow-sidebar-width",String(nv))}catch{}},title:"Drag to resize · double-click to reset"}):null;return B==="board"?c.jsxs("div",{className:`sidebar sidebar-board-mode ${t?"open":""}`,style:_t,children:[yt(),Lt]}):c.jsxs("div",{className:`sidebar ${t?"open":""}`,style:_t,children:[c.jsxs("div",{className:"sidebar-topbar",children:[c.jsxs("div",{className:"sidebar-logo",children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[c.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"}),c.jsx("path",{d:"M15 5l4 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),c.jsx("span",{className:"sidebar-logo-text",children:"OpenWriter"})]}),c.jsxs("div",{className:"sidebar-topbar-actions",children:[c.jsx(e8,{profiles:ne,activeProfile:oe,trashedProfiles:ue,onSwitch:L,onCreate:ee,onDelete:we,onRestore:Ee}),c.jsx("button",{className:`sidebar-collapse-btn${J?" sidebar-collapse-btn--active":""}`,onClick:()=>{$(!J),q(!1)},title:"Schedule",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),c.jsx("line",{x1:"16",x2:"16",y1:"1",y2:"5"}),c.jsx("line",{x1:"8",x2:"8",y1:"1",y2:"5"}),c.jsx("line",{x1:"3",x2:"21",y1:"9",y2:"9"})]})}),c.jsx("button",{className:`sidebar-collapse-btn${W?" sidebar-collapse-btn--active":""}`,onClick:()=>{q(!W),$(!1)},title:"Tasks",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),c.jsx("path",{d:"m9 12 2 2 4-4"})]})}),m&&c.jsx("button",{className:"sidebar-collapse-btn",onClick:m,title:"Close sidebar",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",stroke:"currentColor",strokeWidth:"2"}),c.jsx("path",{d:"M9 3v18",stroke:"currentColor",strokeWidth:"2"}),c.jsx("path",{d:"M15 10l-2 2 2 2",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})]}),W?c.jsx(Z$,{onBack:()=>q(!1)}):J?c.jsx(X$,{onBack:()=>$(!1)}):c.jsxs(c.Fragment,{children:[Ct,yt()]}),Lt]})}function dy(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 t8(t,e){const n=Fn(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 n8(t,e){const n=Fn(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 r8(t,e){var o;const n=Fn(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=dy(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function s8(t,e){var o;const n=Fn(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=dy(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function i8(t,e){var o,l;const n=Fn(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=(l=r.attrs)==null?void 0:l.pendingOriginalContent;if(i)t.chain().deleteRange({from:s,to:s+r.nodeSize}).insertContentAt(s,i).run();else{const d=dy(t.state.doc,s,s+r.nodeSize);t.chain().deleteRange(d).run()}return!0}function o8(t,e){var i;const n=Fn(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 a8(t,e){const n=nf(t,e);if(n.length===0)return!1;for(const r of[...n].reverse()){const s=Fn(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 l8(t,e){var l;const n=nf(t,e);if(n.length===0)return!1;const r=(l=n[0].node.attrs)==null?void 0:l.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 FT(t,e){var i,o;const n=Fn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return a8(t,r);switch((o=n.node.attrs)==null?void 0:o.pendingStatus){case"insert":return t8(t,e);case"rewrite":return n8(t,e);case"delete":return r8(t,e);default:return!1}}function zT(t,e){var i,o;const n=Fn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return l8(t,r);switch((o=n.node.attrs)==null?void 0:o.pendingStatus){case"insert":return s8(t,e);case"rewrite":return i8(t,e);case"delete":return o8(t,e);default:return!1}}function c8(t){const e=UT(t).reverse();for(const n of e)FT(t,n);t.view&&ly(t.view)}function u8(t){const e=UT(t).reverse();for(const n of e)zT(t,n);t.view&&ly(t.view)}function fy(t){const e=[],n=new Set;return t.state.doc.descendants((r,s)=>{var o,l,d;const i=(o=r.attrs)==null?void 0:o.pendingStatus;if(i&&((l=r.attrs)!=null&&l.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(...fy(n));return e}function UT(t){return fy(t).map(e=>e.nodeId)}function d8(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 tl(t,e){if(t.isDestroyed)return;let n=-1;if(t.state.doc.descendants((i,o)=>{var l;return((l=i.attrs)==null?void 0:l.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 l=o.getBoundingClientRect(),d=i.top-l.top+o.scrollTop-o.clientHeight/2;o.scrollTo({top:d,behavior:"smooth"})}}catch{}}function f8(t){const[e,n]=x.useState([]),[r,s]=x.useState(0),i=x.useRef(),o=x.useRef(new Set),l=x.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 T=o.current,M=new Set(N.map(R=>R.nodeId));let _=-1;if(T.size>0){for(let R=0;R<N.length;R++)if(!T.has(N[R].nodeId)){_=R;break}}o.current=M,_>=0?(s(_),tl(N[_].editor,N[_].nodeId)):N.length===0?s(0):s(R=>Math.min(R,N.length-1))},[t]);x.useEffect(()=>{const S=t.filter(M=>M&&!M.isDestroyed);if(S.length===0)return;const N=()=>{clearTimeout(i.current),i.current=setTimeout(l,50)};for(const M of S)M.on("transaction",N);l();const T=setTimeout(()=>{const M=Pp(S.filter(_=>!_.isDestroyed));M.length>0&&tl(M[0].editor,M[0].nodeId)},150);return()=>{for(const M of S)M.isDestroyed||M.off("transaction",N);clearTimeout(i.current),clearTimeout(T)}},[t,l]),x.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&&ly(S.editor.view),()=>{lk(null)}},[r,e]);const d=d8(e),f=e[r]??null,h=x.useCallback(()=>{if(e.length===0)return;const S=(r+1)%e.length;s(S),e[S]&&tl(e[S].editor,e[S].nodeId)},[e,r]),m=x.useCallback(()=>{if(e.length===0)return;const S=(r-1+e.length)%e.length;s(S),e[S]&&tl(e[S].editor,e[S].nodeId)},[e,r]),g=x.useCallback(()=>{const S=t.filter(M=>M&&!M.isDestroyed),N=Pp(S);if(N.length===0)return;const T=Math.min(r,N.length-1);tl(N[T].editor,N[T].nodeId)},[t,r]),v=x.useCallback(()=>{f&&(FT(f.editor,f.nodeId),l(),g())},[f,l,g]),b=x.useCallback(()=>{f&&(zT(f.editor,f.nodeId),l(),g())},[f,l,g]),k=x.useCallback(()=>{const S=t.filter(N=>N&&!N.isDestroyed);for(const N of S)c8(N);l()},[t,l]),w=x.useCallback(()=>{const S=t.filter(N=>N&&!N.isDestroyed);for(const N of S)u8(N);l()},[t,l]);return{pendingNodes:e,counts:d,currentNode:f,currentIndex:r,hasPending:d.total>0,goToNext:h,goToPrevious:m,acceptCurrent:v,rejectCurrent:b,acceptAll:k,rejectAll:w,refresh:l}}const HT="ow-review-scope";function h8(){try{return localStorage.getItem(HT)==="workspace"?"workspace":"all"}catch{return"all"}}function p8(t){try{localStorage.setItem(HT,t)}catch{}}function WT(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(...WT(n.items));return e}function VT(t,e){if(!t)return!1;for(const n of t)if(n.type==="doc"&&n.file===e||n.type==="container"&&n.items&&VT(n.items,e))return!0;return!1}const Ri={strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},m8=()=>c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:c.jsx("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",...Ri})}),g8=()=>c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:c.jsx("path",{d:"M6 3l5 5-5 5",stroke:"currentColor",...Ri})}),v8=()=>c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:c.jsx("path",{d:"M3 10l5-5 5 5",stroke:"currentColor",...Ri})}),y8=()=>c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:c.jsx("path",{d:"M3 6l5 5 5-5",stroke:"currentColor",...Ri})}),b8=()=>c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:c.jsx("path",{d:"M3 8.5l3.5 3.5L13 5",stroke:"currentColor",...Ri})}),x8=()=>c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[c.jsx("path",{d:"M1 8.5l3.5 3.5L11 5",stroke:"currentColor",...Ri}),c.jsx("path",{d:"M8 12l.5.5L15 6",stroke:"currentColor",...Ri})]}),Pk=()=>c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:c.jsx("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor",...Ri})});function qT(t,e,n){const r=Fn(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:l})=>(l.setMeta("addToHistory",!1),!0)).deleteRange({from:s,to:s+i.nodeSize}).insertContentAt(s,o).run(),!0}catch{return!1}}function KT(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 Eu(t,e){if(!ay()||!e)return!1;const n=w5();return x5()&&n&&Array.isArray(n)?KT(t,e,n):n&&qT(t,e,n),al(!1),!0}function w8(t,e){return t.indexOf(e)}function k8({editors:t,pendingDocs:e,currentFilename:n,docId:r,pendingTitle:s,onSwitchDocument:i,sendMessage:o,getDocument:l,docVersionRef:d}){const{counts:f,currentNode:h,currentIndex:m,hasPending:g,goToNext:v,goToPrevious:b,acceptCurrent:k,rejectCurrent:w,acceptAll:S,rejectAll:N}=f8(t),[T,M]=x.useState(s?"title":"body");x.useEffect(()=>{s&&T!=="title"&&f.total===0?M("title"):!s&&T==="title"&&M("body")},[s,f.total,T]);const _=!!s,R=f.total+(_?1:0),I=T==="title"?0:(_?1:0)+m,[P,B]=x.useState(!1);x.useEffect(()=>{T!=="title"&&B(!1)},[T]),x.useEffect(()=>{const De=!!s&&T==="title",ve={docId:r,titleFocused:De,titleShowOriginal:De&&P};return window.dispatchEvent(new CustomEvent("ow-pending-review-cursor",{detail:ve})),()=>{window.dispatchEvent(new CustomEvent("ow-pending-review-cursor",{detail:{docId:r,titleFocused:!1,titleShowOriginal:!1}}))}},[r,s,T,P]);const z=x.useCallback(()=>{r&&o({type:"accept-pending-title",docId:r})},[r,o]),K=x.useCallback(()=>{r&&o({type:"reject-pending-title",docId:r})},[r,o]),F=x.useRef(null),J=x.useRef(null),[$,W]=x.useState(()=>h8()),[q,ne]=x.useState([]);x.useEffect(()=>{let De=!1;async function ve(){try{const Q=await(await fetch("/api/workspaces")).json();if(!Array.isArray(Q))return;const he=await Promise.all(Q.map(async me=>{try{const Oe=await(await fetch(`/api/workspaces/${encodeURIComponent(me.filename)}`)).json();return{...me,workspace:Oe}}catch{return me}}));De||ne(he)}catch{}}ve();const Z=()=>ve();return window.addEventListener("ow-workspaces-changed",Z),()=>{De=!0,window.removeEventListener("ow-workspaces-changed",Z)}},[]);const V=x.useMemo(()=>{var ve;if(q.length===0||!n)return null;const De=q.find(Z=>{var je;return VT((je=Z.workspace)==null?void 0:je.root,n)});return De?new Set(WT((ve=De.workspace)==null?void 0:ve.root)):null},[q,n]),oe=x.useMemo(()=>$==="all"||!V?e.filenames:e.filenames.filter(De=>V.has(De)),[$,e.filenames,V]),Y=x.useCallback(De=>{W(De),p8(De)},[]),A=oe.length,L=w8(oe,n),ee=(h==null?void 0:h.pendingStatus)==="rewrite",ue=!!(h!=null&&h.groupId),be=ee,re=x.useCallback(()=>{var ve,Z;const De=h==null?void 0:h.editor;if(!(!De||!h||h.pendingStatus!=="rewrite"))if(P)J.current&&Eu(J.current,F.current),F.current=null,J.current=null,B(!1);else if(ue&&h.groupId){const je=nf(De,h.groupId);if(je.length===0)return;const Q=(ve=je[0].node.attrs)==null?void 0:ve.pendingOriginalContent;if(!Q||!Array.isArray(Q))return;const he=je.map(Oe=>Oe.node.toJSON()),me=Q.map((Oe,Ve)=>({...Oe,attrs:{...Oe.attrs||{},pendingStatus:"rewrite",pendingGroupId:h.groupId,...Ve===0?{pendingOriginalContent:Q}:{}}}));if(al(!0,h.nodeId,he,h.groupId),!KT(De,h.groupId,me)){al(!1);return}F.current=h.nodeId,J.current=De,B(!0)}else{const je=Fn(De,h.nodeId);if(!je)return;const{node:Q}=je,he=(Z=Q.attrs)==null?void 0:Z.pendingOriginalContent;if(!he)return;const me=Q.toJSON();if(al(!0,h.nodeId,me),!qT(De,h.nodeId,he)){al(!1);return}F.current=h.nodeId,J.current=De,B(!0)}},[h,P,ue]);x.useEffect(()=>{if(!P)return;const De=F.current,ve=J.current;De&&ve&&(h==null?void 0:h.nodeId)!==De&&(Eu(ve,De),F.current=null,J.current=null,B(!1))},[h==null?void 0:h.nodeId,P]),x.useEffect(()=>{if(t.length!==0)return()=>{ay()&&F.current&&J.current&&(Eu(J.current,F.current),F.current=null,J.current=null)}},[t]);const we=x.useCallback(De=>{if(!n)return;if(!t.some(Z=>!Z||Z.isDestroyed?!1:fy(Z).length>0)){const Z=l==null?void 0:l();Z&&o({type:"doc-update",document:Z,filename:n,version:(d==null?void 0:d.current)??0}),o({type:"pending-resolved",filename:n,action:De})}},[t,n,o,l,d]),Ee=x.useCallback(()=>{J.current&&P&&F.current&&(Eu(J.current,F.current),F.current=null,J.current=null,B(!1))},[P]),$e=x.useCallback(()=>{if(T==="title"&&s){z(),f.total>0&&M("body");return}Ee(),k(),we("accept")},[T,s,z,f.total,Ee,k,we]),Fe=x.useCallback(()=>{if(T==="title"&&s){K(),f.total>0&&M("body");return}Ee(),w(),we("reject")},[T,s,K,f.total,Ee,w,we]),Ze=x.useCallback(()=>{Ee(),s&&z(),S(),we("accept")},[Ee,s,z,S,we]);x.useEffect(()=>{const De=()=>Ze();return window.addEventListener("ow-accept-all",De),()=>window.removeEventListener("ow-accept-all",De)},[Ze]);const Re=x.useCallback(()=>{Ee(),s&&K(),N(),we("reject")},[Ee,s,K,N,we]),tt=x.useCallback(()=>{if(!(R<=1)){if(T==="title"){M("body");return}if(_&&m>=f.total-1){v(),M("title");return}v()}},[R,T,_,m,f.total,v]),gt=x.useCallback(()=>{if(!(R<=1)){if(T==="title"){b(),M("body");return}if(_&&m===0){M("title");return}b()}},[R,T,_,m,b]),ut=x.useCallback(()=>{if(A===0||A===1&&L===0)return;const De=L<=0?A-1:L-1;i(oe[De])},[A,L,oe,i]),ge=x.useCallback(()=>{if(A===0||A===1&&L===0)return;const De=L>=A-1?0:L+1;i(oe[De])},[A,L,oe,i]);x.useEffect(()=>{if(!g&&!s)return;const De=ve=>{if(!(ve.target instanceof HTMLInputElement||ve.target instanceof HTMLTextAreaElement)&&!(ve.target instanceof HTMLElement&&ve.target.closest("[contenteditable]")))switch(ve.key){case"j":case"ArrowDown":!ve.metaKey&&!ve.ctrlKey&&(ve.preventDefault(),tt());break;case"k":case"ArrowUp":!ve.metaKey&&!ve.ctrlKey&&(ve.preventDefault(),gt());break;case"h":case"ArrowLeft":!ve.metaKey&&!ve.ctrlKey&&!ve.altKey&&(ve.preventDefault(),ut());break;case"l":case"ArrowRight":!ve.metaKey&&!ve.ctrlKey&&!ve.altKey&&(ve.preventDefault(),ge());break;case"a":!ve.metaKey&&!ve.ctrlKey&&!ve.shiftKey&&(ve.preventDefault(),$e());break;case"r":!ve.metaKey&&!ve.ctrlKey&&(ve.preventDefault(),Fe());break;case"A":ve.shiftKey&&!ve.metaKey&&!ve.ctrlKey&&(ve.preventDefault(),Ze());break;case"R":ve.shiftKey&&!ve.metaKey&&!ve.ctrlKey&&(ve.preventDefault(),Re());break;case"o":!ve.metaKey&&!ve.ctrlKey&&!ve.shiftKey&&(ve.preventDefault(),T==="title"?B(Z=>!Z):re());break}};return window.addEventListener("keydown",De),()=>window.removeEventListener("keydown",De)},[g,s,tt,gt,ut,ge,$e,Fe,Ze,Re,re]);const yt=L>=0?`${L+1} / ${A}`:`— / ${A}`,Ct=e.filenames.length,_t=!V,at=Ct>0?c.jsxs("div",{className:"review-tab__section",children:[c.jsx("div",{className:"review-tab__section-label",children:"Scope"}),c.jsxs("div",{className:"review-tab__toggle",children:[c.jsx("button",{type:"button",className:`review-panel__toggle-btn${$==="all"?" review-panel__toggle-btn--active":""}`,onClick:()=>Y("all"),title:"Cycle every pending doc in the profile",children:"All"}),c.jsx("button",{type:"button",className:`review-panel__toggle-btn${$==="workspace"?" review-panel__toggle-btn--active":""}`,onClick:()=>!_t&&Y("workspace"),disabled:_t,title:_t?"Current doc is not in a workspace":"Only cycle pending docs in this workspace",children:"Workspace"})]})]}):null;return!g&&!s?c.jsxs("div",{className:"review-tab__empty",children:[c.jsx("div",{className:"review-tab__empty-title",children:"All caught up"}),c.jsx("div",{className:"review-tab__empty-note",children:"No pending agent changes. New writes from agents will land here for review."})]}):c.jsxs("div",{className:"review-tab",children:[at,A>1&&c.jsxs("div",{className:"review-tab__section",children:[c.jsx("div",{className:"review-tab__section-label",children:"Document"}),c.jsxs("div",{className:"review-tab__row",children:[c.jsx("button",{className:"review-panel__btn",onClick:ut,title:"Previous doc (h)",children:c.jsx(m8,{})}),c.jsx("button",{className:"review-panel__btn",onClick:ge,title:"Next doc (l)",children:c.jsx(g8,{})}),c.jsx("span",{className:"review-panel__counter",children:yt})]})]}),c.jsx("div",{className:"review-tab__section review-tab__section--actions",children:c.jsxs("div",{className:"review-tab__toggle",children:[c.jsx("button",{className:`review-panel__toggle-btn${(be||T==="title")&&!P?" review-panel__toggle-btn--active":""}`,onClick:()=>{T==="title"?P&&B(!1):be&&P&&re()},disabled:!be&&T!=="title",title:"Show modified (o)",children:"Modified"}),c.jsx("button",{className:`review-panel__toggle-btn${(be||T==="title")&&P?" review-panel__toggle-btn--active":""}`,onClick:()=>{T==="title"?P||B(!0):be&&!P&&re()},disabled:!be&&T!=="title",title:"Show original (o)",children:"Original"})]})}),c.jsxs("div",{className:"review-tab__section",children:[c.jsx("div",{className:"review-tab__section-label",children:T==="title"?"Title":"Change"}),c.jsxs("div",{className:"review-tab__row",children:[c.jsx("button",{className:"review-panel__btn",onClick:gt,disabled:R<=1,title:"Previous (k)",children:c.jsx(v8,{})}),c.jsx("button",{className:"review-panel__btn",onClick:tt,disabled:R<=1,title:"Next (j)",children:c.jsx(y8,{})}),c.jsxs("span",{className:"review-panel__counter",children:[I+1," / ",R]})]})]}),c.jsx("div",{className:"review-tab__section",children:c.jsxs("div",{className:"review-tab__row",children:[c.jsxs("button",{className:"review-tab__judge-btn review-tab__judge-btn--accept",onClick:$e,title:"Accept (a)",children:[c.jsx(b8,{}),c.jsx("span",{children:"Accept"})]}),c.jsxs("button",{className:"review-tab__judge-btn review-tab__judge-btn--reject",onClick:Fe,title:"Reject (r)",children:[c.jsx(Pk,{}),c.jsx("span",{children:"Reject"})]})]})}),c.jsx("div",{className:"review-tab__section",children:c.jsxs("div",{className:"review-tab__row",children:[c.jsxs("button",{className:"review-tab__bulk-btn review-tab__bulk-btn--accept",onClick:Ze,title:"Accept all (Shift+A)",children:[c.jsx(x8,{}),c.jsx("span",{children:"Accept all"})]}),c.jsxs("button",{className:"review-tab__bulk-btn review-tab__bulk-btn--reject",onClick:Re,title:"Reject all (Shift+R)",children:[c.jsx(Pk,{}),c.jsx("span",{children:"Reject all"})]})]})})]})}function S8(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 E8(t){return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function N8({currentFilename:t}){const[e,n]=x.useState([]),[r,s]=x.useState(null),[i,o]=x.useState(!1),l=x.useCallback(()=>{fetch("/api/versions").then(f=>f.json()).then(f=>{n(Array.isArray(f)?f:[]),s(null)}).catch(()=>n([]))},[]);x.useEffect(()=>{l()},[t,l]);const d=x.useCallback(async f=>{if(r!==null){o(!0);try{(await fetch(`/api/versions/${r}/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:f})})).ok&&l()}catch{}o(!1)}},[r,l]);return c.jsxs("div",{className:"versions-tab",children:[c.jsx("div",{className:"versions-tab__list",children:e.length===0?c.jsx("div",{className:"versions-tab__empty",children:"No versions yet. Versions are created automatically when you save."}):e.map(f=>c.jsxs("div",{className:`versions-tab__item${r===f.timestamp?" versions-tab__item--selected":""}`,onClick:()=>s(f.timestamp===r?null:f.timestamp),children:[c.jsx("span",{className:"versions-tab__item-time",children:S8(f.timestamp)}),c.jsxs("span",{className:"versions-tab__item-meta",children:[f.wordCount.toLocaleString()," words · ",E8(f.size)]})]},f.timestamp))}),e.length>0&&c.jsxs("div",{className:"versions-tab__footer",children:[c.jsx("button",{className:"versions-tab__review-btn",disabled:r===null||i,onClick:()=>d("review"),children:"Review"}),c.jsx("button",{className:"versions-tab__restore-btn",disabled:r===null||i,onClick:()=>d("full"),children:"Restore"})]})]})}function C8({docId:t,currentFilename:e,onSwitchDocument:n}){const[r,s]=x.useState(new Map),[i,o]=x.useState([]),[l,d]=x.useState([]),[f,h]=x.useState(!0),[m,g]=x.useState(!1);x.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)}},[]),x.useEffect(()=>{if(!t){o([]);return}let w=!1;const S=()=>{g(!0),fetch(`/api/backlinks/${t}`).then(T=>T.ok?T.json():[]).then(T=>{w||o(Array.isArray(T)?T:[])}).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]),x.useEffect(()=>{let w=!1;const S=()=>{fetch("/api/document").then(T=>T.json()).then(T=>{var _;if(w)return;const M=(_=T==null?void 0:T.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=x.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]),b=x.useMemo(()=>l.map(w=>{const S=r.get(w);return S?{docId:w,title:S.title,filename:S.filename}:null}).filter(w=>w!==null),[l,r]);if(!t)return c.jsxs("div",{className:"backlinks-tab__empty",children:[c.jsx("div",{className:"backlinks-tab__empty-title",children:"No document open"}),c.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 c.jsxs("div",{className:"backlinks-tab",children:[c.jsxs("div",{className:"backlinks-tab__group",children:[c.jsxs("div",{className:"backlinks-tab__group-label",children:["Inbound ",c.jsx("span",{className:"backlinks-tab__count",children:v.length})]}),k&&v.length===0?c.jsx("div",{className:"backlinks-tab__empty-note backlinks-tab__inline-note",children:"Loading…"}):v.length===0?c.jsx("div",{className:"backlinks-tab__empty-note backlinks-tab__inline-note",children:"No docs link to this one yet."}):v.map(w=>c.jsxs("button",{type:"button",className:"backlinks-tab__entry",onClick:()=>n(w.filename),children:[c.jsx("div",{className:"backlinks-tab__entry-title",children:w.title}),w.snippet&&c.jsx("div",{className:"backlinks-tab__entry-snippet",children:w.snippet})]},w.docId))]}),c.jsxs("div",{className:"backlinks-tab__group",children:[c.jsxs("div",{className:"backlinks-tab__group-label",children:["Outbound ",c.jsx("span",{className:"backlinks-tab__count",children:b.length})]}),b.length===0?c.jsx("div",{className:"backlinks-tab__empty-note backlinks-tab__inline-note",children:"This doc doesn’t reference others yet."}):b.map(w=>c.jsx("button",{type:"button",className:"backlinks-tab__entry",onClick:()=>n(w.filename),children:c.jsx("div",{className:"backlinks-tab__entry-title",children:w.title})},w.docId))]})]})}const _8=[{key:"md",label:"Markdown",desc:"Plain .md file",icon:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),c.jsx("path",{d:"M14 2v6h6"})]})},{key:"html",label:"HTML",desc:"Styled web page",icon:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"16 18 22 12 16 6"}),c.jsx("polyline",{points:"8 6 2 12 8 18"})]})},{key:"docx",label:"Word",desc:"Microsoft Word .docx",icon:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),c.jsx("path",{d:"M14 2v6h6"}),c.jsx("path",{d:"M16 13H8"}),c.jsx("path",{d:"M16 17H8"}),c.jsx("path",{d:"M10 9H8"})]})},{key:"txt",label:"Plain Text",desc:"Unformatted .txt file",icon:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 6.1H3"}),c.jsx("path",{d:"M21 12.1H3"}),c.jsx("path",{d:"M15.1 18H3"})]})},{key:"pdf",label:"PDF",desc:"Print preview for save as PDF",icon:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"6 9 6 2 18 2 18 9"}),c.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"}),c.jsx("rect",{x:"6",y:"14",width:"12",height:"8"})]})}];function T8(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 c.jsx("div",{className:"exports-tab",children:c.jsx("div",{className:"exports-tab__list",children:_8.map(n=>c.jsxs("button",{type:"button",className:"exports-tab__item",onClick:()=>e(n.key),children:[c.jsx("span",{className:"exports-tab__item-icon",children:n.icon}),c.jsxs("span",{className:"exports-tab__item-text",children:[c.jsx("span",{className:"exports-tab__item-label",children:n.label}),c.jsx("span",{className:"exports-tab__item-desc",children:n.desc})]})]},n.key))})})}const j8=3e4,M8=500;let xi={entries:[],freshKeys:new Set};const rv=new Set;function GT(t){return`${t.ts}:${t.kind}:${t.headline}`}function A8(){for(const t of rv)t(xi)}function sv(t){xi=t,A8()}function R8(t){return rv.add(t),()=>{rv.delete(t)}}function O8(){return xi}function I8(t){const e=t.detail;e!=null&&e.entries&&sv({entries:e.entries,freshKeys:new Set})}function L8(t){const e=t.detail;if(!(e!=null&&e.event))return;const n=e.event,r=GT(n),s={entries:[n,...xi.entries].slice(0,M8),freshKeys:new Set([...xi.freshKeys,r])};sv(s),window.setTimeout(()=>{if(xi.freshKeys.has(r)){const i=new Set(xi.freshKeys);i.delete(r),sv({...xi,freshKeys:i})}},j8)}typeof window<"u"&&(window.addEventListener("ow-activity-seed",I8),window.addEventListener("ow-activity-event",L8));function D8(){const[t,e]=x.useState(O8);return x.useEffect(()=>R8(e),[]),t}function P8(){const[t,e]=x.useState(()=>({byDocId:new Map,filenameSet:new Set}));return x.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 l of s)l.filename&&o.add(l.filename),l.docId&&l.filename&&i.set(l.docId,l.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 B8(t,e){return t.docId?e.byDocId.get(t.docId)??null:t.filename&&e.filenameSet.has(t.filename)?t.filename:null}function $8(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 F8({onSwitchDocument:t}){const{entries:e,freshKeys:n}=D8(),r=P8(),[s,i]=x.useState(()=>Date.now());x.useEffect(()=>{const l=setInterval(()=>i(Date.now()),3e4);return()=>clearInterval(l)},[]);const o=x.useMemo(()=>z8(e,s),[e,s]);return e.length===0?c.jsxs("div",{className:"activity-tab__empty",children:[c.jsx("div",{className:"activity-tab__empty-title",children:"No activity yet"}),c.jsx("div",{className:"activity-tab__empty-note",children:"Agent actions — writes, enrichment, backlink propagation — will appear here as they happen."})]}):c.jsx("div",{className:"activity-tab",children:o.map(l=>c.jsxs("div",{className:"activity-tab__group",children:[c.jsx("div",{className:"activity-tab__group-label",children:l.label}),l.entries.map(d=>{const f=GT(d),h=n.has(f),m=d.kind==="doc-deleted"?null:B8(d,r),g=m!==null,v=!g,b=v&&d.kind!=="doc-deleted"?"Doc no longer available":void 0,k=()=>{m&&t(m)};return c.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:b,onClick:k,onKeyDown:w=>{g&&(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),k())},children:[c.jsx("span",{className:`activity-tab__kind-dot activity-tab__kind-dot--${d.kind}`,"aria-hidden":"true"}),c.jsxs("div",{className:"activity-tab__entry-body",children:[c.jsx("div",{className:"activity-tab__headline",children:d.headline}),d.detail&&c.jsx("div",{className:"activity-tab__detail",children:d.detail})]}),c.jsx("div",{className:"activity-tab__ts",title:new Date(d.ts).toLocaleString(),children:$8(d.ts,s)})]},f)})]},l.label))})}function z8(t,e){if(t.length===0)return[];const n=Bk(e),r=n-1440*60*1e3,s=[];let i=null;for(const o of t){const l=Bk(o.ts);let d;l===n?d="Today":l===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 Bk(t){const e=new Date(t);return e.setHours(0,0,0,0),e.getTime()}async function Nu(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 U8(){const[t,e]=x.useState([]),[n,r]=x.useState(!0),[s,i]=x.useState("closed"),[o,l]=x.useState(""),[d,f]=x.useState(!1),[h,m]=x.useState(null),[g,v]=x.useState(null),[b,k]=x.useState(null),w=x.useCallback(async()=>{r(!0);try{const _=await Nu("list_blog_sites");e((_==null?void 0:_.sites)||[])}finally{r(!1)}},[]);x.useEffect(()=>{w()},[w]);const S=()=>{i("closed"),l(""),m(null),v(null),k(null)},N=async()=>{if(o.trim()){f(!0),m(null);try{const _=await Nu("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)}}},T=async()=>{if(g){i("saving"),k(null);try{const _=await Nu("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
|
-
This only removes the OpenWriter registration. Your GitHub repo is untouched.`))return;const I=await Nu("remove_blog_site",{id:_.id});if(I!=null&&I.error){alert(`Remove failed: ${I.error}`);return}await w()};return c.jsxs("div",{className:"github-plugin-settings",children:[c.jsxs("div",{className:"github-plugin-settings__header",children:[c.jsx("span",{className:"github-plugin-settings__title",children:"Blog repos"}),s==="closed"&&c.jsx("button",{className:"github-plugin-settings__add-btn",onClick:()=>i("url"),children:"+ Add"})]}),n?c.jsx("div",{className:"github-plugin-settings__loading",children:"Loading…"}):t.length===0&&s==="closed"?c.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 ",c.jsx("code",{children:"gh auth login"}),"."]}):c.jsx("div",{className:"github-plugin-settings__list",children:t.map(_=>c.jsxs("div",{className:"github-plugin-settings__site",children:[c.jsxs("div",{className:"github-plugin-settings__site-info",children:[c.jsxs("div",{className:"github-plugin-settings__site-row1",children:[c.jsx("span",{className:"github-plugin-settings__site-label",children:_.label}),c.jsx("span",{className:`github-plugin-settings__site-framework github-plugin-settings__site-framework--${_.framework}`,children:_.framework})]}),c.jsxs("div",{className:"github-plugin-settings__site-repo",children:[_.owner,"/",_.repo,"@",_.branch]}),c.jsxs("div",{className:"github-plugin-settings__site-dirs",children:[c.jsx("span",{title:"content_dir",children:_.content_dir}),c.jsx("span",{className:"github-plugin-settings__site-sep",children:"·"}),c.jsx("span",{title:"image_public_prefix",children:_.image_public_prefix})]})]}),c.jsx("button",{className:"github-plugin-settings__remove-btn",onClick:()=>M(_),title:"Remove",children:"×"})]},_.id))}),s==="url"&&c.jsxs("div",{className:"github-plugin-settings__form",children:[c.jsx("label",{className:"github-plugin-settings__label",children:"GitHub repo"}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",placeholder:"owner/repo or https://github.com/owner/repo",value:o,onChange:_=>l(_.target.value),onKeyDown:_=>{_.key==="Enter"&&!d&&N()},autoFocus:!0}),h&&c.jsx("div",{className:"github-plugin-settings__error",children:h}),c.jsxs("div",{className:"github-plugin-settings__form-buttons",children:[c.jsx("button",{className:"github-plugin-settings__btn github-plugin-settings__btn--primary",onClick:N,disabled:d||!o.trim(),children:d?"Inspecting…":"Inspect"}),c.jsx("button",{className:"github-plugin-settings__btn",onClick:S,disabled:d,children:"Cancel"})]})]}),(s==="review"||s==="saving")&&g&&c.jsxs("div",{className:"github-plugin-settings__form",children:[c.jsxs("div",{className:"github-plugin-settings__form-meta",children:[c.jsxs("span",{children:["Detected: ",g.framework]}),c.jsx("span",{children:"·"}),c.jsxs("span",{children:[g.markdown_files_found," posts"]}),c.jsx("span",{children:"·"}),c.jsxs("span",{className:`github-plugin-settings__confidence github-plugin-settings__confidence--${g.confidence}`,children:[g.confidence," confidence"]})]}),c.jsx("label",{className:"github-plugin-settings__label",children:"Label"}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.label,onChange:_=>v({...g,label:_.target.value})}),c.jsx("label",{className:"github-plugin-settings__label",children:"Branch"}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.branch,onChange:_=>v({...g,branch:_.target.value})}),c.jsx("label",{className:"github-plugin-settings__label",children:"Content directory"}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.content_dir,onChange:_=>v({...g,content_dir:_.target.value})}),c.jsx("label",{className:"github-plugin-settings__label",children:"Image directory"}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.image_dir,onChange:_=>v({...g,image_dir:_.target.value})}),c.jsx("label",{className:"github-plugin-settings__label",children:"Image public prefix"}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.image_public_prefix,onChange:_=>v({...g,image_public_prefix:_.target.value})}),c.jsxs("label",{className:"github-plugin-settings__label",children:["Site URL ",c.jsx("span",{className:"github-plugin-settings__hint",children:"— optional, used for the live link after publish"})]}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",placeholder:"https://example.com",value:g.site_url||"",onChange:_=>v({...g,site_url:_.target.value})}),c.jsxs("label",{className:"github-plugin-settings__label",children:["Blog URL pattern ",c.jsxs("span",{className:"github-plugin-settings__hint",children:["— uses ","{slug}"," placeholder"]})]}),c.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})}),c.jsx("label",{className:"github-plugin-settings__label",children:"Framework"}),c.jsxs("select",{className:"github-plugin-settings__input",value:g.framework,onChange:_=>v({...g,framework:_.target.value}),children:[c.jsx("option",{value:"astro",children:"Astro"}),c.jsx("option",{value:"next",children:"Next"}),c.jsx("option",{value:"jekyll",children:"Jekyll"}),c.jsx("option",{value:"hugo",children:"Hugo"}),c.jsx("option",{value:"unknown",children:"Unknown"})]}),g.frontmatter_schema.length>0&&c.jsxs("div",{className:"github-plugin-settings__schema",children:[c.jsxs("span",{className:"github-plugin-settings__label",children:["Frontmatter keys detected (",g.samples_analyzed," ",g.samples_analyzed===1?"sample":"samples",")"]}),c.jsx("code",{children:g.frontmatter_schema.join(", ")})]}),Object.keys(g.frontmatter_defaults||{}).length>0&&c.jsxs("div",{className:"github-plugin-settings__schema",children:[c.jsx("span",{className:"github-plugin-settings__label",children:"Frontmatter defaults (constants applied to every post)"}),c.jsx("code",{children:Object.entries(g.frontmatter_defaults).map(([_,R])=>c.jsxs("div",{children:[_,": ",typeof R=="string"?R:JSON.stringify(R)]},_))})]}),Object.keys(g.frontmatter_field_map||{}).length>0&&c.jsxs("div",{className:"github-plugin-settings__schema",children:[c.jsx("span",{className:"github-plugin-settings__label",children:"Field name mapping (openwriter → site)"}),c.jsx("code",{children:Object.entries(g.frontmatter_field_map).map(([_,R])=>c.jsxs("div",{children:[_," → ",R]},_))})]}),b&&c.jsx("div",{className:"github-plugin-settings__error",children:b}),c.jsxs("div",{className:"github-plugin-settings__form-buttons",children:[c.jsx("button",{className:"github-plugin-settings__btn github-plugin-settings__btn--primary",onClick:T,disabled:s==="saving"||!g.label.trim(),children:s==="saving"?"Saving…":"Add site"}),c.jsx("button",{className:"github-plugin-settings__btn",onClick:S,disabled:s==="saving",children:"Cancel"})]})]})]})}const H8={none:"No Plan",free:"No Plan",creator:"Publish — $19/mo",growth:"Publish+Email — $49/mo"},W8=[{plan:"creator",label:"Publish $19/mo"},{plan:"growth",label:"Publish+Email $49/mo"}];function V8(){var d,f;const[t,e]=x.useState(null),[n,r]=x.useState(!0);x.useEffect(()=>{fetch("/api/billing").then(h=>h.json()).then(h=>e(h)).catch(()=>{}).finally(()=>r(!1))},[]);const s=x.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=x.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 c.jsx("div",{className:"billing-section",children:c.jsx("div",{className:"billing-loading",children:"Loading..."})});if(!(t!=null&&t.authenticated))return null;const o=t.plan||"free",l=W8.filter(h=>{const m=["free","creator","growth"];return m.indexOf(h.plan)>m.indexOf(o)});return c.jsxs("div",{className:"billing-section",children:[c.jsxs("div",{className:"billing-plan",children:[c.jsx("span",{className:"billing-plan-label",children:"Plan"}),c.jsx("span",{className:`billing-plan-badge billing-plan-badge--${o}`,children:H8[o]||o})]}),((d=t.billing)==null?void 0:d.paymentFailed)&&c.jsx("div",{className:"billing-warning",children:"Payment failed — update card to keep your plan."}),l.length>0&&c.jsx("div",{className:"billing-upgrades",children:l.map(h=>c.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)&&c.jsx("button",{className:"billing-manage-btn",onClick:i,children:"Manage Billing"})]})}const q8=[{label:"Fast",cost:"free"},{label:"Fast+",cost:"$"},{label:"Sonnet",cost:"$$"},{label:"Opus",cost:"$$$"}];function K8(){const[t,e]=x.useState(null),[n,r]=x.useState([]),[s,i]=x.useState(!0),[o,l]=x.useState(!1),d=x.useCallback(()=>{Promise.all([a$(),l$()]).then(([f,h])=>{f!=null&&f.wallet&&e(f.wallet.balanceCents),r(h)}).finally(()=>i(!1))},[]);return x.useEffect(()=>{d()},[d]),x.useEffect(()=>{const f=()=>{document.visibilityState==="visible"&&d()};return document.addEventListener("visibilitychange",f),()=>document.removeEventListener("visibilitychange",f)},[d]),s?c.jsx("div",{className:"billing-section",children:c.jsx("div",{className:"billing-loading",children:"Loading…"})}):t===null&&n.length===0?null:c.jsxs("div",{className:"billing-section",children:[c.jsxs("div",{className:"billing-plan",children:[c.jsx("span",{className:"billing-plan-label",children:"Balance"}),c.jsx("span",{className:"av-credits-balance",children:t===null?"—":o$(t)})]}),c.jsx("div",{className:"av-credits-legend",children:q8.map(f=>c.jsxs("span",{className:"av-credits-legend-item",children:[c.jsx("span",{className:"av-credits-model",children:f.label}),c.jsx("span",{className:"av-credits-cost",children:f.cost})]},f.label))}),n.length>0&&c.jsxs(c.Fragment,{children:[c.jsxs("button",{className:"av-credits-topup-toggle",onClick:()=>l(f=>!f),children:[c.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:c.jsx("polyline",{points:"9 18 15 12 9 6"})}),"Add balance"]}),o&&c.jsx("div",{className:"billing-upgrades",children:n.map(f=>c.jsxs("button",{className:"billing-upgrade-btn",onClick:()=>CT(f.amountDollars),children:["Add $",f.amountDollars]},f.priceId))})]})]})}function $k(t){return t.replace(/^@openwriter\/plugin-/,"").replace(/-/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function G8({status:t}){return t==="saving"?c.jsx("span",{className:"plugin-config-status plugin-config-status--saving",children:"Saving…"}):t==="saved"?c.jsxs("span",{className:"plugin-config-status plugin-config-status--saved",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#22c55e",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Saved"]}):t==="error"?c.jsxs("span",{className:"plugin-config-status plugin-config-status--error",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),"Failed"]}):null}function J8(t){const[e,n]=x.useState([]),[r,s]=x.useState(null),[i,o]=x.useState(new Set),[l,d]=x.useState({}),f=x.useCallback(()=>{fetch("/api/available-plugins").then(g=>g.json()).then(g=>n(g.plugins||[])).catch(()=>{})},[]);x.useEffect(()=>{f()},[f]),x.useEffect(()=>{const g=()=>f();return window.addEventListener("ow-plugins-changed",g),()=>window.removeEventListener("ow-plugins-changed",g)},[f]);const h=x.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=x.useCallback(async(g,v,b)=>{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]:b}})});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 c.jsx("div",{className:"plugins-tab",children:e.length===0?c.jsx("div",{className:"plugin-empty",children:"No plugins found"}):e.map(g=>c.jsxs("div",{className:"plugin-item",children:[c.jsxs("div",{className:"plugin-item-header",children:[c.jsxs("div",{className:"plugin-item-info",children:[c.jsxs("div",{className:"plugin-item-name",children:[$k(g.name),c.jsxs("span",{className:"plugin-item-version",children:["v",g.version]})]}),g.description&&c.jsx("div",{className:"plugin-item-desc",children:g.description})]}),c.jsxs("label",{className:`plugin-toggle${r===g.name?" loading":""}`,children:[c.jsx("input",{type:"checkbox",checked:g.enabled,disabled:r===g.name,onChange:()=>h(g.name,g.enabled)}),c.jsx("span",{className:"plugin-toggle-track"}),c.jsx("span",{className:"plugin-toggle-thumb"})]})]}),g.enabled&&(()=>{const v=Object.entries(g.configSchema||{}),b=v.filter(([,T])=>T.type==="select"),k=v.filter(([,T])=>T.type!=="select"),w=v.some(([T,M])=>M.required&&!g.config[T]),S=g.name==="@openwriter/plugin-authors-voice"?c.jsx(K8,{}):g.name==="@openwriter/plugin-publish"?c.jsx(V8,{}):g.name==="@openwriter/plugin-github"?c.jsx(U8,{}):null,N=(T,M)=>{const _=l[`${g.name}:${T}`]||"idle";return c.jsxs("div",{className:"plugin-config-field",children:[c.jsxs("label",{className:"plugin-config-label",children:[M.description||T,c.jsx(G8,{status:_})]}),M.options?c.jsxs("select",{className:"plugin-config-input",defaultValue:g.config[T]||"",onChange:R=>m(g.name,T,R.target.value),children:[!M.required&&!M.options.some(R=>R.value==="")&&c.jsx("option",{value:"",children:"—"}),M.options.map(R=>c.jsx("option",{value:R.value,children:R.label},R.value))]}):c.jsx("input",{className:"plugin-config-input",type:T.toLowerCase().includes("key")||T.toLowerCase().includes("secret")||T.toLowerCase().includes("token")?"password":"text",defaultValue:g.config[T]||"",placeholder:M.env?`$${M.env}`:"",onBlur:R=>m(g.name,T,R.target.value)})]},T)};return v.length===0&&!S?null:c.jsxs("div",{className:"plugin-config-section",children:[w&&c.jsxs("div",{className:"plugin-setup-hint",children:["Ask your agent: “set up ",$k(g.name),"”"]}),b.length>0&&c.jsx("div",{className:"plugin-config",children:b.map(([T,M])=>N(T,M))}),S,k.length>0&&c.jsxs(c.Fragment,{children:[c.jsxs("button",{className:"plugin-config-toggle",onClick:()=>o(T=>{const M=new Set(T);return M.has(g.name)?M.delete(g.name):M.add(g.name),M}),children:[c.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:c.jsx("polyline",{points:"9 18 15 12 9 6"})}),"Settings"]}),i.has(g.name)&&c.jsx("div",{className:"plugin-config",children:k.map(([T,M])=>N(T,M))})]})]})})()]},g.name))})}function Y8({existingConnection:t,onClose:e,onSaved:n}){const[r,s]=x.useState("form"),[i,o]=x.useState(null),[l,d]=x.useState((t==null?void 0:t.domain)||""),[f,h]=x.useState(""),[m,g]=x.useState((t==null?void 0:t.from_name)||""),[v,b]=x.useState(""),[k,w]=x.useState((t==null?void 0:t.id)||""),[S,N]=x.useState({dns_verified:!1,sender_verified:!1}),T=x.useRef(null),M=x.useRef(null);x.useEffect(()=>{const K=F=>{r!=="submitting"&&r!=="verifying"&&M.current&&!M.current.contains(F.target)&&e()};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[e,r]),x.useEffect(()=>{const K=F=>{F.key==="Escape"&&r!=="submitting"&&r!=="verifying"&&e()};return document.addEventListener("keydown",K),()=>document.removeEventListener("keydown",K)},[e,r]),x.useEffect(()=>()=>{T.current&&clearInterval(T.current)},[]);async function _(){var K,F;s("submitting"),o(null);try{const $=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"setup_custom_domain",arguments:{domain:l,from_email:f,from_name:m||void 0,physical_address:v}})})).json(),W=(F=(K=$.content)==null?void 0:K[0])!=null&&F.text?JSON.parse($.content[0].text):$;if(W.error){o(W.error),s("error");return}const q=W.connectionId||W.connection_id||k;q&&w(q),I(q)}catch(J){o(J.message),s("error")}}async function R(){var K,F;s("submitting"),o(null);try{const $=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"setup_custom_domain",arguments:{domain:l,from_email:f||void 0,from_name:m||void 0,physical_address:v||void 0}})})).json(),W=(F=(K=$.content)==null?void 0:K[0])!=null&&F.text?JSON.parse($.content[0].text):$;if(W.error){o(W.error),s("error");return}s("done")}catch(J){o(J.message),s("error")}}function I(K){s("verifying"),T.current=setInterval(async()=>{var F,J;try{const W=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"check_domain_status",arguments:{connectionId:K}})})).json(),q=(J=(F=W.content)==null?void 0:F[0])!=null&&J.text?JSON.parse(W.content[0].text):W,ne=!!q.dns_verified,V=!!q.sender_verified;N({dns_verified:ne,sender_verified:V}),ne&&V&&(T.current&&clearInterval(T.current),T.current=null,s("done"))}catch{}},5e3)}function P(){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,z=l.trim()&&f.trim()&&v.trim();return c.jsx("div",{className:"newsletter-modal-overlay",children:c.jsxs("div",{className:"newsletter-modal newsletter-modal--setup",ref:M,children:[c.jsxs("div",{className:"newsletter-modal__header",children:[c.jsx("h3",{children:B?"Newsletter Settings":"Set Up Newsletter"}),c.jsx("button",{className:"newsletter-modal__close",onClick:e,children:"×"})]}),c.jsxs("div",{className:"newsletter-modal__body",children:[r==="form"&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"newsletter-modal__field",children:[c.jsx("label",{className:"newsletter-modal__label",children:"Domain"}),c.jsx("input",{className:"newsletter-modal__input",type:"text",placeholder:"yourdomain.com",value:l,onChange:K=>d(K.target.value),disabled:B,autoComplete:"off"})]}),c.jsxs("div",{className:"newsletter-modal__field",children:[c.jsx("label",{className:"newsletter-modal__label",children:"From Email"}),c.jsx("input",{className:"newsletter-modal__input",type:"email",placeholder:"newsletter@yourdomain.com",value:f,onChange:K=>h(K.target.value),autoComplete:"off"})]}),c.jsxs("div",{className:"newsletter-modal__field",children:[c.jsxs("label",{className:"newsletter-modal__label",children:["From Name ",c.jsx("span",{className:"newsletter-modal__optional",children:"(optional)"})]}),c.jsx("input",{className:"newsletter-modal__input",type:"text",placeholder:"Your Name or Brand",value:m,onChange:K=>g(K.target.value),autoComplete:"off"})]}),c.jsxs("div",{className:"newsletter-modal__field",children:[c.jsxs("label",{className:"newsletter-modal__label",children:["Physical Address ",c.jsx("span",{className:"newsletter-modal__required",children:"*"})]}),c.jsx("textarea",{className:"newsletter-modal__input newsletter-modal__textarea",rows:2,placeholder:"123 Main St, City, State 12345",value:v,onChange:K=>b(K.target.value)}),c.jsx("span",{className:"newsletter-modal__hint",children:"Required by CAN-SPAM. Included in email footer."})]}),c.jsxs("div",{className:"newsletter-modal__actions",children:[c.jsx("button",{className:"newsletter-modal__btn",onClick:e,children:"Cancel"}),c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:B?R:_,disabled:!z,children:B?"Save":"Set Up Domain"})]})]}),r==="submitting"&&c.jsxs("div",{className:"newsletter-modal__status",children:[c.jsx("div",{className:"newsletter-modal__spinner"}),c.jsx("span",{children:B?"Saving...":"Setting up domain..."})]}),r==="verifying"&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"newsletter-modal__verify",children:[c.jsx("p",{className:"newsletter-modal__verify-title",children:"Verifying domain setup..."}),c.jsxs("div",{className:"newsletter-modal__verify-checks",children:[c.jsxs("div",{className:`newsletter-modal__verify-item${S.dns_verified?" newsletter-modal__verify-item--done":""}`,children:[S.dns_verified?"✓":c.jsx("span",{className:"newsletter-modal__spinner newsletter-modal__spinner--sm"}),c.jsx("span",{children:"DNS records"})]}),c.jsxs("div",{className:`newsletter-modal__verify-item${S.sender_verified?" newsletter-modal__verify-item--done":""}`,children:[S.sender_verified?"✓":c.jsx("span",{className:"newsletter-modal__spinner newsletter-modal__spinner--sm"}),c.jsx("span",{children:"Sender verification"})]})]}),c.jsx("p",{className:"newsletter-modal__hint",children:"This may take a few minutes. You can close and check back later."})]}),c.jsxs("div",{className:"newsletter-modal__actions",children:[c.jsx("button",{className:"newsletter-modal__btn",onClick:P,children:"Resend Verification"}),c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>{n(),e()},children:"Close"})]})]}),r==="done"&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"newsletter-modal__status newsletter-modal__status--success",children:B?"Settings saved!":"Newsletter domain configured!"}),c.jsx("div",{className:"newsletter-modal__actions",children:c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>{n(),e()},children:"Done"})})]}),r==="error"&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"newsletter-modal__error",children:i}),c.jsxs("div",{className:"newsletter-modal__actions",children:[c.jsx("button",{className:"newsletter-modal__btn",onClick:e,children:"Cancel"}),c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>s("form"),children:"Try Again"})]})]})]})]})})}const X8={x:[],linkedin:[]};function Q8({connectionId:t,provider:e,displayName:n,onClose:r,onSaved:s}){const[i,o]=x.useState("loading"),[l,d]=x.useState({}),[f,h]=x.useState(null),m=x.useRef(null),g=X8[e]||[];x.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]),x.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]),x.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(l)}),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 b(k){switch(k){case"x":return"X (Twitter)";case"linkedin":return"LinkedIn";default:return k}}return c.jsx("div",{className:"conn-config-overlay",children:c.jsxs("div",{className:"conn-config-modal",ref:m,children:[c.jsxs("div",{className:"conn-config-modal__header",children:[c.jsxs("div",{className:"conn-config-modal__title",children:[b(e)," Settings"]}),c.jsx("div",{className:"conn-config-modal__subtitle",children:n})]}),i==="loading"&&c.jsxs("div",{className:"conn-config-modal__body conn-config-modal__center",children:[c.jsx("div",{className:"conn-config-spinner"}),c.jsx("span",{children:"Loading configuration..."})]}),(i==="form"||i==="error")&&g.length>0&&c.jsxs("div",{className:"conn-config-modal__body",children:[g.map(k=>c.jsxs("div",{className:"conn-config-field",children:[c.jsxs("label",{className:"conn-config-field__label",children:[k.label,k.readonly&&c.jsx("span",{className:"conn-config-field__badge",children:"read-only"})]}),c.jsx("input",{className:"conn-config-field__input",value:l[k.key]||"",placeholder:k.placeholder,readOnly:k.readonly,onChange:w=>d(S=>({...S,[k.key]:w.target.value}))})]},k.key)),f&&c.jsx("div",{className:"conn-config-modal__error",children:f})]}),(i==="form"||i==="error")&&g.length===0&&c.jsx("div",{className:"conn-config-modal__body conn-config-modal__center",children:c.jsxs("span",{className:"conn-config-modal__empty",children:["No configuration needed for ",b(e),"."]})}),i==="saving"&&c.jsxs("div",{className:"conn-config-modal__body conn-config-modal__center",children:[c.jsx("div",{className:"conn-config-spinner"}),c.jsx("span",{children:"Saving..."})]}),i==="saved"&&c.jsxs("div",{className:"conn-config-modal__body conn-config-modal__center",children:[c.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#22c55e",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),c.jsx("span",{children:"Saved"})]}),c.jsxs("div",{className:"conn-config-modal__footer",children:[c.jsx("button",{className:"conn-config-btn conn-config-btn--secondary",onClick:r,children:i==="saved"?"Close":"Cancel"}),g.length>0&&(i==="form"||i==="error")&&c.jsx("button",{className:"conn-config-btn conn-config-btn--primary",onClick:v,children:"Save"})]})]})})}const Z8=[{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 c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:c.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 c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:c.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 c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),c.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]});default:return c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("circle",{cx:"12",cy:"12",r:"10"})})}}function eF(t){return t==="active"?"connections-status--active":t==="expired"?"connections-status--expired":t==="revoked"?"connections-status--revoked":"connections-status--pending"}function tF(t){const[e,n]=x.useState([]),[r,s]=x.useState(null),[i,o]=x.useState(null),[l,d]=x.useState(null),[f,h]=x.useState(null),[m,g]=x.useState(null),v=x.useRef(null);async function b(){try{const R=await(await fetch("/api/connections")).json();s(R.authenticated!==!1);const I=(R.connections||[]).filter(P=>P&&P.id&&P.provider);return n(I),I}catch{return[]}}x.useEffect(()=>{b()},[]),x.useEffect(()=>()=>{v.current&&clearInterval(v.current)},[]);async function k(_){d(_);try{const R=await fetch(`/api/connections/oauth/${_}/start`,{method:"POST"}),I=await R.json();if(!R.ok||!I.url){d(null);return}window.open(I.url,"_blank","width=600,height=700"),v.current=setInterval(async()=>{try{const B=await(await fetch(`/api/connections/oauth/${_}/status/${I.state}`)).json();if(B.status==="completed"){v.current&&clearInterval(v.current),v.current=null,d(null);const z=await b();if(_==="x"){const K=z.find(F=>F.provider==="x"&&F.status==="active");if(K!=null&&K.display_name){const F=K.display_name.replace("@","");localStorage.setItem("ow-x-handle",F),window.dispatchEvent(new StorageEvent("storage",{key:"ow-x-handle",newValue:F}))}}}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 I=await R.json().catch(()=>({error:"Delete failed"}));console.error("[Connections] Delete failed:",I.error)}}catch(R){console.error("[Connections] Delete error:",R)}o(null),await b()}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 T=new Set,M=r===!1;return c.jsxs("div",{className:"connections-tab",children:[m&&c.jsx(Q8,{connectionId:m.id,provider:m.provider,displayName:m.display_name,onClose:()=>g(null),onSaved:()=>b()}),f&&c.jsx(Y8,{existingConnection:f==="edit"?S.get("newsletter"):null,onClose:()=>h(null),onSaved:()=>b()}),M?c.jsxs("div",{className:"connections-dropdown__upsell",children:[c.jsx("p",{children:"Connect your X, LinkedIn, and other accounts to publish directly from OpenWriter."}),c.jsxs("p",{children:["Set up the ",c.jsx("strong",{children:"Publish"})," plugin to get started."]})]}):c.jsx("div",{className:"connections-dropdown__list",children:Z8.flatMap(_=>{const R=T.has(_.id),I=N.get(_.id)||[],P=z=>i===z.id?c.jsxs("div",{className:"connections-dropdown__confirm",children:[c.jsxs("span",{children:["Disconnect ",z.display_name||_.label,"?"]}),c.jsxs("div",{className:"connections-dropdown__confirm-btns",children:[c.jsx("button",{onClick:()=>w(z.id),children:"Yes"}),c.jsx("button",{onClick:()=>o(null),children:"No"})]})]},z.id):c.jsxs("div",{className:"connections-dropdown__item",children:[c.jsx("div",{className:"connections-dropdown__icon",children:Bp(_.id)}),c.jsxs("div",{className:"connections-dropdown__info",children:[c.jsx("div",{className:"connections-dropdown__name",children:z.display_name||z.domain||_.label}),c.jsxs("div",{className:"connections-dropdown__type",children:[c.jsx("span",{className:`connections-status ${eF(z.status)}`}),"Connected"]})]}),c.jsxs("div",{className:"connections-dropdown__actions",children:[c.jsx("button",{className:"connections-dropdown__action-btn",onClick:()=>{_.id==="newsletter"?h("edit"):g({id:z.id,provider:_.id,display_name:z.display_name||_.label})},title:"Settings",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.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"}),c.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),c.jsx("button",{className:"connections-dropdown__action-btn connections-dropdown__action-btn--delete",onClick:()=>o(z.id),title:"Disconnect",children:"×"})]})]},z.id),B=I.map(P);return R?(B.push(c.jsx("div",{className:"connections-dropdown__add-row",children:c.jsx("button",{className:"connections-dropdown__add-btn",onClick:()=>k(_.id),disabled:l!==null,children:l===_.id?"Connecting…":`+ Add ${_.label} repo`})},`${_.id}__add`)),B):I.length>0?B:_.oauth?[c.jsxs("div",{className:"connections-dropdown__item connections-dropdown__item--disconnected",children:[c.jsx("div",{className:"connections-dropdown__icon",children:Bp(_.id)}),c.jsxs("div",{className:"connections-dropdown__info",children:[c.jsx("div",{className:"connections-dropdown__name",children:_.label}),c.jsx("div",{className:"connections-dropdown__type",children:"Not connected"})]}),c.jsx("button",{className:"connections-dropdown__connect-inline-btn",onClick:()=>k(_.id),disabled:l!==null,children:l===_.id?"Connecting…":"Connect"})]},_.id)]:[c.jsxs("div",{className:"connections-dropdown__item connections-dropdown__item--disconnected",children:[c.jsx("div",{className:"connections-dropdown__icon",children:Bp(_.id)}),c.jsxs("div",{className:"connections-dropdown__info",children:[c.jsx("div",{className:"connections-dropdown__name",children:_.label}),c.jsx("div",{className:"connections-dropdown__type",children:"Built-in · Not configured"})]}),c.jsx("button",{className:"connections-dropdown__connect-inline-btn",onClick:()=>h("new"),children:"Configure"})]},_.id)]})})]})}const nF={tree:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M3 3h7v7H3zM14 3h7v4h-7zM14 10h7v4h-7zM3 13h7v8H3z"})}),files:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),c.jsx("polyline",{points:"14 2 14 8 20 8"})]}),timeline:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"2",x2:"12",y2:"22"}),c.jsx("circle",{cx:"12",cy:"6",r:"2"}),c.jsx("circle",{cx:"12",cy:"12",r:"2"}),c.jsx("circle",{cx:"12",cy:"18",r:"2"}),c.jsx("line",{x1:"14",y1:"6",x2:"20",y2:"6"}),c.jsx("line",{x1:"14",y1:"12",x2:"20",y2:"12"}),c.jsx("line",{x1:"14",y1:"18",x2:"20",y2:"18"})]}),board:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"5",height:"18",rx:"1"}),c.jsx("rect",{x:"10",y:"3",width:"5",height:"12",rx:"1"}),c.jsx("rect",{x:"17",y:"3",width:"5",height:"15",rx:"1"})]}),shelf:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M4 19V5"}),c.jsx("path",{d:"M8 19V7"}),c.jsx("path",{d:"M12 19V4"}),c.jsx("path",{d:"M16 19V8"}),c.jsx("path",{d:"M20 19V6"}),c.jsx("line",{x1:"2",y1:"20",x2:"22",y2:"20"})]})};function rF(t){const[e,n]=x.useState(jE),[r,s]=x.useState(ME),[i,o]=x.useState($d),l=AE(),[d,f]=x.useState(OE),[h,m]=x.useState(IE),g=(N=e,T=r,M=i,_=l,R=d,I=h)=>{LE(N,T,M,_,R,I)},v=N=>{n(N),g(N)},b=()=>{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 c.jsxs("div",{className:"appearance-tab",children:[c.jsx("div",{className:"appearance-section",children:c.jsxs("div",{className:"appearance-section-header",children:[c.jsx("span",{className:"appearance-section-title",children:"Mode"}),c.jsxs("button",{className:"appearance-mode-btn",onClick:b,title:r==="light"?"Switch to dark":"Switch to light",children:[r==="light"?c.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"5"}),c.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),c.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),c.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),c.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),c.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),c.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),c.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),c.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]}):c.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})}),c.jsx("span",{children:r==="light"?"Light":"Dark"})]})]})}),c.jsxs("div",{className:"appearance-section",children:[c.jsx("div",{className:"appearance-section-header",children:c.jsx("span",{className:"appearance-section-title",children:"Typography"})}),c.jsx("div",{className:"appearance-typeface-grid",children:NE.map(N=>c.jsx("button",{className:`appearance-style-option ${e===N.id?"active":""}`,onClick:()=>v(N.id),title:N.description,children:N.label},N.id))})]}),c.jsxs("div",{className:"appearance-section",children:[c.jsx("div",{className:"appearance-section-header",children:c.jsx("span",{className:"appearance-section-title",children:"Spacing"})}),c.jsx("div",{className:"appearance-typography-grid",children:TE.map(N=>c.jsx("button",{className:`appearance-style-option ${d===N.id?"active":""}`,onClick:()=>w(N.id),children:N.label},N.id))})]}),c.jsxs("div",{className:"appearance-section",children:[c.jsx("div",{className:"appearance-section-header",children:c.jsx("span",{className:"appearance-section-title",children:"Canvas"})}),c.jsx("div",{className:"appearance-style-grid",children:_E.map(N=>c.jsx("button",{className:`appearance-style-option ${h===N.id?"active":""}`,onClick:()=>S(N.id),children:N.label},N.id))})]}),c.jsxs("div",{className:"appearance-section",children:[c.jsx("div",{className:"appearance-section-header",children:c.jsx("span",{className:"appearance-section-title",children:"Layout"})}),c.jsx("div",{className:"appearance-mode-grid",children:CE.map(N=>c.jsxs("button",{className:`appearance-mode-option ${i===N.id?"active":""}`,onClick:()=>k(N.id),children:[nF[N.icon],c.jsx("span",{children:N.label})]},N.id))})]})]})}const JT=[{id:"review",label:"Review",scope:"doc",icon:c.jsx($5,{}),Component:k8},{id:"activity",label:"Activity",scope:"workspace",icon:c.jsx(H5,{}),Component:F8},{id:"backlinks",label:"Backlinks",scope:"doc",icon:c.jsx(z5,{}),Component:C8},{id:"exports",label:"Export",scope:"doc",icon:c.jsx(U5,{}),Component:T8},{id:"versions",label:"Versions",scope:"doc",icon:c.jsx(F5,{}),Component:N8},{id:"plugins",label:"Plugins",scope:"settings",icon:c.jsx(W5,{}),Component:J8},{id:"connections",label:"Connections",scope:"settings",icon:c.jsx(V5,{}),Component:tF},{id:"appearance",label:"Appearance",scope:"settings",icon:c.jsx(q5,{}),Component:rF}];function sF(t){return t?JT.find(e=>e.id===t)??null:null}function Fk({pendingDocs:t}){const{visible:e,activeTab:n,openTab:r}=Ll(),[s,i]=x.useState(!1),[o,l]=x.useState(!1),d=x.useRef(0);return x.useEffect(()=>{const f=t.filenames.length,h=d.current;d.current=f,h===0&&f>0&&r("review")},[t.filenames.length,r]),x.useEffect(()=>{const f=()=>r("review");return window.addEventListener("ow-pending-write-applied",f),()=>window.removeEventListener("ow-pending-write-applied",f)},[r]),x.useEffect(()=>{const f=()=>{if(!(e&&n==="activity")){i(!0),window.setTimeout(()=>i(!1),500);try{localStorage.getItem("ow-bell-hint-seen")||(l(!0),localStorage.setItem("ow-bell-hint-seen","1"),window.setTimeout(()=>l(!1),6e3))}catch{}}};return window.addEventListener("ow-activity-event",f),()=>window.removeEventListener("ow-activity-event",f)},[e,n]),c.jsx("div",{className:"rail-icon-strip",role:"tablist","aria-label":"Right rail tabs",children:JT.map(f=>{const h=e&&n===f.id,m=f.id==="activity";return c.jsxs("button",{type:"button",role:"tab","aria-selected":h,className:["rail-icon-btn",h?"rail-icon-btn--active":"",`rail-icon-btn--scope-${f.scope}`,m&&s?"rail-icon-btn--pulsing":""].filter(Boolean).join(" "),onClick:()=>r(f.id),title:f.label,"aria-label":f.label,children:[f.icon,m&&o&&c.jsxs("div",{className:"rail-icon-hint",role:"tooltip",children:[c.jsx("span",{children:"Agent activity lives here."}),c.jsx("button",{type:"button",className:"rail-icon-hint-close",onClick:g=>{g.stopPropagation(),l(!1)},"aria-label":"Dismiss",children:"×"})]})]},f.id)})})}function iF(t){const{activeTab:e}=Ll(),n=sF(e);return c.jsx("div",{className:"rail-body",role:"tabpanel",children:n?c.jsx(n.Component,{...t}):null})}const oF=()=>c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:c.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"})}),aF=()=>c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[c.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"}),c.jsx("path",{d:"M9 14l2 2 4-4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),lF=()=>c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[c.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"}),c.jsx("path",{d:"M12 16v-5M9.5 13.5L12 11l2.5 2.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),cF=()=>c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[c.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"}),c.jsx("path",{d:"M14 14l-4 4M10 14l4 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]});function uF({syncStatus:t,onSync:e}){const[n,r]=x.useState(!1),[s,i]=x.useState([]),[o,l]=x.useState(!1),d=x.useRef(null),f=x.useCallback(()=>{if(n){r(!1);return}r(!0),l(!0),fetch("/api/sync/pending").then(h=>h.json()).then(h=>i(h)).catch(()=>i([])).finally(()=>l(!1))},[n]);return x.useEffect(()=>{t.state!=="pending"&&r(!1)},[t.state]),x.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]),c.jsxs("div",{className:"sync-btn-group",ref:d,children:[c.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"&&c.jsxs(c.Fragment,{children:[c.jsx(oF,{})," Sync"]}),t.state==="synced"&&c.jsxs(c.Fragment,{children:[c.jsx(aF,{})," Synced"]}),t.state==="pending"&&c.jsxs(c.Fragment,{children:[c.jsx(lF,{})," Sync",t.pendingFiles?` (${t.pendingFiles})`:""]}),t.state==="syncing"&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"sync-btn-spinner"})," Syncing..."]}),t.state==="error"&&c.jsxs(c.Fragment,{children:[c.jsx(cF,{})," Retry"]})]}),t.state==="pending"&&t.pendingFiles&&t.pendingFiles>0&&c.jsx("button",{className:"sync-details-btn",onClick:f,title:"View pending changes",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:c.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&&c.jsxs("div",{className:"sync-pending-dropdown",children:[c.jsx("div",{className:"sync-pending-header",children:"Changes to push"}),o?c.jsx("div",{className:"sync-pending-loading",children:"Loading..."}):s.length===0?c.jsx("div",{className:"sync-pending-loading",children:"No changes"}):c.jsx("div",{className:"sync-pending-list",children:s.map((h,m)=>c.jsxs("div",{className:`sync-pending-item sync-file-${h.status}`,children:[c.jsx("span",{className:"sync-file-badge",children:h.status[0].toUpperCase()}),c.jsx("span",{className:"sync-file-name",children:h.file})]},m))})]})]})}function dF(t){const{syncStatus:e,onSync:n,onToggleToolbar:r,toolbarOpen:s,focusMode:i,onToggleFocusMode:o,...l}=t,{open:d,visible:f,overlay:h,activeTab:m,width:g,setWidth:v,closeRail:b,openTab:k}=Ll(),w=x.useRef(null),S=x.useRef(null),N=x.useRef(i);x.useEffect(()=>{if(i!==N.current)if(N.current=i,i)S.current={open:d,activeTab:m},d&&b();else{const M=S.current;S.current=null,!h&&(M!=null&&M.open)&&M.activeTab&&k(M.activeTab)}},[i]);const T=x.useCallback(M=>{M.preventDefault();const _=M.clientX,R=g,I=B=>{const z=_-B.clientX;v(R+z)},P=()=>{window.removeEventListener("pointermove",I),window.removeEventListener("pointerup",P)};window.addEventListener("pointermove",I),window.addEventListener("pointerup",P)},[g,v]);return x.useEffect(()=>{if(!d)return;const M=_=>{_.key==="Escape"&&w.current&&w.current.contains(document.activeElement)&&(_.preventDefault(),b())};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[d,b]),f?c.jsxs("aside",{ref:w,className:"right-rail-column",style:{width:g,minWidth:g},"aria-label":"Right rail",children:[!h&&c.jsx("div",{className:"right-rail-resize-handle",onPointerDown:T,"aria-hidden":"true"}),c.jsxs("div",{className:"right-rail-topbar",children:[c.jsxs("div",{className:"right-rail-topbar-actions right-rail-topbar-actions--start",children:[c.jsx("button",{type:"button",className:"right-rail-topbar-btn",onClick:b,title:"Hide rail","aria-label":"Hide rail",children:c.jsx(K5,{})}),c.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:c.jsx(ET,{})}),c.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:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M4 20h16"}),c.jsx("path",{d:"m6 16 6-12 6 12"}),c.jsx("path",{d:"M8 12h8"})]})})]}),c.jsx("div",{className:"right-rail-topbar-actions right-rail-topbar-actions--end",children:c.jsx(uF,{syncStatus:e,onSync:n})})]}),c.jsx(Fk,{pendingDocs:l.pendingDocs}),c.jsx(iF,{...l})]}):c.jsx("div",{className:"right-rail-mount-keepalive",style:{display:"none"},children:c.jsx(Fk,{pendingDocs:l.pendingDocs})})}function fF({onClose:t,onSetupComplete:e}){const[n,r]=x.useState("detecting"),[s,i]=x.useState(null),[o,l]=x.useState("gh"),[d,f]=x.useState("openwriter-docs"),[h,m]=x.useState(!0),[g,v]=x.useState(""),[b,k]=x.useState(""),[w,S]=x.useState(""),[N,T]=x.useState("");x.useEffect(()=>{fetch("/api/sync/capabilities").then(_=>_.json()).then(_=>{i(_),_.ghAuthenticated?l("gh"):(_.gitInstalled,l("pat")),r("setup")}).catch(()=>{S("Failed to detect git capabilities"),r("error")})},[]);const M=x.useCallback(async()=>{r("progress"),T(o==="connect"?"Connecting to repository...":"Creating repository and syncing...");try{const _={method:o,repoName:d,isPrivate:h};o==="pat"&&(_.pat=g),o==="connect"&&(_.remoteUrl=b,_.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 I=await R.json().catch(()=>({}));throw new Error(I.error||`Setup failed (${R.status})`)}r("done"),e()}catch(_){S(_.message),r("error")}},[o,d,h,g,b,e]);return c.jsx("div",{className:"sync-modal-overlay",onClick:t,children:c.jsxs("div",{className:"sync-modal",onClick:_=>_.stopPropagation(),children:[c.jsxs("div",{className:"sync-modal-header",children:[c.jsx("h2",{children:"Sync to GitHub"}),c.jsx("button",{className:"sync-modal-close",onClick:t,children:"×"})]}),n==="detecting"&&c.jsxs("div",{className:"sync-modal-body",children:[c.jsx("div",{className:"sync-spinner"}),c.jsx("p",{children:"Detecting git configuration..."})]}),n==="setup"&&s&&c.jsxs("div",{className:"sync-modal-body",children:[!s.gitInstalled&&c.jsxs("div",{className:"sync-warning",children:["Git is not installed. Please ",c.jsx("a",{href:"https://git-scm.com/downloads",target:"_blank",rel:"noreferrer",children:"install git"})," first."]}),s.gitInstalled&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"sync-tabs",children:[s.ghAuthenticated&&c.jsx("button",{className:`sync-tab${o==="gh"?" active":""}`,onClick:()=>l("gh"),children:"GitHub CLI"}),c.jsx("button",{className:`sync-tab${o==="pat"?" active":""}`,onClick:()=>l("pat"),children:"Personal Access Token"}),c.jsx("button",{className:`sync-tab${o==="connect"?" active":""}`,onClick:()=>l("connect"),children:"Connect Existing"})]}),o==="gh"&&c.jsxs("div",{className:"sync-form",children:[c.jsxs("label",{children:["Repository name",c.jsx("input",{type:"text",value:d,onChange:_=>f(_.target.value),placeholder:"openwriter-docs"})]}),c.jsxs("label",{className:"sync-checkbox",children:[c.jsx("input",{type:"checkbox",checked:h,onChange:_=>m(_.target.checked)}),"Private repository"]})]}),o==="pat"&&c.jsxs("div",{className:"sync-form",children:[!s.ghAuthenticated&&!s.ghInstalled&&c.jsxs("p",{className:"sync-hint",children:["Create a ",c.jsx("a",{href:"https://github.com/settings/tokens/new?scopes=repo&description=OpenWriter",target:"_blank",rel:"noreferrer",children:"Personal Access Token"})," with ",c.jsx("code",{children:"repo"})," scope."]}),c.jsxs("label",{children:["Personal Access Token",c.jsx("input",{type:"password",value:g,onChange:_=>v(_.target.value),placeholder:"ghp_..."})]}),c.jsxs("label",{children:["Repository name",c.jsx("input",{type:"text",value:d,onChange:_=>f(_.target.value),placeholder:"openwriter-docs"})]}),c.jsxs("label",{className:"sync-checkbox",children:[c.jsx("input",{type:"checkbox",checked:h,onChange:_=>m(_.target.checked)}),"Private repository"]})]}),o==="connect"&&c.jsxs("div",{className:"sync-form",children:[c.jsxs("label",{children:["Remote URL",c.jsx("input",{type:"text",value:b,onChange:_=>k(_.target.value),placeholder:"https://github.com/user/repo.git"})]}),c.jsxs("label",{children:["PAT (optional, for private repos)",c.jsx("input",{type:"password",value:g,onChange:_=>v(_.target.value),placeholder:"ghp_..."})]})]}),c.jsxs("div",{className:"sync-modal-actions",children:[c.jsx("button",{className:"sync-btn secondary",onClick:t,children:"Cancel"}),c.jsx("button",{className:"sync-btn primary",onClick:M,disabled:o==="pat"&&!g||o==="connect"&&!b||o!=="connect"&&!d,children:o==="connect"?"Connect & Sync":"Create & Sync"})]})]})]}),n==="progress"&&c.jsxs("div",{className:"sync-modal-body",children:[c.jsx("div",{className:"sync-spinner"}),c.jsx("p",{children:N})]}),n==="done"&&c.jsxs("div",{className:"sync-modal-body",children:[c.jsx("div",{className:"sync-success-icon",children:"✓"}),c.jsx("p",{children:"Successfully synced to GitHub!"}),c.jsx("div",{className:"sync-modal-actions",children:c.jsx("button",{className:"sync-btn primary",onClick:t,children:"Done"})})]}),n==="error"&&c.jsxs("div",{className:"sync-modal-body",children:[c.jsx("div",{className:"sync-error-msg",children:w}),c.jsxs("div",{className:"sync-modal-actions",children:[c.jsx("button",{className:"sync-btn secondary",onClick:()=>r("setup"),children:"Back"}),c.jsx("button",{className:"sync-btn secondary",onClick:t,children:"Close"})]})]})]})})}function hF({onNodeChanges:t,onAgentStatus:e,onDocumentSwitched:n,onDocumentReloaded:r,onDocumentsChanged:s,onWorkspacesChanged:i,onTitleChanged:o,onPendingDocsChanged:l,onMetadataChanged:d,onSyncStatus:f,onWritingStarted:h,onWritingFinished:m,onIdRewrites:g,onPendingFilenamesChanged:v,getEditorState:b}){const k=x.useRef(null),[w,S]=x.useState(!1),N=x.useRef(0),T=x.useRef(new Set),M=()=>{var A;return(A=ne.current)==null?void 0:A.call(ne,new Set(T.current))},_=x.useRef(t),R=x.useRef(e),I=x.useRef(n),P=x.useRef(s),B=x.useRef(i),z=x.useRef(o),K=x.useRef(l),F=x.useRef(f),J=x.useRef(d),$=x.useRef(h),W=x.useRef(m),q=x.useRef(g),ne=x.useRef(v),V=x.useRef(r),oe=x.useRef(b);_.current=t,R.current=e,I.current=n,P.current=s,B.current=i,z.current=o,K.current=l,J.current=d,F.current=f,$.current=h,W.current=m,q.current=g,ne.current=v,V.current=r,oe.current=b,x.useEffect(()=>{const L=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;let ee,ue=!1,be=1e3;function re(){const Ee=new WebSocket(L);k.current=Ee,Ee.onopen=()=>{S(!0),be=1e3,ue&&Ee.send(JSON.stringify({type:"request-document"})),ue=!0},Ee.onmessage=$e=>{var Fe,Ze,Re,tt,gt,ut,ge,yt,Ct,_t,Lt,at,De,ve;try{const Z=JSON.parse($e.data);if(Z.type==="node-changes"&&Z.changes&&((Fe=_.current)==null||Fe.call(_,Z.changes),typeof Z.version=="number"&&(N.current=Z.version)),Z.type==="id-rewrites"&&Array.isArray(Z.rewrites)&&((Ze=q.current)==null||Ze.call(q,Z.rewrites)),Z.type==="agent-status"&&((Re=R.current)==null||Re.call(R,!!Z.agentConnected)),Z.type==="document-switched"&&(N.current=0,(tt=I.current)==null||tt.call(I,{document:Z.document,title:Z.title,filename:Z.filename,docId:Z.docId,metadata:Z.metadata,pendingMetadata:Z.pendingMetadata??null}),window.dispatchEvent(new CustomEvent("ow-pending-metadata-changed",{detail:{docId:Z.docId,pendingMetadata:Z.pendingMetadata??null}}))),Z.type==="pending-metadata-changed"&&window.dispatchEvent(new CustomEvent("ow-pending-metadata-changed",{detail:{docId:Z.docId,pendingMetadata:Z.pendingMetadata??null}})),Z.type==="document-reloaded"&&(typeof Z.version=="number"&&(N.current=Z.version),(gt=V.current)==null||gt.call(V,{document:Z.document,title:Z.title,filename:Z.filename,docId:Z.docId,metadata:Z.metadata,orphanCount:typeof Z.orphanCount=="number"?Z.orphanCount:0,staleBaselineCount:typeof Z.staleBaselineCount=="number"?Z.staleBaselineCount:0})),Z.type==="metadata-changed"&&Z.metadata&&((ut=J.current)==null||ut.call(J,Z.metadata)),Z.type==="documents-changed"&&((ge=P.current)==null||ge.call(P)),Z.type==="workspaces-changed"&&((yt=B.current)==null||yt.call(B)),Z.type==="title-changed"&&Z.title&&((Ct=z.current)==null||Ct.call(z,Z.title)),Z.type==="pending-docs-changed"&&Z.pendingDocs&&((_t=K.current)==null||_t.call(K,Z.pendingDocs)),Z.type==="sync-status"&&((Lt=F.current)==null||Lt.call(F,{state:Z.state,lastSyncTime:Z.lastSyncTime,pendingFiles:Z.pendingFiles,error:Z.error})),Z.type==="writing-started"&&Z.title&&(typeof Z.key=="string"&&(T.current.add(Z.key),M()),(at=$.current)==null||at.call($,Z.title,Z.target||null)),Z.type==="writing-finished"&&(typeof Z.key=="string"&&Z.key?T.current.delete(Z.key):T.current.clear(),M(),(De=W.current)==null||De.call(W)),Z.type==="pending-writes-sync"&&Array.isArray(Z.writes)&&(T.current=new Set(Z.writes.map(je=>je.key).filter(Boolean)),M(),Z.writes.length>0)){const je=Z.writes.reduce((Q,he)=>Q.startedAt>he.startedAt?Q:he);je!=null&&je.title&&((ve=$.current)==null||ve.call($,je.title,je.target||null))}if(Z.type==="plugins-changed"&&window.dispatchEvent(new CustomEvent("ow-plugins-changed")),Z.type==="comments-changed"&&Z.filename&&window.dispatchEvent(new CustomEvent("ow-comments-changed",{detail:{filename:Z.filename}})),Z.type==="documents-changed"&&window.dispatchEvent(new CustomEvent("ow-documents-changed")),Z.type==="metadata-changed"&&window.dispatchEvent(new CustomEvent("ow-metadata-changed",{detail:{metadata:Z.metadata}})),Z.type==="activity-log"&&Array.isArray(Z.entries)&&window.dispatchEvent(new CustomEvent("ow-activity-seed",{detail:{entries:Z.entries}})),Z.type==="activity-event"&&Z.event&&window.dispatchEvent(new CustomEvent("ow-activity-event",{detail:{event:Z.event}})),Z.type==="toast"&&typeof Z.message=="string"){const je=Z.kind==="error"?"error":"info";_i(Z.message,je,typeof Z.durationMs=="number"?Z.durationMs:je==="error"?9e3:3500)}}catch{}},Ee.onclose=()=>{S(!1),ee=setTimeout(re,be),be=Math.min(be*1.5,8e3)},Ee.onerror=()=>{Ee.close()}}re();function we(){var Ee;document.visibilityState==="visible"&&((Ee=k.current)==null?void 0:Ee.readyState)!==WebSocket.OPEN&&(clearTimeout(ee),be=1e3,re())}return document.addEventListener("visibilitychange",we),()=>{clearTimeout(ee),document.removeEventListener("visibilitychange",we),k.current&&(k.current.onclose=null,k.current.close())}},[]);const Y=x.useCallback(A=>{var L;((L=k.current)==null?void 0:L.readyState)===WebSocket.OPEN&&k.current.send(JSON.stringify(A))},[]);return{connected:w,sendMessage:Y,docVersionRef:N}}function pF(t){const[e,n]=x.useState(null),[r,s]=x.useState(!1),[i,o]=x.useState(null),l=x.useRef(void 0);return x.useEffect(()=>{if(!t){n(null),s(!1),o(null),l.current=void 0;return}t!==l.current&&(l.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(`
|
|
210
|
+
This only removes the OpenWriter registration. Your GitHub repo is untouched.`))return;const I=await Nu("remove_blog_site",{id:_.id});if(I!=null&&I.error){alert(`Remove failed: ${I.error}`);return}await w()};return c.jsxs("div",{className:"github-plugin-settings",children:[c.jsxs("div",{className:"github-plugin-settings__header",children:[c.jsx("span",{className:"github-plugin-settings__title",children:"Blog repos"}),s==="closed"&&c.jsx("button",{className:"github-plugin-settings__add-btn",onClick:()=>i("url"),children:"+ Add"})]}),n?c.jsx("div",{className:"github-plugin-settings__loading",children:"Loading…"}):t.length===0&&s==="closed"?c.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 ",c.jsx("code",{children:"gh auth login"}),"."]}):c.jsx("div",{className:"github-plugin-settings__list",children:t.map(_=>c.jsxs("div",{className:"github-plugin-settings__site",children:[c.jsxs("div",{className:"github-plugin-settings__site-info",children:[c.jsxs("div",{className:"github-plugin-settings__site-row1",children:[c.jsx("span",{className:"github-plugin-settings__site-label",children:_.label}),c.jsx("span",{className:`github-plugin-settings__site-framework github-plugin-settings__site-framework--${_.framework}`,children:_.framework})]}),c.jsxs("div",{className:"github-plugin-settings__site-repo",children:[_.owner,"/",_.repo,"@",_.branch]}),c.jsxs("div",{className:"github-plugin-settings__site-dirs",children:[c.jsx("span",{title:"content_dir",children:_.content_dir}),c.jsx("span",{className:"github-plugin-settings__site-sep",children:"·"}),c.jsx("span",{title:"image_public_prefix",children:_.image_public_prefix})]})]}),c.jsx("button",{className:"github-plugin-settings__remove-btn",onClick:()=>M(_),title:"Remove",children:"×"})]},_.id))}),s==="url"&&c.jsxs("div",{className:"github-plugin-settings__form",children:[c.jsx("label",{className:"github-plugin-settings__label",children:"GitHub repo"}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",placeholder:"owner/repo or https://github.com/owner/repo",value:o,onChange:_=>l(_.target.value),onKeyDown:_=>{_.key==="Enter"&&!d&&N()},autoFocus:!0}),h&&c.jsx("div",{className:"github-plugin-settings__error",children:h}),c.jsxs("div",{className:"github-plugin-settings__form-buttons",children:[c.jsx("button",{className:"github-plugin-settings__btn github-plugin-settings__btn--primary",onClick:N,disabled:d||!o.trim(),children:d?"Inspecting…":"Inspect"}),c.jsx("button",{className:"github-plugin-settings__btn",onClick:S,disabled:d,children:"Cancel"})]})]}),(s==="review"||s==="saving")&&g&&c.jsxs("div",{className:"github-plugin-settings__form",children:[c.jsxs("div",{className:"github-plugin-settings__form-meta",children:[c.jsxs("span",{children:["Detected: ",g.framework]}),c.jsx("span",{children:"·"}),c.jsxs("span",{children:[g.markdown_files_found," posts"]}),c.jsx("span",{children:"·"}),c.jsxs("span",{className:`github-plugin-settings__confidence github-plugin-settings__confidence--${g.confidence}`,children:[g.confidence," confidence"]})]}),c.jsx("label",{className:"github-plugin-settings__label",children:"Label"}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.label,onChange:_=>v({...g,label:_.target.value})}),c.jsx("label",{className:"github-plugin-settings__label",children:"Branch"}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.branch,onChange:_=>v({...g,branch:_.target.value})}),c.jsx("label",{className:"github-plugin-settings__label",children:"Content directory"}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.content_dir,onChange:_=>v({...g,content_dir:_.target.value})}),c.jsx("label",{className:"github-plugin-settings__label",children:"Image directory"}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.image_dir,onChange:_=>v({...g,image_dir:_.target.value})}),c.jsx("label",{className:"github-plugin-settings__label",children:"Image public prefix"}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",value:g.image_public_prefix,onChange:_=>v({...g,image_public_prefix:_.target.value})}),c.jsxs("label",{className:"github-plugin-settings__label",children:["Site URL ",c.jsx("span",{className:"github-plugin-settings__hint",children:"— optional, used for the live link after publish"})]}),c.jsx("input",{className:"github-plugin-settings__input",type:"text",placeholder:"https://example.com",value:g.site_url||"",onChange:_=>v({...g,site_url:_.target.value})}),c.jsxs("label",{className:"github-plugin-settings__label",children:["Blog URL pattern ",c.jsxs("span",{className:"github-plugin-settings__hint",children:["— uses ","{slug}"," placeholder"]})]}),c.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})}),c.jsx("label",{className:"github-plugin-settings__label",children:"Framework"}),c.jsxs("select",{className:"github-plugin-settings__input",value:g.framework,onChange:_=>v({...g,framework:_.target.value}),children:[c.jsx("option",{value:"astro",children:"Astro"}),c.jsx("option",{value:"next",children:"Next"}),c.jsx("option",{value:"jekyll",children:"Jekyll"}),c.jsx("option",{value:"hugo",children:"Hugo"}),c.jsx("option",{value:"unknown",children:"Unknown"})]}),g.frontmatter_schema.length>0&&c.jsxs("div",{className:"github-plugin-settings__schema",children:[c.jsxs("span",{className:"github-plugin-settings__label",children:["Frontmatter keys detected (",g.samples_analyzed," ",g.samples_analyzed===1?"sample":"samples",")"]}),c.jsx("code",{children:g.frontmatter_schema.join(", ")})]}),Object.keys(g.frontmatter_defaults||{}).length>0&&c.jsxs("div",{className:"github-plugin-settings__schema",children:[c.jsx("span",{className:"github-plugin-settings__label",children:"Frontmatter defaults (constants applied to every post)"}),c.jsx("code",{children:Object.entries(g.frontmatter_defaults).map(([_,R])=>c.jsxs("div",{children:[_,": ",typeof R=="string"?R:JSON.stringify(R)]},_))})]}),Object.keys(g.frontmatter_field_map||{}).length>0&&c.jsxs("div",{className:"github-plugin-settings__schema",children:[c.jsx("span",{className:"github-plugin-settings__label",children:"Field name mapping (openwriter → site)"}),c.jsx("code",{children:Object.entries(g.frontmatter_field_map).map(([_,R])=>c.jsxs("div",{children:[_," → ",R]},_))})]}),b&&c.jsx("div",{className:"github-plugin-settings__error",children:b}),c.jsxs("div",{className:"github-plugin-settings__form-buttons",children:[c.jsx("button",{className:"github-plugin-settings__btn github-plugin-settings__btn--primary",onClick:T,disabled:s==="saving"||!g.label.trim(),children:s==="saving"?"Saving…":"Add site"}),c.jsx("button",{className:"github-plugin-settings__btn",onClick:S,disabled:s==="saving",children:"Cancel"})]})]})]})}const H8={none:"No Plan",free:"No Plan",creator:"Publish — $19/mo",growth:"Publish+Email — $49/mo"},W8=[{plan:"creator",label:"Publish $19/mo"},{plan:"growth",label:"Publish+Email $49/mo"}];function V8(){var d,f;const[t,e]=x.useState(null),[n,r]=x.useState(!0);x.useEffect(()=>{fetch("/api/billing").then(h=>h.json()).then(h=>e(h)).catch(()=>{}).finally(()=>r(!1))},[]);const s=x.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=x.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 c.jsx("div",{className:"billing-section",children:c.jsx("div",{className:"billing-loading",children:"Loading..."})});if(!(t!=null&&t.authenticated))return null;const o=t.plan||"free",l=W8.filter(h=>{const m=["free","creator","growth"];return m.indexOf(h.plan)>m.indexOf(o)});return c.jsxs("div",{className:"billing-section",children:[c.jsxs("div",{className:"billing-plan",children:[c.jsx("span",{className:"billing-plan-label",children:"Plan"}),c.jsx("span",{className:`billing-plan-badge billing-plan-badge--${o}`,children:H8[o]||o})]}),((d=t.billing)==null?void 0:d.paymentFailed)&&c.jsx("div",{className:"billing-warning",children:"Payment failed — update card to keep your plan."}),l.length>0&&c.jsx("div",{className:"billing-upgrades",children:l.map(h=>c.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)&&c.jsx("button",{className:"billing-manage-btn",onClick:i,children:"Manage Billing"})]})}const q8=[{label:"Fast",cost:"free"},{label:"Fast+",cost:"$"},{label:"Sonnet",cost:"$$"},{label:"Opus",cost:"$$$"}];function K8(){const[t,e]=x.useState(null),[n,r]=x.useState([]),[s,i]=x.useState(!0),[o,l]=x.useState(!1),d=x.useCallback(()=>{Promise.all([a$(),l$()]).then(([f,h])=>{f!=null&&f.wallet&&e(f.wallet.balanceCents),r(h)}).finally(()=>i(!1))},[]);return x.useEffect(()=>{d()},[d]),x.useEffect(()=>{const f=()=>{document.visibilityState==="visible"&&d()};return document.addEventListener("visibilitychange",f),()=>document.removeEventListener("visibilitychange",f)},[d]),s?c.jsx("div",{className:"billing-section",children:c.jsx("div",{className:"billing-loading",children:"Loading…"})}):t===null&&n.length===0?null:c.jsxs("div",{className:"billing-section",children:[c.jsxs("div",{className:"billing-plan",children:[c.jsx("span",{className:"billing-plan-label",children:"Balance"}),c.jsx("span",{className:"av-credits-balance",children:t===null?"—":o$(t)})]}),c.jsx("div",{className:"av-credits-legend",children:q8.map(f=>c.jsxs("span",{className:"av-credits-legend-item",children:[c.jsx("span",{className:"av-credits-model",children:f.label}),c.jsx("span",{className:"av-credits-cost",children:f.cost})]},f.label))}),n.length>0&&c.jsxs(c.Fragment,{children:[c.jsxs("button",{className:"av-credits-topup-toggle",onClick:()=>l(f=>!f),children:[c.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:c.jsx("polyline",{points:"9 18 15 12 9 6"})}),"Add balance"]}),o&&c.jsx("div",{className:"billing-upgrades",children:n.map(f=>c.jsxs("button",{className:"billing-upgrade-btn",onClick:()=>CT(f.amountDollars),children:["Add $",f.amountDollars]},f.priceId))})]})]})}function $k(t){return t.replace(/^@openwriter\/plugin-/,"").replace(/-/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function G8({status:t}){return t==="saving"?c.jsx("span",{className:"plugin-config-status plugin-config-status--saving",children:"Saving…"}):t==="saved"?c.jsxs("span",{className:"plugin-config-status plugin-config-status--saved",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#22c55e",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Saved"]}):t==="error"?c.jsxs("span",{className:"plugin-config-status plugin-config-status--error",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),"Failed"]}):null}function J8(t){const[e,n]=x.useState([]),[r,s]=x.useState(null),[i,o]=x.useState(new Set),[l,d]=x.useState({}),f=x.useCallback(()=>{fetch("/api/available-plugins").then(g=>g.json()).then(g=>n(g.plugins||[])).catch(()=>{})},[]);x.useEffect(()=>{f()},[f]),x.useEffect(()=>{const g=()=>f();return window.addEventListener("ow-plugins-changed",g),()=>window.removeEventListener("ow-plugins-changed",g)},[f]);const h=x.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=x.useCallback(async(g,v,b)=>{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]:b}})});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 c.jsx("div",{className:"plugins-tab",children:e.length===0?c.jsx("div",{className:"plugin-empty",children:"No plugins found"}):e.map(g=>c.jsxs("div",{className:"plugin-item",children:[c.jsxs("div",{className:"plugin-item-header",children:[c.jsxs("div",{className:"plugin-item-info",children:[c.jsxs("div",{className:"plugin-item-name",children:[$k(g.name),c.jsxs("span",{className:"plugin-item-version",children:["v",g.version]})]}),g.description&&c.jsx("div",{className:"plugin-item-desc",children:g.description})]}),c.jsxs("label",{className:`plugin-toggle${r===g.name?" loading":""}`,children:[c.jsx("input",{type:"checkbox",checked:g.enabled,disabled:r===g.name,onChange:()=>h(g.name,g.enabled)}),c.jsx("span",{className:"plugin-toggle-track"}),c.jsx("span",{className:"plugin-toggle-thumb"})]})]}),g.enabled&&(()=>{const v=Object.entries(g.configSchema||{}),b=v.filter(([,T])=>T.type==="select"),k=v.filter(([,T])=>T.type!=="select"),w=v.some(([T,M])=>M.required&&!g.config[T]),S=g.name==="@openwriter/plugin-authors-voice"?c.jsx(K8,{}):g.name==="@openwriter/plugin-publish"?c.jsx(V8,{}):g.name==="@openwriter/plugin-github"?c.jsx(U8,{}):null,N=(T,M)=>{const _=l[`${g.name}:${T}`]||"idle";return c.jsxs("div",{className:"plugin-config-field",children:[c.jsxs("label",{className:"plugin-config-label",children:[M.description||T,c.jsx(G8,{status:_})]}),M.options?c.jsxs("select",{className:"plugin-config-input",defaultValue:g.config[T]||"",onChange:R=>m(g.name,T,R.target.value),children:[!M.required&&!M.options.some(R=>R.value==="")&&c.jsx("option",{value:"",children:"—"}),M.options.map(R=>c.jsx("option",{value:R.value,children:R.label},R.value))]}):c.jsx("input",{className:"plugin-config-input",type:T.toLowerCase().includes("key")||T.toLowerCase().includes("secret")||T.toLowerCase().includes("token")?"password":"text",defaultValue:g.config[T]||"",placeholder:M.env?`$${M.env}`:"",onBlur:R=>m(g.name,T,R.target.value)})]},T)};return v.length===0&&!S?null:c.jsxs("div",{className:"plugin-config-section",children:[w&&c.jsxs("div",{className:"plugin-setup-hint",children:["Ask your agent: “set up ",$k(g.name),"”"]}),b.length>0&&c.jsx("div",{className:"plugin-config",children:b.map(([T,M])=>N(T,M))}),S,k.length>0&&c.jsxs(c.Fragment,{children:[c.jsxs("button",{className:"plugin-config-toggle",onClick:()=>o(T=>{const M=new Set(T);return M.has(g.name)?M.delete(g.name):M.add(g.name),M}),children:[c.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:c.jsx("polyline",{points:"9 18 15 12 9 6"})}),"Settings"]}),i.has(g.name)&&c.jsx("div",{className:"plugin-config",children:k.map(([T,M])=>N(T,M))})]})]})})()]},g.name))})}function Y8({existingConnection:t,onClose:e,onSaved:n}){const[r,s]=x.useState("form"),[i,o]=x.useState(null),[l,d]=x.useState((t==null?void 0:t.domain)||""),[f,h]=x.useState(""),[m,g]=x.useState((t==null?void 0:t.from_name)||""),[v,b]=x.useState(""),[k,w]=x.useState((t==null?void 0:t.id)||""),[S,N]=x.useState({dns_verified:!1,sender_verified:!1}),T=x.useRef(null),M=x.useRef(null);x.useEffect(()=>{const K=F=>{r!=="submitting"&&r!=="verifying"&&M.current&&!M.current.contains(F.target)&&e()};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[e,r]),x.useEffect(()=>{const K=F=>{F.key==="Escape"&&r!=="submitting"&&r!=="verifying"&&e()};return document.addEventListener("keydown",K),()=>document.removeEventListener("keydown",K)},[e,r]),x.useEffect(()=>()=>{T.current&&clearInterval(T.current)},[]);async function _(){var K,F;s("submitting"),o(null);try{const $=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"setup_custom_domain",arguments:{domain:l,from_email:f,from_name:m||void 0,physical_address:v}})})).json(),W=(F=(K=$.content)==null?void 0:K[0])!=null&&F.text?JSON.parse($.content[0].text):$;if(W.error){o(W.error),s("error");return}const q=W.connectionId||W.connection_id||k;q&&w(q),I(q)}catch(J){o(J.message),s("error")}}async function R(){var K,F;s("submitting"),o(null);try{const $=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"setup_custom_domain",arguments:{domain:l,from_email:f||void 0,from_name:m||void 0,physical_address:v||void 0}})})).json(),W=(F=(K=$.content)==null?void 0:K[0])!=null&&F.text?JSON.parse($.content[0].text):$;if(W.error){o(W.error),s("error");return}s("done")}catch(J){o(J.message),s("error")}}function I(K){s("verifying"),T.current=setInterval(async()=>{var F,J;try{const W=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"check_domain_status",arguments:{connectionId:K}})})).json(),q=(J=(F=W.content)==null?void 0:F[0])!=null&&J.text?JSON.parse(W.content[0].text):W,ne=!!q.dns_verified,V=!!q.sender_verified;N({dns_verified:ne,sender_verified:V}),ne&&V&&(T.current&&clearInterval(T.current),T.current=null,s("done"))}catch{}},5e3)}function P(){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,z=l.trim()&&f.trim()&&v.trim();return c.jsx("div",{className:"newsletter-modal-overlay",children:c.jsxs("div",{className:"newsletter-modal newsletter-modal--setup",ref:M,children:[c.jsxs("div",{className:"newsletter-modal__header",children:[c.jsx("h3",{children:B?"Newsletter Settings":"Set Up Newsletter"}),c.jsx("button",{className:"newsletter-modal__close",onClick:e,children:"×"})]}),c.jsxs("div",{className:"newsletter-modal__body",children:[r==="form"&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"newsletter-modal__field",children:[c.jsx("label",{className:"newsletter-modal__label",children:"Domain"}),c.jsx("input",{className:"newsletter-modal__input",type:"text",placeholder:"yourdomain.com",value:l,onChange:K=>d(K.target.value),disabled:B,autoComplete:"off"})]}),c.jsxs("div",{className:"newsletter-modal__field",children:[c.jsx("label",{className:"newsletter-modal__label",children:"From Email"}),c.jsx("input",{className:"newsletter-modal__input",type:"email",placeholder:"newsletter@yourdomain.com",value:f,onChange:K=>h(K.target.value),autoComplete:"off"})]}),c.jsxs("div",{className:"newsletter-modal__field",children:[c.jsxs("label",{className:"newsletter-modal__label",children:["From Name ",c.jsx("span",{className:"newsletter-modal__optional",children:"(optional)"})]}),c.jsx("input",{className:"newsletter-modal__input",type:"text",placeholder:"Your Name or Brand",value:m,onChange:K=>g(K.target.value),autoComplete:"off"})]}),c.jsxs("div",{className:"newsletter-modal__field",children:[c.jsxs("label",{className:"newsletter-modal__label",children:["Physical Address ",c.jsx("span",{className:"newsletter-modal__required",children:"*"})]}),c.jsx("textarea",{className:"newsletter-modal__input newsletter-modal__textarea",rows:2,placeholder:"123 Main St, City, State 12345",value:v,onChange:K=>b(K.target.value)}),c.jsx("span",{className:"newsletter-modal__hint",children:"Required by CAN-SPAM. Included in email footer."})]}),c.jsxs("div",{className:"newsletter-modal__actions",children:[c.jsx("button",{className:"newsletter-modal__btn",onClick:e,children:"Cancel"}),c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:B?R:_,disabled:!z,children:B?"Save":"Set Up Domain"})]})]}),r==="submitting"&&c.jsxs("div",{className:"newsletter-modal__status",children:[c.jsx("div",{className:"newsletter-modal__spinner"}),c.jsx("span",{children:B?"Saving...":"Setting up domain..."})]}),r==="verifying"&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"newsletter-modal__verify",children:[c.jsx("p",{className:"newsletter-modal__verify-title",children:"Verifying domain setup..."}),c.jsxs("div",{className:"newsletter-modal__verify-checks",children:[c.jsxs("div",{className:`newsletter-modal__verify-item${S.dns_verified?" newsletter-modal__verify-item--done":""}`,children:[S.dns_verified?"✓":c.jsx("span",{className:"newsletter-modal__spinner newsletter-modal__spinner--sm"}),c.jsx("span",{children:"DNS records"})]}),c.jsxs("div",{className:`newsletter-modal__verify-item${S.sender_verified?" newsletter-modal__verify-item--done":""}`,children:[S.sender_verified?"✓":c.jsx("span",{className:"newsletter-modal__spinner newsletter-modal__spinner--sm"}),c.jsx("span",{children:"Sender verification"})]})]}),c.jsx("p",{className:"newsletter-modal__hint",children:"This may take a few minutes. You can close and check back later."})]}),c.jsxs("div",{className:"newsletter-modal__actions",children:[c.jsx("button",{className:"newsletter-modal__btn",onClick:P,children:"Resend Verification"}),c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>{n(),e()},children:"Close"})]})]}),r==="done"&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"newsletter-modal__status newsletter-modal__status--success",children:B?"Settings saved!":"Newsletter domain configured!"}),c.jsx("div",{className:"newsletter-modal__actions",children:c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>{n(),e()},children:"Done"})})]}),r==="error"&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"newsletter-modal__error",children:i}),c.jsxs("div",{className:"newsletter-modal__actions",children:[c.jsx("button",{className:"newsletter-modal__btn",onClick:e,children:"Cancel"}),c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>s("form"),children:"Try Again"})]})]})]})]})})}const X8={x:[],linkedin:[]};function Q8({connectionId:t,provider:e,displayName:n,onClose:r,onSaved:s}){const[i,o]=x.useState("loading"),[l,d]=x.useState({}),[f,h]=x.useState(null),m=x.useRef(null),g=X8[e]||[];x.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]),x.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]),x.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(l)}),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 b(k){switch(k){case"x":return"X (Twitter)";case"linkedin":return"LinkedIn";default:return k}}return c.jsx("div",{className:"conn-config-overlay",children:c.jsxs("div",{className:"conn-config-modal",ref:m,children:[c.jsxs("div",{className:"conn-config-modal__header",children:[c.jsxs("div",{className:"conn-config-modal__title",children:[b(e)," Settings"]}),c.jsx("div",{className:"conn-config-modal__subtitle",children:n})]}),i==="loading"&&c.jsxs("div",{className:"conn-config-modal__body conn-config-modal__center",children:[c.jsx("div",{className:"conn-config-spinner"}),c.jsx("span",{children:"Loading configuration..."})]}),(i==="form"||i==="error")&&g.length>0&&c.jsxs("div",{className:"conn-config-modal__body",children:[g.map(k=>c.jsxs("div",{className:"conn-config-field",children:[c.jsxs("label",{className:"conn-config-field__label",children:[k.label,k.readonly&&c.jsx("span",{className:"conn-config-field__badge",children:"read-only"})]}),c.jsx("input",{className:"conn-config-field__input",value:l[k.key]||"",placeholder:k.placeholder,readOnly:k.readonly,onChange:w=>d(S=>({...S,[k.key]:w.target.value}))})]},k.key)),f&&c.jsx("div",{className:"conn-config-modal__error",children:f})]}),(i==="form"||i==="error")&&g.length===0&&c.jsx("div",{className:"conn-config-modal__body conn-config-modal__center",children:c.jsxs("span",{className:"conn-config-modal__empty",children:["No configuration needed for ",b(e),"."]})}),i==="saving"&&c.jsxs("div",{className:"conn-config-modal__body conn-config-modal__center",children:[c.jsx("div",{className:"conn-config-spinner"}),c.jsx("span",{children:"Saving..."})]}),i==="saved"&&c.jsxs("div",{className:"conn-config-modal__body conn-config-modal__center",children:[c.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#22c55e",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),c.jsx("span",{children:"Saved"})]}),c.jsxs("div",{className:"conn-config-modal__footer",children:[c.jsx("button",{className:"conn-config-btn conn-config-btn--secondary",onClick:r,children:i==="saved"?"Close":"Cancel"}),g.length>0&&(i==="form"||i==="error")&&c.jsx("button",{className:"conn-config-btn conn-config-btn--primary",onClick:v,children:"Save"})]})]})})}const Z8=[{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 c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:c.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 c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:c.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 c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),c.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]});default:return c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("circle",{cx:"12",cy:"12",r:"10"})})}}function eF(t){return t==="active"?"connections-status--active":t==="expired"?"connections-status--expired":t==="revoked"?"connections-status--revoked":"connections-status--pending"}function tF(t){const[e,n]=x.useState([]),[r,s]=x.useState(null),[i,o]=x.useState(null),[l,d]=x.useState(null),[f,h]=x.useState(null),[m,g]=x.useState(null),v=x.useRef(null);async function b(){try{const R=await(await fetch("/api/connections")).json();s(R.authenticated!==!1);const I=(R.connections||[]).filter(P=>P&&P.id&&P.provider);return n(I),I}catch{return[]}}x.useEffect(()=>{b()},[]),x.useEffect(()=>()=>{v.current&&clearInterval(v.current)},[]);async function k(_){d(_);try{const R=await fetch(`/api/connections/oauth/${_}/start`,{method:"POST"}),I=await R.json();if(!R.ok||!I.url){d(null);return}window.open(I.url,"_blank","width=600,height=700"),v.current=setInterval(async()=>{try{const B=await(await fetch(`/api/connections/oauth/${_}/status/${I.state}`)).json();if(B.status==="completed"){v.current&&clearInterval(v.current),v.current=null,d(null);const z=await b();if(_==="x"){const K=z.find(F=>F.provider==="x"&&F.status==="active");if(K!=null&&K.display_name){const F=K.display_name.replace("@","");localStorage.setItem("ow-x-handle",F),window.dispatchEvent(new StorageEvent("storage",{key:"ow-x-handle",newValue:F}))}}}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 I=await R.json().catch(()=>({error:"Delete failed"}));console.error("[Connections] Delete failed:",I.error)}}catch(R){console.error("[Connections] Delete error:",R)}o(null),await b()}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 T=new Set,M=r===!1;return c.jsxs("div",{className:"connections-tab",children:[m&&c.jsx(Q8,{connectionId:m.id,provider:m.provider,displayName:m.display_name,onClose:()=>g(null),onSaved:()=>b()}),f&&c.jsx(Y8,{existingConnection:f==="edit"?S.get("newsletter"):null,onClose:()=>h(null),onSaved:()=>b()}),M?c.jsxs("div",{className:"connections-dropdown__upsell",children:[c.jsx("p",{children:"Connect your X, LinkedIn, and other accounts to publish directly from OpenWriter."}),c.jsxs("p",{children:["Set up the ",c.jsx("strong",{children:"Publish"})," plugin to get started."]})]}):c.jsx("div",{className:"connections-dropdown__list",children:Z8.flatMap(_=>{const R=T.has(_.id),I=N.get(_.id)||[],P=z=>i===z.id?c.jsxs("div",{className:"connections-dropdown__confirm",children:[c.jsxs("span",{children:["Disconnect ",z.display_name||_.label,"?"]}),c.jsxs("div",{className:"connections-dropdown__confirm-btns",children:[c.jsx("button",{onClick:()=>w(z.id),children:"Yes"}),c.jsx("button",{onClick:()=>o(null),children:"No"})]})]},z.id):c.jsxs("div",{className:"connections-dropdown__item",children:[c.jsx("div",{className:"connections-dropdown__icon",children:Bp(_.id)}),c.jsxs("div",{className:"connections-dropdown__info",children:[c.jsx("div",{className:"connections-dropdown__name",children:z.display_name||z.domain||_.label}),c.jsxs("div",{className:"connections-dropdown__type",children:[c.jsx("span",{className:`connections-status ${eF(z.status)}`}),"Connected"]})]}),c.jsxs("div",{className:"connections-dropdown__actions",children:[c.jsx("button",{className:"connections-dropdown__action-btn",onClick:()=>{_.id==="newsletter"?h("edit"):g({id:z.id,provider:_.id,display_name:z.display_name||_.label})},title:"Settings",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.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"}),c.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),c.jsx("button",{className:"connections-dropdown__action-btn connections-dropdown__action-btn--delete",onClick:()=>o(z.id),title:"Disconnect",children:"×"})]})]},z.id),B=I.map(P);return R?(B.push(c.jsx("div",{className:"connections-dropdown__add-row",children:c.jsx("button",{className:"connections-dropdown__add-btn",onClick:()=>k(_.id),disabled:l!==null,children:l===_.id?"Connecting…":`+ Add ${_.label} repo`})},`${_.id}__add`)),B):I.length>0?B:_.oauth?[c.jsxs("div",{className:"connections-dropdown__item connections-dropdown__item--disconnected",children:[c.jsx("div",{className:"connections-dropdown__icon",children:Bp(_.id)}),c.jsxs("div",{className:"connections-dropdown__info",children:[c.jsx("div",{className:"connections-dropdown__name",children:_.label}),c.jsx("div",{className:"connections-dropdown__type",children:"Not connected"})]}),c.jsx("button",{className:"connections-dropdown__connect-inline-btn",onClick:()=>k(_.id),disabled:l!==null,children:l===_.id?"Connecting…":"Connect"})]},_.id)]:[c.jsxs("div",{className:"connections-dropdown__item connections-dropdown__item--disconnected",children:[c.jsx("div",{className:"connections-dropdown__icon",children:Bp(_.id)}),c.jsxs("div",{className:"connections-dropdown__info",children:[c.jsx("div",{className:"connections-dropdown__name",children:_.label}),c.jsx("div",{className:"connections-dropdown__type",children:"Built-in · Not configured"})]}),c.jsx("button",{className:"connections-dropdown__connect-inline-btn",onClick:()=>h("new"),children:"Configure"})]},_.id)]})})]})}const nF={tree:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M3 3h7v7H3zM14 3h7v4h-7zM14 10h7v4h-7zM3 13h7v8H3z"})}),files:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),c.jsx("polyline",{points:"14 2 14 8 20 8"})]}),timeline:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"2",x2:"12",y2:"22"}),c.jsx("circle",{cx:"12",cy:"6",r:"2"}),c.jsx("circle",{cx:"12",cy:"12",r:"2"}),c.jsx("circle",{cx:"12",cy:"18",r:"2"}),c.jsx("line",{x1:"14",y1:"6",x2:"20",y2:"6"}),c.jsx("line",{x1:"14",y1:"12",x2:"20",y2:"12"}),c.jsx("line",{x1:"14",y1:"18",x2:"20",y2:"18"})]}),board:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"5",height:"18",rx:"1"}),c.jsx("rect",{x:"10",y:"3",width:"5",height:"12",rx:"1"}),c.jsx("rect",{x:"17",y:"3",width:"5",height:"15",rx:"1"})]}),shelf:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M4 19V5"}),c.jsx("path",{d:"M8 19V7"}),c.jsx("path",{d:"M12 19V4"}),c.jsx("path",{d:"M16 19V8"}),c.jsx("path",{d:"M20 19V6"}),c.jsx("line",{x1:"2",y1:"20",x2:"22",y2:"20"})]})};function rF(t){const[e,n]=x.useState(jE),[r,s]=x.useState(ME),[i,o]=x.useState($d),l=AE(),[d,f]=x.useState(OE),[h,m]=x.useState(IE),g=(N=e,T=r,M=i,_=l,R=d,I=h)=>{LE(N,T,M,_,R,I)},v=N=>{n(N),g(N)},b=()=>{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 c.jsxs("div",{className:"appearance-tab",children:[c.jsx("div",{className:"appearance-section",children:c.jsxs("div",{className:"appearance-section-header",children:[c.jsx("span",{className:"appearance-section-title",children:"Mode"}),c.jsxs("button",{className:"appearance-mode-btn",onClick:b,title:r==="light"?"Switch to dark":"Switch to light",children:[r==="light"?c.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"5"}),c.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),c.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),c.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),c.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),c.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),c.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),c.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),c.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]}):c.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})}),c.jsx("span",{children:r==="light"?"Light":"Dark"})]})]})}),c.jsxs("div",{className:"appearance-section",children:[c.jsx("div",{className:"appearance-section-header",children:c.jsx("span",{className:"appearance-section-title",children:"Typography"})}),c.jsx("div",{className:"appearance-typeface-grid",children:NE.map(N=>c.jsx("button",{className:`appearance-style-option ${e===N.id?"active":""}`,onClick:()=>v(N.id),title:N.description,children:N.label},N.id))})]}),c.jsxs("div",{className:"appearance-section",children:[c.jsx("div",{className:"appearance-section-header",children:c.jsx("span",{className:"appearance-section-title",children:"Spacing"})}),c.jsx("div",{className:"appearance-typography-grid",children:TE.map(N=>c.jsx("button",{className:`appearance-style-option ${d===N.id?"active":""}`,onClick:()=>w(N.id),children:N.label},N.id))})]}),c.jsxs("div",{className:"appearance-section",children:[c.jsx("div",{className:"appearance-section-header",children:c.jsx("span",{className:"appearance-section-title",children:"Canvas"})}),c.jsx("div",{className:"appearance-style-grid",children:_E.map(N=>c.jsx("button",{className:`appearance-style-option ${h===N.id?"active":""}`,onClick:()=>S(N.id),children:N.label},N.id))})]}),c.jsxs("div",{className:"appearance-section",children:[c.jsx("div",{className:"appearance-section-header",children:c.jsx("span",{className:"appearance-section-title",children:"Layout"})}),c.jsx("div",{className:"appearance-mode-grid",children:CE.map(N=>c.jsxs("button",{className:`appearance-mode-option ${i===N.id?"active":""}`,onClick:()=>k(N.id),children:[nF[N.icon],c.jsx("span",{children:N.label})]},N.id))})]})]})}const JT=[{id:"review",label:"Review",scope:"doc",icon:c.jsx($5,{}),Component:k8},{id:"activity",label:"Activity",scope:"workspace",icon:c.jsx(H5,{}),Component:F8},{id:"backlinks",label:"Backlinks",scope:"doc",icon:c.jsx(z5,{}),Component:C8},{id:"exports",label:"Export",scope:"doc",icon:c.jsx(U5,{}),Component:T8},{id:"versions",label:"Versions",scope:"doc",icon:c.jsx(F5,{}),Component:N8},{id:"plugins",label:"Plugins",scope:"settings",icon:c.jsx(W5,{}),Component:J8},{id:"connections",label:"Connections",scope:"settings",icon:c.jsx(V5,{}),Component:tF},{id:"appearance",label:"Appearance",scope:"settings",icon:c.jsx(q5,{}),Component:rF}];function sF(t){return t?JT.find(e=>e.id===t)??null:null}let Fk=0;function iF({pendingDocs:t}){const{visible:e,activeTab:n,openTab:r}=Ll(),[s,i]=x.useState(!1),[o,l]=x.useState(!1);return x.useEffect(()=>{const d=t.filenames.length,f=Fk;Fk=d,f===0&&d>0&&r("review")},[t.filenames.length,r]),x.useEffect(()=>{const d=()=>r("review");return window.addEventListener("ow-pending-write-applied",d),()=>window.removeEventListener("ow-pending-write-applied",d)},[r]),x.useEffect(()=>{const d=()=>{if(!(e&&n==="activity")){i(!0),window.setTimeout(()=>i(!1),500);try{localStorage.getItem("ow-bell-hint-seen")||(l(!0),localStorage.setItem("ow-bell-hint-seen","1"),window.setTimeout(()=>l(!1),6e3))}catch{}}};return window.addEventListener("ow-activity-event",d),()=>window.removeEventListener("ow-activity-event",d)},[e,n]),c.jsx("div",{className:"rail-icon-strip",role:"tablist","aria-label":"Right rail tabs",children:JT.map(d=>{const f=e&&n===d.id,h=d.id==="activity";return c.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&&c.jsxs("div",{className:"rail-icon-hint",role:"tooltip",children:[c.jsx("span",{children:"Agent activity lives here."}),c.jsx("button",{type:"button",className:"rail-icon-hint-close",onClick:m=>{m.stopPropagation(),l(!1)},"aria-label":"Dismiss",children:"×"})]})]},d.id)})})}function oF(t){const{activeTab:e}=Ll(),n=sF(e);return c.jsx("div",{className:"rail-body",role:"tabpanel",children:n?c.jsx(n.Component,{...t}):null})}const aF=()=>c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:c.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"})}),lF=()=>c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[c.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"}),c.jsx("path",{d:"M9 14l2 2 4-4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),cF=()=>c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[c.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"}),c.jsx("path",{d:"M12 16v-5M9.5 13.5L12 11l2.5 2.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),uF=()=>c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[c.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"}),c.jsx("path",{d:"M14 14l-4 4M10 14l4 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]});function dF({syncStatus:t,onSync:e}){const[n,r]=x.useState(!1),[s,i]=x.useState([]),[o,l]=x.useState(!1),d=x.useRef(null),f=x.useCallback(()=>{if(n){r(!1);return}r(!0),l(!0),fetch("/api/sync/pending").then(h=>h.json()).then(h=>i(h)).catch(()=>i([])).finally(()=>l(!1))},[n]);return x.useEffect(()=>{t.state!=="pending"&&r(!1)},[t.state]),x.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]),c.jsxs("div",{className:"sync-btn-group",ref:d,children:[c.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"&&c.jsxs(c.Fragment,{children:[c.jsx(aF,{})," Sync"]}),t.state==="synced"&&c.jsxs(c.Fragment,{children:[c.jsx(lF,{})," Synced"]}),t.state==="pending"&&c.jsxs(c.Fragment,{children:[c.jsx(cF,{})," Sync",t.pendingFiles?` (${t.pendingFiles})`:""]}),t.state==="syncing"&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"sync-btn-spinner"})," Syncing..."]}),t.state==="error"&&c.jsxs(c.Fragment,{children:[c.jsx(uF,{})," Retry"]})]}),t.state==="pending"&&t.pendingFiles&&t.pendingFiles>0&&c.jsx("button",{className:"sync-details-btn",onClick:f,title:"View pending changes",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:c.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&&c.jsxs("div",{className:"sync-pending-dropdown",children:[c.jsx("div",{className:"sync-pending-header",children:"Changes to push"}),o?c.jsx("div",{className:"sync-pending-loading",children:"Loading..."}):s.length===0?c.jsx("div",{className:"sync-pending-loading",children:"No changes"}):c.jsx("div",{className:"sync-pending-list",children:s.map((h,m)=>c.jsxs("div",{className:`sync-pending-item sync-file-${h.status}`,children:[c.jsx("span",{className:"sync-file-badge",children:h.status[0].toUpperCase()}),c.jsx("span",{className:"sync-file-name",children:h.file})]},m))})]})]})}function fF(t){const{syncStatus:e,onSync:n,onToggleToolbar:r,toolbarOpen:s,focusMode:i,onToggleFocusMode:o,...l}=t,{open:d,visible:f,overlay:h,activeTab:m,width:g,setWidth:v,closeRail:b,openTab:k}=Ll(),w=x.useRef(null),S=x.useRef(null),N=x.useRef(i);x.useEffect(()=>{if(i!==N.current)if(N.current=i,i)S.current={open:d,activeTab:m},d&&b();else{const _=S.current;S.current=null,!h&&(_!=null&&_.open)&&_.activeTab&&k(_.activeTab)}},[i]);const T=x.useCallback(_=>{_.preventDefault();const R=_.clientX,I=g,P=z=>{const K=R-z.clientX;v(I+K)},B=()=>{window.removeEventListener("pointermove",P),window.removeEventListener("pointerup",B)};window.addEventListener("pointermove",P),window.addEventListener("pointerup",B)},[g,v]);x.useEffect(()=>{if(!d)return;const _=R=>{R.key==="Escape"&&w.current&&w.current.contains(document.activeElement)&&(R.preventDefault(),b())};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[d,b]);const M=!f;return c.jsxs("aside",{ref:w,className:`right-rail-column${M?"":" open"}`,style:M?void 0:{width:g,minWidth:g},"aria-label":"Right rail",children:[!h&&!M&&c.jsx("div",{className:"right-rail-resize-handle",onPointerDown:T,"aria-hidden":"true"}),c.jsxs("div",{className:"right-rail-topbar",children:[c.jsxs("div",{className:"right-rail-topbar-actions right-rail-topbar-actions--start",children:[c.jsx("button",{type:"button",className:"right-rail-topbar-btn",onClick:b,title:"Hide rail","aria-label":"Hide rail",children:c.jsx(K5,{})}),c.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:c.jsx(ET,{})}),c.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:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M4 20h16"}),c.jsx("path",{d:"m6 16 6-12 6 12"}),c.jsx("path",{d:"M8 12h8"})]})})]}),c.jsx("div",{className:"right-rail-topbar-actions right-rail-topbar-actions--end",children:c.jsx(dF,{syncStatus:e,onSync:n})})]}),c.jsx(iF,{pendingDocs:l.pendingDocs}),c.jsx(oF,{...l})]})}function hF({onClose:t,onSetupComplete:e}){const[n,r]=x.useState("detecting"),[s,i]=x.useState(null),[o,l]=x.useState("gh"),[d,f]=x.useState("openwriter-docs"),[h,m]=x.useState(!0),[g,v]=x.useState(""),[b,k]=x.useState(""),[w,S]=x.useState(""),[N,T]=x.useState("");x.useEffect(()=>{fetch("/api/sync/capabilities").then(_=>_.json()).then(_=>{i(_),_.ghAuthenticated?l("gh"):(_.gitInstalled,l("pat")),r("setup")}).catch(()=>{S("Failed to detect git capabilities"),r("error")})},[]);const M=x.useCallback(async()=>{r("progress"),T(o==="connect"?"Connecting to repository...":"Creating repository and syncing...");try{const _={method:o,repoName:d,isPrivate:h};o==="pat"&&(_.pat=g),o==="connect"&&(_.remoteUrl=b,_.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 I=await R.json().catch(()=>({}));throw new Error(I.error||`Setup failed (${R.status})`)}r("done"),e()}catch(_){S(_.message),r("error")}},[o,d,h,g,b,e]);return c.jsx("div",{className:"sync-modal-overlay",onClick:t,children:c.jsxs("div",{className:"sync-modal",onClick:_=>_.stopPropagation(),children:[c.jsxs("div",{className:"sync-modal-header",children:[c.jsx("h2",{children:"Sync to GitHub"}),c.jsx("button",{className:"sync-modal-close",onClick:t,children:"×"})]}),n==="detecting"&&c.jsxs("div",{className:"sync-modal-body",children:[c.jsx("div",{className:"sync-spinner"}),c.jsx("p",{children:"Detecting git configuration..."})]}),n==="setup"&&s&&c.jsxs("div",{className:"sync-modal-body",children:[!s.gitInstalled&&c.jsxs("div",{className:"sync-warning",children:["Git is not installed. Please ",c.jsx("a",{href:"https://git-scm.com/downloads",target:"_blank",rel:"noreferrer",children:"install git"})," first."]}),s.gitInstalled&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"sync-tabs",children:[s.ghAuthenticated&&c.jsx("button",{className:`sync-tab${o==="gh"?" active":""}`,onClick:()=>l("gh"),children:"GitHub CLI"}),c.jsx("button",{className:`sync-tab${o==="pat"?" active":""}`,onClick:()=>l("pat"),children:"Personal Access Token"}),c.jsx("button",{className:`sync-tab${o==="connect"?" active":""}`,onClick:()=>l("connect"),children:"Connect Existing"})]}),o==="gh"&&c.jsxs("div",{className:"sync-form",children:[c.jsxs("label",{children:["Repository name",c.jsx("input",{type:"text",value:d,onChange:_=>f(_.target.value),placeholder:"openwriter-docs"})]}),c.jsxs("label",{className:"sync-checkbox",children:[c.jsx("input",{type:"checkbox",checked:h,onChange:_=>m(_.target.checked)}),"Private repository"]})]}),o==="pat"&&c.jsxs("div",{className:"sync-form",children:[!s.ghAuthenticated&&!s.ghInstalled&&c.jsxs("p",{className:"sync-hint",children:["Create a ",c.jsx("a",{href:"https://github.com/settings/tokens/new?scopes=repo&description=OpenWriter",target:"_blank",rel:"noreferrer",children:"Personal Access Token"})," with ",c.jsx("code",{children:"repo"})," scope."]}),c.jsxs("label",{children:["Personal Access Token",c.jsx("input",{type:"password",value:g,onChange:_=>v(_.target.value),placeholder:"ghp_..."})]}),c.jsxs("label",{children:["Repository name",c.jsx("input",{type:"text",value:d,onChange:_=>f(_.target.value),placeholder:"openwriter-docs"})]}),c.jsxs("label",{className:"sync-checkbox",children:[c.jsx("input",{type:"checkbox",checked:h,onChange:_=>m(_.target.checked)}),"Private repository"]})]}),o==="connect"&&c.jsxs("div",{className:"sync-form",children:[c.jsxs("label",{children:["Remote URL",c.jsx("input",{type:"text",value:b,onChange:_=>k(_.target.value),placeholder:"https://github.com/user/repo.git"})]}),c.jsxs("label",{children:["PAT (optional, for private repos)",c.jsx("input",{type:"password",value:g,onChange:_=>v(_.target.value),placeholder:"ghp_..."})]})]}),c.jsxs("div",{className:"sync-modal-actions",children:[c.jsx("button",{className:"sync-btn secondary",onClick:t,children:"Cancel"}),c.jsx("button",{className:"sync-btn primary",onClick:M,disabled:o==="pat"&&!g||o==="connect"&&!b||o!=="connect"&&!d,children:o==="connect"?"Connect & Sync":"Create & Sync"})]})]})]}),n==="progress"&&c.jsxs("div",{className:"sync-modal-body",children:[c.jsx("div",{className:"sync-spinner"}),c.jsx("p",{children:N})]}),n==="done"&&c.jsxs("div",{className:"sync-modal-body",children:[c.jsx("div",{className:"sync-success-icon",children:"✓"}),c.jsx("p",{children:"Successfully synced to GitHub!"}),c.jsx("div",{className:"sync-modal-actions",children:c.jsx("button",{className:"sync-btn primary",onClick:t,children:"Done"})})]}),n==="error"&&c.jsxs("div",{className:"sync-modal-body",children:[c.jsx("div",{className:"sync-error-msg",children:w}),c.jsxs("div",{className:"sync-modal-actions",children:[c.jsx("button",{className:"sync-btn secondary",onClick:()=>r("setup"),children:"Back"}),c.jsx("button",{className:"sync-btn secondary",onClick:t,children:"Close"})]})]})]})})}function pF({onNodeChanges:t,onAgentStatus:e,onDocumentSwitched:n,onDocumentReloaded:r,onDocumentsChanged:s,onWorkspacesChanged:i,onTitleChanged:o,onPendingDocsChanged:l,onMetadataChanged:d,onSyncStatus:f,onWritingStarted:h,onWritingFinished:m,onIdRewrites:g,onPendingFilenamesChanged:v,getEditorState:b}){const k=x.useRef(null),[w,S]=x.useState(!1),N=x.useRef(0),T=x.useRef(new Set),M=()=>{var A;return(A=ne.current)==null?void 0:A.call(ne,new Set(T.current))},_=x.useRef(t),R=x.useRef(e),I=x.useRef(n),P=x.useRef(s),B=x.useRef(i),z=x.useRef(o),K=x.useRef(l),F=x.useRef(f),J=x.useRef(d),$=x.useRef(h),W=x.useRef(m),q=x.useRef(g),ne=x.useRef(v),V=x.useRef(r),oe=x.useRef(b);_.current=t,R.current=e,I.current=n,P.current=s,B.current=i,z.current=o,K.current=l,J.current=d,F.current=f,$.current=h,W.current=m,q.current=g,ne.current=v,V.current=r,oe.current=b,x.useEffect(()=>{const L=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;let ee,ue=!1,be=1e3;function re(){const Ee=new WebSocket(L);k.current=Ee,Ee.onopen=()=>{S(!0),be=1e3,ue&&Ee.send(JSON.stringify({type:"request-document"})),ue=!0},Ee.onmessage=$e=>{var Fe,Ze,Re,tt,gt,ut,ge,yt,Ct,_t,Lt,at,De,ve;try{const Z=JSON.parse($e.data);if(Z.type==="node-changes"&&Z.changes&&((Fe=_.current)==null||Fe.call(_,Z.changes),typeof Z.version=="number"&&(N.current=Z.version)),Z.type==="id-rewrites"&&Array.isArray(Z.rewrites)&&((Ze=q.current)==null||Ze.call(q,Z.rewrites)),Z.type==="agent-status"&&((Re=R.current)==null||Re.call(R,!!Z.agentConnected)),Z.type==="document-switched"&&(N.current=0,(tt=I.current)==null||tt.call(I,{document:Z.document,title:Z.title,filename:Z.filename,docId:Z.docId,metadata:Z.metadata,pendingMetadata:Z.pendingMetadata??null}),window.dispatchEvent(new CustomEvent("ow-pending-metadata-changed",{detail:{docId:Z.docId,pendingMetadata:Z.pendingMetadata??null}}))),Z.type==="pending-metadata-changed"&&window.dispatchEvent(new CustomEvent("ow-pending-metadata-changed",{detail:{docId:Z.docId,pendingMetadata:Z.pendingMetadata??null}})),Z.type==="document-reloaded"&&(typeof Z.version=="number"&&(N.current=Z.version),(gt=V.current)==null||gt.call(V,{document:Z.document,title:Z.title,filename:Z.filename,docId:Z.docId,metadata:Z.metadata,orphanCount:typeof Z.orphanCount=="number"?Z.orphanCount:0,staleBaselineCount:typeof Z.staleBaselineCount=="number"?Z.staleBaselineCount:0})),Z.type==="metadata-changed"&&Z.metadata&&((ut=J.current)==null||ut.call(J,Z.metadata)),Z.type==="documents-changed"&&((ge=P.current)==null||ge.call(P)),Z.type==="workspaces-changed"&&((yt=B.current)==null||yt.call(B)),Z.type==="title-changed"&&Z.title&&((Ct=z.current)==null||Ct.call(z,Z.title)),Z.type==="pending-docs-changed"&&Z.pendingDocs&&((_t=K.current)==null||_t.call(K,Z.pendingDocs)),Z.type==="sync-status"&&((Lt=F.current)==null||Lt.call(F,{state:Z.state,lastSyncTime:Z.lastSyncTime,pendingFiles:Z.pendingFiles,error:Z.error})),Z.type==="writing-started"&&Z.title&&(typeof Z.key=="string"&&(T.current.add(Z.key),M()),(at=$.current)==null||at.call($,Z.title,Z.target||null)),Z.type==="writing-finished"&&(typeof Z.key=="string"&&Z.key?T.current.delete(Z.key):T.current.clear(),M(),(De=W.current)==null||De.call(W)),Z.type==="pending-writes-sync"&&Array.isArray(Z.writes)&&(T.current=new Set(Z.writes.map(je=>je.key).filter(Boolean)),M(),Z.writes.length>0)){const je=Z.writes.reduce((Q,he)=>Q.startedAt>he.startedAt?Q:he);je!=null&&je.title&&((ve=$.current)==null||ve.call($,je.title,je.target||null))}if(Z.type==="plugins-changed"&&window.dispatchEvent(new CustomEvent("ow-plugins-changed")),Z.type==="comments-changed"&&Z.filename&&window.dispatchEvent(new CustomEvent("ow-comments-changed",{detail:{filename:Z.filename}})),Z.type==="documents-changed"&&window.dispatchEvent(new CustomEvent("ow-documents-changed")),Z.type==="metadata-changed"&&window.dispatchEvent(new CustomEvent("ow-metadata-changed",{detail:{metadata:Z.metadata}})),Z.type==="activity-log"&&Array.isArray(Z.entries)&&window.dispatchEvent(new CustomEvent("ow-activity-seed",{detail:{entries:Z.entries}})),Z.type==="activity-event"&&Z.event&&window.dispatchEvent(new CustomEvent("ow-activity-event",{detail:{event:Z.event}})),Z.type==="toast"&&typeof Z.message=="string"){const je=Z.kind==="error"?"error":"info";_i(Z.message,je,typeof Z.durationMs=="number"?Z.durationMs:je==="error"?9e3:3500)}}catch{}},Ee.onclose=()=>{S(!1),ee=setTimeout(re,be),be=Math.min(be*1.5,8e3)},Ee.onerror=()=>{Ee.close()}}re();function we(){var Ee;document.visibilityState==="visible"&&((Ee=k.current)==null?void 0:Ee.readyState)!==WebSocket.OPEN&&(clearTimeout(ee),be=1e3,re())}return document.addEventListener("visibilitychange",we),()=>{clearTimeout(ee),document.removeEventListener("visibilitychange",we),k.current&&(k.current.onclose=null,k.current.close())}},[]);const Y=x.useCallback(A=>{var L;((L=k.current)==null?void 0:L.readyState)===WebSocket.OPEN&&k.current.send(JSON.stringify(A))},[]);return{connected:w,sendMessage:Y,docVersionRef:N}}function mF(t){const[e,n]=x.useState(null),[r,s]=x.useState(!1),[i,o]=x.useState(null),l=x.useRef(void 0);return x.useEffect(()=>{if(!t){n(null),s(!1),o(null),l.current=void 0;return}t!==l.current&&(l.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 gF(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
|
|
|
212
|
-
`)}function gF(t){const e=n=>{var r;if(n.type==="image"&&((r=n.attrs)!=null&&r.src))return n.attrs.src;if(n.content)for(const s of n.content){const i=e(s);if(i)return i}return null};return e(t.getJSON())}async function vF(t){try{const e=await fetch(t);if(!e.ok)return null;const n=await e.blob();return n.type==="image/png"?n:new Promise(r=>{const s=new Image,i=URL.createObjectURL(n);s.onload=()=>{const o=document.createElement("canvas");o.width=s.naturalWidth,o.height=s.naturalHeight,o.getContext("2d").drawImage(s,0,0),o.toBlob(l=>{URL.revokeObjectURL(i),r(l)},"image/png")},s.onerror=()=>{URL.revokeObjectURL(i),r(null)},s.src=i})}catch{return null}}function yF(t,e){const[n,r]=x.useState("idle"),s=x.useRef();return{copyText:x.useCallback(async()=>{const o=t.current[e];if(!o)return;const l=mF(o),d=gF(o);if(!(!l&&!d)){try{const f={};if(l&&(f["text/plain"]=new Blob([l],{type:"text/plain"})),d){const h=await vF(d);h&&(f["image/png"]=h)}Object.keys(f).length>0&&await navigator.clipboard.write([new ClipboardItem(f)])}catch{if(l){const f=document.createElement("textarea");f.value=l,f.style.position="fixed",f.style.opacity="0",document.body.appendChild(f),f.select(),document.execCommand("copy"),document.body.removeChild(f)}}r("copied"),s.current&&clearTimeout(s.current),s.current=setTimeout(()=>r("idle"),2e3)}},[t,e]),copyState:n}}function $p(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e4?`${(t/1e3).toFixed(0)}K`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function bF(t){try{const e=Date.now(),n=new Date(t).getTime(),r=Math.floor((e-n)/1e3);if(r<60)return`${r}s`;const s=Math.floor(r/60);if(s<60)return`${s}m`;const i=Math.floor(s/60);return i<24?`${i}h`:new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric"})}catch{return""}}const xF=()=>c.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:c.jsx("path",{fill:"currentColor",d:"M1.751 10c0-4.42 3.584-8 8.005-8h4.366c4.49 0 8.129 3.64 8.129 8.13 0 2.96-1.607 5.68-4.196 7.11l-8.054 4.46v-3.69h-.067c-4.49.1-8.183-3.51-8.183-8.01zm8.005-6c-3.317 0-6.005 2.69-6.005 6 0 3.37 2.77 6.08 6.138 6.01l.351-.01h1.761v2.3l5.087-2.81c1.951-1.08 3.163-3.13 3.163-5.36 0-3.39-2.744-6.13-6.129-6.13H9.756z"})}),wF=()=>c.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:c.jsx("path",{fill:"currentColor",d:"M4.5 3.88l4.432 4.14-1.364 1.46L5.5 7.55V16c0 1.1.896 2 2 2H13v2H7.5c-2.209 0-4-1.79-4-4V7.55L1.432 9.48.068 8.02 4.5 3.88zM16.5 6H11V4h5.5c2.209 0 4 1.79 4 4v8.45l2.068-1.93 1.364 1.46-4.432 4.14-4.432-4.14 1.364-1.46 2.068 1.93V8c0-1.1-.896-2-2-2z"})}),kF=()=>c.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:c.jsx("path",{fill:"currentColor",d:"M16.697 5.5c-1.222-.06-2.679.51-3.89 2.16l-.805 1.09-.806-1.09C9.984 6.01 8.526 5.44 7.304 5.5c-1.243.07-2.349.78-2.91 1.91-.552 1.12-.633 2.78.479 4.82 1.074 1.97 3.257 4.27 7.129 6.61 3.87-2.34 6.052-4.64 7.126-6.61 1.111-2.04 1.03-3.7.477-4.82-.561-1.13-1.666-1.84-2.908-1.91zm4.187 7.69c-1.351 2.48-4.001 5.12-8.379 7.67l-.503.3-.504-.3c-4.379-2.55-7.029-5.19-8.382-7.67-1.36-2.5-1.41-4.86-.514-6.67.887-1.79 2.647-2.91 4.601-3.01 1.651-.09 3.368.56 4.798 2.01 1.429-1.45 3.146-2.1 4.796-2.01 1.954.1 3.714 1.22 4.601 3.01.896 1.81.846 4.17-.514 6.67z"})}),SF=()=>c.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:c.jsx("path",{fill:"currentColor",d:"M4 4.5C4 3.12 5.119 2 6.5 2h11C18.881 2 20 3.12 20 4.5v18.44l-8-5.71-8 5.71V4.5zM6.5 4c-.276 0-.5.22-.5.5v14.56l6-4.29 6 4.29V4.5c0-.28-.224-.5-.5-.5h-11z"})}),EF=()=>c.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:c.jsx("path",{fill:"currentColor",d:"M12 2.59l5.7 5.7-1.41 1.42L13 6.41V16h-2V6.41l-3.3 3.3-1.41-1.42L12 2.59zM21 15l-.02 3.51c0 1.38-1.12 2.49-2.5 2.49H5.5C4.11 21 3 19.88 3 18.5V15h2v3.5c0 .28.22.5.5.5h12.98c.28 0 .5-.22.5-.5L19 15h2z"})});function YT({tweet:t,nested:e,url:n}){const r=bF(t.createdAt);return c.jsxs("div",{className:`tweet-embed-card${e?" tweet-embed-nested":""}${n?" tweet-embed-card--clickable":""}`,onClick:n?()=>window.open(n,"_blank","noopener,noreferrer"):void 0,role:n?"link":void 0,children:[c.jsxs("div",{className:"tweet-author-row",children:[t.author.avatarUrl?c.jsx("img",{className:"tweet-avatar",src:t.author.avatarUrl,alt:""}):c.jsx("div",{className:"tweet-avatar tweet-avatar-placeholder"}),c.jsxs("div",{className:"tweet-author-info",children:[c.jsx("span",{className:"tweet-author-name",children:t.author.name}),c.jsxs("span",{className:"tweet-author-handle",children:["@",t.author.username]}),r&&c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"tweet-author-separator",children:"·"}),c.jsx("span",{className:"tweet-author-timestamp",children:r})]})]})]}),c.jsx("div",{className:"tweet-text",children:t.text}),t.media&&t.media.length>0&&c.jsx("div",{className:"tweet-media","data-count":t.media.length,children:t.media.map((s,i)=>s.type==="photo"?c.jsx("img",{className:"tweet-media-img",src:s.url,alt:"",loading:"lazy"},i):s.type==="video"||s.type==="gif"?c.jsx("div",{className:"tweet-media-video-placeholder",children:c.jsx("span",{children:"Video"})},i):null)}),t.quoteTweet&&c.jsx(YT,{tweet:t.quoteTweet,nested:!0}),!e&&c.jsxs("div",{className:"tweet-actions-row",children:[c.jsxs("span",{className:"tweet-action tweet-action-reply",children:[c.jsx(xF,{}),t.metrics.replies>0&&$p(t.metrics.replies)]}),c.jsxs("span",{className:"tweet-action tweet-action-retweet",children:[c.jsx(wF,{}),t.metrics.retweets>0&&$p(t.metrics.retweets)]}),c.jsxs("span",{className:"tweet-action tweet-action-like",children:[c.jsx(kF,{}),t.metrics.likes>0&&$p(t.metrics.likes)]}),c.jsx("span",{className:"tweet-action tweet-action-bookmark",children:c.jsx(SF,{})}),c.jsx("span",{className:"tweet-action tweet-action-share",children:c.jsx(EF,{})})]})]})}function zk({tweet:t,url:e}){return c.jsx(YT,{tweet:t,url:e})}function NF({initialContent:t,initialPreviewImages:e,placeholder:n="What is happening?!",onUpdate:r,onReady:s,onFocus:i,onPreviewImagesChange:o}){const[l,d]=x.useState(e||[]),f=x.useRef(e||[]),h=x.useRef(!1),m=x.useRef(s);m.current=s;const g=x.useRef(o);g.current=o;const v=x.useCallback(S=>{var T;const N=S.slice(0,4);f.current=N,d(N),(T=g.current)==null||T.call(g,N)},[]),b=x.useCallback(S=>{if(h.current)return;const N=[],T=[];if(S.state.doc.descendants((I,P)=>{var B;I.type.name==="image"&&((B=I.attrs)!=null&&B.src)&&(N.push(I.attrs.src),T.push({from:P,to:P+I.nodeSize}))}),N.length===0)return;h.current=!0;const{tr:M}=S.state;for(let I=T.length-1;I>=0;I--)M.delete(T[I].from,T[I].to);S.view.dispatch(M);const _=f.current,R=4-_.length;R>0&&v([..._,...N.slice(0,R)]),h.current=!1},[v]),k=XC({extensions:[...fT,ef.configure({placeholder:n})],content:t||"<p></p>",onCreate:({editor:S})=>{b(S)},onUpdate:({editor:S})=>{b(S),r==null||r(S)},onFocus:()=>{i==null||i()},editorProps:{handlePaste:wT,handleDrop:kT}},[t]);x.useEffect(()=>{k&&M5(k.view,{addToPreview:S=>{const N=f.current;N.length>=4||v([...N,S])},getPreviewImages:()=>f.current})},[k,v]),x.useEffect(()=>{if(!k)return;const{state:S}=k.view;if(S.plugins.some(M=>M.key==="pendingDecoration$"))return;const N=vT(),T=S.reconfigure({plugins:[...S.plugins,N]});k.view.updateState(T)},[k]),x.useEffect(()=>{if(!k)return;const{state:S}=k.view;if(S.plugins.some(M=>M.key==="commentDecoration$"))return;const N=bT(),T=S.reconfigure({plugins:[...S.plugins,N]});k.view.updateState(T)},[k]),x.useEffect(()=>{var S;k&&((S=m.current)==null||S.call(m,k))},[k]);const w=x.useCallback(S=>{v(f.current.filter((N,T)=>T!==S))},[v]);return k?c.jsxs(c.Fragment,{children:[c.jsx(Pv,{editor:k}),l.length>0&&c.jsx("div",{className:"tweet-preview-grid","data-count":l.length,children:l.map((S,N)=>c.jsxs("div",{className:"tweet-image-card",children:[c.jsx("img",{className:"tweet-image-card-img",src:S,alt:"",draggable:!1}),c.jsx("button",{className:"tweet-image-card-remove",onClick:()=>w(N),title:"Remove image",children:"×"})]},S))})]}):null}function CF({count:t,softLimit:e=280}){const n=e-t,r=Math.min(t/e,1),s=n<=20,i=s?30:26,o=2,l=(i-o)/2,d=2*Math.PI*l,f=d*(1-r);let h="var(--x-blue, #1d9bf0)";return n<=0?h="var(--x-red, #f4212e)":n<=20&&(h="var(--x-yellow, #ffd400)"),t===0?null:c.jsxs("div",{className:"tweet-char-counter",title:`${t} / ${e}`,style:{width:i,height:i},children:[c.jsxs("svg",{width:i,height:i,viewBox:`0 0 ${i} ${i}`,children:[c.jsx("circle",{cx:i/2,cy:i/2,r:l,fill:"none",stroke:"var(--x-border, #eff3f4)",strokeWidth:o}),c.jsx("circle",{cx:i/2,cy:i/2,r:l,fill:"none",stroke:h,strokeWidth:o,strokeDasharray:d,strokeDashoffset:f,strokeLinecap:"round",transform:`rotate(-90 ${i/2} ${i/2})`,style:{transition:"stroke-dashoffset 0.15s ease, stroke 0.15s ease"}})]}),s&&c.jsx("span",{className:"tweet-char-number",style:{color:h,fontSize:n<-9||n>9?10:11},children:n})]})}const Uk="@openwriter/plugin-x-api",Hk=[{key:"api-key",label:"API Key",env:"X_API_KEY"},{key:"api-secret",label:"API Secret",env:"X_API_SECRET"},{key:"access-token",label:"Access Token",env:"X_ACCESS_TOKEN"},{key:"access-token-secret",label:"Access Token Secret",env:"X_ACCESS_TOKEN_SECRET"}];function _F({onConnected:t,onCancel:e}){const[n,r]=x.useState({"api-key":"","api-secret":"","access-token":"","access-token-secret":""}),[s,i]=x.useState(!1),[o,l]=x.useState(""),d=Hk.every(h=>n[h.key].trim()),f=async()=>{i(!0),l("");try{if(!(await fetch("/api/plugins/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Uk,config:n})})).ok)throw new Error("Failed to save config");const g=await(await fetch("/api/plugins/enable",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Uk})})).json();if(!g.success)throw new Error(g.error||"Failed to enable plugin");const b=await(await fetch("/api/x/status")).json();b.connected?t():l(b.error||"Could not verify X credentials. Check your API keys.")}catch(h){l(h.message||"Connection failed")}finally{i(!1)}};return c.jsxs("div",{className:"x-connect-prompt",children:[c.jsxs("div",{className:"x-connect-header",children:[c.jsx("span",{className:"x-connect-title",children:"Connect your X account to post"}),c.jsx("button",{className:"x-connect-cancel",onClick:e,title:"Cancel",children:c.jsx("svg",{viewBox:"0 0 24 24",width:"18",height:"18",children:c.jsx("path",{fill:"currentColor",d:"M10.59 12L4.54 5.96l1.42-1.42L12 10.59l6.04-6.05 1.42 1.42L13.41 12l6.05 6.04-1.42 1.42L12 13.41l-6.04 6.05-1.42-1.42L10.59 12z"})})})]}),c.jsx("div",{className:"x-connect-fields",children:Hk.map(h=>c.jsxs("div",{className:"x-connect-field",children:[c.jsx("label",{className:"x-connect-label",children:h.label}),c.jsx("input",{type:"password",className:"x-connect-input",value:n[h.key],onChange:m=>r(g=>({...g,[h.key]:m.target.value})),placeholder:h.env,spellCheck:!1,autoComplete:"off"})]},h.key))}),o&&c.jsx("div",{className:"x-connect-error",children:o}),c.jsxs("div",{className:"x-connect-actions",children:[c.jsx("a",{className:"x-connect-dev-link",href:"https://developer.x.com/en/portal/dashboard",target:"_blank",rel:"noopener noreferrer",children:"Get credentials"}),c.jsx("button",{className:"x-connect-btn",onClick:f,disabled:!d||s,children:s?"Connecting...":"Connect"})]})]})}var Wk={},Fp,Vk;function Ws(){return Vk||(Vk=1,Fp=function(t){return typeof t=="object"?t!==null:typeof t=="function"}),Fp}var zp,qk;function Mr(){if(qk)return zp;qk=1;var t=Ws();return zp=function(e){if(!t(e))throw TypeError(e+" is not an object!");return e},zp}var Up,Kk;function sf(){return Kk||(Kk=1,Up=function(t){if(t==null)throw TypeError("Can't call method on "+t);return t}),Up}var Hp,Gk;function Di(){if(Gk)return Hp;Gk=1;var t=sf();return Hp=function(e){return Object(t(e))},Hp}var Wp,Jk;function of(){if(Jk)return Wp;Jk=1;var t=Math.ceil,e=Math.floor;return Wp=function(n){return isNaN(n=+n)?0:(n>0?e:t)(n)},Wp}var Vp,Yk;function wo(){if(Yk)return Vp;Yk=1;var t=of(),e=Math.min;return Vp=function(n){return n>0?e(t(n),9007199254740991):0},Vp}var qp,Xk;function XT(){if(Xk)return qp;Xk=1;var t=of(),e=sf();return qp=function(n){return function(r,s){var i=String(e(r)),o=t(s),l=i.length,d,f;return o<0||o>=l?n?"":void 0:(d=i.charCodeAt(o),d<55296||d>56319||o+1===l||(f=i.charCodeAt(o+1))<56320||f>57343?n?i.charAt(o):d:n?i.slice(o,o+2):(d-55296<<10)+(f-56320)+65536)}},qp}var Kp,Qk;function hy(){if(Qk)return Kp;Qk=1;var t=XT()(!0);return Kp=function(e,n,r){return n+(r?t(e,n).length:1)},Kp}var Gp,Zk;function af(){if(Zk)return Gp;Zk=1;var t={}.toString;return Gp=function(e){return t.call(e).slice(8,-1)},Gp}var Jp={exports:{}},Yp={exports:{}},Xp={exports:{}},e1;function ga(){if(e1)return Xp.exports;e1=1;var t=Xp.exports={version:"2.6.12"};return typeof __e=="number"&&(__e=t),Xp.exports}var Qp={exports:{}},t1;function Kr(){if(t1)return Qp.exports;t1=1;var t=Qp.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();return typeof __g=="number"&&(__g=t),Qp.exports}var Zp,n1;function lf(){return n1||(n1=1,Zp=!1),Zp}var r1;function cf(){if(r1)return Yp.exports;r1=1;var t=ga(),e=Kr(),n="__core-js_shared__",r=e[n]||(e[n]={});return(Yp.exports=function(s,i){return r[s]||(r[s]=i!==void 0?i:{})})("versions",[]).push({version:t.version,mode:lf()?"pure":"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"}),Yp.exports}var em,s1;function Hl(){if(s1)return em;s1=1;var t=0,e=Math.random();return em=function(n){return"Symbol(".concat(n===void 0?"":n,")_",(++t+e).toString(36))},em}var i1;function zn(){if(i1)return Jp.exports;i1=1;var t=cf()("wks"),e=Hl(),n=Kr().Symbol,r=typeof n=="function",s=Jp.exports=function(i){return t[i]||(t[i]=r&&n[i]||(r?n:e)("Symbol."+i))};return s.store=t,Jp.exports}var tm,o1;function py(){if(o1)return tm;o1=1;var t=af(),e=zn()("toStringTag"),n=t((function(){return arguments})())=="Arguments",r=function(s,i){try{return s[i]}catch{}};return tm=function(s){var i,o,l;return s===void 0?"Undefined":s===null?"Null":typeof(o=r(i=Object(s),e))=="string"?o:n?t(i):(l=t(i))=="Object"&&typeof i.callee=="function"?"Arguments":l},tm}var nm,a1;function my(){if(a1)return nm;a1=1;var t=py(),e=RegExp.prototype.exec;return nm=function(n,r){var s=n.exec;if(typeof s=="function"){var i=s.call(n,r);if(typeof i!="object")throw new TypeError("RegExp exec method returned something other than an Object or null");return i}if(t(n)!=="RegExp")throw new TypeError("RegExp#exec called on incompatible receiver");return e.call(n,r)},nm}var l1={},rm,c1;function uf(){if(c1)return rm;c1=1;var t=Mr();return rm=function(){var e=t(this),n="";return e.global&&(n+="g"),e.ignoreCase&&(n+="i"),e.multiline&&(n+="m"),e.unicode&&(n+="u"),e.sticky&&(n+="y"),n},rm}var sm,u1;function gy(){if(u1)return sm;u1=1;var t=uf(),e=RegExp.prototype.exec,n=String.prototype.replace,r=e,s="lastIndex",i=(function(){var d=/a/,f=/b*/g;return e.call(d,"a"),e.call(f,"a"),d[s]!==0||f[s]!==0})(),o=/()??/.exec("")[1]!==void 0,l=i||o;return l&&(r=function(f){var h=this,m,g,v,b;return o&&(g=new RegExp("^"+h.source+"$(?!\\s)",t.call(h))),i&&(m=h[s]),v=e.call(h,f),i&&v&&(h[s]=h.global?v.index+v[0].length:m),o&&v&&v.length>1&&n.call(v[0],g,function(){for(b=1;b<arguments.length-2;b++)arguments[b]===void 0&&(v[b]=void 0)}),v}),sm=r,sm}var im={},om,d1;function ls(){return d1||(d1=1,om=function(t){try{return!!t()}catch{return!0}}),om}var am,f1;function Gr(){return f1||(f1=1,am=!ls()(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})),am}var lm,h1;function QT(){if(h1)return lm;h1=1;var t=Ws(),e=Kr().document,n=t(e)&&t(e.createElement);return lm=function(r){return n?e.createElement(r):{}},lm}var cm,p1;function ZT(){return p1||(p1=1,cm=!Gr()&&!ls()(function(){return Object.defineProperty(QT()("div"),"a",{get:function(){return 7}}).a!=7})),cm}var um,m1;function vy(){if(m1)return um;m1=1;var t=Ws();return um=function(e,n){if(!t(e))return e;var r,s;if(n&&typeof(r=e.toString)=="function"&&!t(s=r.call(e))||typeof(r=e.valueOf)=="function"&&!t(s=r.call(e))||!n&&typeof(r=e.toString)=="function"&&!t(s=r.call(e)))return s;throw TypeError("Can't convert object to primitive value")},um}var g1;function cs(){if(g1)return im;g1=1;var t=Mr(),e=ZT(),n=vy(),r=Object.defineProperty;return im.f=Gr()?Object.defineProperty:function(i,o,l){if(t(i),o=n(o,!0),t(l),e)try{return r(i,o,l)}catch{}if("get"in l||"set"in l)throw TypeError("Accessors not supported!");return"value"in l&&(i[o]=l.value),i},im}var dm,v1;function Wl(){return v1||(v1=1,dm=function(t,e){return{enumerable:!(t&1),configurable:!(t&2),writable:!(t&4),value:e}}),dm}var fm,y1;function Pi(){if(y1)return fm;y1=1;var t=cs(),e=Wl();return fm=Gr()?function(n,r,s){return t.f(n,r,e(1,s))}:function(n,r,s){return n[r]=s,n},fm}var hm={exports:{}},pm,b1;function ko(){if(b1)return pm;b1=1;var t={}.hasOwnProperty;return pm=function(e,n){return t.call(e,n)},pm}var mm,x1;function TF(){return x1||(x1=1,mm=cf()("native-function-to-string",Function.toString)),mm}var w1;function Vs(){if(w1)return hm.exports;w1=1;var t=Kr(),e=Pi(),n=ko(),r=Hl()("src"),s=TF(),i="toString",o=(""+s).split(i);return ga().inspectSource=function(l){return s.call(l)},(hm.exports=function(l,d,f,h){var m=typeof f=="function";m&&(n(f,"name")||e(f,"name",d)),l[d]!==f&&(m&&(n(f,r)||e(f,r,l[d]?""+l[d]:o.join(String(d)))),l===t?l[d]=f:h?l[d]?l[d]=f:e(l,d,f):(delete l[d],e(l,d,f)))})(Function.prototype,i,function(){return typeof this=="function"&&this[r]||s.call(this)}),hm.exports}var gm,k1;function df(){return k1||(k1=1,gm=function(t){if(typeof t!="function")throw TypeError(t+" is not a function!");return t}),gm}var vm,S1;function ff(){if(S1)return vm;S1=1;var t=df();return vm=function(e,n,r){if(t(e),n===void 0)return e;switch(r){case 1:return function(s){return e.call(n,s)};case 2:return function(s,i){return e.call(n,s,i)};case 3:return function(s,i,o){return e.call(n,s,i,o)}}return function(){return e.apply(n,arguments)}},vm}var ym,E1;function xr(){if(E1)return ym;E1=1;var t=Kr(),e=ga(),n=Pi(),r=Vs(),s=ff(),i="prototype",o=function(l,d,f){var h=l&o.F,m=l&o.G,g=l&o.S,v=l&o.P,b=l&o.B,k=m?t:g?t[d]||(t[d]={}):(t[d]||{})[i],w=m?e:e[d]||(e[d]={}),S=w[i]||(w[i]={}),N,T,M,_;m&&(f=d);for(N in f)T=!h&&k&&k[N]!==void 0,M=(T?k:f)[N],_=b&&T?s(M,t):v&&typeof M=="function"?s(Function.call,M):M,k&&r(k,N,M,l&o.U),w[N]!=M&&n(w,N,_),v&&S[N]!=M&&(S[N]=M)};return t.core=e,o.F=1,o.G=2,o.S=4,o.P=8,o.B=16,o.W=32,o.U=64,o.R=128,ym=o,ym}var N1;function jF(){if(N1)return l1;N1=1;var t=gy();return xr()({target:"RegExp",proto:!0,forced:t!==/./.exec},{exec:t}),l1}var bm,C1;function yy(){if(C1)return bm;C1=1,jF();var t=Vs(),e=Pi(),n=ls(),r=sf(),s=zn(),i=gy(),o=s("species"),l=!n(function(){var f=/./;return f.exec=function(){var h=[];return h.groups={a:"7"},h},"".replace(f,"$<a>")!=="7"}),d=(function(){var f=/(?:)/,h=f.exec;f.exec=function(){return h.apply(this,arguments)};var m="ab".split(f);return m.length===2&&m[0]==="a"&&m[1]==="b"})();return bm=function(f,h,m){var g=s(f),v=!n(function(){var T={};return T[g]=function(){return 7},""[f](T)!=7}),b=v?!n(function(){var T=!1,M=/a/;return M.exec=function(){return T=!0,null},f==="split"&&(M.constructor={},M.constructor[o]=function(){return M}),M[g](""),!T}):void 0;if(!v||!b||f==="replace"&&!l||f==="split"&&!d){var k=/./[g],w=m(r,g,""[f],function(M,_,R,I,P){return _.exec===i?v&&!P?{done:!0,value:k.call(_,R,I)}:{done:!0,value:M.call(R,_,I)}:{done:!1}}),S=w[0],N=w[1];t(String.prototype,f,S),e(RegExp.prototype,g,h==2?function(T,M){return N.call(T,this,M)}:function(T){return N.call(T,this)})}},bm}var _1;function MF(){if(_1)return Wk;_1=1;var t=Mr(),e=Di(),n=wo(),r=of(),s=hy(),i=my(),o=Math.max,l=Math.min,d=Math.floor,f=/\$([$&`']|\d\d?|<[^>]*>)/g,h=/\$([$&`']|\d\d?)/g,m=function(g){return g===void 0?g:String(g)};return yy()("replace",2,function(g,v,b,k){return[function(N,T){var M=g(this),_=N==null?void 0:N[v];return _!==void 0?_.call(N,M,T):b.call(String(M),N,T)},function(S,N){var T=k(b,S,this,N);if(T.done)return T.value;var M=t(S),_=String(this),R=typeof N=="function";R||(N=String(N));var I=M.global;if(I){var P=M.unicode;M.lastIndex=0}for(var B=[];;){var z=i(M,_);if(z===null||(B.push(z),!I))break;var K=String(z[0]);K===""&&(M.lastIndex=s(_,n(M.lastIndex),P))}for(var F="",J=0,$=0;$<B.length;$++){z=B[$];for(var W=String(z[0]),q=o(l(r(z.index),_.length),0),ne=[],V=1;V<z.length;V++)ne.push(m(z[V]));var oe=z.groups;if(R){var Y=[W].concat(ne,q,_);oe!==void 0&&Y.push(oe);var A=String(N.apply(void 0,Y))}else A=w(W,_,q,ne,oe,N);q>=J&&(F+=_.slice(J,q)+A,J=q+W.length)}return F+_.slice(J)}];function w(S,N,T,M,_,R){var I=T+S.length,P=M.length,B=h;return _!==void 0&&(_=e(_),B=f),b.call(R,B,function(z,K){var F;switch(K.charAt(0)){case"$":return"$";case"&":return S;case"`":return N.slice(0,T);case"'":return N.slice(I);case"<":F=_[K.slice(1,-1)];break;default:var J=+K;if(J===0)return z;if(J>P){var $=d(J/10);return $===0?z:$<=P?M[$-1]===void 0?K.charAt(1):M[$-1]+K.charAt(1):z}F=M[J-1]}return F===void 0?"":F})}}),Wk}MF();var T1={},xm,j1;function by(){if(j1)return xm;j1=1;var t=af();return xm=Object("z").propertyIsEnumerable(0)?Object:function(e){return t(e)=="String"?e.split(""):Object(e)},xm}var wm,M1;function So(){if(M1)return wm;M1=1;var t=by(),e=sf();return wm=function(n){return t(e(n))},wm}var km,A1;function AF(){if(A1)return km;A1=1;var t=of(),e=Math.max,n=Math.min;return km=function(r,s){return r=t(r),r<0?e(r+s,0):n(r,s)},km}var Sm,R1;function e2(){if(R1)return Sm;R1=1;var t=So(),e=wo(),n=AF();return Sm=function(r){return function(s,i,o){var l=t(s),d=e(l.length),f=n(o,d),h;if(r&&i!=i){for(;d>f;)if(h=l[f++],h!=h)return!0}else for(;d>f;f++)if((r||f in l)&&l[f]===i)return r||f||0;return!r&&-1}},Sm}var Em,O1;function Vl(){if(O1)return Em;O1=1;var t=ls();return Em=function(e,n){return!!e&&t(function(){n?e.call(null,function(){},1):e.call(null)})},Em}var I1;function RF(){if(I1)return T1;I1=1;var t=xr(),e=e2()(!1),n=[].indexOf,r=!!n&&1/[1].indexOf(1,-0)<0;return t(t.P+t.F*(r||!Vl()(n)),"Array",{indexOf:function(i){return r?n.apply(this,arguments)||0:e(this,i,arguments[1])}}),T1}RF();var OF=/[a-z]{1,6}(?:[._][a-z]{1,2})?/i,t2=/\!'#%&'\(\)*\+,\\\-\.\/:;<=>\?@\[\]\^_{|}~\$/,L1={},Nm={},Cm={},D1;function xy(){return D1||(D1=1,Cm.f={}.propertyIsEnumerable),Cm}var P1;function wy(){if(P1)return Nm;P1=1;var t=xy(),e=Wl(),n=So(),r=vy(),s=ko(),i=ZT(),o=Object.getOwnPropertyDescriptor;return Nm.f=Gr()?o:function(d,f){if(d=n(d),f=r(f,!0),i)try{return o(d,f)}catch{}if(s(d,f))return e(!t.f.call(d,f),d[f])},Nm}var _m,B1;function IF(){if(B1)return _m;B1=1;var t=Ws(),e=Mr(),n=function(r,s){if(e(r),!t(s)&&s!==null)throw TypeError(s+": can't set as prototype!")};return _m={set:Object.setPrototypeOf||("__proto__"in{}?(function(r,s,i){try{i=ff()(Function.call,wy().f(Object.prototype,"__proto__").set,2),i(r,[]),s=!(r instanceof Array)}catch{s=!0}return function(l,d){return n(l,d),s?l.__proto__=d:i(l,d),l}})({},!1):void 0),check:n},_m}var Tm,$1;function LF(){if($1)return Tm;$1=1;var t=Ws(),e=IF().set;return Tm=function(n,r,s){var i=r.constructor,o;return i!==s&&typeof i=="function"&&(o=i.prototype)!==s.prototype&&t(o)&&e&&e(n,o),n},Tm}var jm={},Mm,F1;function ky(){if(F1)return Mm;F1=1;var t=cf()("keys"),e=Hl();return Mm=function(n){return t[n]||(t[n]=e(n))},Mm}var Am,z1;function n2(){if(z1)return Am;z1=1;var t=ko(),e=So(),n=e2()(!1),r=ky()("IE_PROTO");return Am=function(s,i){var o=e(s),l=0,d=[],f;for(f in o)f!=r&&t(o,f)&&d.push(f);for(;i.length>l;)t(o,f=i[l++])&&(~n(d,f)||d.push(f));return d},Am}var Rm,U1;function Sy(){return U1||(U1=1,Rm="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")),Rm}var H1;function hf(){if(H1)return jm;H1=1;var t=n2(),e=Sy().concat("length","prototype");return jm.f=Object.getOwnPropertyNames||function(r){return t(r,e)},jm}var Om,W1;function r2(){if(W1)return Om;W1=1;var t=Ws(),e=af(),n=zn()("match");return Om=function(r){var s;return t(r)&&((s=r[n])!==void 0?!!s:e(r)=="RegExp")},Om}var Im,V1;function DF(){if(V1)return Im;V1=1;var t=Kr(),e=cs(),n=Gr(),r=zn()("species");return Im=function(s){var i=t[s];n&&i&&!i[r]&&e.f(i,r,{configurable:!0,get:function(){return this}})},Im}var q1;function PF(){if(q1)return L1;q1=1;var t=Kr(),e=LF(),n=cs().f,r=hf().f,s=r2(),i=uf(),o=t.RegExp,l=o,d=o.prototype,f=/a/g,h=/a/g,m=new o(f)!==f;if(Gr()&&(!m||ls()(function(){return h[zn()("match")]=!1,o(f)!=f||o(h)==h||o(f,"i")!="/a/i"}))){o=function(w,S){var N=this instanceof o,T=s(w),M=S===void 0;return!N&&T&&w.constructor===o&&M?w:e(m?new l(T&&!M?w.source:w,S):l((T=w instanceof o)?w.source:w,T&&M?i.call(w):S),N?this:d,o)};for(var g=function(k){k in o||n(o,k,{configurable:!0,get:function(){return l[k]},set:function(w){l[k]=w}})},v=r(l),b=0;v.length>b;)g(v[b++]);d.constructor=o,o.prototype=d,Vs()(t,"RegExp",o)}return DF()("RegExp"),L1}PF();function Rt(t,e,n){return n=n||"",typeof t!="string"&&(t.global&&n.indexOf("g")<0&&(n+="g"),t.ignoreCase&&n.indexOf("i")<0&&(n+="i"),t.multiline&&n.indexOf("m")<0&&(n+="m"),t=t.source),new RegExp(t.replace(/#\{(\w+)\}/g,function(r,s){var i=e[s]||"";return typeof i!="string"&&(i=i.source),i}),n)}var s2=/\x09-\x0D\x20\x85\xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000/;const i2=Rt(/[#{spacesGroup}]/,{spacesGroup:s2});Rt("(^|#{spaces})(\\$)(#{cashtag})(?=$|\\s|[#{punct}])",{cashtag:OF,spaces:i2,punct:t2},"gi");var K1={},G1;function BF(){if(G1)return K1;G1=1;var t=Mr(),e=wo(),n=hy(),r=my();return yy()("match",1,function(s,i,o,l){return[function(f){var h=s(this),m=f==null?void 0:f[i];return m!==void 0?m.call(f,h):new RegExp(f)[i](String(h))},function(d){var f=l(o,d,this);if(f.done)return f.value;var h=t(d),m=String(this);if(!h.global)return r(h,m);var g=h.unicode;h.lastIndex=0;for(var v=[],b=0,k;(k=r(h,m))!==null;){var w=String(k[0]);v[b]=w,w===""&&(h.lastIndex=n(m,e(h.lastIndex),g)),b++}return b===0?null:v}]}),K1}BF();var o2=/[##]/;Rt(/^(?:#{hashSigns}|:\/\/)/,{hashSigns:o2});var a2=Rt(RegExp("(?:(?:한국|香港|澳門|新加坡|台灣|台湾|中國|中国|გე|ລາວ|ไทย|ලංකා|ഭാരതം|ಭಾರತ|భారత్|சிங்கப்பூர்|இலங்கை|இந்தியா|ଭାରତ|ભારત|ਭਾਰਤ|ভাৰত|ভারত|বাংলা|भारोत|भारतम्|भारत|ڀارت|پاکستان|موريتانيا|مليسيا|مصر|قطر|فلسطين|عمان|عراق|سورية|سودان|تونس|بھارت|بارت|ایران|امارات|المغرب|السعودية|الجزائر|البحرين|الاردن|հայ|қаз|укр|срб|рф|мон|мкд|ею|бел|бг|ευ|ελ|zw|zm|za|yt|ye|ws|wf|vu|vn|vi|vg|ve|vc|va|uz|uy|us|um|uk|ug|ua|tz|tw|tv|tt|tr|tp|to|tn|tm|tl|tk|tj|th|tg|tf|td|tc|sz|sy|sx|sv|su|st|ss|sr|so|sn|sm|sl|sk|sj|si|sh|sg|se|sd|sc|sb|sa|rw|ru|rs|ro|re|qa|py|pw|pt|ps|pr|pn|pm|pl|pk|ph|pg|pf|pe|pa|om|nz|nu|nr|np|no|nl|ni|ng|nf|ne|nc|na|mz|my|mx|mw|mv|mu|mt|ms|mr|mq|mp|mo|mn|mm|ml|mk|mh|mg|mf|me|md|mc|ma|ly|lv|lu|lt|ls|lr|lk|li|lc|lb|la|kz|ky|kw|kr|kp|kn|km|ki|kh|kg|ke|jp|jo|jm|je|it|is|ir|iq|io|in|im|il|ie|id|hu|ht|hr|hn|hm|hk|gy|gw|gu|gt|gs|gr|gq|gp|gn|gm|gl|gi|gh|gg|gf|ge|gd|gb|ga|fr|fo|fm|fk|fj|fi|eu|et|es|er|eh|eg|ee|ec|dz|do|dm|dk|dj|de|cz|cy|cx|cw|cv|cu|cr|co|cn|cm|cl|ck|ci|ch|cg|cf|cd|cc|ca|bz|by|bw|bv|bt|bs|br|bq|bo|bn|bm|bl|bj|bi|bh|bg|bf|be|bd|bb|ba|az|ax|aw|au|at|as|ar|aq|ao|an|am|al|ai|ag|af|ae|ad|ac)(?=[^0-9a-zA-Z@+-]|$))")),l2=/\u202A-\u202E\u061C\u200E\u200F\u2066\u2067\u2068\u2069/,Ey=/\uFFFE\uFEFF\uFFFF/;function $F(t,e){return t.replace(/#\{(\w+)\}/g,function(n,r){return e[r]||""})}var FF=$F("#{punct}#{spacesGroup}#{invalidCharsGroup}#{directionalMarkersGroup}",{punct:t2,spacesGroup:s2,invalidCharsGroup:Ey,directionalMarkersGroup:l2}),c2=Rt(/[^#{invalidDomainChars}]/,{invalidDomainChars:FF}),zF=Rt(/(?:(?:#{validDomainChars}(?:-|#{validDomainChars})*)?#{validDomainChars}\.)/,{validDomainChars:c2}),u2=Rt(RegExp("(?:(?:삼성|닷컴|닷넷|香格里拉|餐厅|食品|飞利浦|電訊盈科|集团|通販|购物|谷歌|诺基亚|联通|网络|网站|网店|网址|组织机构|移动|珠宝|点看|游戏|淡马锡|机构|書籍|时尚|新闻|政府|政务|招聘|手表|手机|我爱你|慈善|微博|广东|工行|家電|娱乐|天主教|大拿|大众汽车|在线|嘉里大酒店|嘉里|商标|商店|商城|公益|公司|八卦|健康|信息|佛山|企业|中文网|中信|世界|ポイント|ファッション|セール|ストア|コム|グーグル|クラウド|みんな|คอม|संगठन|नेट|कॉम|همراه|موقع|موبايلي|كوم|كاثوليك|عرب|شبكة|بيتك|بازار|العليان|ارامكو|اتصالات|ابوظبي|קום|сайт|рус|орг|онлайн|москва|ком|католик|дети|zuerich|zone|zippo|zip|zero|zara|zappos|yun|youtube|you|yokohama|yoga|yodobashi|yandex|yamaxun|yahoo|yachts|xyz|xxx|xperia|xin|xihuan|xfinity|xerox|xbox|wtf|wtc|wow|world|works|work|woodside|wolterskluwer|wme|winners|wine|windows|win|williamhill|wiki|wien|whoswho|weir|weibo|wedding|wed|website|weber|webcam|weatherchannel|weather|watches|watch|warman|wanggou|wang|walter|walmart|wales|vuelos|voyage|voto|voting|vote|volvo|volkswagen|vodka|vlaanderen|vivo|viva|vistaprint|vista|vision|visa|virgin|vip|vin|villas|viking|vig|video|viajes|vet|versicherung|vermögensberatung|vermögensberater|verisign|ventures|vegas|vanguard|vana|vacations|ups|uol|uno|university|unicom|uconnect|ubs|ubank|tvs|tushu|tunes|tui|tube|trv|trust|travelersinsurance|travelers|travelchannel|travel|training|trading|trade|toys|toyota|town|tours|total|toshiba|toray|top|tools|tokyo|today|tmall|tkmaxx|tjx|tjmaxx|tirol|tires|tips|tiffany|tienda|tickets|tiaa|theatre|theater|thd|teva|tennis|temasek|telefonica|telecity|tel|technology|tech|team|tdk|tci|taxi|tax|tattoo|tatar|tatamotors|target|taobao|talk|taipei|tab|systems|symantec|sydney|swiss|swiftcover|swatch|suzuki|surgery|surf|support|supply|supplies|sucks|style|study|studio|stream|store|storage|stockholm|stcgroup|stc|statoil|statefarm|statebank|starhub|star|staples|stada|srt|srl|spreadbetting|spot|sport|spiegel|space|soy|sony|song|solutions|solar|sohu|software|softbank|social|soccer|sncf|smile|smart|sling|skype|sky|skin|ski|site|singles|sina|silk|shriram|showtime|show|shouji|shopping|shop|shoes|shiksha|shia|shell|shaw|sharp|shangrila|sfr|sexy|sex|sew|seven|ses|services|sener|select|seek|security|secure|seat|search|scot|scor|scjohnson|science|schwarz|schule|school|scholarships|schmidt|schaeffler|scb|sca|sbs|sbi|saxo|save|sas|sarl|sapo|sap|sanofi|sandvikcoromant|sandvik|samsung|samsclub|salon|sale|sakura|safety|safe|saarland|ryukyu|rwe|run|ruhr|rugby|rsvp|room|rogers|rodeo|rocks|rocher|rmit|rip|rio|ril|rightathome|ricoh|richardli|rich|rexroth|reviews|review|restaurant|rest|republican|report|repair|rentals|rent|ren|reliance|reit|reisen|reise|rehab|redumbrella|redstone|red|recipes|realty|realtor|realestate|read|raid|radio|racing|qvc|quest|quebec|qpon|pwc|pub|prudential|pru|protection|property|properties|promo|progressive|prof|productions|prod|pro|prime|press|praxi|pramerica|post|porn|politie|poker|pohl|pnc|plus|plumbing|playstation|play|place|pizza|pioneer|pink|ping|pin|pid|pictures|pictet|pics|piaget|physio|photos|photography|photo|phone|philips|phd|pharmacy|pfizer|pet|pccw|pay|passagens|party|parts|partners|pars|paris|panerai|panasonic|pamperedchef|page|ovh|ott|otsuka|osaka|origins|orientexpress|organic|org|orange|oracle|open|ooo|onyourside|online|onl|ong|one|omega|ollo|oldnavy|olayangroup|olayan|okinawa|office|off|observer|obi|nyc|ntt|nrw|nra|nowtv|nowruz|now|norton|northwesternmutual|nokia|nissay|nissan|ninja|nikon|nike|nico|nhk|ngo|nfl|nexus|nextdirect|next|news|newholland|new|neustar|network|netflix|netbank|net|nec|nba|navy|natura|nationwide|name|nagoya|nadex|nab|mutuelle|mutual|museum|mtr|mtpc|mtn|msd|movistar|movie|mov|motorcycles|moto|moscow|mortgage|mormon|mopar|montblanc|monster|money|monash|mom|moi|moe|moda|mobily|mobile|mobi|mma|mls|mlb|mitsubishi|mit|mint|mini|mil|microsoft|miami|metlife|merckmsd|meo|menu|men|memorial|meme|melbourne|meet|media|med|mckinsey|mcdonalds|mcd|mba|mattel|maserati|marshalls|marriott|markets|marketing|market|map|mango|management|man|makeup|maison|maif|madrid|macys|luxury|luxe|lupin|lundbeck|ltda|ltd|lplfinancial|lpl|love|lotto|lotte|london|lol|loft|locus|locker|loans|loan|llp|llc|lixil|living|live|lipsy|link|linde|lincoln|limo|limited|lilly|like|lighting|lifestyle|lifeinsurance|life|lidl|liaison|lgbt|lexus|lego|legal|lefrak|leclerc|lease|lds|lawyer|law|latrobe|latino|lat|lasalle|lanxess|landrover|land|lancome|lancia|lancaster|lamer|lamborghini|ladbrokes|lacaixa|kyoto|kuokgroup|kred|krd|kpn|kpmg|kosher|komatsu|koeln|kiwi|kitchen|kindle|kinder|kim|kia|kfh|kerryproperties|kerrylogistics|kerryhotels|kddi|kaufen|juniper|juegos|jprs|jpmorgan|joy|jot|joburg|jobs|jnj|jmp|jll|jlc|jio|jewelry|jetzt|jeep|jcp|jcb|java|jaguar|iwc|iveco|itv|itau|istanbul|ist|ismaili|iselect|irish|ipiranga|investments|intuit|international|intel|int|insure|insurance|institute|ink|ing|info|infiniti|industries|inc|immobilien|immo|imdb|imamat|ikano|iinet|ifm|ieee|icu|ice|icbc|ibm|hyundai|hyatt|hughes|htc|hsbc|how|house|hotmail|hotels|hoteles|hot|hosting|host|hospital|horse|honeywell|honda|homesense|homes|homegoods|homedepot|holiday|holdings|hockey|hkt|hiv|hitachi|hisamitsu|hiphop|hgtv|hermes|here|helsinki|help|healthcare|health|hdfcbank|hdfc|hbo|haus|hangout|hamburg|hair|guru|guitars|guide|guge|gucci|guardian|group|grocery|gripe|green|gratis|graphics|grainger|gov|got|gop|google|goog|goodyear|goodhands|goo|golf|goldpoint|gold|godaddy|gmx|gmo|gmbh|gmail|globo|global|gle|glass|glade|giving|gives|gifts|gift|ggee|george|genting|gent|gea|gdn|gbiz|gay|garden|gap|games|game|gallup|gallo|gallery|gal|fyi|futbol|furniture|fund|fun|fujixerox|fujitsu|ftr|frontier|frontdoor|frogans|frl|fresenius|free|fox|foundation|forum|forsale|forex|ford|football|foodnetwork|food|foo|fly|flsmidth|flowers|florist|flir|flights|flickr|fitness|fit|fishing|fish|firmdale|firestone|fire|financial|finance|final|film|fido|fidelity|fiat|ferrero|ferrari|feedback|fedex|fast|fashion|farmers|farm|fans|fan|family|faith|fairwinds|fail|fage|extraspace|express|exposed|expert|exchange|everbank|events|eus|eurovision|etisalat|esurance|estate|esq|erni|ericsson|equipment|epson|epost|enterprises|engineering|engineer|energy|emerck|email|education|edu|edeka|eco|eat|earth|dvr|dvag|durban|dupont|duns|dunlop|duck|dubai|dtv|drive|download|dot|doosan|domains|doha|dog|dodge|doctor|docs|dnp|diy|dish|discover|discount|directory|direct|digital|diet|diamonds|dhl|dev|design|desi|dentist|dental|democrat|delta|deloitte|dell|delivery|degree|deals|dealer|deal|dds|dclk|day|datsun|dating|date|data|dance|dad|dabur|cyou|cymru|cuisinella|csc|cruises|cruise|crs|crown|cricket|creditunion|creditcard|credit|cpa|courses|coupons|coupon|country|corsica|coop|cool|cookingchannel|cooking|contractors|contact|consulting|construction|condos|comsec|computer|compare|company|community|commbank|comcast|com|cologne|college|coffee|codes|coach|clubmed|club|cloud|clothing|clinique|clinic|click|cleaning|claims|cityeats|city|citic|citi|citadel|cisco|circle|cipriani|church|chrysler|chrome|christmas|chloe|chintai|cheap|chat|chase|charity|channel|chanel|cfd|cfa|cern|ceo|center|ceb|cbs|cbre|cbn|cba|catholic|catering|cat|casino|cash|caseih|case|casa|cartier|cars|careers|career|care|cards|caravan|car|capitalone|capital|capetown|canon|cancerresearch|camp|camera|cam|calvinklein|call|cal|cafe|cab|bzh|buzz|buy|business|builders|build|bugatti|budapest|brussels|brother|broker|broadway|bridgestone|bradesco|box|boutique|bot|boston|bostik|bosch|boots|booking|book|boo|bond|bom|bofa|boehringer|boats|bnpparibas|bnl|bmw|bms|blue|bloomberg|blog|blockbuster|blanco|blackfriday|black|biz|bio|bingo|bing|bike|bid|bible|bharti|bet|bestbuy|best|berlin|bentley|beer|beauty|beats|bcn|bcg|bbva|bbt|bbc|bayern|bauhaus|basketball|baseball|bargains|barefoot|barclays|barclaycard|barcelona|bar|bank|band|bananarepublic|banamex|baidu|baby|azure|axa|aws|avianca|autos|auto|author|auspost|audio|audible|audi|auction|attorney|athleta|associates|asia|asda|arte|art|arpa|army|archi|aramco|arab|aquarelle|apple|app|apartments|aol|anz|anquan|android|analytics|amsterdam|amica|amfam|amex|americanfamily|americanexpress|alstom|alsace|ally|allstate|allfinanz|alipay|alibaba|alfaromeo|akdn|airtel|airforce|airbus|aigo|aig|agency|agakhan|africa|afl|afamilycompany|aetna|aero|aeg|adult|ads|adac|actor|active|aco|accountants|accountant|accenture|academy|abudhabi|abogado|able|abc|abbvie|abbott|abb|abarth|aarp|aaa|onion)(?=[^0-9a-zA-Z@+-]|$))")),d2=/(?:xn--[\-0-9a-z]+)/,UF=Rt(/(?:(?:#{validDomainChars}(?:[_-]|#{validDomainChars})*)?#{validDomainChars}\.)/,{validDomainChars:c2}),HF=Rt(/(?:#{validSubdomain}*#{validDomainName}(?:#{validGTLD}|#{validCCTLD}|#{validPunycode}))/,{validDomainName:zF,validSubdomain:UF,validGTLD:u2,validCCTLD:a2,validPunycode:d2}),WF=/[0-9]+/,f2=/\u0400-\u04FF/,pf=/\xC0-\xD6\xD8-\xF6\xF8-\xFF\u0100-\u024F\u0253\u0254\u0256\u0257\u0259\u025B\u0263\u0268\u026F\u0272\u0289\u028B\u02BB\u0300-\u036F\u1E00-\u1EFF/,h2=Rt(/[a-z#{cyrillicLettersAndMarks}0-9!\*';:=\+,\.\$\/%#\[\]\-\u2013_~@\|&#{latinAccentChars}]/i,{cyrillicLettersAndMarks:f2,latinAccentChars:pf}),p2=Rt("\\((?:#{validGeneralUrlPathChars}+|(?:#{validGeneralUrlPathChars}*\\(#{validGeneralUrlPathChars}+\\)#{validGeneralUrlPathChars}*))\\)",{validGeneralUrlPathChars:h2},"i"),VF=Rt(/[\+\-a-z#{cyrillicLettersAndMarks}0-9=_#\/#{latinAccentChars}]|(?:#{validUrlBalancedParens})/i,{cyrillicLettersAndMarks:f2,latinAccentChars:pf,validUrlBalancedParens:p2}),qF=Rt("(?:(?:#{validGeneralUrlPathChars}*(?:#{validUrlBalancedParens}#{validGeneralUrlPathChars}*)*#{validUrlPathEndingChars})|(?:@#{validGeneralUrlPathChars}+/))",{validGeneralUrlPathChars:h2,validUrlBalancedParens:p2,validUrlPathEndingChars:VF},"i"),KF=Rt(/(?:[^A-Za-z0-9@@$###{invalidCharsGroup}]|[#{directionalMarkersGroup}]|^)/,{invalidCharsGroup:Ey,directionalMarkersGroup:l2}),m2=/[a-z0-9!?\*'@\(\);:&=\+\$\/%#\[\]\-_\.,~|]/i,g2=/[a-z0-9\-_&=#\/]/i,J1=Rt("((#{validUrlPrecedingChars})((https?:\\/\\/)?(#{validDomain})(?::(#{validPortNumber}))?(\\/#{validUrlPath}*)?(\\?#{validUrlQueryChars}*#{validUrlQueryEndingChars})?))",{validUrlPrecedingChars:KF,validDomain:HF,validPortNumber:WF,validUrlPath:qF,validUrlQueryChars:m2,validUrlQueryEndingChars:g2},"gi"),GF=/[-_.\/]$/,Y1={},Lm,X1;function JF(){if(X1)return Lm;X1=1;var t=Mr(),e=df(),n=zn()("species");return Lm=function(r,s){var i=t(r).constructor,o;return i===void 0||(o=t(i)[n])==null?s:e(o)},Lm}var Q1;function YF(){if(Q1)return Y1;Q1=1;var t=r2(),e=Mr(),n=JF(),r=hy(),s=wo(),i=my(),o=gy(),l=ls(),d=Math.min,f=[].push,h="split",m="length",g="lastIndex",v=4294967295,b=!l(function(){});return yy()("split",2,function(k,w,S,N){var T;return"abbc"[h](/(b)*/)[1]=="c"||"test"[h](/(?:)/,-1)[m]!=4||"ab"[h](/(?:ab)*/)[m]!=2||"."[h](/(.?)(.?)/)[m]!=4||"."[h](/()()/)[m]>1||""[h](/.?/)[m]?T=function(M,_){var R=String(this);if(M===void 0&&_===0)return[];if(!t(M))return S.call(R,M,_);for(var I=[],P=(M.ignoreCase?"i":"")+(M.multiline?"m":"")+(M.unicode?"u":"")+(M.sticky?"y":""),B=0,z=_===void 0?v:_>>>0,K=new RegExp(M.source,P+"g"),F,J,$;(F=o.call(K,R))&&(J=K[g],!(J>B&&(I.push(R.slice(B,F.index)),F[m]>1&&F.index<R[m]&&f.apply(I,F.slice(1)),$=F[0][m],B=J,I[m]>=z)));)K[g]===F.index&&K[g]++;return B===R[m]?($||!K.test(""))&&I.push(""):I.push(R.slice(B)),I[m]>z?I.slice(0,z):I}:"0"[h](void 0,0)[m]?T=function(M,_){return M===void 0&&_===0?[]:S.call(this,M,_)}:T=S,[function(_,R){var I=k(this),P=_==null?void 0:_[w];return P!==void 0?P.call(_,I,R):T.call(String(I),_,R)},function(M,_){var R=N(T,M,this,_,T!==S);if(R.done)return R.value;var I=e(M),P=String(this),B=n(I,RegExp),z=I.unicode,K=(I.ignoreCase?"i":"")+(I.multiline?"m":"")+(I.unicode?"u":"")+(b?"y":"g"),F=new B(b?I:"^(?:"+I.source+")",K),J=_===void 0?v:_>>>0;if(J===0)return[];if(P.length===0)return i(F,P)===null?[P]:[];for(var $=0,W=0,q=[];W<P.length;){F.lastIndex=b?W:0;var ne=i(F,b?P:P.slice(W)),V;if(ne===null||(V=d(s(F.lastIndex+(b?0:W)),P.length))===$)W=r(P,W,z);else{if(q.push(P.slice($,W)),q.length===J)return q;for(var oe=1;oe<=ne.length-1;oe++)if(q.push(ne[oe]),q.length===J)return q;W=$=V}}return q.push(P.slice($)),q}]}),Y1}YF();var ll={exports:{}};/*! https://mths.be/punycode v1.4.1 by @mathias */var XF=ll.exports,Z1;function QF(){return Z1||(Z1=1,(function(t,e){(function(n){var r=e&&!e.nodeType&&e,s=t&&!t.nodeType&&t,i=typeof q0=="object"&&q0;(i.global===i||i.window===i||i.self===i)&&(n=i);var o,l=2147483647,d=36,f=1,h=26,m=38,g=700,v=72,b=128,k="-",w=/^xn--/,S=/[^\x20-\x7E]/,N=/[\x2E\u3002\uFF0E\uFF61]/g,T={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},M=d-f,_=Math.floor,R=String.fromCharCode,I;function P(Y){throw new RangeError(T[Y])}function B(Y,A){for(var L=Y.length,ee=[];L--;)ee[L]=A(Y[L]);return ee}function z(Y,A){var L=Y.split("@"),ee="";L.length>1&&(ee=L[0]+"@",Y=L[1]),Y=Y.replace(N,".");var ue=Y.split("."),be=B(ue,A).join(".");return ee+be}function K(Y){for(var A=[],L=0,ee=Y.length,ue,be;L<ee;)ue=Y.charCodeAt(L++),ue>=55296&&ue<=56319&&L<ee?(be=Y.charCodeAt(L++),(be&64512)==56320?A.push(((ue&1023)<<10)+(be&1023)+65536):(A.push(ue),L--)):A.push(ue);return A}function F(Y){return B(Y,function(A){var L="";return A>65535&&(A-=65536,L+=R(A>>>10&1023|55296),A=56320|A&1023),L+=R(A),L}).join("")}function J(Y){return Y-48<10?Y-22:Y-65<26?Y-65:Y-97<26?Y-97:d}function $(Y,A){return Y+22+75*(Y<26)-((A!=0)<<5)}function W(Y,A,L){var ee=0;for(Y=L?_(Y/g):Y>>1,Y+=_(Y/A);Y>M*h>>1;ee+=d)Y=_(Y/M);return _(ee+(M+1)*Y/(Y+m))}function q(Y){var A=[],L=Y.length,ee,ue=0,be=b,re=v,we,Ee,$e,Fe,Ze,Re,tt,gt,ut;for(we=Y.lastIndexOf(k),we<0&&(we=0),Ee=0;Ee<we;++Ee)Y.charCodeAt(Ee)>=128&&P("not-basic"),A.push(Y.charCodeAt(Ee));for($e=we>0?we+1:0;$e<L;){for(Fe=ue,Ze=1,Re=d;$e>=L&&P("invalid-input"),tt=J(Y.charCodeAt($e++)),(tt>=d||tt>_((l-ue)/Ze))&&P("overflow"),ue+=tt*Ze,gt=Re<=re?f:Re>=re+h?h:Re-re,!(tt<gt);Re+=d)ut=d-gt,Ze>_(l/ut)&&P("overflow"),Ze*=ut;ee=A.length+1,re=W(ue-Fe,ee,Fe==0),_(ue/ee)>l-be&&P("overflow"),be+=_(ue/ee),ue%=ee,A.splice(ue++,0,be)}return F(A)}function ne(Y){var A,L,ee,ue,be,re,we,Ee,$e,Fe,Ze,Re=[],tt,gt,ut,ge;for(Y=K(Y),tt=Y.length,A=b,L=0,be=v,re=0;re<tt;++re)Ze=Y[re],Ze<128&&Re.push(R(Ze));for(ee=ue=Re.length,ue&&Re.push(k);ee<tt;){for(we=l,re=0;re<tt;++re)Ze=Y[re],Ze>=A&&Ze<we&&(we=Ze);for(gt=ee+1,we-A>_((l-L)/gt)&&P("overflow"),L+=(we-A)*gt,A=we,re=0;re<tt;++re)if(Ze=Y[re],Ze<A&&++L>l&&P("overflow"),Ze==A){for(Ee=L,$e=d;Fe=$e<=be?f:$e>=be+h?h:$e-be,!(Ee<Fe);$e+=d)ge=Ee-Fe,ut=d-Fe,Re.push(R($(Fe+ge%ut,0))),Ee=_(ge/ut);Re.push(R($(Ee,0))),be=W(L,gt,ee==ue),L=0,++ee}++L,++A}return Re.join("")}function V(Y){return z(Y,function(A){return w.test(A)?q(A.slice(4).toLowerCase()):A})}function oe(Y){return z(Y,function(A){return S.test(A)?"xn--"+ne(A):A})}if(o={version:"1.4.1",ucs2:{decode:K,encode:F},decode:q,encode:ne,toASCII:oe,toUnicode:V},r&&s)if(t.exports==r)s.exports=o;else for(I in o)o.hasOwnProperty(I)&&(r[I]=o[I]);else n.punycode=o})(XF)})(ll,ll.exports)),ll.exports}var ZF=QF();const ez=Ol(ZF);var v2=Rt(/(?:(?:[\-a-z0-9#{latinAccentChars}]+)\.)+(?:#{validGTLD}|#{validCCTLD}|#{validPunycode})/gi,{latinAccentChars:pf,validGTLD:u2,validCCTLD:a2,validPunycode:d2}),tz=63,nz="xn--",rz={toAscii:function(e){if(!(e.substring(0,4)===nz&&!e.match(v2))){for(var n=e.split("."),r=0;r<n.length;r++){var s=n[r],i=ez.toASCII(s);if(i.length<1||i.length>tz)return}return n.join(".")}}},sz=Rt(/^https?:\/\/t\.co\/([a-z0-9]+)(?:\?#{validUrlQueryChars}*#{validUrlQueryEndingChars})?/,{validUrlQueryChars:m2,validUrlQueryEndingChars:g2},"i"),iz="https://",oz={extractUrlsWithoutProtocol:!0},az=4096,lz=40,cz=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:oz;if(!e||(n.extractUrlsWithoutProtocol?!e.match(/\./):!e.match(/:/)))return[];for(var r=[],s=function(){var l=RegExp.$2,d=RegExp.$3,f=RegExp.$4,h=RegExp.$5,m=RegExp.$7,g=J1.lastIndex,v=g-d.length;if(!uz(d,f||iz,h))return"continue";if(f){if(d.match(sz)){var w=RegExp.$1;if(w&&w.length>lz)return"continue";d=RegExp.lastMatch,g=v+d.length}r.push({url:d,indices:[v,g]})}else{if(!n.extractUrlsWithoutProtocol||l.match(GF))return"continue";var b=null,k=0;if(h.replace(v2,function(S){var N=h.indexOf(S,k);k=N+S.length,b={url:S,indices:[v+N,v+k]},r.push(b)}),b==null)return"continue";m&&(b.url=d.replace(h,b.url),b.indices[1]=g)}};J1.exec(e);)var i=s();return r},uz=function(e,n,r){var s=e.length,i=rz.toAscii(r);return!i||!i.length?!1:(s=s+i.length-r.length,n.length+s<=az)},eS={},tS;function dz(){if(tS)return eS;tS=1;var t=xr(),e=df(),n=Di(),r=ls(),s=[].sort,i=[1,2,3];return t(t.P+t.F*(r(function(){i.sort(void 0)})||!r(function(){i.sort(null)})||!Vl()(s)),"Array",{sort:function(l){return l===void 0?s.call(n(this)):s.call(n(this),e(l))}}),eS}dz();var y2=/\ud800[\udc00-\udc0b\udc0d-\udc26\udc28-\udc3a\udc3c\udc3d\udc3f-\udc4d\udc50-\udc5d\udc80-\udcfa\uddfd\ude80-\ude9c\udea0-\uded0\udee0\udf00-\udf1f\udf30-\udf40\udf42-\udf49\udf50-\udf7a\udf80-\udf9d\udfa0-\udfc3\udfc8-\udfcf]|\ud801[\udc00-\udc9d\udd00-\udd27\udd30-\udd63\ude00-\udf36\udf40-\udf55\udf60-\udf67]|\ud802[\udc00-\udc05\udc08\udc0a-\udc35\udc37\udc38\udc3c\udc3f-\udc55\udc60-\udc76\udc80-\udc9e\udd00-\udd15\udd20-\udd39\udd80-\uddb7\uddbe\uddbf\ude00-\ude03\ude05\ude06\ude0c-\ude13\ude15-\ude17\ude19-\ude33\ude38-\ude3a\ude3f\ude60-\ude7c\ude80-\ude9c\udec0-\udec7\udec9-\udee6\udf00-\udf35\udf40-\udf55\udf60-\udf72\udf80-\udf91]|\ud803[\udc00-\udc48]|\ud804[\udc00-\udc46\udc7f-\udcba\udcd0-\udce8\udd00-\udd34\udd50-\udd73\udd76\udd80-\uddc4\uddda\ude00-\ude11\ude13-\ude37\udeb0-\udeea\udf01-\udf03\udf05-\udf0c\udf0f\udf10\udf13-\udf28\udf2a-\udf30\udf32\udf33\udf35-\udf39\udf3c-\udf44\udf47\udf48\udf4b-\udf4d\udf57\udf5d-\udf63\udf66-\udf6c\udf70-\udf74]|\ud805[\udc80-\udcc5\udcc7\udd80-\uddb5\uddb8-\uddc0\ude00-\ude40\ude44\ude80-\udeb7]|\ud806[\udca0-\udcdf\udcff\udec0-\udef8]|\ud808[\udc00-\udf98]|\ud80c[\udc00-\udfff]|\ud80d[\udc00-\udc2e]|\ud81a[\udc00-\ude38\ude40-\ude5e\uded0-\udeed\udef0-\udef4\udf00-\udf36\udf40-\udf43\udf63-\udf77\udf7d-\udf8f]|\ud81b[\udf00-\udf44\udf50-\udf7e\udf8f-\udf9f]|\ud82c[\udc00\udc01]|\ud82f[\udc00-\udc6a\udc70-\udc7c\udc80-\udc88\udc90-\udc99\udc9d\udc9e]|\ud834[\udd65-\udd69\udd6d-\udd72\udd7b-\udd82\udd85-\udd8b\uddaa-\uddad\ude42-\ude44]|\ud835[\udc00-\udc54\udc56-\udc9c\udc9e\udc9f\udca2\udca5\udca6\udca9-\udcac\udcae-\udcb9\udcbb\udcbd-\udcc3\udcc5-\udd05\udd07-\udd0a\udd0d-\udd14\udd16-\udd1c\udd1e-\udd39\udd3b-\udd3e\udd40-\udd44\udd46\udd4a-\udd50\udd52-\udea5\udea8-\udec0\udec2-\udeda\udedc-\udefa\udefc-\udf14\udf16-\udf34\udf36-\udf4e\udf50-\udf6e\udf70-\udf88\udf8a-\udfa8\udfaa-\udfc2\udfc4-\udfcb]|\ud83a[\udc00-\udcc4\udcd0-\udcd6]|\ud83b[\ude00-\ude03\ude05-\ude1f\ude21\ude22\ude24\ude27\ude29-\ude32\ude34-\ude37\ude39\ude3b\ude42\ude47\ude49\ude4b\ude4d-\ude4f\ude51\ude52\ude54\ude57\ude59\ude5b\ude5d\ude5f\ude61\ude62\ude64\ude67-\ude6a\ude6c-\ude72\ude74-\ude77\ude79-\ude7c\ude7e\ude80-\ude89\ude8b-\ude9b\udea1-\udea3\udea5-\udea9\udeab-\udebb]|\ud840[\udc00-\udfff]|\ud841[\udc00-\udfff]|\ud842[\udc00-\udfff]|\ud843[\udc00-\udfff]|\ud844[\udc00-\udfff]|\ud845[\udc00-\udfff]|\ud846[\udc00-\udfff]|\ud847[\udc00-\udfff]|\ud848[\udc00-\udfff]|\ud849[\udc00-\udfff]|\ud84a[\udc00-\udfff]|\ud84b[\udc00-\udfff]|\ud84c[\udc00-\udfff]|\ud84d[\udc00-\udfff]|\ud84e[\udc00-\udfff]|\ud84f[\udc00-\udfff]|\ud850[\udc00-\udfff]|\ud851[\udc00-\udfff]|\ud852[\udc00-\udfff]|\ud853[\udc00-\udfff]|\ud854[\udc00-\udfff]|\ud855[\udc00-\udfff]|\ud856[\udc00-\udfff]|\ud857[\udc00-\udfff]|\ud858[\udc00-\udfff]|\ud859[\udc00-\udfff]|\ud85a[\udc00-\udfff]|\ud85b[\udc00-\udfff]|\ud85c[\udc00-\udfff]|\ud85d[\udc00-\udfff]|\ud85e[\udc00-\udfff]|\ud85f[\udc00-\udfff]|\ud860[\udc00-\udfff]|\ud861[\udc00-\udfff]|\ud862[\udc00-\udfff]|\ud863[\udc00-\udfff]|\ud864[\udc00-\udfff]|\ud865[\udc00-\udfff]|\ud866[\udc00-\udfff]|\ud867[\udc00-\udfff]|\ud868[\udc00-\udfff]|\ud869[\udc00-\uded6\udf00-\udfff]|\ud86a[\udc00-\udfff]|\ud86b[\udc00-\udfff]|\ud86c[\udc00-\udfff]|\ud86d[\udc00-\udf34\udf40-\udfff]|\ud86e[\udc00-\udc1d]|\ud87e[\udc00-\ude1d]|\udb40[\udd00-\uddef]/,b2=/A-Za-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u052f\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u065f\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06ef\u06fa-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07ca-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0-\u08b2\u08e4-\u0963\u0971-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09f0\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a70-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0c00-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c81-\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0cf1\u0cf2\u0d01-\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u103f\u1050-\u108f\u109a-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16f1-\u16f8\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u180b-\u180d\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191e\u1920-\u192b\u1930-\u193b\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f\u1aa7\u1ab0-\u1abe\u1b00-\u1b4b\u1b6b-\u1b73\u1b80-\u1baf\u1bba-\u1bf3\u1c00-\u1c37\u1c4d-\u1c4f\u1c5a-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1cf8\u1cf9\u1d00-\u1df5\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u20d0-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2183\u2184\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005\u3006\u302a-\u302f\u3031-\u3035\u303b\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua672\ua674-\ua67d\ua67f-\ua69d\ua69f-\ua6e5\ua6f0\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua7ad\ua7b0\ua7b1\ua7f7-\ua827\ua840-\ua873\ua880-\ua8c4\ua8e0-\ua8f7\ua8fb\ua90a-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf\ua9e0-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa36\uaa40-\uaa4d\uaa60-\uaa76\uaa7a-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab5f\uab64\uab65\uabc0-\uabea\uabec\uabed\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf870-\uf87f\uf882\uf884-\uf89f\uf8b8\uf8c1-\uf8d6\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe2d\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc/,x2=/[\uD800-\uDBFF][\uDC00-\uDFFF]/gm,fz=Rt(/(?:[#{bmpLetterAndMarks}]|(?=#{nonBmpCodePairs})(?:#{astralLetterAndMarks}))/,{bmpLetterAndMarks:b2,nonBmpCodePairs:x2,astralLetterAndMarks:y2}),hz=/\ud801[\udca0-\udca9]|\ud804[\udc66-\udc6f\udcf0-\udcf9\udd36-\udd3f\uddd0-\uddd9\udef0-\udef9]|\ud805[\udcd0-\udcd9\ude50-\ude59\udec0-\udec9]|\ud806[\udce0-\udce9]|\ud81a[\ude60-\ude69\udf50-\udf59]|\ud835[\udfce-\udfff]/,pz=/0-9\u0660-\u0669\u06f0-\u06f9\u07c0-\u07c9\u0966-\u096f\u09e6-\u09ef\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be6-\u0bef\u0c66-\u0c6f\u0ce6-\u0cef\u0d66-\u0d6f\u0de6-\u0def\u0e50-\u0e59\u0ed0-\u0ed9\u0f20-\u0f29\u1040-\u1049\u1090-\u1099\u17e0-\u17e9\u1810-\u1819\u1946-\u194f\u19d0-\u19d9\u1a80-\u1a89\u1a90-\u1a99\u1b50-\u1b59\u1bb0-\u1bb9\u1c40-\u1c49\u1c50-\u1c59\ua620-\ua629\ua8d0-\ua8d9\ua900-\ua909\ua9d0-\ua9d9\ua9f0-\ua9f9\uaa50-\uaa59\uabf0-\uabf9\uff10-\uff19/,mz=/_\u200c\u200d\ua67e\u05be\u05f3\u05f4\uff5e\u301c\u309b\u309c\u30a0\u30fb\u3003\u0f0b\u0f0c\xb7/,w2=Rt(/(?:[#{bmpLetterAndMarks}#{bmpNumerals}#{hashtagSpecialChars}]|(?=#{nonBmpCodePairs})(?:#{astralLetterAndMarks}|#{astralNumerals}))/,{bmpLetterAndMarks:b2,bmpNumerals:pz,hashtagSpecialChars:mz,nonBmpCodePairs:x2,astralLetterAndMarks:y2,astralNumerals:hz}),gz=/(?:[^\uD800-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF])/,vz=Rt(/(?:^|\uFE0E|\uFE0F|$|(?!#{hashtagAlphaNumeric}|&)#{codePoint})/,{codePoint:gz,hashtagAlphaNumeric:w2});Rt(/(#{hashtagBoundary})(#{hashSigns})(?!\uFE0F|\u20E3)(#{hashtagAlphaNumeric}*#{hashtagAlpha}#{hashtagAlphaNumeric}*)/gi,{hashtagBoundary:vz,hashSigns:o2,hashtagAlphaNumeric:w2,hashtagAlpha:fz});var Ny=/[@@]/;Rt(/^(?:#{atSigns}|[#{latinAccentChars}]|:\/\/)/,{atSigns:Ny,latinAccentChars:pf});var yz=/(?:^|[^a-zA-Z0-9_!#$%&*@@]|(?:^|[^a-zA-Z0-9_+~.-])(?:rt|RT|rT|Rt):?)/,bz=Rt("(#{validMentionPrecedingChars})(#{atSigns})([a-zA-Z0-9_]{1,20})(/[a-zA-Z][a-zA-Z0-9_-]{0,24})?",{validMentionPrecedingChars:yz,atSigns:Ny},"g"),nS={},rS={},sS;function xz(){return sS||(sS=1,Gr()&&/./g.flags!="g"&&cs().f(RegExp.prototype,"flags",{configurable:!0,get:uf()})),rS}var iS;function wz(){if(iS)return nS;iS=1,xz();var t=Mr(),e=uf(),n=Gr(),r="toString",s=/./[r],i=function(o){Vs()(RegExp.prototype,r,o,!0)};return ls()(function(){return s.call({source:"a",flags:"b"})!="/a/b"})?i(function(){var l=t(this);return"/".concat(l.source,"/","flags"in l?l.flags:!n&&l instanceof RegExp?e.call(l):void 0)}):s.name!=r&&i(function(){return s.call(this)}),nS}wz();var oS={},aS;function kz(){if(aS)return oS;aS=1;var t=Date.prototype,e="Invalid Date",n="toString",r=t[n],s=t.getTime;return new Date(NaN)+""!=e&&Vs()(t,n,function(){var o=s.call(this);return o===o?r.call(this):e}),oS}kz();var lS={},cS;function Sz(){if(cS)return lS;cS=1;var t=py(),e={};return e[zn()("toStringTag")]="z",e+""!="[object z]"&&Vs()(Object.prototype,"toString",function(){return"[object "+t(this)+"]"},!0),lS}Sz();const uS={defaults:{version:3,maxWeightedTweetLength:280,scale:100,defaultWeight:200,emojiParsingEnabled:!0,transformedURLLength:23,ranges:[{start:0,end:4351,weight:100},{start:8192,end:8205,weight:100},{start:8208,end:8223,weight:100},{start:8242,end:8247,weight:100}]}};Rt(/^(?:#{spaces})*#{atSigns}([a-zA-Z0-9_]{1,20})/,{atSigns:Ny,spaces:i2});var dS={},Dm,fS;function Cy(){if(fS)return Dm;fS=1;var t=af();return Dm=Array.isArray||function(n){return t(n)=="Array"},Dm}var hS;function Ez(){if(hS)return dS;hS=1;var t=xr();return t(t.S,"Array",{isArray:Cy()}),dS}Ez();var Nz=function(e,n){var r=n.defaultWeight,s=n.ranges,i=r,o=e.charCodeAt(0);if(Array.isArray(s))for(var l=0,d=s.length;l<d;l++){var f=s[l];if(o>=f.start&&o<=f.end){i=f.weight;break}}return i},pS={},Pm,mS;function Cz(){if(mS)return Pm;mS=1;var t=df(),e=Di(),n=by(),r=wo();return Pm=function(s,i,o,l,d){t(i);var f=e(s),h=n(f),m=r(f.length),g=d?m-1:0,v=d?-1:1;if(o<2)for(;;){if(g in h){l=h[g],g+=v;break}if(g+=v,d?g<0:m<=g)throw TypeError("Reduce of empty array with no initial value")}for(;d?g>=0:m>g;g+=v)g in h&&(l=i(l,h[g],g,f));return l},Pm}var gS;function _z(){if(gS)return pS;gS=1;var t=xr(),e=Cz();return t(t.P+t.F*!Vl()([].reduce,!0),"Array",{reduce:function(r){return e(this,r,arguments.length,arguments[1],!1)}}),pS}_z();var vS={},Bm,yS;function Tz(){if(yS)return Bm;yS=1;var t=zn()("unscopables"),e=Array.prototype;return e[t]==null&&Pi()(e,t,{}),Bm=function(n){e[t][n]=!0},Bm}var $m,bS;function jz(){return bS||(bS=1,$m=function(t,e){return{value:e,done:!!t}}),$m}var Fm,xS;function ql(){return xS||(xS=1,Fm={}),Fm}var zm,wS;function Kl(){if(wS)return zm;wS=1;var t=n2(),e=Sy();return zm=Object.keys||function(r){return t(r,e)},zm}var Um,kS;function k2(){if(kS)return Um;kS=1;var t=cs(),e=Mr(),n=Kl();return Um=Gr()?Object.defineProperties:function(s,i){e(s);for(var o=n(i),l=o.length,d=0,f;l>d;)t.f(s,f=o[d++],i[f]);return s},Um}var Hm,SS;function Mz(){if(SS)return Hm;SS=1;var t=Kr().document;return Hm=t&&t.documentElement,Hm}var Wm,ES;function S2(){if(ES)return Wm;ES=1;var t=Mr(),e=k2(),n=Sy(),r=ky()("IE_PROTO"),s=function(){},i="prototype",o=function(){var l=QT()("iframe"),d=n.length,f="<",h=">",m;for(l.style.display="none",Mz().appendChild(l),l.src="javascript:",m=l.contentWindow.document,m.open(),m.write(f+"script"+h+"document.F=Object"+f+"/script"+h),m.close(),o=m.F;d--;)delete o[i][n[d]];return o()};return Wm=Object.create||function(d,f){var h;return d!==null?(s[i]=t(d),h=new s,s[i]=null,h[r]=d):h=o(),f===void 0?h:e(h,f)},Wm}var Vm,NS;function _y(){if(NS)return Vm;NS=1;var t=cs().f,e=ko(),n=zn()("toStringTag");return Vm=function(r,s,i){r&&!e(r=i?r:r.prototype,n)&&t(r,n,{configurable:!0,value:s})},Vm}var qm,CS;function Az(){if(CS)return qm;CS=1;var t=S2(),e=Wl(),n=_y(),r={};return Pi()(r,zn()("iterator"),function(){return this}),qm=function(s,i,o){s.prototype=t(r,{next:e(1,o)}),n(s,i+" Iterator")},qm}var Km,_S;function Rz(){if(_S)return Km;_S=1;var t=ko(),e=Di(),n=ky()("IE_PROTO"),r=Object.prototype;return Km=Object.getPrototypeOf||function(s){return s=e(s),t(s,n)?s[n]:typeof s.constructor=="function"&&s instanceof s.constructor?s.constructor.prototype:s instanceof Object?r:null},Km}var Gm,TS;function E2(){if(TS)return Gm;TS=1;var t=lf(),e=xr(),n=Vs(),r=Pi(),s=ql(),i=Az(),o=_y(),l=Rz(),d=zn()("iterator"),f=!([].keys&&"next"in[].keys()),h="@@iterator",m="keys",g="values",v=function(){return this};return Gm=function(b,k,w,S,N,T,M){i(w,k,S);var _=function(ne){if(!f&&ne in B)return B[ne];switch(ne){case m:return function(){return new w(this,ne)};case g:return function(){return new w(this,ne)}}return function(){return new w(this,ne)}},R=k+" Iterator",I=N==g,P=!1,B=b.prototype,z=B[d]||B[h]||N&&B[N],K=z||_(N),F=N?I?_("entries"):K:void 0,J=k=="Array"&&B.entries||z,$,W,q;if(J&&(q=l(J.call(new b)),q!==Object.prototype&&q.next&&(o(q,R,!0),!t&&typeof q[d]!="function"&&r(q,d,v))),I&&z&&z.name!==g&&(P=!0,K=function(){return z.call(this)}),(!t||M)&&(f||P||!B[d])&&r(B,d,K),s[k]=K,s[R]=v,N)if($={values:I?K:_(g),keys:T?K:_(m),entries:F},M)for(W in $)W in B||n(B,W,$[W]);else e(e.P+e.F*(f||P),k,$);return $},Gm}var Jm,jS;function N2(){if(jS)return Jm;jS=1;var t=Tz(),e=jz(),n=ql(),r=So();return Jm=E2()(Array,"Array",function(s,i){this._t=r(s),this._i=0,this._k=i},function(){var s=this._t,i=this._k,o=this._i++;return!s||o>=s.length?(this._t=void 0,e(1)):i=="keys"?e(0,o):i=="values"?e(0,s[o]):e(0,[o,s[o]])},"values"),n.Arguments=n.Array,t("keys"),t("values"),t("entries"),Jm}var MS;function Oz(){if(MS)return vS;MS=1;for(var t=N2(),e=Kl(),n=Vs(),r=Kr(),s=Pi(),i=ql(),o=zn(),l=o("iterator"),d=o("toStringTag"),f=i.Array,h={CSSRuleList:!0,CSSStyleDeclaration:!1,CSSValueList:!1,ClientRectList:!1,DOMRectList:!1,DOMStringList:!1,DOMTokenList:!0,DataTransferItemList:!1,FileList:!1,HTMLAllCollection:!1,HTMLCollection:!1,HTMLFormElement:!1,HTMLSelectElement:!1,MediaList:!0,MimeTypeArray:!1,NamedNodeMap:!1,NodeList:!0,PaintRequestList:!1,Plugin:!1,PluginArray:!1,SVGLengthList:!1,SVGNumberList:!1,SVGPathSegList:!1,SVGPointList:!1,SVGStringList:!1,SVGTransformList:!1,SourceBufferList:!1,StyleSheetList:!0,TextTrackCueList:!1,TextTrackList:!1,TouchList:!1},m=e(h),g=0;g<m.length;g++){var v=m[g],b=h[v],k=r[v],w=k&&k.prototype,S;if(w&&(w[l]||s(w,l,f),w[d]||s(w,d,v),i[v]=f,b))for(S in t)w[S]||n(w,S,t[S],!0)}return vS}Oz();N2();var AS={},Ym,RS;function Iz(){if(RS)return Ym;RS=1;var t=xr(),e=ga(),n=ls();return Ym=function(r,s){var i=(e.Object||{})[r]||Object[r],o={};o[r]=s(i),t(t.S+t.F*n(function(){i(1)}),"Object",o)},Ym}var OS;function Lz(){if(OS)return AS;OS=1;var t=Di(),e=Kl();return Iz()("keys",function(){return function(r){return e(t(r))}}),AS}Lz();var Dz=Rt(/[#{invalidCharsGroup}]/,{invalidCharsGroup:Ey});function Pz(t){return Dz.test(t)}var Zi={},Cu={},IS;function Bz(){return IS||(IS=1,Object.defineProperty(Cu,"__esModule",{value:!0}),Cu.default=/(?:\ud83d[\udc68\udc69])(?:\ud83c[\udffb-\udfff])?\u200d(?:\u2695\ufe0f|\u2696\ufe0f|\u2708\ufe0f|\ud83c[\udf3e\udf73\udf93\udfa4\udfa8\udfeb\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92]|\ud83e[\uddb0-\uddb3])|(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75]|\u26f9)((?:\ud83c[\udffb-\udfff]|\ufe0f)\u200d[\u2640\u2642]\ufe0f)|(?:\ud83c[\udfc3\udfc4\udfca]|\ud83d[\udc6e\udc71\udc73\udc77\udc81\udc82\udc86\udc87\ude45-\ude47\ude4b\ude4d\ude4e\udea3\udeb4-\udeb6]|\ud83e[\udd26\udd35\udd37-\udd39\udd3d\udd3e\uddb8\uddb9\uddd6-\udddd])(?:\ud83c[\udffb-\udfff])?\u200d[\u2640\u2642]\ufe0f|(?:\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83c\udff3\ufe0f\u200d\ud83c\udf08|\ud83c\udff4\u200d\u2620\ufe0f|\ud83d\udc41\u200d\ud83d\udde8|\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc6f\u200d\u2640\ufe0f|\ud83d\udc6f\u200d\u2642\ufe0f|\ud83e\udd3c\u200d\u2640\ufe0f|\ud83e\udd3c\u200d\u2642\ufe0f|\ud83e\uddde\u200d\u2640\ufe0f|\ud83e\uddde\u200d\u2642\ufe0f|\ud83e\udddf\u200d\u2640\ufe0f|\ud83e\udddf\u200d\u2642\ufe0f)|[#*0-9]\ufe0f?\u20e3|(?:[©®\u2122\u265f]\ufe0f)|(?:\ud83c[\udc04\udd70\udd71\udd7e\udd7f\ude02\ude1a\ude2f\ude37\udf21\udf24-\udf2c\udf36\udf7d\udf96\udf97\udf99-\udf9b\udf9e\udf9f\udfcd\udfce\udfd4-\udfdf\udff3\udff5\udff7]|\ud83d[\udc3f\udc41\udcfd\udd49\udd4a\udd6f\udd70\udd73\udd76-\udd79\udd87\udd8a-\udd8d\udda5\udda8\uddb1\uddb2\uddbc\uddc2-\uddc4\uddd1-\uddd3\udddc-\uddde\udde1\udde3\udde8\uddef\uddf3\uddfa\udecb\udecd-\udecf\udee0-\udee5\udee9\udef0\udef3]|[\u203c\u2049\u2139\u2194-\u2199\u21a9\u21aa\u231a\u231b\u2328\u23cf\u23ed-\u23ef\u23f1\u23f2\u23f8-\u23fa\u24c2\u25aa\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262a\u262e\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267b\u267f\u2692-\u2697\u2699\u269b\u269c\u26a0\u26a1\u26aa\u26ab\u26b0\u26b1\u26bd\u26be\u26c4\u26c5\u26c8\u26cf\u26d1\u26d3\u26d4\u26e9\u26ea\u26f0-\u26f5\u26f8\u26fa\u26fd\u2702\u2708\u2709\u270f\u2712\u2714\u2716\u271d\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u2764\u27a1\u2934\u2935\u2b05-\u2b07\u2b1b\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299])(?:\ufe0f|(?!\ufe0e))|(?:(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75\udd90]|[\u261d\u26f7\u26f9\u270c\u270d])(?:\ufe0f|(?!\ufe0e))|(?:\ud83c[\udf85\udfc2-\udfc4\udfc7\udfca]|\ud83d[\udc42\udc43\udc46-\udc50\udc66-\udc69\udc6e\udc70-\udc78\udc7c\udc81-\udc83\udc85-\udc87\udcaa\udd7a\udd95\udd96\ude45-\ude47\ude4b-\ude4f\udea3\udeb4-\udeb6\udec0\udecc]|\ud83e[\udd18-\udd1c\udd1e\udd1f\udd26\udd30-\udd39\udd3d\udd3e\uddb5\uddb6\uddb8\uddb9\uddd1-\udddd]|[\u270a\u270b]))(?:\ud83c[\udffb-\udfff])?|(?:\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc77\udb40\udc6c\udb40\udc73\udb40\udc7f|\ud83c\udde6\ud83c[\udde8-\uddec\uddee\uddf1\uddf2\uddf4\uddf6-\uddfa\uddfc\uddfd\uddff]|\ud83c\udde7\ud83c[\udde6\udde7\udde9-\uddef\uddf1-\uddf4\uddf6-\uddf9\uddfb\uddfc\uddfe\uddff]|\ud83c\udde8\ud83c[\udde6\udde8\udde9\uddeb-\uddee\uddf0-\uddf5\uddf7\uddfa-\uddff]|\ud83c\udde9\ud83c[\uddea\uddec\uddef\uddf0\uddf2\uddf4\uddff]|\ud83c\uddea\ud83c[\udde6\udde8\uddea\uddec\udded\uddf7-\uddfa]|\ud83c\uddeb\ud83c[\uddee-\uddf0\uddf2\uddf4\uddf7]|\ud83c\uddec\ud83c[\udde6\udde7\udde9-\uddee\uddf1-\uddf3\uddf5-\uddfa\uddfc\uddfe]|\ud83c\udded\ud83c[\uddf0\uddf2\uddf3\uddf7\uddf9\uddfa]|\ud83c\uddee\ud83c[\udde8-\uddea\uddf1-\uddf4\uddf6-\uddf9]|\ud83c\uddef\ud83c[\uddea\uddf2\uddf4\uddf5]|\ud83c\uddf0\ud83c[\uddea\uddec-\uddee\uddf2\uddf3\uddf5\uddf7\uddfc\uddfe\uddff]|\ud83c\uddf1\ud83c[\udde6-\udde8\uddee\uddf0\uddf7-\uddfb\uddfe]|\ud83c\uddf2\ud83c[\udde6\udde8-\udded\uddf0-\uddff]|\ud83c\uddf3\ud83c[\udde6\udde8\uddea-\uddec\uddee\uddf1\uddf4\uddf5\uddf7\uddfa\uddff]|\ud83c\uddf4\ud83c\uddf2|\ud83c\uddf5\ud83c[\udde6\uddea-\udded\uddf0-\uddf3\uddf7-\uddf9\uddfc\uddfe]|\ud83c\uddf6\ud83c\udde6|\ud83c\uddf7\ud83c[\uddea\uddf4\uddf8\uddfa\uddfc]|\ud83c\uddf8\ud83c[\udde6-\uddea\uddec-\uddf4\uddf7-\uddf9\uddfb\uddfd-\uddff]|\ud83c\uddf9\ud83c[\udde6\udde8\udde9\uddeb-\udded\uddef-\uddf4\uddf7\uddf9\uddfb\uddfc\uddff]|\ud83c\uddfa\ud83c[\udde6\uddec\uddf2\uddf3\uddf8\uddfe\uddff]|\ud83c\uddfb\ud83c[\udde6\udde8\uddea\uddec\uddee\uddf3\uddfa]|\ud83c\uddfc\ud83c[\uddeb\uddf8]|\ud83c\uddfd\ud83c\uddf0|\ud83c\uddfe\ud83c[\uddea\uddf9]|\ud83c\uddff\ud83c[\udde6\uddf2\uddfc]|\ud83c[\udccf\udd8e\udd91-\udd9a\udde6-\uddff\ude01\ude32-\ude36\ude38-\ude3a\ude50\ude51\udf00-\udf20\udf2d-\udf35\udf37-\udf7c\udf7e-\udf84\udf86-\udf93\udfa0-\udfc1\udfc5\udfc6\udfc8\udfc9\udfcf-\udfd3\udfe0-\udff0\udff4\udff8-\udfff]|\ud83d[\udc00-\udc3e\udc40\udc44\udc45\udc51-\udc65\udc6a-\udc6d\udc6f\udc79-\udc7b\udc7d-\udc80\udc84\udc88-\udca9\udcab-\udcfc\udcff-\udd3d\udd4b-\udd4e\udd50-\udd67\udda4\uddfb-\ude44\ude48-\ude4a\ude80-\udea2\udea4-\udeb3\udeb7-\udebf\udec1-\udec5\uded0-\uded2\udeeb\udeec\udef4-\udef9]|\ud83e[\udd10-\udd17\udd1d\udd20-\udd25\udd27-\udd2f\udd3a\udd3c\udd40-\udd45\udd47-\udd70\udd73-\udd76\udd7a\udd7c-\udda2\uddb4\uddb7\uddc0-\uddc2\uddd0\uddde-\uddff]|[\u23e9-\u23ec\u23f0\u23f3\u267e\u26ce\u2705\u2728\u274c\u274e\u2753-\u2755\u2795-\u2797\u27b0\u27bf\ue50a])|\ufe0f/g),Cu}var LS;function $z(){if(LS)return Zi;LS=1,Object.defineProperty(Zi,"__esModule",{value:!0}),Zi.TypeName=void 0,Zi.parse=s,Zi.toCodePoints=d;var t=Bz(),e=n(t);function n(f){return f&&f.__esModule?f:{default:f}}var r=Zi.TypeName="emoji";function s(f,h){var m=h&&h.assetType?h.assetType:"svg",g=h&&h.buildUrl?h.buildUrl:function(S,N){return N==="png"?"https://twemoji.maxcdn.com/2/72x72/"+S+".png":"https://twemoji.maxcdn.com/2/svg/"+S+".svg"},v=[];for(e.default.lastIndex=0;;){var b=e.default.exec(f);if(!b)break;var k=b[0],w=d(l(k)).join("-");v.push({url:w?g(w,m):"",indices:[b.index,e.default.lastIndex],text:k,type:r})}return v}var i=/\uFE0F/g,o="",l=function(h){return h.indexOf(o)<0?h.replace(i,""):h};function d(f){for(var h=[],m=0,g=0,v=0;v<f.length;)m=f.charCodeAt(v++),g?(h.push((65536+(g-55296<<10)+(m-56320)).toString(16)),g=0):m>55296&&m<=56319?g=m:h.push(m.toString(16));return h}return Zi}var Fz=$z(),zz=function(){for(var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:uS.defaults,r=Object.keys(n).length?n:uS.defaults,s=r.defaultWeight,i=r.emojiParsingEnabled,o=r.scale,l=r.maxWeightedTweetLength,d=r.transformedURLLength,f=typeof String.prototype.normalize=="function"?e.normalize():e,h=DS(cz(f)),m=i?DS(Fz.parse(f)):[],g=f.length,v=0,b=0,k=!0,w=0;w<g;w++){if(h[w]){var S=h[w],N=S.url;S.indices,v+=d*o,w+=N.length-1}else if(i&&m[w]){var T=m[w],M=T.text;T.indices,v+=s,w+=M.length-1}else w+=Uz(f,w)?1:0,v+=Nz(f.charAt(w),r);k&&(k=!Pz(f.substring(w,w+1))),k&&v<=l*o&&(b=w)}v=v/o,k=k&&v>0&&v<=l;var _=Math.floor(v/l*1e3),R=e.length-f.length;return b+=R,{weightedLength:v,valid:k,permillage:_,validRangeStart:0,validRangeEnd:b,displayRangeStart:0,displayRangeEnd:e.length>0?e.length-1:0}},DS=function(e){return e.reduce(function(n,r){return n[r.indices[0]]=r,n},{})},Uz=function(e,n){if(n<e.length-1){var r=e.charCodeAt(n),s=e.charCodeAt(n+1);return 55296<=r&&r<=56319&&56320<=s&&s<=57343}return!1},PS={},BS;function Hz(){if(BS)return PS;BS=1;var t=xr();return t(t.S+t.F*!Gr(),"Object",{defineProperty:cs().f}),PS}Hz();var $S={},FS;function Wz(){if(FS)return $S;FS=1;var t=xr();return t(t.S+t.F*!Gr(),"Object",{defineProperties:k2()}),$S}Wz();var zS={},Xm={},US;function Ty(){return US||(US=1,Xm.f=Object.getOwnPropertySymbols),Xm}var Qm,HS;function Vz(){if(HS)return Qm;HS=1;var t=hf(),e=Ty(),n=Mr(),r=Kr().Reflect;return Qm=r&&r.ownKeys||function(i){var o=t.f(n(i)),l=e.f;return l?o.concat(l(i)):o},Qm}var Zm,WS;function C2(){if(WS)return Zm;WS=1;var t=cs(),e=Wl();return Zm=function(n,r,s){r in n?t.f(n,r,e(0,s)):n[r]=s},Zm}var VS;function qz(){if(VS)return zS;VS=1;var t=xr(),e=Vz(),n=So(),r=wy(),s=C2();return t(t.S,"Object",{getOwnPropertyDescriptors:function(o){for(var l=n(o),d=r.f,f=e(l),h={},m=0,g,v;f.length>m;)v=d(l,g=f[m++]),v!==void 0&&s(h,g,v);return h}}),zS}qz();var qS={},eg,KS;function Kz(){if(KS)return eg;KS=1;var t=Ws(),e=Cy(),n=zn()("species");return eg=function(r){var s;return e(r)&&(s=r.constructor,typeof s=="function"&&(s===Array||e(s.prototype))&&(s=void 0),t(s)&&(s=s[n],s===null&&(s=void 0))),s===void 0?Array:s},eg}var tg,GS;function Gz(){if(GS)return tg;GS=1;var t=Kz();return tg=function(e,n){return new(t(e))(n)},tg}var ng,JS;function _2(){if(JS)return ng;JS=1;var t=ff(),e=by(),n=Di(),r=wo(),s=Gz();return ng=function(i,o){var l=i==1,d=i==2,f=i==3,h=i==4,m=i==6,g=i==5||m,v=o||s;return function(b,k,w){for(var S=n(b),N=e(S),T=t(k,w,3),M=r(N.length),_=0,R=l?v(b,M):d?v(b,0):void 0,I,P;M>_;_++)if((g||_ in N)&&(I=N[_],P=T(I,_,S),i)){if(l)R[_]=P;else if(P)switch(i){case 3:return!0;case 5:return I;case 6:return _;case 2:R.push(I)}else if(h)return!1}return m?-1:f||h?h:R}},ng}var YS;function Jz(){if(YS)return qS;YS=1;var t=xr(),e=_2()(0),n=Vl()([].forEach,!0);return t(t.P+t.F*!n,"Array",{forEach:function(s){return e(this,s,arguments[1])}}),qS}Jz();var XS={},QS;function Yz(){if(QS)return XS;QS=1;var t=xr(),e=_2()(2);return t(t.P+t.F*!Vl()([].filter,!0),"Array",{filter:function(r){return e(this,r,arguments[1])}}),XS}Yz();var ZS={},rg={exports:{}},eE;function Xz(){if(eE)return rg.exports;eE=1;var t=Hl()("meta"),e=Ws(),n=ko(),r=cs().f,s=0,i=Object.isExtensible||function(){return!0},o=!ls()(function(){return i(Object.preventExtensions({}))}),l=function(g){r(g,t,{value:{i:"O"+ ++s,w:{}}})},d=function(g,v){if(!e(g))return typeof g=="symbol"?g:(typeof g=="string"?"S":"P")+g;if(!n(g,t)){if(!i(g))return"F";if(!v)return"E";l(g)}return g[t].i},f=function(g,v){if(!n(g,t)){if(!i(g))return!0;if(!v)return!1;l(g)}return g[t].w},h=function(g){return o&&m.NEED&&i(g)&&!n(g,t)&&l(g),g},m=rg.exports={KEY:t,NEED:!1,fastKey:d,getWeak:f,onFreeze:h};return rg.exports}var sg={},tE;function T2(){return tE||(tE=1,sg.f=zn()),sg}var ig,nE;function Qz(){if(nE)return ig;nE=1;var t=Kr(),e=ga(),n=lf(),r=T2(),s=cs().f;return ig=function(i){var o=e.Symbol||(e.Symbol=n?{}:t.Symbol||{});i.charAt(0)!="_"&&!(i in o)&&s(o,i,{value:r.f(i)})},ig}var og,rE;function Zz(){if(rE)return og;rE=1;var t=Kl(),e=Ty(),n=xy();return og=function(r){var s=t(r),i=e.f;if(i)for(var o=i(r),l=n.f,d=0,f;o.length>d;)l.call(r,f=o[d++])&&s.push(f);return s},og}var ag={},sE;function eU(){if(sE)return ag;sE=1;var t=So(),e=hf().f,n={}.toString,r=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],s=function(i){try{return e(i)}catch{return r.slice()}};return ag.f=function(o){return r&&n.call(o)=="[object Window]"?s(o):e(t(o))},ag}var iE;function tU(){if(iE)return ZS;iE=1;var t=Kr(),e=ko(),n=Gr(),r=xr(),s=Vs(),i=Xz().KEY,o=ls(),l=cf(),d=_y(),f=Hl(),h=zn(),m=T2(),g=Qz(),v=Zz(),b=Cy(),k=Mr(),w=Ws(),S=Di(),N=So(),T=vy(),M=Wl(),_=S2(),R=eU(),I=wy(),P=Ty(),B=cs(),z=Kl(),K=I.f,F=B.f,J=R.f,$=t.Symbol,W=t.JSON,q=W&&W.stringify,ne="prototype",V=h("_hidden"),oe=h("toPrimitive"),Y={}.propertyIsEnumerable,A=l("symbol-registry"),L=l("symbols"),ee=l("op-symbols"),ue=Object[ne],be=typeof $=="function"&&!!P.f,re=t.QObject,we=!re||!re[ne]||!re[ne].findChild,Ee=n&&o(function(){return _(F({},"a",{get:function(){return F(this,"a",{value:7}).a}})).a!=7})?function(ve,Z,je){var Q=K(ue,Z);Q&&delete ue[Z],F(ve,Z,je),Q&&ve!==ue&&F(ue,Z,Q)}:F,$e=function(ve){var Z=L[ve]=_($[ne]);return Z._k=ve,Z},Fe=be&&typeof $.iterator=="symbol"?function(ve){return typeof ve=="symbol"}:function(ve){return ve instanceof $},Ze=function(Z,je,Q){return Z===ue&&Ze(ee,je,Q),k(Z),je=T(je,!0),k(Q),e(L,je)?(Q.enumerable?(e(Z,V)&&Z[V][je]&&(Z[V][je]=!1),Q=_(Q,{enumerable:M(0,!1)})):(e(Z,V)||F(Z,V,M(1,{})),Z[V][je]=!0),Ee(Z,je,Q)):F(Z,je,Q)},Re=function(Z,je){k(Z);for(var Q=v(je=N(je)),he=0,me=Q.length,Ue;me>he;)Ze(Z,Ue=Q[he++],je[Ue]);return Z},tt=function(Z,je){return je===void 0?_(Z):Re(_(Z),je)},gt=function(Z){var je=Y.call(this,Z=T(Z,!0));return this===ue&&e(L,Z)&&!e(ee,Z)?!1:je||!e(this,Z)||!e(L,Z)||e(this,V)&&this[V][Z]?je:!0},ut=function(Z,je){if(Z=N(Z),je=T(je,!0),!(Z===ue&&e(L,je)&&!e(ee,je))){var Q=K(Z,je);return Q&&e(L,je)&&!(e(Z,V)&&Z[V][je])&&(Q.enumerable=!0),Q}},ge=function(Z){for(var je=J(N(Z)),Q=[],he=0,me;je.length>he;)!e(L,me=je[he++])&&me!=V&&me!=i&&Q.push(me);return Q},yt=function(Z){for(var je=Z===ue,Q=J(je?ee:N(Z)),he=[],me=0,Ue;Q.length>me;)e(L,Ue=Q[me++])&&(!je||e(ue,Ue))&&he.push(L[Ue]);return he};be||($=function(){if(this instanceof $)throw TypeError("Symbol is not a constructor!");var Z=f(arguments.length>0?arguments[0]:void 0),je=function(Q){this===ue&&je.call(ee,Q),e(this,V)&&e(this[V],Z)&&(this[V][Z]=!1),Ee(this,Z,M(1,Q))};return n&&we&&Ee(ue,Z,{configurable:!0,set:je}),$e(Z)},s($[ne],"toString",function(){return this._k}),I.f=ut,B.f=Ze,hf().f=R.f=ge,xy().f=gt,P.f=yt,n&&!lf()&&s(ue,"propertyIsEnumerable",gt,!0),m.f=function(ve){return $e(h(ve))}),r(r.G+r.W+r.F*!be,{Symbol:$});for(var Ct="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),_t=0;Ct.length>_t;)h(Ct[_t++]);for(var Lt=z(h.store),at=0;Lt.length>at;)g(Lt[at++]);r(r.S+r.F*!be,"Symbol",{for:function(ve){return e(A,ve+="")?A[ve]:A[ve]=$(ve)},keyFor:function(Z){if(!Fe(Z))throw TypeError(Z+" is not a symbol!");for(var je in A)if(A[je]===Z)return je},useSetter:function(){we=!0},useSimple:function(){we=!1}}),r(r.S+r.F*!be,"Object",{create:tt,defineProperty:Ze,defineProperties:Re,getOwnPropertyDescriptor:ut,getOwnPropertyNames:ge,getOwnPropertySymbols:yt});var De=o(function(){P.f(1)});return r(r.S+r.F*De,"Object",{getOwnPropertySymbols:function(Z){return P.f(S(Z))}}),W&&r(r.S+r.F*(!be||o(function(){var ve=$();return q([ve])!="[null]"||q({a:ve})!="{}"||q(Object(ve))!="{}"})),"JSON",{stringify:function(Z){for(var je=[Z],Q=1,he,me;arguments.length>Q;)je.push(arguments[Q++]);if(me=he=je[1],!(!w(he)&&Z===void 0||Fe(Z)))return b(he)||(he=function(Ue,Oe){if(typeof me=="function"&&(Oe=me.call(this,Ue,Oe)),!Fe(Oe))return Oe}),je[1]=he,q.apply(W,je)}}),$[ne][oe]||Pi()($[ne],oe,$[ne].valueOf),d($,"Symbol"),d(Math,"Math",!0),d(t.JSON,"JSON",!0),ZS}tU();Rt(/^#{validMentionOrList}$/,{validMentionOrList:bz});var j2=/[a-z\u0400-\u04FF0-9\-._~]/i,M2=/(?:%[0-9a-f]{2})/i,A2=/[!$&'()*+,;=]/i,R2=Rt("(?:#{validateUrlUnreserved}|#{validateUrlPctEncoded}|#{validateUrlSubDelims}|:)*",{validateUrlUnreserved:j2,validateUrlPctEncoded:M2,validateUrlSubDelims:A2},"i"),nU=/(?:[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?)/i,rU=/(?:[a-z](?:[a-z0-9\-]*[a-z0-9])?)/i,sU=/(?:[a-z0-9](?:[a-z0-9_\-]*[a-z0-9])?)/i,iU=Rt(/(?:(?:#{validateUrlSubDomainSegment}\.)*(?:#{validateUrlDomainSegment}\.)#{validateUrlDomainTld})/i,{validateUrlSubDomainSegment:sU,validateUrlDomainSegment:nU,validateUrlDomainTld:rU}),oU=/(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9]{2})|(?:2[0-4][0-9])|(?:25[0-5]))/i,aU=Rt(/(?:#{validateUrlDecOctet}(?:\.#{validateUrlDecOctet}){3})/i,{validateUrlDecOctet:oU}),lU=/(?:\[[a-f0-9:\.]+\])/i,O2=Rt("(?:#{validateUrlIpv4}|#{validateUrlIpv6})",{validateUrlIpv4:aU,validateUrlIpv6:lU},"i"),cU=Rt("(?:#{validateUrlIp}|#{validateUrlDomain})",{validateUrlIp:O2,validateUrlDomain:iU},"i"),I2=/[0-9]{1,5}/;Rt("(?:(#{validateUrlUserinfo})@)?(#{validateUrlHost})(?::(#{validateUrlPort}))?",{validateUrlUserinfo:R2,validateUrlHost:cU,validateUrlPort:I2},"i");var jy=Rt("(?:#{validateUrlUnreserved}|#{validateUrlPctEncoded}|#{validateUrlSubDelims}|[:|@])",{validateUrlUnreserved:j2,validateUrlPctEncoded:M2,validateUrlSubDelims:A2},"i");Rt(/(#{validateUrlPchar}|\/|\?)*/i,{validateUrlPchar:jy});Rt(/(\/#{validateUrlPchar}*)*/i,{validateUrlPchar:jy});Rt(/(#{validateUrlPchar}|\/|\?)*/i,{validateUrlPchar:jy});Rt("^(?:([^:/?#]+):\\/\\/)?([^/?#]*)([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$","i");var uU=/(?:(?:[a-z0-9]|[^\u0000-\u007f])(?:(?:[a-z0-9_\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i,dU=/(?:(?:[a-z0-9]|[^\u0000-\u007f])(?:(?:[a-z0-9\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i,fU=/(?:(?:[a-z]|[^\u0000-\u007f])(?:(?:[a-z0-9\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i,hU=Rt(/(?:(?:#{validateUrlUnicodeSubDomainSegment}\.)*(?:#{validateUrlUnicodeDomainSegment}\.)#{validateUrlUnicodeDomainTld})/i,{validateUrlUnicodeSubDomainSegment:uU,validateUrlUnicodeDomainSegment:dU,validateUrlUnicodeDomainTld:fU}),pU=Rt("(?:#{validateUrlIp}|#{validateUrlUnicodeDomain})",{validateUrlIp:O2,validateUrlUnicodeDomain:hU},"i");Rt("(?:(#{validateUrlUserinfo})@)?(#{validateUrlUnicodeHost})(?::(#{validateUrlPort}))?",{validateUrlUserinfo:R2,validateUrlUnicodeHost:pU,validateUrlPort:I2},"i");var oE={},aE;function mU(){if(aE)return oE;aE=1;var t=XT()(!0);return E2()(String,"String",function(e){this._t=String(e),this._i=0},function(){var e=this._t,n=this._i,r;return n>=e.length?{value:void 0,done:!0}:(r=t(e,n),this._i+=r.length,{value:r,done:!1})}),oE}mU();var lE={},lg,cE;function gU(){if(cE)return lg;cE=1;var t=Mr();return lg=function(e,n,r,s){try{return s?n(t(r)[0],r[1]):n(r)}catch(o){var i=e.return;throw i!==void 0&&t(i.call(e)),o}},lg}var cg,uE;function vU(){if(uE)return cg;uE=1;var t=ql(),e=zn()("iterator"),n=Array.prototype;return cg=function(r){return r!==void 0&&(t.Array===r||n[e]===r)},cg}var ug,dE;function yU(){if(dE)return ug;dE=1;var t=py(),e=zn()("iterator"),n=ql();return ug=ga().getIteratorMethod=function(r){if(r!=null)return r[e]||r["@@iterator"]||n[t(r)]},ug}var dg,fE;function bU(){if(fE)return dg;fE=1;var t=zn()("iterator"),e=!1;try{var n=[7][t]();n.return=function(){e=!0},Array.from(n,function(){throw 2})}catch{}return dg=function(r,s){if(!s&&!e)return!1;var i=!1;try{var o=[7],l=o[t]();l.next=function(){return{done:i=!0}},o[t]=function(){return l},r(o)}catch{}return i},dg}var hE;function xU(){if(hE)return lE;hE=1;var t=ff(),e=xr(),n=Di(),r=gU(),s=vU(),i=wo(),o=C2(),l=yU();return e(e.S+e.F*!bU()(function(d){Array.from(d)}),"Array",{from:function(f){var h=n(f),m=typeof this=="function"?this:Array,g=arguments.length,v=g>1?arguments[1]:void 0,b=v!==void 0,k=0,w=l(h),S,N,T,M;if(b&&(v=t(v,g>2?arguments[2]:void 0,2)),w!=null&&!(m==Array&&s(w)))for(M=w.call(h),N=new m;!(T=M.next()).done;k++)o(N,k,b?r(M,v,[T.value,k],!0):T.value);else for(S=i(h.length),N=new m(S);S>k;k++)o(N,k,b?v(h[k],k):h[k]);return N.length=k,N}}),lE}xU();const wU={parseTweet:zz},{parseTweet:kU}=wU;function pE(t){return kU(t).weightedLength}const mE="ow-x-handle";function SU(){const[t,e]=x.useState(()=>localStorage.getItem(mE)||""),[n,r]=x.useState(!1),[s,i]=x.useState(""),o=x.useRef(null),l=x.useRef(null),d=()=>{const m=s.replace(/^@/,"").trim();m&&(localStorage.setItem(mE,m),e(m)),r(!1)},f=()=>{i(t),r(!0),setTimeout(()=>{var m;return(m=o.current)==null?void 0:m.focus()},0)};x.useEffect(()=>{if(!n)return;const m=g=>{l.current&&!l.current.contains(g.target)&&d()};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[n,s]);const h=t?`https://unavatar.io/twitter/${t}`:"";return c.jsxs("div",{className:"tweet-compose-avatar-wrapper",ref:l,children:[t?c.jsx("img",{className:"tweet-compose-avatar tweet-compose-avatar-img",src:h,alt:`@${t}`,onClick:f,title:`@${t} — click to change`}):c.jsx("div",{className:"tweet-compose-avatar",onClick:f,title:"Set your @handle"}),n&&c.jsx("div",{className:"tweet-handle-popover",children:c.jsx("input",{ref:o,className:"tweet-handle-input",value:s,onChange:m=>i(m.target.value),onKeyDown:m=>{m.key==="Enter"&&d(),m.key==="Escape"&&r(!1)},placeholder:"your_handle",spellCheck:!1})})]})}const EU={tweet:!0,reply:!0,quote:!1};function gE(){return c.jsxs("div",{className:"tweet-skeleton",children:[c.jsxs("div",{className:"tweet-author-row",children:[c.jsx("div",{className:"tweet-avatar tweet-avatar-placeholder tweet-pulse"}),c.jsxs("div",{className:"tweet-author-info",children:[c.jsx("span",{className:"tweet-skeleton-line tweet-pulse",style:{width:120}}),c.jsx("span",{className:"tweet-skeleton-line tweet-pulse",style:{width:80}})]})]}),c.jsx("div",{className:"tweet-skeleton-line tweet-pulse",style:{width:"100%",height:16,marginTop:12}}),c.jsx("div",{className:"tweet-skeleton-line tweet-pulse",style:{width:"75%",height:16,marginTop:8}})]})}function NU(t){var e;if(t)return(e=t.match(/\/status\/(\d+)/))==null?void 0:e[1]}function _u(t){if(!t)return[null];if(typeof t=="string"){const e=t.split(/<hr\s*\/?>/i).map(n=>n.trim()).filter(Boolean);return e.length?e:[null]}if((t==null?void 0:t.type)==="doc"&&Array.isArray(t.content)){const e=[[]];for(const r of t.content)r.type==="horizontalRule"?e.push([]):e[e.length-1].push(r);const n=e.map(r=>r.length?{type:"doc",content:r}:null).filter(Boolean);return n.length?n:[null]}return[t]}function Tu(t){var n;if(!t||typeof t=="string"||!t.content)return[];const e=[];for(let r=t.content.length-1;r>=0&&(t.content[r].type==="image"&&((n=t.content[r].attrs)!=null&&n.src));r--)e.unshift(t.content[r].attrs.src);return e}function vE(t,e){if(!t||typeof t=="string"||!t.content||e===0)return t;const n=t.content.slice(0,t.content.length-e);return n.length===0?{type:"doc",content:[{type:"paragraph",content:[]}]}:{...t,content:n}}function ju(t,e){const n=[];let r=0;return t.forEach((s,i)=>{if(!s)return;r>0&&n.push({type:"horizontalRule"});const o=s.getJSON();o.content&&n.push(...o.content);const l=e==null?void 0:e[i];if(l)for(const d of l){const f=crypto.randomUUID().replace(/-/g,"").slice(0,8);n.push({type:"image",attrs:{src:d,id:f}})}r++}),{type:"doc",content:n}}function yE(t,e){const n=[],r=s=>{var i;s.type==="image"&&((i=s.attrs)!=null&&i.src)&&n.push(s.attrs.src),s.content&&s.content.forEach(r)};return r(t.getJSON()),e&&n.push(...e),n.slice(0,4)}function Mu(t){fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tweetContext:t}),keepalive:!0}).catch(()=>{})}function CU({tweetContext:t,initialContent:e,onUpdate:n,onEditorReady:r,onEditorsChange:s,onActiveEditorChange:i,filename:o,title:l,autoplug:d}){var Et;const{tweet:f,loading:h,error:m}=pF(t==null?void 0:t.url),[g,v]=x.useState(()=>_u(e).map(Ne=>{const Ke=Tu(Ne);return vE(Ne,Ke.length)})),[b,k]=x.useState(0),w=x.useRef([]),S=x.useRef(null),N=x.useRef(!0),T=x.useRef(!1),M=x.useRef(g.length),[_,R]=x.useState(()=>g.map(()=>0)),[I,P]=x.useState(0),[B,z]=x.useState(0),K=x.useRef(_u(e).map(_e=>Tu(_e))),[F,J]=x.useState(()=>_u(e).map(Ne=>Tu(Ne).length)),[$,W]=x.useState(null),[q,ne]=x.useState(),[V,oe]=x.useState(!1),[Y,A]=x.useState("idle"),[L,ee]=x.useState(""),ue=x.useRef(),{copyText:be,copyState:re}=yF(w,I),[we,Ee]=x.useState(!1),$e=EU[(t==null?void 0:t.mode)??"tweet"],Fe=!!((Et=t==null?void 0:t.lastPost)!=null&&Et.postedAt),[Ze,Re]=x.useState(!1),[tt,gt]=x.useState(""),ut=x.useRef(null),ge=x.useRef(null);x.useEffect(()=>{if(!Ze)return;setTimeout(()=>{var Ne;return(Ne=ut.current)==null?void 0:Ne.focus()},0);const _e=Ne=>{ge.current&&!ge.current.contains(Ne.target)&&(Re(!1),gt(""))};return document.addEventListener("mousedown",_e),()=>document.removeEventListener("mousedown",_e)},[Ze]);const yt=()=>{var st;const _e=tt.trim();if(!(!_e||_e.includes("x.com")||_e.includes("twitter.com")))return;const Ke=(st=t==null?void 0:t.lastPost)==null?void 0:st.postedAt;Mu({lastPost:{postedAt:Ke??new Date().toISOString(),tweetUrl:_e||void 0}}),Re(!1),gt("")},Ct=()=>{Mu({lastPost:null})},_t=d!==!1,Lt=()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoplug:!_t}),keepalive:!0}).catch(()=>{})};x.useEffect(()=>{let _e=!1;return(async()=>{try{const Ne=await fetch("/api/x/status");if(_e)return;if(Ne.ok){const Ke=await Ne.json();W(Ke.connected),ne(Ke.username)}else W(!1)}catch{_e||W(!1)}})(),()=>{_e=!0}},[]),x.useEffect(()=>{if(N.current){N.current=!1;return}if(!e||JSON.stringify(e)===S.current)return;const Ne=_u(e),Ke=Ne.map(Ye=>Tu(Ye)),st=Ne.map((Ye,jt)=>vE(Ye,Ke[jt].length));T.current=!0,M.current=st.length,w.current=[],K.current=Ke,v(st),R(st.map(()=>0)),J(Ke.map(Ye=>Ye.length)),k(Ye=>Ye+1)},[e]);const at=x.useCallback((_e,Ne)=>{if(w.current[_e]=Ne,R(st=>{const Ye=[...st];return Ye[_e]=pE(Ne.getText()),Ye}),T.current)return;const Ke=ju(w.current,K.current);S.current=JSON.stringify(Ke),n==null||n(Ke)},[n]),De=x.useCallback((_e,Ne)=>{if(w.current[_e]=Ne,R(Ke=>{const st=[...Ke];return st[_e]=pE(Ne.getText()),st}),z(Ke=>Ke+1),T.current&&w.current.filter(Boolean).length>=M.current){T.current=!1;const st=ju(w.current,K.current);S.current=JSON.stringify(st)}_e===0&&(r==null||r(Ne)),s==null||s(w.current.filter(Boolean))},[r,s]),ve=g.length>1;_.reduce((_e,Ne)=>_e+Ne,0);const Z=x.useCallback(()=>{const _e=I+1;v(Ne=>[...Ne.slice(0,_e),"<p></p>",...Ne.slice(_e)]),R(Ne=>[...Ne.slice(0,_e),0,...Ne.slice(_e)]),K.current.splice(_e,0,[]),J(Ne=>[...Ne.slice(0,_e),0,...Ne.slice(_e)]),P(_e)},[I]),je=x.useCallback(_e=>{_e!==0&&(w.current.splice(_e,1),K.current.splice(_e,1),v(Ne=>Ne.filter((Ke,st)=>st!==_e)),R(Ne=>Ne.filter((Ke,st)=>st!==_e)),J(Ne=>Ne.filter((Ke,st)=>st!==_e)),setTimeout(()=>{const Ne=ju(w.current,K.current);n==null||n(Ne),s==null||s(w.current.filter(Boolean))},0))},[n,s]),Q=!!(t!=null&&t.url),he=(t==null?void 0:t.mode)==="reply",me=(()=>{const Ne=w.current.filter(Boolean).some(st=>st.getText().trim()||yE(st).length>0),Ke=F.some(st=>st>0);return Ne||Ke})(),Ue=$&&me&&Y==="idle",Oe=async()=>{if(!$){oe(!0);return}if(Ue){A("uploading"),ee("");try{const _e=[];for(let Ke=0;Ke<w.current.length;Ke++){const st=w.current[Ke];if(!st)continue;const Ye=st.getText().trim(),jt=yE(st,K.current[Ke]);if(!Ye&&jt.length===0)continue;const j=[];for(const U of jt){const D=await(await fetch("/api/x/upload-media",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({src:U})})).json();if(!D.success)throw new Error(D.error||"Image upload failed");j.push(D.mediaId)}_e.push({text:Ye,mediaIds:j})}if(_e.length===0)return;A("posting");const Ne=NU(t==null?void 0:t.url);if(_e.length===1){const Ke={};_e[0].text&&(Ke.text=_e[0].text),_e[0].mediaIds.length>0&&(Ke.mediaIds=_e[0].mediaIds),(t==null?void 0:t.mode)==="reply"&&Ne?Ke.replyTo=Ne:(t==null?void 0:t.mode)==="quote"&&Ne&&(Ke.quoteTweetId=Ne);const Ye=await(await fetch("/api/x/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ke)})).json();Ye.success?(Mu({lastPost:{postedAt:new Date().toISOString(),tweetUrl:Ye.tweetUrl}}),A("success"),ue.current=setTimeout(()=>A("idle"),2500)):(console.error("[TweetCompose] Post error:",Ye.error),ee(Ye.error||"Post failed"),A("error"),setTimeout(()=>A("idle"),3e3))}else{const st={tweets:_e.map(j=>({text:j.text,...j.mediaIds.length>0?{mediaIds:j.mediaIds}:{}}))};(t==null?void 0:t.mode)==="reply"&&Ne&&(st.replyTo=Ne);const jt=await(await fetch("/api/x/post-thread",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(st)})).json();jt.success?(Mu({lastPost:{postedAt:new Date().toISOString(),tweetUrl:jt.threadUrl}}),A("success"),ue.current=setTimeout(()=>A("idle"),2500)):(ee(jt.error||"Thread post failed"),A("error"),setTimeout(()=>A("idle"),3e3))}}catch(_e){ee(_e.message||"Network error"),A("error"),setTimeout(()=>A("idle"),3e3)}}};x.useEffect(()=>()=>{ue.current&&clearTimeout(ue.current)},[]);const Ve=()=>{W(!0),oe(!1),fetch("/api/x/status").then(_e=>_e.json()).then(_e=>{_e.username&&ne(_e.username)}).catch(()=>{})},et=Y==="uploading"?"Uploading...":Y==="posting"?"Posting...":Y==="success"?"Posted!":Y==="error"?"Failed":ve?I===0?"Post Thread":"Post All":"Post",ft=g.map((_e,Ne)=>Ne===0?he?"Post your reply":"What is happening?!":"Add another tweet"),We=_e=>{var Ne;return c.jsxs("div",{className:`tweet-compose-footer${_e?" tweet-compose-footer--inline":""}`,children:[I===0&&((Ne=t==null?void 0:t.lastPost)==null?void 0:Ne.postedAt)&&c.jsxs("a",{className:"tweet-posted-status",href:t.lastPost.tweetUrl,target:"_blank",rel:"noopener noreferrer",title:t.lastPost.tweetUrl||"Posted to X",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Posted ",new Date(t.lastPost.postedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})]}),Y==="error"&&L&&c.jsx("span",{className:"tweet-post-error",children:L}),ve&&c.jsxs("span",{className:"tweet-thread-counter",children:[I+1,"/",g.length]}),c.jsx(CF,{count:_[I]||0}),c.jsx("button",{className:"tweet-thread-add",onClick:Z,title:"Add another tweet",children:c.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:[c.jsx("line",{x1:"10",y1:"4",x2:"10",y2:"16",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),c.jsx("line",{x1:"4",y1:"10",x2:"16",y2:"10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})}),c.jsx("button",{className:`tweet-copy-btn${re==="copied"?" tweet-copy-btn--copied":""}`,disabled:!me,onClick:be,title:"Copy tweet text to clipboard",children:re==="copied"?c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:c.jsx("path",{d:"M3 8.5L6.5 12L13 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Copied!"]}):c.jsxs(c.Fragment,{children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[c.jsx("rect",{x:"5.5",y:"2",width:"8.5",height:"10.5",rx:"1.5",stroke:"currentColor",strokeWidth:"1.5"}),c.jsx("path",{d:"M3.5 5H2.5A1.5 1.5 0 001 6.5V13a1.5 1.5 0 001.5 1.5H9A1.5 1.5 0 0010.5 13v-1",stroke:"currentColor",strokeWidth:"1.5"})]}),"Copy"]})}),I===0&&!$e&&(()=>{var Ye;const Ke=((Ye=t==null?void 0:t.lastPost)==null?void 0:Ye.tweetUrl)??"",st=()=>{if(Fe){Ct(),Re(!1),gt("");return}gt(Ke),Re(!0)};return c.jsxs("div",{className:"tweet-mark-sent-wrap",ref:ge,children:[c.jsx("button",{className:`tweet-mark-sent-btn${Fe?" tweet-mark-sent-btn--done":""}`,onClick:st,title:Fe?Ke?`Posted — click to unmark (${Ke})`:"Posted — click to unmark":"Mark as manually posted",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:Fe?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("polyline",{points:"8 12 11 15 16 9",stroke:Fe?"#fff":"currentColor"})]})}),Ze&&(()=>{const jt=tt.trim(),j=!jt||jt.includes("x.com")||jt.includes("twitter.com");return c.jsxs("div",{className:"tweet-mark-sent-url",children:[c.jsx("input",{ref:ut,type:"text",placeholder:"Paste posted tweet URL...",value:tt,onChange:U=>gt(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),yt()),U.key==="Escape"&&(Re(!1),gt(""))}}),c.jsx("button",{onClick:yt,disabled:!j,title:jt?"Save URL":"Mark posted without URL",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})})]})})()]})})(),c.jsx("button",{className:`tweet-autoplug-toggle${_t?" tweet-autoplug-toggle--on":""}`,onClick:Lt,title:_t?"Auto-plug ON — engagement autoplugs may reply to this post with your configured promo. Click to opt out.":"Auto-plug OFF — this post is excluded from autoplugs. Click to opt in.",children:_t?"Auto-plug on":"Auto-plug off"}),o&&!Fe&&c.jsx("button",{className:"tweet-schedule-btn",onClick:()=>Ee(!0),title:"Schedule post",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("polyline",{points:"12 6 12 12 16 14"})]})}),$e&&c.jsx("button",{className:`tweet-post-btn${Ue||!$&&$!==null?" tweet-post-btn--active":""}${Y==="success"?" tweet-post-btn--success":""}${Y==="error"?" tweet-post-btn--error":""}`,disabled:$?!Ue:!1,onClick:Oe,title:$?q?`Post as @${q}`:"Post to X":"Connect X to post",children:et})]})},Ge=Q&&!he,vt=()=>c.jsx("div",{className:"tweet-thread-editors",children:g.map((_e,Ne)=>c.jsxs("div",{className:`tweet-thread-item${Ne===I?" tweet-thread-item--active":" tweet-thread-item--inactive"}`,children:[c.jsxs("div",{className:"tweet-thread-item-left",children:[c.jsx(SU,{}),Ne<g.length-1&&c.jsx("div",{className:"tweet-thread-line"})]}),c.jsxs("div",{className:"tweet-thread-item-right",children:[Ne>0&&c.jsx("button",{className:"tweet-thread-remove",onClick:()=>je(Ne),title:"Remove this tweet",children:"×"}),c.jsx("div",{className:`tweet-compose-box${Ne===0&&!ve?" tweet-compose-box--standalone":""}`,children:c.jsx(NF,{initialContent:_e,initialPreviewImages:K.current[Ne],placeholder:ft[Ne],onUpdate:Ke=>at(Ne,Ke),onReady:Ke=>De(Ne,Ke),onFocus:()=>{P(Ne);const Ke=w.current[Ne];Ke&&(i==null||i(Ke))},onPreviewImagesChange:Ke=>{if(K.current[Ne]=Ke,J(st=>{const Ye=[...st];return Ye[Ne]=Ke.length,Ye}),!T.current){const st=ju(w.current,K.current);S.current=JSON.stringify(st),n==null||n(st)}}})}),Ne===I&&!Ge&&We(Ne<g.length-1)]})]},`${b}-${Ne}`))});return c.jsxs("div",{className:"tweet-compose-wrapper",children:[Q&&he&&c.jsxs(c.Fragment,{children:[h&&c.jsx("div",{className:"tweet-context-section",children:c.jsx(gE,{})}),m&&c.jsx("div",{className:"tweet-context-section",children:c.jsxs("div",{className:"tweet-embed-error",children:[c.jsx("span",{children:"Could not load tweet"}),c.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",className:"tweet-fallback-link",children:t.url})]})}),f&&c.jsxs("div",{className:"tweet-reply-parent-section",children:[c.jsx("div",{className:"tweet-reply-parent-card",children:c.jsx(zk,{tweet:f,url:t==null?void 0:t.url})}),c.jsxs("div",{className:"tweet-replying-to",children:["Replying to ",c.jsxs("span",{className:"tweet-reply-handle",children:["@",f.author.username]})]})]}),vt()]}),Ge&&c.jsxs(c.Fragment,{children:[vt(),c.jsxs("div",{className:"tweet-quote-section",style:{padding:"0 16px 12px"},children:[h&&c.jsx(gE,{}),m&&c.jsxs("div",{className:"tweet-embed-error",children:[c.jsx("span",{children:"Could not load tweet"}),c.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",className:"tweet-fallback-link",children:t.url})]}),f&&c.jsx(zk,{tweet:f,url:t==null?void 0:t.url})]}),c.jsx("div",{className:"tweet-quote-footer",children:We()})]}),!Q&&vt(),V&&c.jsx(_F,{onConnected:Ve,onCancel:()=>oe(!1)}),we&&o&&c.jsx(Ul,{filename:o,title:l||"Untitled",onClose:()=>Ee(!1)})]})}function _U(){const[t,e]=x.useState("idle"),n=x.useRef();return{copyAsHtml:x.useCallback(async()=>{const s=document.querySelector(".ProseMirror");if(!s)return;const i=s.cloneNode(!0);i.querySelectorAll(".ProseMirror-widget, [data-widget], .ProseMirror-gapcursor").forEach(h=>h.remove());let o="";const l=document.querySelector(".article-title-input");l!=null&&l.value&&l.value!=="Untitled"&&(o+=`<h1>${l.value}</h1>
|
|
213
|
-
`);const d=o+i.innerHTML,f=
|
|
212
|
+
`)}function vF(t){const e=n=>{var r;if(n.type==="image"&&((r=n.attrs)!=null&&r.src))return n.attrs.src;if(n.content)for(const s of n.content){const i=e(s);if(i)return i}return null};return e(t.getJSON())}async function yF(t){try{const e=await fetch(t);if(!e.ok)return null;const n=await e.blob();return n.type==="image/png"?n:new Promise(r=>{const s=new Image,i=URL.createObjectURL(n);s.onload=()=>{const o=document.createElement("canvas");o.width=s.naturalWidth,o.height=s.naturalHeight,o.getContext("2d").drawImage(s,0,0),o.toBlob(l=>{URL.revokeObjectURL(i),r(l)},"image/png")},s.onerror=()=>{URL.revokeObjectURL(i),r(null)},s.src=i})}catch{return null}}function bF(t,e){const[n,r]=x.useState("idle"),s=x.useRef();return{copyText:x.useCallback(async()=>{const o=t.current[e];if(!o)return;const l=gF(o),d=vF(o);if(!(!l&&!d)){try{const f={};if(l&&(f["text/plain"]=new Blob([l],{type:"text/plain"})),d){const h=await yF(d);h&&(f["image/png"]=h)}Object.keys(f).length>0&&await navigator.clipboard.write([new ClipboardItem(f)])}catch{if(l){const f=document.createElement("textarea");f.value=l,f.style.position="fixed",f.style.opacity="0",document.body.appendChild(f),f.select(),document.execCommand("copy"),document.body.removeChild(f)}}r("copied"),s.current&&clearTimeout(s.current),s.current=setTimeout(()=>r("idle"),2e3)}},[t,e]),copyState:n}}function $p(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e4?`${(t/1e3).toFixed(0)}K`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function xF(t){try{const e=Date.now(),n=new Date(t).getTime(),r=Math.floor((e-n)/1e3);if(r<60)return`${r}s`;const s=Math.floor(r/60);if(s<60)return`${s}m`;const i=Math.floor(s/60);return i<24?`${i}h`:new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric"})}catch{return""}}const wF=()=>c.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:c.jsx("path",{fill:"currentColor",d:"M1.751 10c0-4.42 3.584-8 8.005-8h4.366c4.49 0 8.129 3.64 8.129 8.13 0 2.96-1.607 5.68-4.196 7.11l-8.054 4.46v-3.69h-.067c-4.49.1-8.183-3.51-8.183-8.01zm8.005-6c-3.317 0-6.005 2.69-6.005 6 0 3.37 2.77 6.08 6.138 6.01l.351-.01h1.761v2.3l5.087-2.81c1.951-1.08 3.163-3.13 3.163-5.36 0-3.39-2.744-6.13-6.129-6.13H9.756z"})}),kF=()=>c.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:c.jsx("path",{fill:"currentColor",d:"M4.5 3.88l4.432 4.14-1.364 1.46L5.5 7.55V16c0 1.1.896 2 2 2H13v2H7.5c-2.209 0-4-1.79-4-4V7.55L1.432 9.48.068 8.02 4.5 3.88zM16.5 6H11V4h5.5c2.209 0 4 1.79 4 4v8.45l2.068-1.93 1.364 1.46-4.432 4.14-4.432-4.14 1.364-1.46 2.068 1.93V8c0-1.1-.896-2-2-2z"})}),SF=()=>c.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:c.jsx("path",{fill:"currentColor",d:"M16.697 5.5c-1.222-.06-2.679.51-3.89 2.16l-.805 1.09-.806-1.09C9.984 6.01 8.526 5.44 7.304 5.5c-1.243.07-2.349.78-2.91 1.91-.552 1.12-.633 2.78.479 4.82 1.074 1.97 3.257 4.27 7.129 6.61 3.87-2.34 6.052-4.64 7.126-6.61 1.111-2.04 1.03-3.7.477-4.82-.561-1.13-1.666-1.84-2.908-1.91zm4.187 7.69c-1.351 2.48-4.001 5.12-8.379 7.67l-.503.3-.504-.3c-4.379-2.55-7.029-5.19-8.382-7.67-1.36-2.5-1.41-4.86-.514-6.67.887-1.79 2.647-2.91 4.601-3.01 1.651-.09 3.368.56 4.798 2.01 1.429-1.45 3.146-2.1 4.796-2.01 1.954.1 3.714 1.22 4.601 3.01.896 1.81.846 4.17-.514 6.67z"})}),EF=()=>c.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:c.jsx("path",{fill:"currentColor",d:"M4 4.5C4 3.12 5.119 2 6.5 2h11C18.881 2 20 3.12 20 4.5v18.44l-8-5.71-8 5.71V4.5zM6.5 4c-.276 0-.5.22-.5.5v14.56l6-4.29 6 4.29V4.5c0-.28-.224-.5-.5-.5h-11z"})}),NF=()=>c.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:c.jsx("path",{fill:"currentColor",d:"M12 2.59l5.7 5.7-1.41 1.42L13 6.41V16h-2V6.41l-3.3 3.3-1.41-1.42L12 2.59zM21 15l-.02 3.51c0 1.38-1.12 2.49-2.5 2.49H5.5C4.11 21 3 19.88 3 18.5V15h2v3.5c0 .28.22.5.5.5h12.98c.28 0 .5-.22.5-.5L19 15h2z"})});function YT({tweet:t,nested:e,url:n}){const r=xF(t.createdAt);return c.jsxs("div",{className:`tweet-embed-card${e?" tweet-embed-nested":""}${n?" tweet-embed-card--clickable":""}`,onClick:n?()=>window.open(n,"_blank","noopener,noreferrer"):void 0,role:n?"link":void 0,children:[c.jsxs("div",{className:"tweet-author-row",children:[t.author.avatarUrl?c.jsx("img",{className:"tweet-avatar",src:t.author.avatarUrl,alt:""}):c.jsx("div",{className:"tweet-avatar tweet-avatar-placeholder"}),c.jsxs("div",{className:"tweet-author-info",children:[c.jsx("span",{className:"tweet-author-name",children:t.author.name}),c.jsxs("span",{className:"tweet-author-handle",children:["@",t.author.username]}),r&&c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"tweet-author-separator",children:"·"}),c.jsx("span",{className:"tweet-author-timestamp",children:r})]})]})]}),c.jsx("div",{className:"tweet-text",children:t.text}),t.media&&t.media.length>0&&c.jsx("div",{className:"tweet-media","data-count":t.media.length,children:t.media.map((s,i)=>s.type==="photo"?c.jsx("img",{className:"tweet-media-img",src:s.url,alt:"",loading:"lazy"},i):s.type==="video"||s.type==="gif"?c.jsx("div",{className:"tweet-media-video-placeholder",children:c.jsx("span",{children:"Video"})},i):null)}),t.quoteTweet&&c.jsx(YT,{tweet:t.quoteTweet,nested:!0}),!e&&c.jsxs("div",{className:"tweet-actions-row",children:[c.jsxs("span",{className:"tweet-action tweet-action-reply",children:[c.jsx(wF,{}),t.metrics.replies>0&&$p(t.metrics.replies)]}),c.jsxs("span",{className:"tweet-action tweet-action-retweet",children:[c.jsx(kF,{}),t.metrics.retweets>0&&$p(t.metrics.retweets)]}),c.jsxs("span",{className:"tweet-action tweet-action-like",children:[c.jsx(SF,{}),t.metrics.likes>0&&$p(t.metrics.likes)]}),c.jsx("span",{className:"tweet-action tweet-action-bookmark",children:c.jsx(EF,{})}),c.jsx("span",{className:"tweet-action tweet-action-share",children:c.jsx(NF,{})})]})]})}function zk({tweet:t,url:e}){return c.jsx(YT,{tweet:t,url:e})}function CF({initialContent:t,initialPreviewImages:e,placeholder:n="What is happening?!",onUpdate:r,onReady:s,onFocus:i,onPreviewImagesChange:o}){const[l,d]=x.useState(e||[]),f=x.useRef(e||[]),h=x.useRef(!1),m=x.useRef(s);m.current=s;const g=x.useRef(o);g.current=o;const v=x.useCallback(S=>{var T;const N=S.slice(0,4);f.current=N,d(N),(T=g.current)==null||T.call(g,N)},[]),b=x.useCallback(S=>{if(h.current)return;const N=[],T=[];if(S.state.doc.descendants((I,P)=>{var B;I.type.name==="image"&&((B=I.attrs)!=null&&B.src)&&(N.push(I.attrs.src),T.push({from:P,to:P+I.nodeSize}))}),N.length===0)return;h.current=!0;const{tr:M}=S.state;for(let I=T.length-1;I>=0;I--)M.delete(T[I].from,T[I].to);S.view.dispatch(M);const _=f.current,R=4-_.length;R>0&&v([..._,...N.slice(0,R)]),h.current=!1},[v]),k=XC({extensions:[...fT,ef.configure({placeholder:n})],content:t||"<p></p>",onCreate:({editor:S})=>{b(S)},onUpdate:({editor:S})=>{b(S),r==null||r(S)},onFocus:()=>{i==null||i()},editorProps:{handlePaste:wT,handleDrop:kT}},[t]);x.useEffect(()=>{k&&M5(k.view,{addToPreview:S=>{const N=f.current;N.length>=4||v([...N,S])},getPreviewImages:()=>f.current})},[k,v]),x.useEffect(()=>{if(!k)return;const{state:S}=k.view;if(S.plugins.some(M=>M.key==="pendingDecoration$"))return;const N=vT(),T=S.reconfigure({plugins:[...S.plugins,N]});k.view.updateState(T)},[k]),x.useEffect(()=>{if(!k)return;const{state:S}=k.view;if(S.plugins.some(M=>M.key==="commentDecoration$"))return;const N=bT(),T=S.reconfigure({plugins:[...S.plugins,N]});k.view.updateState(T)},[k]),x.useEffect(()=>{var S;k&&((S=m.current)==null||S.call(m,k))},[k]);const w=x.useCallback(S=>{v(f.current.filter((N,T)=>T!==S))},[v]);return k?c.jsxs(c.Fragment,{children:[c.jsx(Pv,{editor:k}),l.length>0&&c.jsx("div",{className:"tweet-preview-grid","data-count":l.length,children:l.map((S,N)=>c.jsxs("div",{className:"tweet-image-card",children:[c.jsx("img",{className:"tweet-image-card-img",src:S,alt:"",draggable:!1}),c.jsx("button",{className:"tweet-image-card-remove",onClick:()=>w(N),title:"Remove image",children:"×"})]},S))})]}):null}function _F({count:t,softLimit:e=280}){const n=e-t,r=Math.min(t/e,1),s=n<=20,i=s?30:26,o=2,l=(i-o)/2,d=2*Math.PI*l,f=d*(1-r);let h="var(--x-blue, #1d9bf0)";return n<=0?h="var(--x-red, #f4212e)":n<=20&&(h="var(--x-yellow, #ffd400)"),t===0?null:c.jsxs("div",{className:"tweet-char-counter",title:`${t} / ${e}`,style:{width:i,height:i},children:[c.jsxs("svg",{width:i,height:i,viewBox:`0 0 ${i} ${i}`,children:[c.jsx("circle",{cx:i/2,cy:i/2,r:l,fill:"none",stroke:"var(--x-border, #eff3f4)",strokeWidth:o}),c.jsx("circle",{cx:i/2,cy:i/2,r:l,fill:"none",stroke:h,strokeWidth:o,strokeDasharray:d,strokeDashoffset:f,strokeLinecap:"round",transform:`rotate(-90 ${i/2} ${i/2})`,style:{transition:"stroke-dashoffset 0.15s ease, stroke 0.15s ease"}})]}),s&&c.jsx("span",{className:"tweet-char-number",style:{color:h,fontSize:n<-9||n>9?10:11},children:n})]})}const Uk="@openwriter/plugin-x-api",Hk=[{key:"api-key",label:"API Key",env:"X_API_KEY"},{key:"api-secret",label:"API Secret",env:"X_API_SECRET"},{key:"access-token",label:"Access Token",env:"X_ACCESS_TOKEN"},{key:"access-token-secret",label:"Access Token Secret",env:"X_ACCESS_TOKEN_SECRET"}];function TF({onConnected:t,onCancel:e}){const[n,r]=x.useState({"api-key":"","api-secret":"","access-token":"","access-token-secret":""}),[s,i]=x.useState(!1),[o,l]=x.useState(""),d=Hk.every(h=>n[h.key].trim()),f=async()=>{i(!0),l("");try{if(!(await fetch("/api/plugins/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Uk,config:n})})).ok)throw new Error("Failed to save config");const g=await(await fetch("/api/plugins/enable",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Uk})})).json();if(!g.success)throw new Error(g.error||"Failed to enable plugin");const b=await(await fetch("/api/x/status")).json();b.connected?t():l(b.error||"Could not verify X credentials. Check your API keys.")}catch(h){l(h.message||"Connection failed")}finally{i(!1)}};return c.jsxs("div",{className:"x-connect-prompt",children:[c.jsxs("div",{className:"x-connect-header",children:[c.jsx("span",{className:"x-connect-title",children:"Connect your X account to post"}),c.jsx("button",{className:"x-connect-cancel",onClick:e,title:"Cancel",children:c.jsx("svg",{viewBox:"0 0 24 24",width:"18",height:"18",children:c.jsx("path",{fill:"currentColor",d:"M10.59 12L4.54 5.96l1.42-1.42L12 10.59l6.04-6.05 1.42 1.42L13.41 12l6.05 6.04-1.42 1.42L12 13.41l-6.04 6.05-1.42-1.42L10.59 12z"})})})]}),c.jsx("div",{className:"x-connect-fields",children:Hk.map(h=>c.jsxs("div",{className:"x-connect-field",children:[c.jsx("label",{className:"x-connect-label",children:h.label}),c.jsx("input",{type:"password",className:"x-connect-input",value:n[h.key],onChange:m=>r(g=>({...g,[h.key]:m.target.value})),placeholder:h.env,spellCheck:!1,autoComplete:"off"})]},h.key))}),o&&c.jsx("div",{className:"x-connect-error",children:o}),c.jsxs("div",{className:"x-connect-actions",children:[c.jsx("a",{className:"x-connect-dev-link",href:"https://developer.x.com/en/portal/dashboard",target:"_blank",rel:"noopener noreferrer",children:"Get credentials"}),c.jsx("button",{className:"x-connect-btn",onClick:f,disabled:!d||s,children:s?"Connecting...":"Connect"})]})]})}var Wk={},Fp,Vk;function Ws(){return Vk||(Vk=1,Fp=function(t){return typeof t=="object"?t!==null:typeof t=="function"}),Fp}var zp,qk;function Mr(){if(qk)return zp;qk=1;var t=Ws();return zp=function(e){if(!t(e))throw TypeError(e+" is not an object!");return e},zp}var Up,Kk;function sf(){return Kk||(Kk=1,Up=function(t){if(t==null)throw TypeError("Can't call method on "+t);return t}),Up}var Hp,Gk;function Di(){if(Gk)return Hp;Gk=1;var t=sf();return Hp=function(e){return Object(t(e))},Hp}var Wp,Jk;function of(){if(Jk)return Wp;Jk=1;var t=Math.ceil,e=Math.floor;return Wp=function(n){return isNaN(n=+n)?0:(n>0?e:t)(n)},Wp}var Vp,Yk;function wo(){if(Yk)return Vp;Yk=1;var t=of(),e=Math.min;return Vp=function(n){return n>0?e(t(n),9007199254740991):0},Vp}var qp,Xk;function XT(){if(Xk)return qp;Xk=1;var t=of(),e=sf();return qp=function(n){return function(r,s){var i=String(e(r)),o=t(s),l=i.length,d,f;return o<0||o>=l?n?"":void 0:(d=i.charCodeAt(o),d<55296||d>56319||o+1===l||(f=i.charCodeAt(o+1))<56320||f>57343?n?i.charAt(o):d:n?i.slice(o,o+2):(d-55296<<10)+(f-56320)+65536)}},qp}var Kp,Qk;function hy(){if(Qk)return Kp;Qk=1;var t=XT()(!0);return Kp=function(e,n,r){return n+(r?t(e,n).length:1)},Kp}var Gp,Zk;function af(){if(Zk)return Gp;Zk=1;var t={}.toString;return Gp=function(e){return t.call(e).slice(8,-1)},Gp}var Jp={exports:{}},Yp={exports:{}},Xp={exports:{}},e1;function ga(){if(e1)return Xp.exports;e1=1;var t=Xp.exports={version:"2.6.12"};return typeof __e=="number"&&(__e=t),Xp.exports}var Qp={exports:{}},t1;function Kr(){if(t1)return Qp.exports;t1=1;var t=Qp.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();return typeof __g=="number"&&(__g=t),Qp.exports}var Zp,n1;function lf(){return n1||(n1=1,Zp=!1),Zp}var r1;function cf(){if(r1)return Yp.exports;r1=1;var t=ga(),e=Kr(),n="__core-js_shared__",r=e[n]||(e[n]={});return(Yp.exports=function(s,i){return r[s]||(r[s]=i!==void 0?i:{})})("versions",[]).push({version:t.version,mode:lf()?"pure":"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"}),Yp.exports}var em,s1;function Hl(){if(s1)return em;s1=1;var t=0,e=Math.random();return em=function(n){return"Symbol(".concat(n===void 0?"":n,")_",(++t+e).toString(36))},em}var i1;function zn(){if(i1)return Jp.exports;i1=1;var t=cf()("wks"),e=Hl(),n=Kr().Symbol,r=typeof n=="function",s=Jp.exports=function(i){return t[i]||(t[i]=r&&n[i]||(r?n:e)("Symbol."+i))};return s.store=t,Jp.exports}var tm,o1;function py(){if(o1)return tm;o1=1;var t=af(),e=zn()("toStringTag"),n=t((function(){return arguments})())=="Arguments",r=function(s,i){try{return s[i]}catch{}};return tm=function(s){var i,o,l;return s===void 0?"Undefined":s===null?"Null":typeof(o=r(i=Object(s),e))=="string"?o:n?t(i):(l=t(i))=="Object"&&typeof i.callee=="function"?"Arguments":l},tm}var nm,a1;function my(){if(a1)return nm;a1=1;var t=py(),e=RegExp.prototype.exec;return nm=function(n,r){var s=n.exec;if(typeof s=="function"){var i=s.call(n,r);if(typeof i!="object")throw new TypeError("RegExp exec method returned something other than an Object or null");return i}if(t(n)!=="RegExp")throw new TypeError("RegExp#exec called on incompatible receiver");return e.call(n,r)},nm}var l1={},rm,c1;function uf(){if(c1)return rm;c1=1;var t=Mr();return rm=function(){var e=t(this),n="";return e.global&&(n+="g"),e.ignoreCase&&(n+="i"),e.multiline&&(n+="m"),e.unicode&&(n+="u"),e.sticky&&(n+="y"),n},rm}var sm,u1;function gy(){if(u1)return sm;u1=1;var t=uf(),e=RegExp.prototype.exec,n=String.prototype.replace,r=e,s="lastIndex",i=(function(){var d=/a/,f=/b*/g;return e.call(d,"a"),e.call(f,"a"),d[s]!==0||f[s]!==0})(),o=/()??/.exec("")[1]!==void 0,l=i||o;return l&&(r=function(f){var h=this,m,g,v,b;return o&&(g=new RegExp("^"+h.source+"$(?!\\s)",t.call(h))),i&&(m=h[s]),v=e.call(h,f),i&&v&&(h[s]=h.global?v.index+v[0].length:m),o&&v&&v.length>1&&n.call(v[0],g,function(){for(b=1;b<arguments.length-2;b++)arguments[b]===void 0&&(v[b]=void 0)}),v}),sm=r,sm}var im={},om,d1;function ls(){return d1||(d1=1,om=function(t){try{return!!t()}catch{return!0}}),om}var am,f1;function Gr(){return f1||(f1=1,am=!ls()(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})),am}var lm,h1;function QT(){if(h1)return lm;h1=1;var t=Ws(),e=Kr().document,n=t(e)&&t(e.createElement);return lm=function(r){return n?e.createElement(r):{}},lm}var cm,p1;function ZT(){return p1||(p1=1,cm=!Gr()&&!ls()(function(){return Object.defineProperty(QT()("div"),"a",{get:function(){return 7}}).a!=7})),cm}var um,m1;function vy(){if(m1)return um;m1=1;var t=Ws();return um=function(e,n){if(!t(e))return e;var r,s;if(n&&typeof(r=e.toString)=="function"&&!t(s=r.call(e))||typeof(r=e.valueOf)=="function"&&!t(s=r.call(e))||!n&&typeof(r=e.toString)=="function"&&!t(s=r.call(e)))return s;throw TypeError("Can't convert object to primitive value")},um}var g1;function cs(){if(g1)return im;g1=1;var t=Mr(),e=ZT(),n=vy(),r=Object.defineProperty;return im.f=Gr()?Object.defineProperty:function(i,o,l){if(t(i),o=n(o,!0),t(l),e)try{return r(i,o,l)}catch{}if("get"in l||"set"in l)throw TypeError("Accessors not supported!");return"value"in l&&(i[o]=l.value),i},im}var dm,v1;function Wl(){return v1||(v1=1,dm=function(t,e){return{enumerable:!(t&1),configurable:!(t&2),writable:!(t&4),value:e}}),dm}var fm,y1;function Pi(){if(y1)return fm;y1=1;var t=cs(),e=Wl();return fm=Gr()?function(n,r,s){return t.f(n,r,e(1,s))}:function(n,r,s){return n[r]=s,n},fm}var hm={exports:{}},pm,b1;function ko(){if(b1)return pm;b1=1;var t={}.hasOwnProperty;return pm=function(e,n){return t.call(e,n)},pm}var mm,x1;function jF(){return x1||(x1=1,mm=cf()("native-function-to-string",Function.toString)),mm}var w1;function Vs(){if(w1)return hm.exports;w1=1;var t=Kr(),e=Pi(),n=ko(),r=Hl()("src"),s=jF(),i="toString",o=(""+s).split(i);return ga().inspectSource=function(l){return s.call(l)},(hm.exports=function(l,d,f,h){var m=typeof f=="function";m&&(n(f,"name")||e(f,"name",d)),l[d]!==f&&(m&&(n(f,r)||e(f,r,l[d]?""+l[d]:o.join(String(d)))),l===t?l[d]=f:h?l[d]?l[d]=f:e(l,d,f):(delete l[d],e(l,d,f)))})(Function.prototype,i,function(){return typeof this=="function"&&this[r]||s.call(this)}),hm.exports}var gm,k1;function df(){return k1||(k1=1,gm=function(t){if(typeof t!="function")throw TypeError(t+" is not a function!");return t}),gm}var vm,S1;function ff(){if(S1)return vm;S1=1;var t=df();return vm=function(e,n,r){if(t(e),n===void 0)return e;switch(r){case 1:return function(s){return e.call(n,s)};case 2:return function(s,i){return e.call(n,s,i)};case 3:return function(s,i,o){return e.call(n,s,i,o)}}return function(){return e.apply(n,arguments)}},vm}var ym,E1;function xr(){if(E1)return ym;E1=1;var t=Kr(),e=ga(),n=Pi(),r=Vs(),s=ff(),i="prototype",o=function(l,d,f){var h=l&o.F,m=l&o.G,g=l&o.S,v=l&o.P,b=l&o.B,k=m?t:g?t[d]||(t[d]={}):(t[d]||{})[i],w=m?e:e[d]||(e[d]={}),S=w[i]||(w[i]={}),N,T,M,_;m&&(f=d);for(N in f)T=!h&&k&&k[N]!==void 0,M=(T?k:f)[N],_=b&&T?s(M,t):v&&typeof M=="function"?s(Function.call,M):M,k&&r(k,N,M,l&o.U),w[N]!=M&&n(w,N,_),v&&S[N]!=M&&(S[N]=M)};return t.core=e,o.F=1,o.G=2,o.S=4,o.P=8,o.B=16,o.W=32,o.U=64,o.R=128,ym=o,ym}var N1;function MF(){if(N1)return l1;N1=1;var t=gy();return xr()({target:"RegExp",proto:!0,forced:t!==/./.exec},{exec:t}),l1}var bm,C1;function yy(){if(C1)return bm;C1=1,MF();var t=Vs(),e=Pi(),n=ls(),r=sf(),s=zn(),i=gy(),o=s("species"),l=!n(function(){var f=/./;return f.exec=function(){var h=[];return h.groups={a:"7"},h},"".replace(f,"$<a>")!=="7"}),d=(function(){var f=/(?:)/,h=f.exec;f.exec=function(){return h.apply(this,arguments)};var m="ab".split(f);return m.length===2&&m[0]==="a"&&m[1]==="b"})();return bm=function(f,h,m){var g=s(f),v=!n(function(){var T={};return T[g]=function(){return 7},""[f](T)!=7}),b=v?!n(function(){var T=!1,M=/a/;return M.exec=function(){return T=!0,null},f==="split"&&(M.constructor={},M.constructor[o]=function(){return M}),M[g](""),!T}):void 0;if(!v||!b||f==="replace"&&!l||f==="split"&&!d){var k=/./[g],w=m(r,g,""[f],function(M,_,R,I,P){return _.exec===i?v&&!P?{done:!0,value:k.call(_,R,I)}:{done:!0,value:M.call(R,_,I)}:{done:!1}}),S=w[0],N=w[1];t(String.prototype,f,S),e(RegExp.prototype,g,h==2?function(T,M){return N.call(T,this,M)}:function(T){return N.call(T,this)})}},bm}var _1;function AF(){if(_1)return Wk;_1=1;var t=Mr(),e=Di(),n=wo(),r=of(),s=hy(),i=my(),o=Math.max,l=Math.min,d=Math.floor,f=/\$([$&`']|\d\d?|<[^>]*>)/g,h=/\$([$&`']|\d\d?)/g,m=function(g){return g===void 0?g:String(g)};return yy()("replace",2,function(g,v,b,k){return[function(N,T){var M=g(this),_=N==null?void 0:N[v];return _!==void 0?_.call(N,M,T):b.call(String(M),N,T)},function(S,N){var T=k(b,S,this,N);if(T.done)return T.value;var M=t(S),_=String(this),R=typeof N=="function";R||(N=String(N));var I=M.global;if(I){var P=M.unicode;M.lastIndex=0}for(var B=[];;){var z=i(M,_);if(z===null||(B.push(z),!I))break;var K=String(z[0]);K===""&&(M.lastIndex=s(_,n(M.lastIndex),P))}for(var F="",J=0,$=0;$<B.length;$++){z=B[$];for(var W=String(z[0]),q=o(l(r(z.index),_.length),0),ne=[],V=1;V<z.length;V++)ne.push(m(z[V]));var oe=z.groups;if(R){var Y=[W].concat(ne,q,_);oe!==void 0&&Y.push(oe);var A=String(N.apply(void 0,Y))}else A=w(W,_,q,ne,oe,N);q>=J&&(F+=_.slice(J,q)+A,J=q+W.length)}return F+_.slice(J)}];function w(S,N,T,M,_,R){var I=T+S.length,P=M.length,B=h;return _!==void 0&&(_=e(_),B=f),b.call(R,B,function(z,K){var F;switch(K.charAt(0)){case"$":return"$";case"&":return S;case"`":return N.slice(0,T);case"'":return N.slice(I);case"<":F=_[K.slice(1,-1)];break;default:var J=+K;if(J===0)return z;if(J>P){var $=d(J/10);return $===0?z:$<=P?M[$-1]===void 0?K.charAt(1):M[$-1]+K.charAt(1):z}F=M[J-1]}return F===void 0?"":F})}}),Wk}AF();var T1={},xm,j1;function by(){if(j1)return xm;j1=1;var t=af();return xm=Object("z").propertyIsEnumerable(0)?Object:function(e){return t(e)=="String"?e.split(""):Object(e)},xm}var wm,M1;function So(){if(M1)return wm;M1=1;var t=by(),e=sf();return wm=function(n){return t(e(n))},wm}var km,A1;function RF(){if(A1)return km;A1=1;var t=of(),e=Math.max,n=Math.min;return km=function(r,s){return r=t(r),r<0?e(r+s,0):n(r,s)},km}var Sm,R1;function e2(){if(R1)return Sm;R1=1;var t=So(),e=wo(),n=RF();return Sm=function(r){return function(s,i,o){var l=t(s),d=e(l.length),f=n(o,d),h;if(r&&i!=i){for(;d>f;)if(h=l[f++],h!=h)return!0}else for(;d>f;f++)if((r||f in l)&&l[f]===i)return r||f||0;return!r&&-1}},Sm}var Em,O1;function Vl(){if(O1)return Em;O1=1;var t=ls();return Em=function(e,n){return!!e&&t(function(){n?e.call(null,function(){},1):e.call(null)})},Em}var I1;function OF(){if(I1)return T1;I1=1;var t=xr(),e=e2()(!1),n=[].indexOf,r=!!n&&1/[1].indexOf(1,-0)<0;return t(t.P+t.F*(r||!Vl()(n)),"Array",{indexOf:function(i){return r?n.apply(this,arguments)||0:e(this,i,arguments[1])}}),T1}OF();var IF=/[a-z]{1,6}(?:[._][a-z]{1,2})?/i,t2=/\!'#%&'\(\)*\+,\\\-\.\/:;<=>\?@\[\]\^_{|}~\$/,L1={},Nm={},Cm={},D1;function xy(){return D1||(D1=1,Cm.f={}.propertyIsEnumerable),Cm}var P1;function wy(){if(P1)return Nm;P1=1;var t=xy(),e=Wl(),n=So(),r=vy(),s=ko(),i=ZT(),o=Object.getOwnPropertyDescriptor;return Nm.f=Gr()?o:function(d,f){if(d=n(d),f=r(f,!0),i)try{return o(d,f)}catch{}if(s(d,f))return e(!t.f.call(d,f),d[f])},Nm}var _m,B1;function LF(){if(B1)return _m;B1=1;var t=Ws(),e=Mr(),n=function(r,s){if(e(r),!t(s)&&s!==null)throw TypeError(s+": can't set as prototype!")};return _m={set:Object.setPrototypeOf||("__proto__"in{}?(function(r,s,i){try{i=ff()(Function.call,wy().f(Object.prototype,"__proto__").set,2),i(r,[]),s=!(r instanceof Array)}catch{s=!0}return function(l,d){return n(l,d),s?l.__proto__=d:i(l,d),l}})({},!1):void 0),check:n},_m}var Tm,$1;function DF(){if($1)return Tm;$1=1;var t=Ws(),e=LF().set;return Tm=function(n,r,s){var i=r.constructor,o;return i!==s&&typeof i=="function"&&(o=i.prototype)!==s.prototype&&t(o)&&e&&e(n,o),n},Tm}var jm={},Mm,F1;function ky(){if(F1)return Mm;F1=1;var t=cf()("keys"),e=Hl();return Mm=function(n){return t[n]||(t[n]=e(n))},Mm}var Am,z1;function n2(){if(z1)return Am;z1=1;var t=ko(),e=So(),n=e2()(!1),r=ky()("IE_PROTO");return Am=function(s,i){var o=e(s),l=0,d=[],f;for(f in o)f!=r&&t(o,f)&&d.push(f);for(;i.length>l;)t(o,f=i[l++])&&(~n(d,f)||d.push(f));return d},Am}var Rm,U1;function Sy(){return U1||(U1=1,Rm="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")),Rm}var H1;function hf(){if(H1)return jm;H1=1;var t=n2(),e=Sy().concat("length","prototype");return jm.f=Object.getOwnPropertyNames||function(r){return t(r,e)},jm}var Om,W1;function r2(){if(W1)return Om;W1=1;var t=Ws(),e=af(),n=zn()("match");return Om=function(r){var s;return t(r)&&((s=r[n])!==void 0?!!s:e(r)=="RegExp")},Om}var Im,V1;function PF(){if(V1)return Im;V1=1;var t=Kr(),e=cs(),n=Gr(),r=zn()("species");return Im=function(s){var i=t[s];n&&i&&!i[r]&&e.f(i,r,{configurable:!0,get:function(){return this}})},Im}var q1;function BF(){if(q1)return L1;q1=1;var t=Kr(),e=DF(),n=cs().f,r=hf().f,s=r2(),i=uf(),o=t.RegExp,l=o,d=o.prototype,f=/a/g,h=/a/g,m=new o(f)!==f;if(Gr()&&(!m||ls()(function(){return h[zn()("match")]=!1,o(f)!=f||o(h)==h||o(f,"i")!="/a/i"}))){o=function(w,S){var N=this instanceof o,T=s(w),M=S===void 0;return!N&&T&&w.constructor===o&&M?w:e(m?new l(T&&!M?w.source:w,S):l((T=w instanceof o)?w.source:w,T&&M?i.call(w):S),N?this:d,o)};for(var g=function(k){k in o||n(o,k,{configurable:!0,get:function(){return l[k]},set:function(w){l[k]=w}})},v=r(l),b=0;v.length>b;)g(v[b++]);d.constructor=o,o.prototype=d,Vs()(t,"RegExp",o)}return PF()("RegExp"),L1}BF();function Rt(t,e,n){return n=n||"",typeof t!="string"&&(t.global&&n.indexOf("g")<0&&(n+="g"),t.ignoreCase&&n.indexOf("i")<0&&(n+="i"),t.multiline&&n.indexOf("m")<0&&(n+="m"),t=t.source),new RegExp(t.replace(/#\{(\w+)\}/g,function(r,s){var i=e[s]||"";return typeof i!="string"&&(i=i.source),i}),n)}var s2=/\x09-\x0D\x20\x85\xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000/;const i2=Rt(/[#{spacesGroup}]/,{spacesGroup:s2});Rt("(^|#{spaces})(\\$)(#{cashtag})(?=$|\\s|[#{punct}])",{cashtag:IF,spaces:i2,punct:t2},"gi");var K1={},G1;function $F(){if(G1)return K1;G1=1;var t=Mr(),e=wo(),n=hy(),r=my();return yy()("match",1,function(s,i,o,l){return[function(f){var h=s(this),m=f==null?void 0:f[i];return m!==void 0?m.call(f,h):new RegExp(f)[i](String(h))},function(d){var f=l(o,d,this);if(f.done)return f.value;var h=t(d),m=String(this);if(!h.global)return r(h,m);var g=h.unicode;h.lastIndex=0;for(var v=[],b=0,k;(k=r(h,m))!==null;){var w=String(k[0]);v[b]=w,w===""&&(h.lastIndex=n(m,e(h.lastIndex),g)),b++}return b===0?null:v}]}),K1}$F();var o2=/[##]/;Rt(/^(?:#{hashSigns}|:\/\/)/,{hashSigns:o2});var a2=Rt(RegExp("(?:(?:한국|香港|澳門|新加坡|台灣|台湾|中國|中国|გე|ລາວ|ไทย|ලංකා|ഭാരതം|ಭಾರತ|భారత్|சிங்கப்பூர்|இலங்கை|இந்தியா|ଭାରତ|ભારત|ਭਾਰਤ|ভাৰত|ভারত|বাংলা|भारोत|भारतम्|भारत|ڀارت|پاکستان|موريتانيا|مليسيا|مصر|قطر|فلسطين|عمان|عراق|سورية|سودان|تونس|بھارت|بارت|ایران|امارات|المغرب|السعودية|الجزائر|البحرين|الاردن|հայ|қаз|укр|срб|рф|мон|мкд|ею|бел|бг|ευ|ελ|zw|zm|za|yt|ye|ws|wf|vu|vn|vi|vg|ve|vc|va|uz|uy|us|um|uk|ug|ua|tz|tw|tv|tt|tr|tp|to|tn|tm|tl|tk|tj|th|tg|tf|td|tc|sz|sy|sx|sv|su|st|ss|sr|so|sn|sm|sl|sk|sj|si|sh|sg|se|sd|sc|sb|sa|rw|ru|rs|ro|re|qa|py|pw|pt|ps|pr|pn|pm|pl|pk|ph|pg|pf|pe|pa|om|nz|nu|nr|np|no|nl|ni|ng|nf|ne|nc|na|mz|my|mx|mw|mv|mu|mt|ms|mr|mq|mp|mo|mn|mm|ml|mk|mh|mg|mf|me|md|mc|ma|ly|lv|lu|lt|ls|lr|lk|li|lc|lb|la|kz|ky|kw|kr|kp|kn|km|ki|kh|kg|ke|jp|jo|jm|je|it|is|ir|iq|io|in|im|il|ie|id|hu|ht|hr|hn|hm|hk|gy|gw|gu|gt|gs|gr|gq|gp|gn|gm|gl|gi|gh|gg|gf|ge|gd|gb|ga|fr|fo|fm|fk|fj|fi|eu|et|es|er|eh|eg|ee|ec|dz|do|dm|dk|dj|de|cz|cy|cx|cw|cv|cu|cr|co|cn|cm|cl|ck|ci|ch|cg|cf|cd|cc|ca|bz|by|bw|bv|bt|bs|br|bq|bo|bn|bm|bl|bj|bi|bh|bg|bf|be|bd|bb|ba|az|ax|aw|au|at|as|ar|aq|ao|an|am|al|ai|ag|af|ae|ad|ac)(?=[^0-9a-zA-Z@+-]|$))")),l2=/\u202A-\u202E\u061C\u200E\u200F\u2066\u2067\u2068\u2069/,Ey=/\uFFFE\uFEFF\uFFFF/;function FF(t,e){return t.replace(/#\{(\w+)\}/g,function(n,r){return e[r]||""})}var zF=FF("#{punct}#{spacesGroup}#{invalidCharsGroup}#{directionalMarkersGroup}",{punct:t2,spacesGroup:s2,invalidCharsGroup:Ey,directionalMarkersGroup:l2}),c2=Rt(/[^#{invalidDomainChars}]/,{invalidDomainChars:zF}),UF=Rt(/(?:(?:#{validDomainChars}(?:-|#{validDomainChars})*)?#{validDomainChars}\.)/,{validDomainChars:c2}),u2=Rt(RegExp("(?:(?:삼성|닷컴|닷넷|香格里拉|餐厅|食品|飞利浦|電訊盈科|集团|通販|购物|谷歌|诺基亚|联通|网络|网站|网店|网址|组织机构|移动|珠宝|点看|游戏|淡马锡|机构|書籍|时尚|新闻|政府|政务|招聘|手表|手机|我爱你|慈善|微博|广东|工行|家電|娱乐|天主教|大拿|大众汽车|在线|嘉里大酒店|嘉里|商标|商店|商城|公益|公司|八卦|健康|信息|佛山|企业|中文网|中信|世界|ポイント|ファッション|セール|ストア|コム|グーグル|クラウド|みんな|คอม|संगठन|नेट|कॉम|همراه|موقع|موبايلي|كوم|كاثوليك|عرب|شبكة|بيتك|بازار|العليان|ارامكو|اتصالات|ابوظبي|קום|сайт|рус|орг|онлайн|москва|ком|католик|дети|zuerich|zone|zippo|zip|zero|zara|zappos|yun|youtube|you|yokohama|yoga|yodobashi|yandex|yamaxun|yahoo|yachts|xyz|xxx|xperia|xin|xihuan|xfinity|xerox|xbox|wtf|wtc|wow|world|works|work|woodside|wolterskluwer|wme|winners|wine|windows|win|williamhill|wiki|wien|whoswho|weir|weibo|wedding|wed|website|weber|webcam|weatherchannel|weather|watches|watch|warman|wanggou|wang|walter|walmart|wales|vuelos|voyage|voto|voting|vote|volvo|volkswagen|vodka|vlaanderen|vivo|viva|vistaprint|vista|vision|visa|virgin|vip|vin|villas|viking|vig|video|viajes|vet|versicherung|vermögensberatung|vermögensberater|verisign|ventures|vegas|vanguard|vana|vacations|ups|uol|uno|university|unicom|uconnect|ubs|ubank|tvs|tushu|tunes|tui|tube|trv|trust|travelersinsurance|travelers|travelchannel|travel|training|trading|trade|toys|toyota|town|tours|total|toshiba|toray|top|tools|tokyo|today|tmall|tkmaxx|tjx|tjmaxx|tirol|tires|tips|tiffany|tienda|tickets|tiaa|theatre|theater|thd|teva|tennis|temasek|telefonica|telecity|tel|technology|tech|team|tdk|tci|taxi|tax|tattoo|tatar|tatamotors|target|taobao|talk|taipei|tab|systems|symantec|sydney|swiss|swiftcover|swatch|suzuki|surgery|surf|support|supply|supplies|sucks|style|study|studio|stream|store|storage|stockholm|stcgroup|stc|statoil|statefarm|statebank|starhub|star|staples|stada|srt|srl|spreadbetting|spot|sport|spiegel|space|soy|sony|song|solutions|solar|sohu|software|softbank|social|soccer|sncf|smile|smart|sling|skype|sky|skin|ski|site|singles|sina|silk|shriram|showtime|show|shouji|shopping|shop|shoes|shiksha|shia|shell|shaw|sharp|shangrila|sfr|sexy|sex|sew|seven|ses|services|sener|select|seek|security|secure|seat|search|scot|scor|scjohnson|science|schwarz|schule|school|scholarships|schmidt|schaeffler|scb|sca|sbs|sbi|saxo|save|sas|sarl|sapo|sap|sanofi|sandvikcoromant|sandvik|samsung|samsclub|salon|sale|sakura|safety|safe|saarland|ryukyu|rwe|run|ruhr|rugby|rsvp|room|rogers|rodeo|rocks|rocher|rmit|rip|rio|ril|rightathome|ricoh|richardli|rich|rexroth|reviews|review|restaurant|rest|republican|report|repair|rentals|rent|ren|reliance|reit|reisen|reise|rehab|redumbrella|redstone|red|recipes|realty|realtor|realestate|read|raid|radio|racing|qvc|quest|quebec|qpon|pwc|pub|prudential|pru|protection|property|properties|promo|progressive|prof|productions|prod|pro|prime|press|praxi|pramerica|post|porn|politie|poker|pohl|pnc|plus|plumbing|playstation|play|place|pizza|pioneer|pink|ping|pin|pid|pictures|pictet|pics|piaget|physio|photos|photography|photo|phone|philips|phd|pharmacy|pfizer|pet|pccw|pay|passagens|party|parts|partners|pars|paris|panerai|panasonic|pamperedchef|page|ovh|ott|otsuka|osaka|origins|orientexpress|organic|org|orange|oracle|open|ooo|onyourside|online|onl|ong|one|omega|ollo|oldnavy|olayangroup|olayan|okinawa|office|off|observer|obi|nyc|ntt|nrw|nra|nowtv|nowruz|now|norton|northwesternmutual|nokia|nissay|nissan|ninja|nikon|nike|nico|nhk|ngo|nfl|nexus|nextdirect|next|news|newholland|new|neustar|network|netflix|netbank|net|nec|nba|navy|natura|nationwide|name|nagoya|nadex|nab|mutuelle|mutual|museum|mtr|mtpc|mtn|msd|movistar|movie|mov|motorcycles|moto|moscow|mortgage|mormon|mopar|montblanc|monster|money|monash|mom|moi|moe|moda|mobily|mobile|mobi|mma|mls|mlb|mitsubishi|mit|mint|mini|mil|microsoft|miami|metlife|merckmsd|meo|menu|men|memorial|meme|melbourne|meet|media|med|mckinsey|mcdonalds|mcd|mba|mattel|maserati|marshalls|marriott|markets|marketing|market|map|mango|management|man|makeup|maison|maif|madrid|macys|luxury|luxe|lupin|lundbeck|ltda|ltd|lplfinancial|lpl|love|lotto|lotte|london|lol|loft|locus|locker|loans|loan|llp|llc|lixil|living|live|lipsy|link|linde|lincoln|limo|limited|lilly|like|lighting|lifestyle|lifeinsurance|life|lidl|liaison|lgbt|lexus|lego|legal|lefrak|leclerc|lease|lds|lawyer|law|latrobe|latino|lat|lasalle|lanxess|landrover|land|lancome|lancia|lancaster|lamer|lamborghini|ladbrokes|lacaixa|kyoto|kuokgroup|kred|krd|kpn|kpmg|kosher|komatsu|koeln|kiwi|kitchen|kindle|kinder|kim|kia|kfh|kerryproperties|kerrylogistics|kerryhotels|kddi|kaufen|juniper|juegos|jprs|jpmorgan|joy|jot|joburg|jobs|jnj|jmp|jll|jlc|jio|jewelry|jetzt|jeep|jcp|jcb|java|jaguar|iwc|iveco|itv|itau|istanbul|ist|ismaili|iselect|irish|ipiranga|investments|intuit|international|intel|int|insure|insurance|institute|ink|ing|info|infiniti|industries|inc|immobilien|immo|imdb|imamat|ikano|iinet|ifm|ieee|icu|ice|icbc|ibm|hyundai|hyatt|hughes|htc|hsbc|how|house|hotmail|hotels|hoteles|hot|hosting|host|hospital|horse|honeywell|honda|homesense|homes|homegoods|homedepot|holiday|holdings|hockey|hkt|hiv|hitachi|hisamitsu|hiphop|hgtv|hermes|here|helsinki|help|healthcare|health|hdfcbank|hdfc|hbo|haus|hangout|hamburg|hair|guru|guitars|guide|guge|gucci|guardian|group|grocery|gripe|green|gratis|graphics|grainger|gov|got|gop|google|goog|goodyear|goodhands|goo|golf|goldpoint|gold|godaddy|gmx|gmo|gmbh|gmail|globo|global|gle|glass|glade|giving|gives|gifts|gift|ggee|george|genting|gent|gea|gdn|gbiz|gay|garden|gap|games|game|gallup|gallo|gallery|gal|fyi|futbol|furniture|fund|fun|fujixerox|fujitsu|ftr|frontier|frontdoor|frogans|frl|fresenius|free|fox|foundation|forum|forsale|forex|ford|football|foodnetwork|food|foo|fly|flsmidth|flowers|florist|flir|flights|flickr|fitness|fit|fishing|fish|firmdale|firestone|fire|financial|finance|final|film|fido|fidelity|fiat|ferrero|ferrari|feedback|fedex|fast|fashion|farmers|farm|fans|fan|family|faith|fairwinds|fail|fage|extraspace|express|exposed|expert|exchange|everbank|events|eus|eurovision|etisalat|esurance|estate|esq|erni|ericsson|equipment|epson|epost|enterprises|engineering|engineer|energy|emerck|email|education|edu|edeka|eco|eat|earth|dvr|dvag|durban|dupont|duns|dunlop|duck|dubai|dtv|drive|download|dot|doosan|domains|doha|dog|dodge|doctor|docs|dnp|diy|dish|discover|discount|directory|direct|digital|diet|diamonds|dhl|dev|design|desi|dentist|dental|democrat|delta|deloitte|dell|delivery|degree|deals|dealer|deal|dds|dclk|day|datsun|dating|date|data|dance|dad|dabur|cyou|cymru|cuisinella|csc|cruises|cruise|crs|crown|cricket|creditunion|creditcard|credit|cpa|courses|coupons|coupon|country|corsica|coop|cool|cookingchannel|cooking|contractors|contact|consulting|construction|condos|comsec|computer|compare|company|community|commbank|comcast|com|cologne|college|coffee|codes|coach|clubmed|club|cloud|clothing|clinique|clinic|click|cleaning|claims|cityeats|city|citic|citi|citadel|cisco|circle|cipriani|church|chrysler|chrome|christmas|chloe|chintai|cheap|chat|chase|charity|channel|chanel|cfd|cfa|cern|ceo|center|ceb|cbs|cbre|cbn|cba|catholic|catering|cat|casino|cash|caseih|case|casa|cartier|cars|careers|career|care|cards|caravan|car|capitalone|capital|capetown|canon|cancerresearch|camp|camera|cam|calvinklein|call|cal|cafe|cab|bzh|buzz|buy|business|builders|build|bugatti|budapest|brussels|brother|broker|broadway|bridgestone|bradesco|box|boutique|bot|boston|bostik|bosch|boots|booking|book|boo|bond|bom|bofa|boehringer|boats|bnpparibas|bnl|bmw|bms|blue|bloomberg|blog|blockbuster|blanco|blackfriday|black|biz|bio|bingo|bing|bike|bid|bible|bharti|bet|bestbuy|best|berlin|bentley|beer|beauty|beats|bcn|bcg|bbva|bbt|bbc|bayern|bauhaus|basketball|baseball|bargains|barefoot|barclays|barclaycard|barcelona|bar|bank|band|bananarepublic|banamex|baidu|baby|azure|axa|aws|avianca|autos|auto|author|auspost|audio|audible|audi|auction|attorney|athleta|associates|asia|asda|arte|art|arpa|army|archi|aramco|arab|aquarelle|apple|app|apartments|aol|anz|anquan|android|analytics|amsterdam|amica|amfam|amex|americanfamily|americanexpress|alstom|alsace|ally|allstate|allfinanz|alipay|alibaba|alfaromeo|akdn|airtel|airforce|airbus|aigo|aig|agency|agakhan|africa|afl|afamilycompany|aetna|aero|aeg|adult|ads|adac|actor|active|aco|accountants|accountant|accenture|academy|abudhabi|abogado|able|abc|abbvie|abbott|abb|abarth|aarp|aaa|onion)(?=[^0-9a-zA-Z@+-]|$))")),d2=/(?:xn--[\-0-9a-z]+)/,HF=Rt(/(?:(?:#{validDomainChars}(?:[_-]|#{validDomainChars})*)?#{validDomainChars}\.)/,{validDomainChars:c2}),WF=Rt(/(?:#{validSubdomain}*#{validDomainName}(?:#{validGTLD}|#{validCCTLD}|#{validPunycode}))/,{validDomainName:UF,validSubdomain:HF,validGTLD:u2,validCCTLD:a2,validPunycode:d2}),VF=/[0-9]+/,f2=/\u0400-\u04FF/,pf=/\xC0-\xD6\xD8-\xF6\xF8-\xFF\u0100-\u024F\u0253\u0254\u0256\u0257\u0259\u025B\u0263\u0268\u026F\u0272\u0289\u028B\u02BB\u0300-\u036F\u1E00-\u1EFF/,h2=Rt(/[a-z#{cyrillicLettersAndMarks}0-9!\*';:=\+,\.\$\/%#\[\]\-\u2013_~@\|&#{latinAccentChars}]/i,{cyrillicLettersAndMarks:f2,latinAccentChars:pf}),p2=Rt("\\((?:#{validGeneralUrlPathChars}+|(?:#{validGeneralUrlPathChars}*\\(#{validGeneralUrlPathChars}+\\)#{validGeneralUrlPathChars}*))\\)",{validGeneralUrlPathChars:h2},"i"),qF=Rt(/[\+\-a-z#{cyrillicLettersAndMarks}0-9=_#\/#{latinAccentChars}]|(?:#{validUrlBalancedParens})/i,{cyrillicLettersAndMarks:f2,latinAccentChars:pf,validUrlBalancedParens:p2}),KF=Rt("(?:(?:#{validGeneralUrlPathChars}*(?:#{validUrlBalancedParens}#{validGeneralUrlPathChars}*)*#{validUrlPathEndingChars})|(?:@#{validGeneralUrlPathChars}+/))",{validGeneralUrlPathChars:h2,validUrlBalancedParens:p2,validUrlPathEndingChars:qF},"i"),GF=Rt(/(?:[^A-Za-z0-9@@$###{invalidCharsGroup}]|[#{directionalMarkersGroup}]|^)/,{invalidCharsGroup:Ey,directionalMarkersGroup:l2}),m2=/[a-z0-9!?\*'@\(\);:&=\+\$\/%#\[\]\-_\.,~|]/i,g2=/[a-z0-9\-_&=#\/]/i,J1=Rt("((#{validUrlPrecedingChars})((https?:\\/\\/)?(#{validDomain})(?::(#{validPortNumber}))?(\\/#{validUrlPath}*)?(\\?#{validUrlQueryChars}*#{validUrlQueryEndingChars})?))",{validUrlPrecedingChars:GF,validDomain:WF,validPortNumber:VF,validUrlPath:KF,validUrlQueryChars:m2,validUrlQueryEndingChars:g2},"gi"),JF=/[-_.\/]$/,Y1={},Lm,X1;function YF(){if(X1)return Lm;X1=1;var t=Mr(),e=df(),n=zn()("species");return Lm=function(r,s){var i=t(r).constructor,o;return i===void 0||(o=t(i)[n])==null?s:e(o)},Lm}var Q1;function XF(){if(Q1)return Y1;Q1=1;var t=r2(),e=Mr(),n=YF(),r=hy(),s=wo(),i=my(),o=gy(),l=ls(),d=Math.min,f=[].push,h="split",m="length",g="lastIndex",v=4294967295,b=!l(function(){});return yy()("split",2,function(k,w,S,N){var T;return"abbc"[h](/(b)*/)[1]=="c"||"test"[h](/(?:)/,-1)[m]!=4||"ab"[h](/(?:ab)*/)[m]!=2||"."[h](/(.?)(.?)/)[m]!=4||"."[h](/()()/)[m]>1||""[h](/.?/)[m]?T=function(M,_){var R=String(this);if(M===void 0&&_===0)return[];if(!t(M))return S.call(R,M,_);for(var I=[],P=(M.ignoreCase?"i":"")+(M.multiline?"m":"")+(M.unicode?"u":"")+(M.sticky?"y":""),B=0,z=_===void 0?v:_>>>0,K=new RegExp(M.source,P+"g"),F,J,$;(F=o.call(K,R))&&(J=K[g],!(J>B&&(I.push(R.slice(B,F.index)),F[m]>1&&F.index<R[m]&&f.apply(I,F.slice(1)),$=F[0][m],B=J,I[m]>=z)));)K[g]===F.index&&K[g]++;return B===R[m]?($||!K.test(""))&&I.push(""):I.push(R.slice(B)),I[m]>z?I.slice(0,z):I}:"0"[h](void 0,0)[m]?T=function(M,_){return M===void 0&&_===0?[]:S.call(this,M,_)}:T=S,[function(_,R){var I=k(this),P=_==null?void 0:_[w];return P!==void 0?P.call(_,I,R):T.call(String(I),_,R)},function(M,_){var R=N(T,M,this,_,T!==S);if(R.done)return R.value;var I=e(M),P=String(this),B=n(I,RegExp),z=I.unicode,K=(I.ignoreCase?"i":"")+(I.multiline?"m":"")+(I.unicode?"u":"")+(b?"y":"g"),F=new B(b?I:"^(?:"+I.source+")",K),J=_===void 0?v:_>>>0;if(J===0)return[];if(P.length===0)return i(F,P)===null?[P]:[];for(var $=0,W=0,q=[];W<P.length;){F.lastIndex=b?W:0;var ne=i(F,b?P:P.slice(W)),V;if(ne===null||(V=d(s(F.lastIndex+(b?0:W)),P.length))===$)W=r(P,W,z);else{if(q.push(P.slice($,W)),q.length===J)return q;for(var oe=1;oe<=ne.length-1;oe++)if(q.push(ne[oe]),q.length===J)return q;W=$=V}}return q.push(P.slice($)),q}]}),Y1}XF();var ll={exports:{}};/*! https://mths.be/punycode v1.4.1 by @mathias */var QF=ll.exports,Z1;function ZF(){return Z1||(Z1=1,(function(t,e){(function(n){var r=e&&!e.nodeType&&e,s=t&&!t.nodeType&&t,i=typeof q0=="object"&&q0;(i.global===i||i.window===i||i.self===i)&&(n=i);var o,l=2147483647,d=36,f=1,h=26,m=38,g=700,v=72,b=128,k="-",w=/^xn--/,S=/[^\x20-\x7E]/,N=/[\x2E\u3002\uFF0E\uFF61]/g,T={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},M=d-f,_=Math.floor,R=String.fromCharCode,I;function P(Y){throw new RangeError(T[Y])}function B(Y,A){for(var L=Y.length,ee=[];L--;)ee[L]=A(Y[L]);return ee}function z(Y,A){var L=Y.split("@"),ee="";L.length>1&&(ee=L[0]+"@",Y=L[1]),Y=Y.replace(N,".");var ue=Y.split("."),be=B(ue,A).join(".");return ee+be}function K(Y){for(var A=[],L=0,ee=Y.length,ue,be;L<ee;)ue=Y.charCodeAt(L++),ue>=55296&&ue<=56319&&L<ee?(be=Y.charCodeAt(L++),(be&64512)==56320?A.push(((ue&1023)<<10)+(be&1023)+65536):(A.push(ue),L--)):A.push(ue);return A}function F(Y){return B(Y,function(A){var L="";return A>65535&&(A-=65536,L+=R(A>>>10&1023|55296),A=56320|A&1023),L+=R(A),L}).join("")}function J(Y){return Y-48<10?Y-22:Y-65<26?Y-65:Y-97<26?Y-97:d}function $(Y,A){return Y+22+75*(Y<26)-((A!=0)<<5)}function W(Y,A,L){var ee=0;for(Y=L?_(Y/g):Y>>1,Y+=_(Y/A);Y>M*h>>1;ee+=d)Y=_(Y/M);return _(ee+(M+1)*Y/(Y+m))}function q(Y){var A=[],L=Y.length,ee,ue=0,be=b,re=v,we,Ee,$e,Fe,Ze,Re,tt,gt,ut;for(we=Y.lastIndexOf(k),we<0&&(we=0),Ee=0;Ee<we;++Ee)Y.charCodeAt(Ee)>=128&&P("not-basic"),A.push(Y.charCodeAt(Ee));for($e=we>0?we+1:0;$e<L;){for(Fe=ue,Ze=1,Re=d;$e>=L&&P("invalid-input"),tt=J(Y.charCodeAt($e++)),(tt>=d||tt>_((l-ue)/Ze))&&P("overflow"),ue+=tt*Ze,gt=Re<=re?f:Re>=re+h?h:Re-re,!(tt<gt);Re+=d)ut=d-gt,Ze>_(l/ut)&&P("overflow"),Ze*=ut;ee=A.length+1,re=W(ue-Fe,ee,Fe==0),_(ue/ee)>l-be&&P("overflow"),be+=_(ue/ee),ue%=ee,A.splice(ue++,0,be)}return F(A)}function ne(Y){var A,L,ee,ue,be,re,we,Ee,$e,Fe,Ze,Re=[],tt,gt,ut,ge;for(Y=K(Y),tt=Y.length,A=b,L=0,be=v,re=0;re<tt;++re)Ze=Y[re],Ze<128&&Re.push(R(Ze));for(ee=ue=Re.length,ue&&Re.push(k);ee<tt;){for(we=l,re=0;re<tt;++re)Ze=Y[re],Ze>=A&&Ze<we&&(we=Ze);for(gt=ee+1,we-A>_((l-L)/gt)&&P("overflow"),L+=(we-A)*gt,A=we,re=0;re<tt;++re)if(Ze=Y[re],Ze<A&&++L>l&&P("overflow"),Ze==A){for(Ee=L,$e=d;Fe=$e<=be?f:$e>=be+h?h:$e-be,!(Ee<Fe);$e+=d)ge=Ee-Fe,ut=d-Fe,Re.push(R($(Fe+ge%ut,0))),Ee=_(ge/ut);Re.push(R($(Ee,0))),be=W(L,gt,ee==ue),L=0,++ee}++L,++A}return Re.join("")}function V(Y){return z(Y,function(A){return w.test(A)?q(A.slice(4).toLowerCase()):A})}function oe(Y){return z(Y,function(A){return S.test(A)?"xn--"+ne(A):A})}if(o={version:"1.4.1",ucs2:{decode:K,encode:F},decode:q,encode:ne,toASCII:oe,toUnicode:V},r&&s)if(t.exports==r)s.exports=o;else for(I in o)o.hasOwnProperty(I)&&(r[I]=o[I]);else n.punycode=o})(QF)})(ll,ll.exports)),ll.exports}var ez=ZF();const tz=Ol(ez);var v2=Rt(/(?:(?:[\-a-z0-9#{latinAccentChars}]+)\.)+(?:#{validGTLD}|#{validCCTLD}|#{validPunycode})/gi,{latinAccentChars:pf,validGTLD:u2,validCCTLD:a2,validPunycode:d2}),nz=63,rz="xn--",sz={toAscii:function(e){if(!(e.substring(0,4)===rz&&!e.match(v2))){for(var n=e.split("."),r=0;r<n.length;r++){var s=n[r],i=tz.toASCII(s);if(i.length<1||i.length>nz)return}return n.join(".")}}},iz=Rt(/^https?:\/\/t\.co\/([a-z0-9]+)(?:\?#{validUrlQueryChars}*#{validUrlQueryEndingChars})?/,{validUrlQueryChars:m2,validUrlQueryEndingChars:g2},"i"),oz="https://",az={extractUrlsWithoutProtocol:!0},lz=4096,cz=40,uz=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:az;if(!e||(n.extractUrlsWithoutProtocol?!e.match(/\./):!e.match(/:/)))return[];for(var r=[],s=function(){var l=RegExp.$2,d=RegExp.$3,f=RegExp.$4,h=RegExp.$5,m=RegExp.$7,g=J1.lastIndex,v=g-d.length;if(!dz(d,f||oz,h))return"continue";if(f){if(d.match(iz)){var w=RegExp.$1;if(w&&w.length>cz)return"continue";d=RegExp.lastMatch,g=v+d.length}r.push({url:d,indices:[v,g]})}else{if(!n.extractUrlsWithoutProtocol||l.match(JF))return"continue";var b=null,k=0;if(h.replace(v2,function(S){var N=h.indexOf(S,k);k=N+S.length,b={url:S,indices:[v+N,v+k]},r.push(b)}),b==null)return"continue";m&&(b.url=d.replace(h,b.url),b.indices[1]=g)}};J1.exec(e);)var i=s();return r},dz=function(e,n,r){var s=e.length,i=sz.toAscii(r);return!i||!i.length?!1:(s=s+i.length-r.length,n.length+s<=lz)},eS={},tS;function fz(){if(tS)return eS;tS=1;var t=xr(),e=df(),n=Di(),r=ls(),s=[].sort,i=[1,2,3];return t(t.P+t.F*(r(function(){i.sort(void 0)})||!r(function(){i.sort(null)})||!Vl()(s)),"Array",{sort:function(l){return l===void 0?s.call(n(this)):s.call(n(this),e(l))}}),eS}fz();var y2=/\ud800[\udc00-\udc0b\udc0d-\udc26\udc28-\udc3a\udc3c\udc3d\udc3f-\udc4d\udc50-\udc5d\udc80-\udcfa\uddfd\ude80-\ude9c\udea0-\uded0\udee0\udf00-\udf1f\udf30-\udf40\udf42-\udf49\udf50-\udf7a\udf80-\udf9d\udfa0-\udfc3\udfc8-\udfcf]|\ud801[\udc00-\udc9d\udd00-\udd27\udd30-\udd63\ude00-\udf36\udf40-\udf55\udf60-\udf67]|\ud802[\udc00-\udc05\udc08\udc0a-\udc35\udc37\udc38\udc3c\udc3f-\udc55\udc60-\udc76\udc80-\udc9e\udd00-\udd15\udd20-\udd39\udd80-\uddb7\uddbe\uddbf\ude00-\ude03\ude05\ude06\ude0c-\ude13\ude15-\ude17\ude19-\ude33\ude38-\ude3a\ude3f\ude60-\ude7c\ude80-\ude9c\udec0-\udec7\udec9-\udee6\udf00-\udf35\udf40-\udf55\udf60-\udf72\udf80-\udf91]|\ud803[\udc00-\udc48]|\ud804[\udc00-\udc46\udc7f-\udcba\udcd0-\udce8\udd00-\udd34\udd50-\udd73\udd76\udd80-\uddc4\uddda\ude00-\ude11\ude13-\ude37\udeb0-\udeea\udf01-\udf03\udf05-\udf0c\udf0f\udf10\udf13-\udf28\udf2a-\udf30\udf32\udf33\udf35-\udf39\udf3c-\udf44\udf47\udf48\udf4b-\udf4d\udf57\udf5d-\udf63\udf66-\udf6c\udf70-\udf74]|\ud805[\udc80-\udcc5\udcc7\udd80-\uddb5\uddb8-\uddc0\ude00-\ude40\ude44\ude80-\udeb7]|\ud806[\udca0-\udcdf\udcff\udec0-\udef8]|\ud808[\udc00-\udf98]|\ud80c[\udc00-\udfff]|\ud80d[\udc00-\udc2e]|\ud81a[\udc00-\ude38\ude40-\ude5e\uded0-\udeed\udef0-\udef4\udf00-\udf36\udf40-\udf43\udf63-\udf77\udf7d-\udf8f]|\ud81b[\udf00-\udf44\udf50-\udf7e\udf8f-\udf9f]|\ud82c[\udc00\udc01]|\ud82f[\udc00-\udc6a\udc70-\udc7c\udc80-\udc88\udc90-\udc99\udc9d\udc9e]|\ud834[\udd65-\udd69\udd6d-\udd72\udd7b-\udd82\udd85-\udd8b\uddaa-\uddad\ude42-\ude44]|\ud835[\udc00-\udc54\udc56-\udc9c\udc9e\udc9f\udca2\udca5\udca6\udca9-\udcac\udcae-\udcb9\udcbb\udcbd-\udcc3\udcc5-\udd05\udd07-\udd0a\udd0d-\udd14\udd16-\udd1c\udd1e-\udd39\udd3b-\udd3e\udd40-\udd44\udd46\udd4a-\udd50\udd52-\udea5\udea8-\udec0\udec2-\udeda\udedc-\udefa\udefc-\udf14\udf16-\udf34\udf36-\udf4e\udf50-\udf6e\udf70-\udf88\udf8a-\udfa8\udfaa-\udfc2\udfc4-\udfcb]|\ud83a[\udc00-\udcc4\udcd0-\udcd6]|\ud83b[\ude00-\ude03\ude05-\ude1f\ude21\ude22\ude24\ude27\ude29-\ude32\ude34-\ude37\ude39\ude3b\ude42\ude47\ude49\ude4b\ude4d-\ude4f\ude51\ude52\ude54\ude57\ude59\ude5b\ude5d\ude5f\ude61\ude62\ude64\ude67-\ude6a\ude6c-\ude72\ude74-\ude77\ude79-\ude7c\ude7e\ude80-\ude89\ude8b-\ude9b\udea1-\udea3\udea5-\udea9\udeab-\udebb]|\ud840[\udc00-\udfff]|\ud841[\udc00-\udfff]|\ud842[\udc00-\udfff]|\ud843[\udc00-\udfff]|\ud844[\udc00-\udfff]|\ud845[\udc00-\udfff]|\ud846[\udc00-\udfff]|\ud847[\udc00-\udfff]|\ud848[\udc00-\udfff]|\ud849[\udc00-\udfff]|\ud84a[\udc00-\udfff]|\ud84b[\udc00-\udfff]|\ud84c[\udc00-\udfff]|\ud84d[\udc00-\udfff]|\ud84e[\udc00-\udfff]|\ud84f[\udc00-\udfff]|\ud850[\udc00-\udfff]|\ud851[\udc00-\udfff]|\ud852[\udc00-\udfff]|\ud853[\udc00-\udfff]|\ud854[\udc00-\udfff]|\ud855[\udc00-\udfff]|\ud856[\udc00-\udfff]|\ud857[\udc00-\udfff]|\ud858[\udc00-\udfff]|\ud859[\udc00-\udfff]|\ud85a[\udc00-\udfff]|\ud85b[\udc00-\udfff]|\ud85c[\udc00-\udfff]|\ud85d[\udc00-\udfff]|\ud85e[\udc00-\udfff]|\ud85f[\udc00-\udfff]|\ud860[\udc00-\udfff]|\ud861[\udc00-\udfff]|\ud862[\udc00-\udfff]|\ud863[\udc00-\udfff]|\ud864[\udc00-\udfff]|\ud865[\udc00-\udfff]|\ud866[\udc00-\udfff]|\ud867[\udc00-\udfff]|\ud868[\udc00-\udfff]|\ud869[\udc00-\uded6\udf00-\udfff]|\ud86a[\udc00-\udfff]|\ud86b[\udc00-\udfff]|\ud86c[\udc00-\udfff]|\ud86d[\udc00-\udf34\udf40-\udfff]|\ud86e[\udc00-\udc1d]|\ud87e[\udc00-\ude1d]|\udb40[\udd00-\uddef]/,b2=/A-Za-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u052f\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u065f\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06ef\u06fa-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07ca-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0-\u08b2\u08e4-\u0963\u0971-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09f0\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a70-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0c00-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c81-\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0cf1\u0cf2\u0d01-\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u103f\u1050-\u108f\u109a-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16f1-\u16f8\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u180b-\u180d\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191e\u1920-\u192b\u1930-\u193b\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f\u1aa7\u1ab0-\u1abe\u1b00-\u1b4b\u1b6b-\u1b73\u1b80-\u1baf\u1bba-\u1bf3\u1c00-\u1c37\u1c4d-\u1c4f\u1c5a-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1cf8\u1cf9\u1d00-\u1df5\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u20d0-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2183\u2184\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005\u3006\u302a-\u302f\u3031-\u3035\u303b\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua672\ua674-\ua67d\ua67f-\ua69d\ua69f-\ua6e5\ua6f0\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua7ad\ua7b0\ua7b1\ua7f7-\ua827\ua840-\ua873\ua880-\ua8c4\ua8e0-\ua8f7\ua8fb\ua90a-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf\ua9e0-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa36\uaa40-\uaa4d\uaa60-\uaa76\uaa7a-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab5f\uab64\uab65\uabc0-\uabea\uabec\uabed\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf870-\uf87f\uf882\uf884-\uf89f\uf8b8\uf8c1-\uf8d6\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe2d\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc/,x2=/[\uD800-\uDBFF][\uDC00-\uDFFF]/gm,hz=Rt(/(?:[#{bmpLetterAndMarks}]|(?=#{nonBmpCodePairs})(?:#{astralLetterAndMarks}))/,{bmpLetterAndMarks:b2,nonBmpCodePairs:x2,astralLetterAndMarks:y2}),pz=/\ud801[\udca0-\udca9]|\ud804[\udc66-\udc6f\udcf0-\udcf9\udd36-\udd3f\uddd0-\uddd9\udef0-\udef9]|\ud805[\udcd0-\udcd9\ude50-\ude59\udec0-\udec9]|\ud806[\udce0-\udce9]|\ud81a[\ude60-\ude69\udf50-\udf59]|\ud835[\udfce-\udfff]/,mz=/0-9\u0660-\u0669\u06f0-\u06f9\u07c0-\u07c9\u0966-\u096f\u09e6-\u09ef\u0a66-\u0a6f\u0ae6-\u0aef\u0b66-\u0b6f\u0be6-\u0bef\u0c66-\u0c6f\u0ce6-\u0cef\u0d66-\u0d6f\u0de6-\u0def\u0e50-\u0e59\u0ed0-\u0ed9\u0f20-\u0f29\u1040-\u1049\u1090-\u1099\u17e0-\u17e9\u1810-\u1819\u1946-\u194f\u19d0-\u19d9\u1a80-\u1a89\u1a90-\u1a99\u1b50-\u1b59\u1bb0-\u1bb9\u1c40-\u1c49\u1c50-\u1c59\ua620-\ua629\ua8d0-\ua8d9\ua900-\ua909\ua9d0-\ua9d9\ua9f0-\ua9f9\uaa50-\uaa59\uabf0-\uabf9\uff10-\uff19/,gz=/_\u200c\u200d\ua67e\u05be\u05f3\u05f4\uff5e\u301c\u309b\u309c\u30a0\u30fb\u3003\u0f0b\u0f0c\xb7/,w2=Rt(/(?:[#{bmpLetterAndMarks}#{bmpNumerals}#{hashtagSpecialChars}]|(?=#{nonBmpCodePairs})(?:#{astralLetterAndMarks}|#{astralNumerals}))/,{bmpLetterAndMarks:b2,bmpNumerals:mz,hashtagSpecialChars:gz,nonBmpCodePairs:x2,astralLetterAndMarks:y2,astralNumerals:pz}),vz=/(?:[^\uD800-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF])/,yz=Rt(/(?:^|\uFE0E|\uFE0F|$|(?!#{hashtagAlphaNumeric}|&)#{codePoint})/,{codePoint:vz,hashtagAlphaNumeric:w2});Rt(/(#{hashtagBoundary})(#{hashSigns})(?!\uFE0F|\u20E3)(#{hashtagAlphaNumeric}*#{hashtagAlpha}#{hashtagAlphaNumeric}*)/gi,{hashtagBoundary:yz,hashSigns:o2,hashtagAlphaNumeric:w2,hashtagAlpha:hz});var Ny=/[@@]/;Rt(/^(?:#{atSigns}|[#{latinAccentChars}]|:\/\/)/,{atSigns:Ny,latinAccentChars:pf});var bz=/(?:^|[^a-zA-Z0-9_!#$%&*@@]|(?:^|[^a-zA-Z0-9_+~.-])(?:rt|RT|rT|Rt):?)/,xz=Rt("(#{validMentionPrecedingChars})(#{atSigns})([a-zA-Z0-9_]{1,20})(/[a-zA-Z][a-zA-Z0-9_-]{0,24})?",{validMentionPrecedingChars:bz,atSigns:Ny},"g"),nS={},rS={},sS;function wz(){return sS||(sS=1,Gr()&&/./g.flags!="g"&&cs().f(RegExp.prototype,"flags",{configurable:!0,get:uf()})),rS}var iS;function kz(){if(iS)return nS;iS=1,wz();var t=Mr(),e=uf(),n=Gr(),r="toString",s=/./[r],i=function(o){Vs()(RegExp.prototype,r,o,!0)};return ls()(function(){return s.call({source:"a",flags:"b"})!="/a/b"})?i(function(){var l=t(this);return"/".concat(l.source,"/","flags"in l?l.flags:!n&&l instanceof RegExp?e.call(l):void 0)}):s.name!=r&&i(function(){return s.call(this)}),nS}kz();var oS={},aS;function Sz(){if(aS)return oS;aS=1;var t=Date.prototype,e="Invalid Date",n="toString",r=t[n],s=t.getTime;return new Date(NaN)+""!=e&&Vs()(t,n,function(){var o=s.call(this);return o===o?r.call(this):e}),oS}Sz();var lS={},cS;function Ez(){if(cS)return lS;cS=1;var t=py(),e={};return e[zn()("toStringTag")]="z",e+""!="[object z]"&&Vs()(Object.prototype,"toString",function(){return"[object "+t(this)+"]"},!0),lS}Ez();const uS={defaults:{version:3,maxWeightedTweetLength:280,scale:100,defaultWeight:200,emojiParsingEnabled:!0,transformedURLLength:23,ranges:[{start:0,end:4351,weight:100},{start:8192,end:8205,weight:100},{start:8208,end:8223,weight:100},{start:8242,end:8247,weight:100}]}};Rt(/^(?:#{spaces})*#{atSigns}([a-zA-Z0-9_]{1,20})/,{atSigns:Ny,spaces:i2});var dS={},Dm,fS;function Cy(){if(fS)return Dm;fS=1;var t=af();return Dm=Array.isArray||function(n){return t(n)=="Array"},Dm}var hS;function Nz(){if(hS)return dS;hS=1;var t=xr();return t(t.S,"Array",{isArray:Cy()}),dS}Nz();var Cz=function(e,n){var r=n.defaultWeight,s=n.ranges,i=r,o=e.charCodeAt(0);if(Array.isArray(s))for(var l=0,d=s.length;l<d;l++){var f=s[l];if(o>=f.start&&o<=f.end){i=f.weight;break}}return i},pS={},Pm,mS;function _z(){if(mS)return Pm;mS=1;var t=df(),e=Di(),n=by(),r=wo();return Pm=function(s,i,o,l,d){t(i);var f=e(s),h=n(f),m=r(f.length),g=d?m-1:0,v=d?-1:1;if(o<2)for(;;){if(g in h){l=h[g],g+=v;break}if(g+=v,d?g<0:m<=g)throw TypeError("Reduce of empty array with no initial value")}for(;d?g>=0:m>g;g+=v)g in h&&(l=i(l,h[g],g,f));return l},Pm}var gS;function Tz(){if(gS)return pS;gS=1;var t=xr(),e=_z();return t(t.P+t.F*!Vl()([].reduce,!0),"Array",{reduce:function(r){return e(this,r,arguments.length,arguments[1],!1)}}),pS}Tz();var vS={},Bm,yS;function jz(){if(yS)return Bm;yS=1;var t=zn()("unscopables"),e=Array.prototype;return e[t]==null&&Pi()(e,t,{}),Bm=function(n){e[t][n]=!0},Bm}var $m,bS;function Mz(){return bS||(bS=1,$m=function(t,e){return{value:e,done:!!t}}),$m}var Fm,xS;function ql(){return xS||(xS=1,Fm={}),Fm}var zm,wS;function Kl(){if(wS)return zm;wS=1;var t=n2(),e=Sy();return zm=Object.keys||function(r){return t(r,e)},zm}var Um,kS;function k2(){if(kS)return Um;kS=1;var t=cs(),e=Mr(),n=Kl();return Um=Gr()?Object.defineProperties:function(s,i){e(s);for(var o=n(i),l=o.length,d=0,f;l>d;)t.f(s,f=o[d++],i[f]);return s},Um}var Hm,SS;function Az(){if(SS)return Hm;SS=1;var t=Kr().document;return Hm=t&&t.documentElement,Hm}var Wm,ES;function S2(){if(ES)return Wm;ES=1;var t=Mr(),e=k2(),n=Sy(),r=ky()("IE_PROTO"),s=function(){},i="prototype",o=function(){var l=QT()("iframe"),d=n.length,f="<",h=">",m;for(l.style.display="none",Az().appendChild(l),l.src="javascript:",m=l.contentWindow.document,m.open(),m.write(f+"script"+h+"document.F=Object"+f+"/script"+h),m.close(),o=m.F;d--;)delete o[i][n[d]];return o()};return Wm=Object.create||function(d,f){var h;return d!==null?(s[i]=t(d),h=new s,s[i]=null,h[r]=d):h=o(),f===void 0?h:e(h,f)},Wm}var Vm,NS;function _y(){if(NS)return Vm;NS=1;var t=cs().f,e=ko(),n=zn()("toStringTag");return Vm=function(r,s,i){r&&!e(r=i?r:r.prototype,n)&&t(r,n,{configurable:!0,value:s})},Vm}var qm,CS;function Rz(){if(CS)return qm;CS=1;var t=S2(),e=Wl(),n=_y(),r={};return Pi()(r,zn()("iterator"),function(){return this}),qm=function(s,i,o){s.prototype=t(r,{next:e(1,o)}),n(s,i+" Iterator")},qm}var Km,_S;function Oz(){if(_S)return Km;_S=1;var t=ko(),e=Di(),n=ky()("IE_PROTO"),r=Object.prototype;return Km=Object.getPrototypeOf||function(s){return s=e(s),t(s,n)?s[n]:typeof s.constructor=="function"&&s instanceof s.constructor?s.constructor.prototype:s instanceof Object?r:null},Km}var Gm,TS;function E2(){if(TS)return Gm;TS=1;var t=lf(),e=xr(),n=Vs(),r=Pi(),s=ql(),i=Rz(),o=_y(),l=Oz(),d=zn()("iterator"),f=!([].keys&&"next"in[].keys()),h="@@iterator",m="keys",g="values",v=function(){return this};return Gm=function(b,k,w,S,N,T,M){i(w,k,S);var _=function(ne){if(!f&&ne in B)return B[ne];switch(ne){case m:return function(){return new w(this,ne)};case g:return function(){return new w(this,ne)}}return function(){return new w(this,ne)}},R=k+" Iterator",I=N==g,P=!1,B=b.prototype,z=B[d]||B[h]||N&&B[N],K=z||_(N),F=N?I?_("entries"):K:void 0,J=k=="Array"&&B.entries||z,$,W,q;if(J&&(q=l(J.call(new b)),q!==Object.prototype&&q.next&&(o(q,R,!0),!t&&typeof q[d]!="function"&&r(q,d,v))),I&&z&&z.name!==g&&(P=!0,K=function(){return z.call(this)}),(!t||M)&&(f||P||!B[d])&&r(B,d,K),s[k]=K,s[R]=v,N)if($={values:I?K:_(g),keys:T?K:_(m),entries:F},M)for(W in $)W in B||n(B,W,$[W]);else e(e.P+e.F*(f||P),k,$);return $},Gm}var Jm,jS;function N2(){if(jS)return Jm;jS=1;var t=jz(),e=Mz(),n=ql(),r=So();return Jm=E2()(Array,"Array",function(s,i){this._t=r(s),this._i=0,this._k=i},function(){var s=this._t,i=this._k,o=this._i++;return!s||o>=s.length?(this._t=void 0,e(1)):i=="keys"?e(0,o):i=="values"?e(0,s[o]):e(0,[o,s[o]])},"values"),n.Arguments=n.Array,t("keys"),t("values"),t("entries"),Jm}var MS;function Iz(){if(MS)return vS;MS=1;for(var t=N2(),e=Kl(),n=Vs(),r=Kr(),s=Pi(),i=ql(),o=zn(),l=o("iterator"),d=o("toStringTag"),f=i.Array,h={CSSRuleList:!0,CSSStyleDeclaration:!1,CSSValueList:!1,ClientRectList:!1,DOMRectList:!1,DOMStringList:!1,DOMTokenList:!0,DataTransferItemList:!1,FileList:!1,HTMLAllCollection:!1,HTMLCollection:!1,HTMLFormElement:!1,HTMLSelectElement:!1,MediaList:!0,MimeTypeArray:!1,NamedNodeMap:!1,NodeList:!0,PaintRequestList:!1,Plugin:!1,PluginArray:!1,SVGLengthList:!1,SVGNumberList:!1,SVGPathSegList:!1,SVGPointList:!1,SVGStringList:!1,SVGTransformList:!1,SourceBufferList:!1,StyleSheetList:!0,TextTrackCueList:!1,TextTrackList:!1,TouchList:!1},m=e(h),g=0;g<m.length;g++){var v=m[g],b=h[v],k=r[v],w=k&&k.prototype,S;if(w&&(w[l]||s(w,l,f),w[d]||s(w,d,v),i[v]=f,b))for(S in t)w[S]||n(w,S,t[S],!0)}return vS}Iz();N2();var AS={},Ym,RS;function Lz(){if(RS)return Ym;RS=1;var t=xr(),e=ga(),n=ls();return Ym=function(r,s){var i=(e.Object||{})[r]||Object[r],o={};o[r]=s(i),t(t.S+t.F*n(function(){i(1)}),"Object",o)},Ym}var OS;function Dz(){if(OS)return AS;OS=1;var t=Di(),e=Kl();return Lz()("keys",function(){return function(r){return e(t(r))}}),AS}Dz();var Pz=Rt(/[#{invalidCharsGroup}]/,{invalidCharsGroup:Ey});function Bz(t){return Pz.test(t)}var Zi={},Cu={},IS;function $z(){return IS||(IS=1,Object.defineProperty(Cu,"__esModule",{value:!0}),Cu.default=/(?:\ud83d[\udc68\udc69])(?:\ud83c[\udffb-\udfff])?\u200d(?:\u2695\ufe0f|\u2696\ufe0f|\u2708\ufe0f|\ud83c[\udf3e\udf73\udf93\udfa4\udfa8\udfeb\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92]|\ud83e[\uddb0-\uddb3])|(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75]|\u26f9)((?:\ud83c[\udffb-\udfff]|\ufe0f)\u200d[\u2640\u2642]\ufe0f)|(?:\ud83c[\udfc3\udfc4\udfca]|\ud83d[\udc6e\udc71\udc73\udc77\udc81\udc82\udc86\udc87\ude45-\ude47\ude4b\ude4d\ude4e\udea3\udeb4-\udeb6]|\ud83e[\udd26\udd35\udd37-\udd39\udd3d\udd3e\uddb8\uddb9\uddd6-\udddd])(?:\ud83c[\udffb-\udfff])?\u200d[\u2640\u2642]\ufe0f|(?:\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc68|\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d[\udc68\udc69]|\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83c\udff3\ufe0f\u200d\ud83c\udf08|\ud83c\udff4\u200d\u2620\ufe0f|\ud83d\udc41\u200d\ud83d\udde8|\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc6f\u200d\u2640\ufe0f|\ud83d\udc6f\u200d\u2642\ufe0f|\ud83e\udd3c\u200d\u2640\ufe0f|\ud83e\udd3c\u200d\u2642\ufe0f|\ud83e\uddde\u200d\u2640\ufe0f|\ud83e\uddde\u200d\u2642\ufe0f|\ud83e\udddf\u200d\u2640\ufe0f|\ud83e\udddf\u200d\u2642\ufe0f)|[#*0-9]\ufe0f?\u20e3|(?:[©®\u2122\u265f]\ufe0f)|(?:\ud83c[\udc04\udd70\udd71\udd7e\udd7f\ude02\ude1a\ude2f\ude37\udf21\udf24-\udf2c\udf36\udf7d\udf96\udf97\udf99-\udf9b\udf9e\udf9f\udfcd\udfce\udfd4-\udfdf\udff3\udff5\udff7]|\ud83d[\udc3f\udc41\udcfd\udd49\udd4a\udd6f\udd70\udd73\udd76-\udd79\udd87\udd8a-\udd8d\udda5\udda8\uddb1\uddb2\uddbc\uddc2-\uddc4\uddd1-\uddd3\udddc-\uddde\udde1\udde3\udde8\uddef\uddf3\uddfa\udecb\udecd-\udecf\udee0-\udee5\udee9\udef0\udef3]|[\u203c\u2049\u2139\u2194-\u2199\u21a9\u21aa\u231a\u231b\u2328\u23cf\u23ed-\u23ef\u23f1\u23f2\u23f8-\u23fa\u24c2\u25aa\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262a\u262e\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267b\u267f\u2692-\u2697\u2699\u269b\u269c\u26a0\u26a1\u26aa\u26ab\u26b0\u26b1\u26bd\u26be\u26c4\u26c5\u26c8\u26cf\u26d1\u26d3\u26d4\u26e9\u26ea\u26f0-\u26f5\u26f8\u26fa\u26fd\u2702\u2708\u2709\u270f\u2712\u2714\u2716\u271d\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u2764\u27a1\u2934\u2935\u2b05-\u2b07\u2b1b\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299])(?:\ufe0f|(?!\ufe0e))|(?:(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75\udd90]|[\u261d\u26f7\u26f9\u270c\u270d])(?:\ufe0f|(?!\ufe0e))|(?:\ud83c[\udf85\udfc2-\udfc4\udfc7\udfca]|\ud83d[\udc42\udc43\udc46-\udc50\udc66-\udc69\udc6e\udc70-\udc78\udc7c\udc81-\udc83\udc85-\udc87\udcaa\udd7a\udd95\udd96\ude45-\ude47\ude4b-\ude4f\udea3\udeb4-\udeb6\udec0\udecc]|\ud83e[\udd18-\udd1c\udd1e\udd1f\udd26\udd30-\udd39\udd3d\udd3e\uddb5\uddb6\uddb8\uddb9\uddd1-\udddd]|[\u270a\u270b]))(?:\ud83c[\udffb-\udfff])?|(?:\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc77\udb40\udc6c\udb40\udc73\udb40\udc7f|\ud83c\udde6\ud83c[\udde8-\uddec\uddee\uddf1\uddf2\uddf4\uddf6-\uddfa\uddfc\uddfd\uddff]|\ud83c\udde7\ud83c[\udde6\udde7\udde9-\uddef\uddf1-\uddf4\uddf6-\uddf9\uddfb\uddfc\uddfe\uddff]|\ud83c\udde8\ud83c[\udde6\udde8\udde9\uddeb-\uddee\uddf0-\uddf5\uddf7\uddfa-\uddff]|\ud83c\udde9\ud83c[\uddea\uddec\uddef\uddf0\uddf2\uddf4\uddff]|\ud83c\uddea\ud83c[\udde6\udde8\uddea\uddec\udded\uddf7-\uddfa]|\ud83c\uddeb\ud83c[\uddee-\uddf0\uddf2\uddf4\uddf7]|\ud83c\uddec\ud83c[\udde6\udde7\udde9-\uddee\uddf1-\uddf3\uddf5-\uddfa\uddfc\uddfe]|\ud83c\udded\ud83c[\uddf0\uddf2\uddf3\uddf7\uddf9\uddfa]|\ud83c\uddee\ud83c[\udde8-\uddea\uddf1-\uddf4\uddf6-\uddf9]|\ud83c\uddef\ud83c[\uddea\uddf2\uddf4\uddf5]|\ud83c\uddf0\ud83c[\uddea\uddec-\uddee\uddf2\uddf3\uddf5\uddf7\uddfc\uddfe\uddff]|\ud83c\uddf1\ud83c[\udde6-\udde8\uddee\uddf0\uddf7-\uddfb\uddfe]|\ud83c\uddf2\ud83c[\udde6\udde8-\udded\uddf0-\uddff]|\ud83c\uddf3\ud83c[\udde6\udde8\uddea-\uddec\uddee\uddf1\uddf4\uddf5\uddf7\uddfa\uddff]|\ud83c\uddf4\ud83c\uddf2|\ud83c\uddf5\ud83c[\udde6\uddea-\udded\uddf0-\uddf3\uddf7-\uddf9\uddfc\uddfe]|\ud83c\uddf6\ud83c\udde6|\ud83c\uddf7\ud83c[\uddea\uddf4\uddf8\uddfa\uddfc]|\ud83c\uddf8\ud83c[\udde6-\uddea\uddec-\uddf4\uddf7-\uddf9\uddfb\uddfd-\uddff]|\ud83c\uddf9\ud83c[\udde6\udde8\udde9\uddeb-\udded\uddef-\uddf4\uddf7\uddf9\uddfb\uddfc\uddff]|\ud83c\uddfa\ud83c[\udde6\uddec\uddf2\uddf3\uddf8\uddfe\uddff]|\ud83c\uddfb\ud83c[\udde6\udde8\uddea\uddec\uddee\uddf3\uddfa]|\ud83c\uddfc\ud83c[\uddeb\uddf8]|\ud83c\uddfd\ud83c\uddf0|\ud83c\uddfe\ud83c[\uddea\uddf9]|\ud83c\uddff\ud83c[\udde6\uddf2\uddfc]|\ud83c[\udccf\udd8e\udd91-\udd9a\udde6-\uddff\ude01\ude32-\ude36\ude38-\ude3a\ude50\ude51\udf00-\udf20\udf2d-\udf35\udf37-\udf7c\udf7e-\udf84\udf86-\udf93\udfa0-\udfc1\udfc5\udfc6\udfc8\udfc9\udfcf-\udfd3\udfe0-\udff0\udff4\udff8-\udfff]|\ud83d[\udc00-\udc3e\udc40\udc44\udc45\udc51-\udc65\udc6a-\udc6d\udc6f\udc79-\udc7b\udc7d-\udc80\udc84\udc88-\udca9\udcab-\udcfc\udcff-\udd3d\udd4b-\udd4e\udd50-\udd67\udda4\uddfb-\ude44\ude48-\ude4a\ude80-\udea2\udea4-\udeb3\udeb7-\udebf\udec1-\udec5\uded0-\uded2\udeeb\udeec\udef4-\udef9]|\ud83e[\udd10-\udd17\udd1d\udd20-\udd25\udd27-\udd2f\udd3a\udd3c\udd40-\udd45\udd47-\udd70\udd73-\udd76\udd7a\udd7c-\udda2\uddb4\uddb7\uddc0-\uddc2\uddd0\uddde-\uddff]|[\u23e9-\u23ec\u23f0\u23f3\u267e\u26ce\u2705\u2728\u274c\u274e\u2753-\u2755\u2795-\u2797\u27b0\u27bf\ue50a])|\ufe0f/g),Cu}var LS;function Fz(){if(LS)return Zi;LS=1,Object.defineProperty(Zi,"__esModule",{value:!0}),Zi.TypeName=void 0,Zi.parse=s,Zi.toCodePoints=d;var t=$z(),e=n(t);function n(f){return f&&f.__esModule?f:{default:f}}var r=Zi.TypeName="emoji";function s(f,h){var m=h&&h.assetType?h.assetType:"svg",g=h&&h.buildUrl?h.buildUrl:function(S,N){return N==="png"?"https://twemoji.maxcdn.com/2/72x72/"+S+".png":"https://twemoji.maxcdn.com/2/svg/"+S+".svg"},v=[];for(e.default.lastIndex=0;;){var b=e.default.exec(f);if(!b)break;var k=b[0],w=d(l(k)).join("-");v.push({url:w?g(w,m):"",indices:[b.index,e.default.lastIndex],text:k,type:r})}return v}var i=/\uFE0F/g,o="",l=function(h){return h.indexOf(o)<0?h.replace(i,""):h};function d(f){for(var h=[],m=0,g=0,v=0;v<f.length;)m=f.charCodeAt(v++),g?(h.push((65536+(g-55296<<10)+(m-56320)).toString(16)),g=0):m>55296&&m<=56319?g=m:h.push(m.toString(16));return h}return Zi}var zz=Fz(),Uz=function(){for(var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:uS.defaults,r=Object.keys(n).length?n:uS.defaults,s=r.defaultWeight,i=r.emojiParsingEnabled,o=r.scale,l=r.maxWeightedTweetLength,d=r.transformedURLLength,f=typeof String.prototype.normalize=="function"?e.normalize():e,h=DS(uz(f)),m=i?DS(zz.parse(f)):[],g=f.length,v=0,b=0,k=!0,w=0;w<g;w++){if(h[w]){var S=h[w],N=S.url;S.indices,v+=d*o,w+=N.length-1}else if(i&&m[w]){var T=m[w],M=T.text;T.indices,v+=s,w+=M.length-1}else w+=Hz(f,w)?1:0,v+=Cz(f.charAt(w),r);k&&(k=!Bz(f.substring(w,w+1))),k&&v<=l*o&&(b=w)}v=v/o,k=k&&v>0&&v<=l;var _=Math.floor(v/l*1e3),R=e.length-f.length;return b+=R,{weightedLength:v,valid:k,permillage:_,validRangeStart:0,validRangeEnd:b,displayRangeStart:0,displayRangeEnd:e.length>0?e.length-1:0}},DS=function(e){return e.reduce(function(n,r){return n[r.indices[0]]=r,n},{})},Hz=function(e,n){if(n<e.length-1){var r=e.charCodeAt(n),s=e.charCodeAt(n+1);return 55296<=r&&r<=56319&&56320<=s&&s<=57343}return!1},PS={},BS;function Wz(){if(BS)return PS;BS=1;var t=xr();return t(t.S+t.F*!Gr(),"Object",{defineProperty:cs().f}),PS}Wz();var $S={},FS;function Vz(){if(FS)return $S;FS=1;var t=xr();return t(t.S+t.F*!Gr(),"Object",{defineProperties:k2()}),$S}Vz();var zS={},Xm={},US;function Ty(){return US||(US=1,Xm.f=Object.getOwnPropertySymbols),Xm}var Qm,HS;function qz(){if(HS)return Qm;HS=1;var t=hf(),e=Ty(),n=Mr(),r=Kr().Reflect;return Qm=r&&r.ownKeys||function(i){var o=t.f(n(i)),l=e.f;return l?o.concat(l(i)):o},Qm}var Zm,WS;function C2(){if(WS)return Zm;WS=1;var t=cs(),e=Wl();return Zm=function(n,r,s){r in n?t.f(n,r,e(0,s)):n[r]=s},Zm}var VS;function Kz(){if(VS)return zS;VS=1;var t=xr(),e=qz(),n=So(),r=wy(),s=C2();return t(t.S,"Object",{getOwnPropertyDescriptors:function(o){for(var l=n(o),d=r.f,f=e(l),h={},m=0,g,v;f.length>m;)v=d(l,g=f[m++]),v!==void 0&&s(h,g,v);return h}}),zS}Kz();var qS={},eg,KS;function Gz(){if(KS)return eg;KS=1;var t=Ws(),e=Cy(),n=zn()("species");return eg=function(r){var s;return e(r)&&(s=r.constructor,typeof s=="function"&&(s===Array||e(s.prototype))&&(s=void 0),t(s)&&(s=s[n],s===null&&(s=void 0))),s===void 0?Array:s},eg}var tg,GS;function Jz(){if(GS)return tg;GS=1;var t=Gz();return tg=function(e,n){return new(t(e))(n)},tg}var ng,JS;function _2(){if(JS)return ng;JS=1;var t=ff(),e=by(),n=Di(),r=wo(),s=Jz();return ng=function(i,o){var l=i==1,d=i==2,f=i==3,h=i==4,m=i==6,g=i==5||m,v=o||s;return function(b,k,w){for(var S=n(b),N=e(S),T=t(k,w,3),M=r(N.length),_=0,R=l?v(b,M):d?v(b,0):void 0,I,P;M>_;_++)if((g||_ in N)&&(I=N[_],P=T(I,_,S),i)){if(l)R[_]=P;else if(P)switch(i){case 3:return!0;case 5:return I;case 6:return _;case 2:R.push(I)}else if(h)return!1}return m?-1:f||h?h:R}},ng}var YS;function Yz(){if(YS)return qS;YS=1;var t=xr(),e=_2()(0),n=Vl()([].forEach,!0);return t(t.P+t.F*!n,"Array",{forEach:function(s){return e(this,s,arguments[1])}}),qS}Yz();var XS={},QS;function Xz(){if(QS)return XS;QS=1;var t=xr(),e=_2()(2);return t(t.P+t.F*!Vl()([].filter,!0),"Array",{filter:function(r){return e(this,r,arguments[1])}}),XS}Xz();var ZS={},rg={exports:{}},eE;function Qz(){if(eE)return rg.exports;eE=1;var t=Hl()("meta"),e=Ws(),n=ko(),r=cs().f,s=0,i=Object.isExtensible||function(){return!0},o=!ls()(function(){return i(Object.preventExtensions({}))}),l=function(g){r(g,t,{value:{i:"O"+ ++s,w:{}}})},d=function(g,v){if(!e(g))return typeof g=="symbol"?g:(typeof g=="string"?"S":"P")+g;if(!n(g,t)){if(!i(g))return"F";if(!v)return"E";l(g)}return g[t].i},f=function(g,v){if(!n(g,t)){if(!i(g))return!0;if(!v)return!1;l(g)}return g[t].w},h=function(g){return o&&m.NEED&&i(g)&&!n(g,t)&&l(g),g},m=rg.exports={KEY:t,NEED:!1,fastKey:d,getWeak:f,onFreeze:h};return rg.exports}var sg={},tE;function T2(){return tE||(tE=1,sg.f=zn()),sg}var ig,nE;function Zz(){if(nE)return ig;nE=1;var t=Kr(),e=ga(),n=lf(),r=T2(),s=cs().f;return ig=function(i){var o=e.Symbol||(e.Symbol=n?{}:t.Symbol||{});i.charAt(0)!="_"&&!(i in o)&&s(o,i,{value:r.f(i)})},ig}var og,rE;function eU(){if(rE)return og;rE=1;var t=Kl(),e=Ty(),n=xy();return og=function(r){var s=t(r),i=e.f;if(i)for(var o=i(r),l=n.f,d=0,f;o.length>d;)l.call(r,f=o[d++])&&s.push(f);return s},og}var ag={},sE;function tU(){if(sE)return ag;sE=1;var t=So(),e=hf().f,n={}.toString,r=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],s=function(i){try{return e(i)}catch{return r.slice()}};return ag.f=function(o){return r&&n.call(o)=="[object Window]"?s(o):e(t(o))},ag}var iE;function nU(){if(iE)return ZS;iE=1;var t=Kr(),e=ko(),n=Gr(),r=xr(),s=Vs(),i=Qz().KEY,o=ls(),l=cf(),d=_y(),f=Hl(),h=zn(),m=T2(),g=Zz(),v=eU(),b=Cy(),k=Mr(),w=Ws(),S=Di(),N=So(),T=vy(),M=Wl(),_=S2(),R=tU(),I=wy(),P=Ty(),B=cs(),z=Kl(),K=I.f,F=B.f,J=R.f,$=t.Symbol,W=t.JSON,q=W&&W.stringify,ne="prototype",V=h("_hidden"),oe=h("toPrimitive"),Y={}.propertyIsEnumerable,A=l("symbol-registry"),L=l("symbols"),ee=l("op-symbols"),ue=Object[ne],be=typeof $=="function"&&!!P.f,re=t.QObject,we=!re||!re[ne]||!re[ne].findChild,Ee=n&&o(function(){return _(F({},"a",{get:function(){return F(this,"a",{value:7}).a}})).a!=7})?function(ve,Z,je){var Q=K(ue,Z);Q&&delete ue[Z],F(ve,Z,je),Q&&ve!==ue&&F(ue,Z,Q)}:F,$e=function(ve){var Z=L[ve]=_($[ne]);return Z._k=ve,Z},Fe=be&&typeof $.iterator=="symbol"?function(ve){return typeof ve=="symbol"}:function(ve){return ve instanceof $},Ze=function(Z,je,Q){return Z===ue&&Ze(ee,je,Q),k(Z),je=T(je,!0),k(Q),e(L,je)?(Q.enumerable?(e(Z,V)&&Z[V][je]&&(Z[V][je]=!1),Q=_(Q,{enumerable:M(0,!1)})):(e(Z,V)||F(Z,V,M(1,{})),Z[V][je]=!0),Ee(Z,je,Q)):F(Z,je,Q)},Re=function(Z,je){k(Z);for(var Q=v(je=N(je)),he=0,me=Q.length,Ue;me>he;)Ze(Z,Ue=Q[he++],je[Ue]);return Z},tt=function(Z,je){return je===void 0?_(Z):Re(_(Z),je)},gt=function(Z){var je=Y.call(this,Z=T(Z,!0));return this===ue&&e(L,Z)&&!e(ee,Z)?!1:je||!e(this,Z)||!e(L,Z)||e(this,V)&&this[V][Z]?je:!0},ut=function(Z,je){if(Z=N(Z),je=T(je,!0),!(Z===ue&&e(L,je)&&!e(ee,je))){var Q=K(Z,je);return Q&&e(L,je)&&!(e(Z,V)&&Z[V][je])&&(Q.enumerable=!0),Q}},ge=function(Z){for(var je=J(N(Z)),Q=[],he=0,me;je.length>he;)!e(L,me=je[he++])&&me!=V&&me!=i&&Q.push(me);return Q},yt=function(Z){for(var je=Z===ue,Q=J(je?ee:N(Z)),he=[],me=0,Ue;Q.length>me;)e(L,Ue=Q[me++])&&(!je||e(ue,Ue))&&he.push(L[Ue]);return he};be||($=function(){if(this instanceof $)throw TypeError("Symbol is not a constructor!");var Z=f(arguments.length>0?arguments[0]:void 0),je=function(Q){this===ue&&je.call(ee,Q),e(this,V)&&e(this[V],Z)&&(this[V][Z]=!1),Ee(this,Z,M(1,Q))};return n&&we&&Ee(ue,Z,{configurable:!0,set:je}),$e(Z)},s($[ne],"toString",function(){return this._k}),I.f=ut,B.f=Ze,hf().f=R.f=ge,xy().f=gt,P.f=yt,n&&!lf()&&s(ue,"propertyIsEnumerable",gt,!0),m.f=function(ve){return $e(h(ve))}),r(r.G+r.W+r.F*!be,{Symbol:$});for(var Ct="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),_t=0;Ct.length>_t;)h(Ct[_t++]);for(var Lt=z(h.store),at=0;Lt.length>at;)g(Lt[at++]);r(r.S+r.F*!be,"Symbol",{for:function(ve){return e(A,ve+="")?A[ve]:A[ve]=$(ve)},keyFor:function(Z){if(!Fe(Z))throw TypeError(Z+" is not a symbol!");for(var je in A)if(A[je]===Z)return je},useSetter:function(){we=!0},useSimple:function(){we=!1}}),r(r.S+r.F*!be,"Object",{create:tt,defineProperty:Ze,defineProperties:Re,getOwnPropertyDescriptor:ut,getOwnPropertyNames:ge,getOwnPropertySymbols:yt});var De=o(function(){P.f(1)});return r(r.S+r.F*De,"Object",{getOwnPropertySymbols:function(Z){return P.f(S(Z))}}),W&&r(r.S+r.F*(!be||o(function(){var ve=$();return q([ve])!="[null]"||q({a:ve})!="{}"||q(Object(ve))!="{}"})),"JSON",{stringify:function(Z){for(var je=[Z],Q=1,he,me;arguments.length>Q;)je.push(arguments[Q++]);if(me=he=je[1],!(!w(he)&&Z===void 0||Fe(Z)))return b(he)||(he=function(Ue,Oe){if(typeof me=="function"&&(Oe=me.call(this,Ue,Oe)),!Fe(Oe))return Oe}),je[1]=he,q.apply(W,je)}}),$[ne][oe]||Pi()($[ne],oe,$[ne].valueOf),d($,"Symbol"),d(Math,"Math",!0),d(t.JSON,"JSON",!0),ZS}nU();Rt(/^#{validMentionOrList}$/,{validMentionOrList:xz});var j2=/[a-z\u0400-\u04FF0-9\-._~]/i,M2=/(?:%[0-9a-f]{2})/i,A2=/[!$&'()*+,;=]/i,R2=Rt("(?:#{validateUrlUnreserved}|#{validateUrlPctEncoded}|#{validateUrlSubDelims}|:)*",{validateUrlUnreserved:j2,validateUrlPctEncoded:M2,validateUrlSubDelims:A2},"i"),rU=/(?:[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?)/i,sU=/(?:[a-z](?:[a-z0-9\-]*[a-z0-9])?)/i,iU=/(?:[a-z0-9](?:[a-z0-9_\-]*[a-z0-9])?)/i,oU=Rt(/(?:(?:#{validateUrlSubDomainSegment}\.)*(?:#{validateUrlDomainSegment}\.)#{validateUrlDomainTld})/i,{validateUrlSubDomainSegment:iU,validateUrlDomainSegment:rU,validateUrlDomainTld:sU}),aU=/(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9]{2})|(?:2[0-4][0-9])|(?:25[0-5]))/i,lU=Rt(/(?:#{validateUrlDecOctet}(?:\.#{validateUrlDecOctet}){3})/i,{validateUrlDecOctet:aU}),cU=/(?:\[[a-f0-9:\.]+\])/i,O2=Rt("(?:#{validateUrlIpv4}|#{validateUrlIpv6})",{validateUrlIpv4:lU,validateUrlIpv6:cU},"i"),uU=Rt("(?:#{validateUrlIp}|#{validateUrlDomain})",{validateUrlIp:O2,validateUrlDomain:oU},"i"),I2=/[0-9]{1,5}/;Rt("(?:(#{validateUrlUserinfo})@)?(#{validateUrlHost})(?::(#{validateUrlPort}))?",{validateUrlUserinfo:R2,validateUrlHost:uU,validateUrlPort:I2},"i");var jy=Rt("(?:#{validateUrlUnreserved}|#{validateUrlPctEncoded}|#{validateUrlSubDelims}|[:|@])",{validateUrlUnreserved:j2,validateUrlPctEncoded:M2,validateUrlSubDelims:A2},"i");Rt(/(#{validateUrlPchar}|\/|\?)*/i,{validateUrlPchar:jy});Rt(/(\/#{validateUrlPchar}*)*/i,{validateUrlPchar:jy});Rt(/(#{validateUrlPchar}|\/|\?)*/i,{validateUrlPchar:jy});Rt("^(?:([^:/?#]+):\\/\\/)?([^/?#]*)([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$","i");var dU=/(?:(?:[a-z0-9]|[^\u0000-\u007f])(?:(?:[a-z0-9_\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i,fU=/(?:(?:[a-z0-9]|[^\u0000-\u007f])(?:(?:[a-z0-9\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i,hU=/(?:(?:[a-z]|[^\u0000-\u007f])(?:(?:[a-z0-9\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i,pU=Rt(/(?:(?:#{validateUrlUnicodeSubDomainSegment}\.)*(?:#{validateUrlUnicodeDomainSegment}\.)#{validateUrlUnicodeDomainTld})/i,{validateUrlUnicodeSubDomainSegment:dU,validateUrlUnicodeDomainSegment:fU,validateUrlUnicodeDomainTld:hU}),mU=Rt("(?:#{validateUrlIp}|#{validateUrlUnicodeDomain})",{validateUrlIp:O2,validateUrlUnicodeDomain:pU},"i");Rt("(?:(#{validateUrlUserinfo})@)?(#{validateUrlUnicodeHost})(?::(#{validateUrlPort}))?",{validateUrlUserinfo:R2,validateUrlUnicodeHost:mU,validateUrlPort:I2},"i");var oE={},aE;function gU(){if(aE)return oE;aE=1;var t=XT()(!0);return E2()(String,"String",function(e){this._t=String(e),this._i=0},function(){var e=this._t,n=this._i,r;return n>=e.length?{value:void 0,done:!0}:(r=t(e,n),this._i+=r.length,{value:r,done:!1})}),oE}gU();var lE={},lg,cE;function vU(){if(cE)return lg;cE=1;var t=Mr();return lg=function(e,n,r,s){try{return s?n(t(r)[0],r[1]):n(r)}catch(o){var i=e.return;throw i!==void 0&&t(i.call(e)),o}},lg}var cg,uE;function yU(){if(uE)return cg;uE=1;var t=ql(),e=zn()("iterator"),n=Array.prototype;return cg=function(r){return r!==void 0&&(t.Array===r||n[e]===r)},cg}var ug,dE;function bU(){if(dE)return ug;dE=1;var t=py(),e=zn()("iterator"),n=ql();return ug=ga().getIteratorMethod=function(r){if(r!=null)return r[e]||r["@@iterator"]||n[t(r)]},ug}var dg,fE;function xU(){if(fE)return dg;fE=1;var t=zn()("iterator"),e=!1;try{var n=[7][t]();n.return=function(){e=!0},Array.from(n,function(){throw 2})}catch{}return dg=function(r,s){if(!s&&!e)return!1;var i=!1;try{var o=[7],l=o[t]();l.next=function(){return{done:i=!0}},o[t]=function(){return l},r(o)}catch{}return i},dg}var hE;function wU(){if(hE)return lE;hE=1;var t=ff(),e=xr(),n=Di(),r=vU(),s=yU(),i=wo(),o=C2(),l=bU();return e(e.S+e.F*!xU()(function(d){Array.from(d)}),"Array",{from:function(f){var h=n(f),m=typeof this=="function"?this:Array,g=arguments.length,v=g>1?arguments[1]:void 0,b=v!==void 0,k=0,w=l(h),S,N,T,M;if(b&&(v=t(v,g>2?arguments[2]:void 0,2)),w!=null&&!(m==Array&&s(w)))for(M=w.call(h),N=new m;!(T=M.next()).done;k++)o(N,k,b?r(M,v,[T.value,k],!0):T.value);else for(S=i(h.length),N=new m(S);S>k;k++)o(N,k,b?v(h[k],k):h[k]);return N.length=k,N}}),lE}wU();const kU={parseTweet:Uz},{parseTweet:SU}=kU;function pE(t){return SU(t).weightedLength}const mE="ow-x-handle";function EU(){const[t,e]=x.useState(()=>localStorage.getItem(mE)||""),[n,r]=x.useState(!1),[s,i]=x.useState(""),o=x.useRef(null),l=x.useRef(null),d=()=>{const m=s.replace(/^@/,"").trim();m&&(localStorage.setItem(mE,m),e(m)),r(!1)},f=()=>{i(t),r(!0),setTimeout(()=>{var m;return(m=o.current)==null?void 0:m.focus()},0)};x.useEffect(()=>{if(!n)return;const m=g=>{l.current&&!l.current.contains(g.target)&&d()};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[n,s]);const h=t?`https://unavatar.io/twitter/${t}`:"";return c.jsxs("div",{className:"tweet-compose-avatar-wrapper",ref:l,children:[t?c.jsx("img",{className:"tweet-compose-avatar tweet-compose-avatar-img",src:h,alt:`@${t}`,onClick:f,title:`@${t} — click to change`}):c.jsx("div",{className:"tweet-compose-avatar",onClick:f,title:"Set your @handle"}),n&&c.jsx("div",{className:"tweet-handle-popover",children:c.jsx("input",{ref:o,className:"tweet-handle-input",value:s,onChange:m=>i(m.target.value),onKeyDown:m=>{m.key==="Enter"&&d(),m.key==="Escape"&&r(!1)},placeholder:"your_handle",spellCheck:!1})})]})}const NU={tweet:!0,reply:!0,quote:!1};function gE(){return c.jsxs("div",{className:"tweet-skeleton",children:[c.jsxs("div",{className:"tweet-author-row",children:[c.jsx("div",{className:"tweet-avatar tweet-avatar-placeholder tweet-pulse"}),c.jsxs("div",{className:"tweet-author-info",children:[c.jsx("span",{className:"tweet-skeleton-line tweet-pulse",style:{width:120}}),c.jsx("span",{className:"tweet-skeleton-line tweet-pulse",style:{width:80}})]})]}),c.jsx("div",{className:"tweet-skeleton-line tweet-pulse",style:{width:"100%",height:16,marginTop:12}}),c.jsx("div",{className:"tweet-skeleton-line tweet-pulse",style:{width:"75%",height:16,marginTop:8}})]})}function CU(t){var e;if(t)return(e=t.match(/\/status\/(\d+)/))==null?void 0:e[1]}function _u(t){if(!t)return[null];if(typeof t=="string"){const e=t.split(/<hr\s*\/?>/i).map(n=>n.trim()).filter(Boolean);return e.length?e:[null]}if((t==null?void 0:t.type)==="doc"&&Array.isArray(t.content)){const e=[[]];for(const r of t.content)r.type==="horizontalRule"?e.push([]):e[e.length-1].push(r);const n=e.map(r=>r.length?{type:"doc",content:r}:null).filter(Boolean);return n.length?n:[null]}return[t]}function Tu(t){var n;if(!t||typeof t=="string"||!t.content)return[];const e=[];for(let r=t.content.length-1;r>=0&&(t.content[r].type==="image"&&((n=t.content[r].attrs)!=null&&n.src));r--)e.unshift(t.content[r].attrs.src);return e}function vE(t,e){if(!t||typeof t=="string"||!t.content||e===0)return t;const n=t.content.slice(0,t.content.length-e);return n.length===0?{type:"doc",content:[{type:"paragraph",content:[]}]}:{...t,content:n}}function ju(t,e){const n=[];let r=0;return t.forEach((s,i)=>{if(!s)return;r>0&&n.push({type:"horizontalRule"});const o=s.getJSON();o.content&&n.push(...o.content);const l=e==null?void 0:e[i];if(l)for(const d of l){const f=crypto.randomUUID().replace(/-/g,"").slice(0,8);n.push({type:"image",attrs:{src:d,id:f}})}r++}),{type:"doc",content:n}}function yE(t,e){const n=[],r=s=>{var i;s.type==="image"&&((i=s.attrs)!=null&&i.src)&&n.push(s.attrs.src),s.content&&s.content.forEach(r)};return r(t.getJSON()),e&&n.push(...e),n.slice(0,4)}function Mu(t){fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tweetContext:t}),keepalive:!0}).catch(()=>{})}function _U({tweetContext:t,initialContent:e,onUpdate:n,onEditorReady:r,onEditorsChange:s,onActiveEditorChange:i,filename:o,title:l,autoplug:d}){var Et;const{tweet:f,loading:h,error:m}=mF(t==null?void 0:t.url),[g,v]=x.useState(()=>_u(e).map(Ne=>{const Ke=Tu(Ne);return vE(Ne,Ke.length)})),[b,k]=x.useState(0),w=x.useRef([]),S=x.useRef(null),N=x.useRef(!0),T=x.useRef(!1),M=x.useRef(g.length),[_,R]=x.useState(()=>g.map(()=>0)),[I,P]=x.useState(0),[B,z]=x.useState(0),K=x.useRef(_u(e).map(_e=>Tu(_e))),[F,J]=x.useState(()=>_u(e).map(Ne=>Tu(Ne).length)),[$,W]=x.useState(null),[q,ne]=x.useState(),[V,oe]=x.useState(!1),[Y,A]=x.useState("idle"),[L,ee]=x.useState(""),ue=x.useRef(),{copyText:be,copyState:re}=bF(w,I),[we,Ee]=x.useState(!1),$e=NU[(t==null?void 0:t.mode)??"tweet"],Fe=!!((Et=t==null?void 0:t.lastPost)!=null&&Et.postedAt),[Ze,Re]=x.useState(!1),[tt,gt]=x.useState(""),ut=x.useRef(null),ge=x.useRef(null);x.useEffect(()=>{if(!Ze)return;setTimeout(()=>{var Ne;return(Ne=ut.current)==null?void 0:Ne.focus()},0);const _e=Ne=>{ge.current&&!ge.current.contains(Ne.target)&&(Re(!1),gt(""))};return document.addEventListener("mousedown",_e),()=>document.removeEventListener("mousedown",_e)},[Ze]);const yt=()=>{var st;const _e=tt.trim();if(!(!_e||_e.includes("x.com")||_e.includes("twitter.com")))return;const Ke=(st=t==null?void 0:t.lastPost)==null?void 0:st.postedAt;Mu({lastPost:{postedAt:Ke??new Date().toISOString(),tweetUrl:_e||void 0}}),Re(!1),gt("")},Ct=()=>{Mu({lastPost:null})},_t=d!==!1,Lt=()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoplug:!_t}),keepalive:!0}).catch(()=>{})};x.useEffect(()=>{let _e=!1;return(async()=>{try{const Ne=await fetch("/api/x/status");if(_e)return;if(Ne.ok){const Ke=await Ne.json();W(Ke.connected),ne(Ke.username)}else W(!1)}catch{_e||W(!1)}})(),()=>{_e=!0}},[]),x.useEffect(()=>{if(N.current){N.current=!1;return}if(!e||JSON.stringify(e)===S.current)return;const Ne=_u(e),Ke=Ne.map(Ye=>Tu(Ye)),st=Ne.map((Ye,jt)=>vE(Ye,Ke[jt].length));T.current=!0,M.current=st.length,w.current=[],K.current=Ke,v(st),R(st.map(()=>0)),J(Ke.map(Ye=>Ye.length)),k(Ye=>Ye+1)},[e]);const at=x.useCallback((_e,Ne)=>{if(w.current[_e]=Ne,R(st=>{const Ye=[...st];return Ye[_e]=pE(Ne.getText()),Ye}),T.current)return;const Ke=ju(w.current,K.current);S.current=JSON.stringify(Ke),n==null||n(Ke)},[n]),De=x.useCallback((_e,Ne)=>{if(w.current[_e]=Ne,R(Ke=>{const st=[...Ke];return st[_e]=pE(Ne.getText()),st}),z(Ke=>Ke+1),T.current&&w.current.filter(Boolean).length>=M.current){T.current=!1;const st=ju(w.current,K.current);S.current=JSON.stringify(st)}_e===0&&(r==null||r(Ne)),s==null||s(w.current.filter(Boolean))},[r,s]),ve=g.length>1;_.reduce((_e,Ne)=>_e+Ne,0);const Z=x.useCallback(()=>{const _e=I+1;v(Ne=>[...Ne.slice(0,_e),"<p></p>",...Ne.slice(_e)]),R(Ne=>[...Ne.slice(0,_e),0,...Ne.slice(_e)]),K.current.splice(_e,0,[]),J(Ne=>[...Ne.slice(0,_e),0,...Ne.slice(_e)]),P(_e)},[I]),je=x.useCallback(_e=>{_e!==0&&(w.current.splice(_e,1),K.current.splice(_e,1),v(Ne=>Ne.filter((Ke,st)=>st!==_e)),R(Ne=>Ne.filter((Ke,st)=>st!==_e)),J(Ne=>Ne.filter((Ke,st)=>st!==_e)),setTimeout(()=>{const Ne=ju(w.current,K.current);n==null||n(Ne),s==null||s(w.current.filter(Boolean))},0))},[n,s]),Q=!!(t!=null&&t.url),he=(t==null?void 0:t.mode)==="reply",me=(()=>{const Ne=w.current.filter(Boolean).some(st=>st.getText().trim()||yE(st).length>0),Ke=F.some(st=>st>0);return Ne||Ke})(),Ue=$&&me&&Y==="idle",Oe=async()=>{if(!$){oe(!0);return}if(Ue){A("uploading"),ee("");try{const _e=[];for(let Ke=0;Ke<w.current.length;Ke++){const st=w.current[Ke];if(!st)continue;const Ye=st.getText().trim(),jt=yE(st,K.current[Ke]);if(!Ye&&jt.length===0)continue;const j=[];for(const U of jt){const D=await(await fetch("/api/x/upload-media",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({src:U})})).json();if(!D.success)throw new Error(D.error||"Image upload failed");j.push(D.mediaId)}_e.push({text:Ye,mediaIds:j})}if(_e.length===0)return;A("posting");const Ne=CU(t==null?void 0:t.url);if(_e.length===1){const Ke={};_e[0].text&&(Ke.text=_e[0].text),_e[0].mediaIds.length>0&&(Ke.mediaIds=_e[0].mediaIds),(t==null?void 0:t.mode)==="reply"&&Ne?Ke.replyTo=Ne:(t==null?void 0:t.mode)==="quote"&&Ne&&(Ke.quoteTweetId=Ne);const Ye=await(await fetch("/api/x/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ke)})).json();Ye.success?(Mu({lastPost:{postedAt:new Date().toISOString(),tweetUrl:Ye.tweetUrl}}),A("success"),ue.current=setTimeout(()=>A("idle"),2500)):(console.error("[TweetCompose] Post error:",Ye.error),ee(Ye.error||"Post failed"),A("error"),setTimeout(()=>A("idle"),3e3))}else{const st={tweets:_e.map(j=>({text:j.text,...j.mediaIds.length>0?{mediaIds:j.mediaIds}:{}}))};(t==null?void 0:t.mode)==="reply"&&Ne&&(st.replyTo=Ne);const jt=await(await fetch("/api/x/post-thread",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(st)})).json();jt.success?(Mu({lastPost:{postedAt:new Date().toISOString(),tweetUrl:jt.threadUrl}}),A("success"),ue.current=setTimeout(()=>A("idle"),2500)):(ee(jt.error||"Thread post failed"),A("error"),setTimeout(()=>A("idle"),3e3))}}catch(_e){ee(_e.message||"Network error"),A("error"),setTimeout(()=>A("idle"),3e3)}}};x.useEffect(()=>()=>{ue.current&&clearTimeout(ue.current)},[]);const Ve=()=>{W(!0),oe(!1),fetch("/api/x/status").then(_e=>_e.json()).then(_e=>{_e.username&&ne(_e.username)}).catch(()=>{})},et=Y==="uploading"?"Uploading...":Y==="posting"?"Posting...":Y==="success"?"Posted!":Y==="error"?"Failed":ve?I===0?"Post Thread":"Post All":"Post",ft=g.map((_e,Ne)=>Ne===0?he?"Post your reply":"What is happening?!":"Add another tweet"),We=_e=>{var Ne;return c.jsxs("div",{className:`tweet-compose-footer${_e?" tweet-compose-footer--inline":""}`,children:[I===0&&((Ne=t==null?void 0:t.lastPost)==null?void 0:Ne.postedAt)&&c.jsxs("a",{className:"tweet-posted-status",href:t.lastPost.tweetUrl,target:"_blank",rel:"noopener noreferrer",title:t.lastPost.tweetUrl||"Posted to X",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Posted ",new Date(t.lastPost.postedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})]}),Y==="error"&&L&&c.jsx("span",{className:"tweet-post-error",children:L}),ve&&c.jsxs("span",{className:"tweet-thread-counter",children:[I+1,"/",g.length]}),c.jsx(_F,{count:_[I]||0}),c.jsx("button",{className:"tweet-thread-add",onClick:Z,title:"Add another tweet",children:c.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:[c.jsx("line",{x1:"10",y1:"4",x2:"10",y2:"16",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),c.jsx("line",{x1:"4",y1:"10",x2:"16",y2:"10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})}),c.jsx("button",{className:`tweet-copy-btn${re==="copied"?" tweet-copy-btn--copied":""}`,disabled:!me,onClick:be,title:"Copy tweet text to clipboard",children:re==="copied"?c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:c.jsx("path",{d:"M3 8.5L6.5 12L13 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Copied!"]}):c.jsxs(c.Fragment,{children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[c.jsx("rect",{x:"5.5",y:"2",width:"8.5",height:"10.5",rx:"1.5",stroke:"currentColor",strokeWidth:"1.5"}),c.jsx("path",{d:"M3.5 5H2.5A1.5 1.5 0 001 6.5V13a1.5 1.5 0 001.5 1.5H9A1.5 1.5 0 0010.5 13v-1",stroke:"currentColor",strokeWidth:"1.5"})]}),"Copy"]})}),I===0&&!$e&&(()=>{var Ye;const Ke=((Ye=t==null?void 0:t.lastPost)==null?void 0:Ye.tweetUrl)??"",st=()=>{if(Fe){Ct(),Re(!1),gt("");return}gt(Ke),Re(!0)};return c.jsxs("div",{className:"tweet-mark-sent-wrap",ref:ge,children:[c.jsx("button",{className:`tweet-mark-sent-btn${Fe?" tweet-mark-sent-btn--done":""}`,onClick:st,title:Fe?Ke?`Posted — click to unmark (${Ke})`:"Posted — click to unmark":"Mark as manually posted",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:Fe?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("polyline",{points:"8 12 11 15 16 9",stroke:Fe?"#fff":"currentColor"})]})}),Ze&&(()=>{const jt=tt.trim(),j=!jt||jt.includes("x.com")||jt.includes("twitter.com");return c.jsxs("div",{className:"tweet-mark-sent-url",children:[c.jsx("input",{ref:ut,type:"text",placeholder:"Paste posted tweet URL...",value:tt,onChange:U=>gt(U.target.value),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),yt()),U.key==="Escape"&&(Re(!1),gt(""))}}),c.jsx("button",{onClick:yt,disabled:!j,title:jt?"Save URL":"Mark posted without URL",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})})]})})()]})})(),c.jsx("button",{className:`tweet-autoplug-toggle${_t?" tweet-autoplug-toggle--on":""}`,onClick:Lt,title:_t?"Auto-plug ON — engagement autoplugs may reply to this post with your configured promo. Click to opt out.":"Auto-plug OFF — this post is excluded from autoplugs. Click to opt in.",children:_t?"Auto-plug on":"Auto-plug off"}),o&&!Fe&&c.jsx("button",{className:"tweet-schedule-btn",onClick:()=>Ee(!0),title:"Schedule post",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("polyline",{points:"12 6 12 12 16 14"})]})}),$e&&c.jsx("button",{className:`tweet-post-btn${Ue||!$&&$!==null?" tweet-post-btn--active":""}${Y==="success"?" tweet-post-btn--success":""}${Y==="error"?" tweet-post-btn--error":""}`,disabled:$?!Ue:!1,onClick:Oe,title:$?q?`Post as @${q}`:"Post to X":"Connect X to post",children:et})]})},Ge=Q&&!he,vt=()=>c.jsx("div",{className:"tweet-thread-editors",children:g.map((_e,Ne)=>c.jsxs("div",{className:`tweet-thread-item${Ne===I?" tweet-thread-item--active":" tweet-thread-item--inactive"}`,children:[c.jsxs("div",{className:"tweet-thread-item-left",children:[c.jsx(EU,{}),Ne<g.length-1&&c.jsx("div",{className:"tweet-thread-line"})]}),c.jsxs("div",{className:"tweet-thread-item-right",children:[Ne>0&&c.jsx("button",{className:"tweet-thread-remove",onClick:()=>je(Ne),title:"Remove this tweet",children:"×"}),c.jsx("div",{className:`tweet-compose-box${Ne===0&&!ve?" tweet-compose-box--standalone":""}`,children:c.jsx(CF,{initialContent:_e,initialPreviewImages:K.current[Ne],placeholder:ft[Ne],onUpdate:Ke=>at(Ne,Ke),onReady:Ke=>De(Ne,Ke),onFocus:()=>{P(Ne);const Ke=w.current[Ne];Ke&&(i==null||i(Ke))},onPreviewImagesChange:Ke=>{if(K.current[Ne]=Ke,J(st=>{const Ye=[...st];return Ye[Ne]=Ke.length,Ye}),!T.current){const st=ju(w.current,K.current);S.current=JSON.stringify(st),n==null||n(st)}}})}),Ne===I&&!Ge&&We(Ne<g.length-1)]})]},`${b}-${Ne}`))});return c.jsxs("div",{className:"tweet-compose-wrapper",children:[Q&&he&&c.jsxs(c.Fragment,{children:[h&&c.jsx("div",{className:"tweet-context-section",children:c.jsx(gE,{})}),m&&c.jsx("div",{className:"tweet-context-section",children:c.jsxs("div",{className:"tweet-embed-error",children:[c.jsx("span",{children:"Could not load tweet"}),c.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",className:"tweet-fallback-link",children:t.url})]})}),f&&c.jsxs("div",{className:"tweet-reply-parent-section",children:[c.jsx("div",{className:"tweet-reply-parent-card",children:c.jsx(zk,{tweet:f,url:t==null?void 0:t.url})}),c.jsxs("div",{className:"tweet-replying-to",children:["Replying to ",c.jsxs("span",{className:"tweet-reply-handle",children:["@",f.author.username]})]})]}),vt()]}),Ge&&c.jsxs(c.Fragment,{children:[vt(),c.jsxs("div",{className:"tweet-quote-section",style:{padding:"0 16px 12px"},children:[h&&c.jsx(gE,{}),m&&c.jsxs("div",{className:"tweet-embed-error",children:[c.jsx("span",{children:"Could not load tweet"}),c.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",className:"tweet-fallback-link",children:t.url})]}),f&&c.jsx(zk,{tweet:f,url:t==null?void 0:t.url})]}),c.jsx("div",{className:"tweet-quote-footer",children:We()})]}),!Q&&vt(),V&&c.jsx(TF,{onConnected:Ve,onCancel:()=>oe(!1)}),we&&o&&c.jsx(Ul,{filename:o,title:l||"Untitled",onClose:()=>Ee(!1)})]})}function TU(){const[t,e]=x.useState("idle"),n=x.useRef();return{copyAsHtml:x.useCallback(async()=>{const s=document.querySelector(".ProseMirror");if(!s)return;const i=s.cloneNode(!0);i.querySelectorAll(".ProseMirror-widget, [data-widget], .ProseMirror-gapcursor").forEach(h=>h.remove());let o="";const l=document.querySelector(".article-title-input");l!=null&&l.value&&l.value!=="Untitled"&&(o+=`<h1>${l.value}</h1>
|
|
213
|
+
`);const d=o+i.innerHTML,f=jU(i);try{const h=new ClipboardItem({"text/html":new Blob([d],{type:"text/html"}),"text/plain":new Blob([f],{type:"text/plain"})});await navigator.clipboard.write([h])}catch{try{await navigator.clipboard.writeText(f)}catch{const h=document.createElement("textarea");h.value=f,h.style.position="fixed",h.style.opacity="0",document.body.appendChild(h),h.select(),document.execCommand("copy"),document.body.removeChild(h)}}e("copied"),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>e("idle"),2e3)},[]),copyState:t}}function jU(t){var n;const e=[];for(const r of t.children){const s=(n=r.innerText)==null?void 0:n.trim();s&&e.push(s)}return e.join(`
|
|
214
214
|
|
|
215
|
-
`)}function L2(t,e){const n=x.useRef(null),r=x.useCallback(()=>{const o=n.current;o&&(o.style.height="auto",o.style.height=`${o.scrollHeight}px`)},[]);x.useLayoutEffect(()=>{r()},[t,r]);const s=x.useCallback(o=>{e(o.target.value.replace(/[\r\n]+/g," ")),r()},[e,r]),i=x.useCallback(o=>{var l;o.key==="Enter"&&(o.preventDefault(),(l=n.current)==null||l.blur())},[]);return{ref:n,onChange:s,onKeyDown:i}}function D2({pendingTitle:t,docId:e,baseClass:n,children:r}){const[s,i]=x.useState(!1),[o,l]=x.useState(!1);return x.useEffect(()=>{function d(f){const h=f.detail;h&&(e&&h.docId&&h.docId!==e||(i(!!h.titleFocused),l(!!h.titleShowOriginal)))}return window.addEventListener("ow-pending-review-cursor",d),()=>window.removeEventListener("ow-pending-review-cursor",d)},[e]),t?o?c.jsx("div",{className:`${n} ${n}--pending${s?" pending-active pending-active--original":""}`,title:`Showing original title. Toggle back to Modified to see the agent's proposal "${t.to}".`,"aria-label":`Original title ${t.from} (agent proposed ${t.to})`,children:c.jsx("span",{className:"pending-original",children:t.from})}):c.jsx("div",{className:`${n} ${n}--pending${s?" pending-active pending-active--insert":""}`,title:`Agent proposed rename from "${t.from}". Accept or reject in the Review panel.`,"aria-label":`Pending title rename from ${t.from} to ${t.to}`,children:c.jsx("span",{className:"pending-insert",children:t.to})}):c.jsx(c.Fragment,{children:r})}const fg="ow-x-handle",bE="ow-x-name",jU=new Set(["Untitled","New Document","Article"]);function MU({src:t,coverImages:e}){const[n,r]=x.useState(t?"display":"empty"),[s,i]=x.useState(t||""),[o,l]=x.useState(e||(t?[t]:[])),[d,f]=x.useState(""),[h,m]=x.useState(""),g=x.useRef(null);x.useEffect(()=>{t?(i(t),r("display")):e&&e.length>0?(i(e[0]),r("display")):(i(""),r("empty"),f(""),m(""))},[t,e]),x.useEffect(()=>{e&&e.length>0?l(e):l(t?[t]:[])},[e]);const v=s?o.indexOf(s):-1,b=o.length,k=b>1,w=x.useCallback(B=>{const z=o[B];z&&(i(z),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({articleContext:{coverImage:z,coverImages:o}})}).catch(()=>{}))},[o]),S=x.useCallback(()=>{v>0&&w(v-1)},[v,w]),N=x.useCallback(()=>{v<b-1&&w(v+1)},[v,b,w]),T=x.useCallback(async()=>{if(d.trim()){r("loading"),m("");try{const B=await fetch("/api/image-gen/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:d.trim()})});if(!B.ok){const K=await B.json().catch(()=>null);m((K==null?void 0:K.error)||`Generation failed (${B.status})`),r("prompt");return}const z=await B.json();if(z.success&&z.src){const K=[...o,z.src];l(K),i(z.src),r("display"),f(""),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({articleContext:{coverImage:z.src,coverImages:K}})}).catch(()=>{})}else m(z.error||"Generation failed"),r("prompt")}catch(B){m(B.message||"Network error"),r("prompt")}}},[d,o]),M=B=>{B.key==="Enter"&&T(),B.key==="Escape"&&(r("empty"),f(""),m(""))},_=()=>{r("prompt"),setTimeout(()=>{var B;return(B=g.current)==null?void 0:B.focus()},0)},R=()=>{const B=o.filter(z=>z!==s);if(l(B),B.length>0){const z=Math.min(v,B.length-1),K=B[z];i(K),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({articleContext:{coverImage:K,coverImages:B}})}).catch(()=>{})}else i(""),r("empty"),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({articleContext:{coverImage:null,coverImages:null}})}).catch(()=>{})},I=()=>{r("prompt"),setTimeout(()=>{var B;return(B=g.current)==null?void 0:B.focus()},0)},P=()=>{const B=document.createElement("a");B.href=s,B.download=`cover-${v+1}.png`,B.click()};return n==="display"&&s?c.jsxs("div",{className:"article-cover article-cover--display",children:[c.jsx("img",{className:"article-cover-img",src:s,alt:"Cover"}),c.jsxs("div",{className:"article-cover-overlay",children:[k&&c.jsx("button",{className:"article-cover-arrow article-cover-arrow--left",onClick:S,disabled:v<=0,children:c.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"15 18 9 12 15 6"})})}),c.jsxs("div",{className:"article-cover-overlay-center",children:[c.jsxs("button",{className:"article-cover-overlay-btn",onClick:I,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"23 4 23 10 17 10"}),c.jsx("polyline",{points:"1 20 1 14 7 14"}),c.jsx("path",{d:"M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15"})]}),"Regenerate"]}),c.jsxs("button",{className:"article-cover-overlay-btn",onClick:P,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),c.jsx("polyline",{points:"7 10 12 15 17 10"}),c.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),"Save"]}),c.jsxs("button",{className:"article-cover-overlay-btn article-cover-overlay-btn--danger",onClick:R,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),"Remove"]})]}),k&&c.jsx("button",{className:"article-cover-arrow article-cover-arrow--right",onClick:N,disabled:v>=b-1,children:c.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})}),k&&c.jsxs("div",{className:"article-cover-counter",children:[v+1," / ",b]})]})]}):n==="loading"?c.jsxs("div",{className:"article-cover article-cover--loading",children:[c.jsx("div",{className:"article-cover-spinner"}),c.jsx("span",{className:"article-cover-loading-text",children:"Generating cover image..."})]}):n==="prompt"?c.jsxs("div",{className:"article-cover article-cover--prompt",children:[c.jsxs("div",{className:"article-cover-prompt-row",children:[c.jsx("input",{ref:g,className:"article-cover-prompt-input",value:d,onChange:B=>f(B.target.value),onKeyDown:M,placeholder:"Describe your cover image...",spellCheck:!1}),c.jsx("button",{className:"article-cover-prompt-btn",onClick:T,disabled:!d.trim(),children:"Generate"}),c.jsx("button",{className:"article-cover-prompt-cancel",onClick:()=>{r(s?"display":"empty"),f(""),m("")},children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),h&&c.jsx("div",{className:"article-cover-error",children:h})]}):c.jsxs("div",{className:"article-cover article-cover--empty",onClick:_,children:[c.jsxs("svg",{className:"article-cover-icon",width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),c.jsx("polyline",{points:"21 15 16 10 5 21"})]}),c.jsx("span",{className:"article-cover-hint",children:"We recommend an image with a 5:2 aspect ratio for best results."})]})}function AU(){const[t,e]=x.useState(()=>localStorage.getItem(fg)||""),[n,r]=x.useState(()=>localStorage.getItem(bE)||""),[s,i]=x.useState(!1),[o,l]=x.useState(""),d=x.useRef(null),f=x.useRef(null),h=()=>{const b=o.replace(/^@/,"").trim();b&&(localStorage.setItem(fg,b),e(b)),i(!1)},m=()=>{l(t),i(!0),setTimeout(()=>{var b;return(b=d.current)==null?void 0:b.focus()},0)};x.useEffect(()=>{if(!s)return;const b=k=>{f.current&&!f.current.contains(k.target)&&h()};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[s,o]),x.useEffect(()=>{const b=()=>{e(localStorage.getItem(fg)||""),r(localStorage.getItem(bE)||"")};return window.addEventListener("storage",b),()=>window.removeEventListener("storage",b)},[]);const g=t?`https://unavatar.io/twitter/${t}`:"",v=n||t||"Set your @handle";return c.jsxs("div",{className:"article-byline",ref:f,children:[c.jsxs("div",{className:"article-byline-row",onClick:m,title:t?`@${t} — click to change`:"Set your @handle",children:[t?c.jsx("img",{className:"article-byline-avatar",src:g,alt:`@${t}`}):c.jsx("div",{className:"article-byline-avatar article-byline-avatar--empty"}),c.jsx("span",{className:"article-byline-name",children:v}),t&&c.jsxs("span",{className:"article-byline-handle",children:["@",t]})]}),s&&c.jsx("div",{className:"article-byline-popover",children:c.jsx("input",{ref:d,className:"article-byline-input",value:o,onChange:b=>l(b.target.value),onKeyDown:b=>{b.key==="Enter"&&h(),b.key==="Escape"&&i(!1)},placeholder:"your_handle",spellCheck:!1})})]})}function RU({children:t,title:e,onTitleChange:n,coverImage:r,coverImages:s,lastPost:i,pendingTitle:o,docId:l,autoplug:d}){const{copyAsHtml:f,copyState:h}=_U(),[m,g]=x.useState(i?"done":"idle"),v=jU.has(e||"")?"":e||"",b=L2(v,z=>n==null?void 0:n(z||"Untitled")),[k,w]=x.useState(!1),[S,N]=x.useState(""),T=x.useRef(null),M=x.useRef(null);x.useEffect(()=>{g(i?"done":"idle")},[i]),x.useEffect(()=>{if(!k)return;setTimeout(()=>{var K;return(K=T.current)==null?void 0:K.focus()},0);const z=K=>{M.current&&!M.current.contains(K.target)&&(w(!1),N(""))};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[k]);const _=x.useCallback(()=>{const z=S.trim();if(!(!z||z.includes("x.com")||z.includes("twitter.com")))return;const F=(i==null?void 0:i.postedAt)??new Date().toISOString();fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({articleContext:{lastPost:z?{postedAt:F,tweetUrl:z}:{postedAt:F}}}),keepalive:!0}).catch(()=>{}),g("done"),w(!1),N("")},[S,i==null?void 0:i.postedAt]),R=x.useCallback(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({articleContext:{lastPost:null}}),keepalive:!0}).catch(()=>{}),g("idle")},[]),I=d!==!1,P=()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoplug:!I}),keepalive:!0}).catch(()=>{})},B=x.useCallback(()=>{if(m==="done"){R(),w(!1),N("");return}N((i==null?void 0:i.tweetUrl)??""),w(!0)},[m,i==null?void 0:i.tweetUrl,R]);return c.jsxs("div",{className:"article-compose-wrapper",children:[c.jsx(MU,{src:r,coverImages:s}),c.jsxs("div",{className:"article-compose-content",children:[c.jsx(D2,{pendingTitle:o,docId:l,baseClass:"article-title-input",children:c.jsx("textarea",{className:"article-title-input",ref:b.ref,value:v,onChange:b.onChange,onKeyDown:b.onKeyDown,placeholder:"Add a title",rows:1,spellCheck:!1})}),c.jsx(AU,{}),c.jsx("div",{className:"article-compose-body",children:t})]}),c.jsxs("div",{className:"article-compose-footer",children:[c.jsxs("div",{className:"article-mark-sent-wrap",ref:M,children:[c.jsx("button",{className:`article-mark-sent-btn${m==="done"?" article-mark-sent-btn--done":""}`,onClick:B,title:m==="done"?i!=null&&i.tweetUrl?`Posted — click to unmark (${i.tweetUrl})`:"Posted — click to unmark":"Mark as manually posted",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:m==="done"?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("polyline",{points:"8 12 11 15 16 9",stroke:m==="done"?"#fff":"currentColor"})]})}),k&&(()=>{const z=S.trim(),K=!z||z.includes("x.com")||z.includes("twitter.com");return c.jsxs("div",{className:"article-mark-sent-url",children:[c.jsx("input",{ref:T,type:"text",placeholder:"Paste posted tweet URL...",value:S,onChange:F=>N(F.target.value),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),_()),F.key==="Escape"&&(w(!1),N(""))}}),c.jsx("button",{onClick:_,disabled:!K,title:z?"Save URL":"Mark posted without URL",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})})]})})()]}),c.jsx("button",{className:`article-autoplug-toggle${I?" article-autoplug-toggle--on":""}`,onClick:P,title:I?"Auto-plug ON — engagement autoplugs may reply to this post with your configured promo. Click to opt out.":"Auto-plug OFF — this post is excluded from autoplugs. Click to opt in.",children:I?"Auto-plug on":"Auto-plug off"}),m==="done"&&i&&(i.tweetUrl?c.jsxs("a",{className:"article-sent-status",href:i.tweetUrl,target:"_blank",rel:"noopener noreferrer",children:["Posted ",new Date(i.postedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})]}):c.jsxs("span",{className:"article-sent-status",children:["Posted ",new Date(i.postedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})]})),c.jsx("button",{className:`article-copy-btn${h==="copied"?" article-copy-btn--copied":""}`,onClick:f,children:h==="copied"?c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Copied!"]}):c.jsxs(c.Fragment,{children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),c.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),"Copy as HTML"]})})]})]})}const xE=new Set(["Untitled","New Document","Blog"]),OU=[];function IU(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}function wE(){return new Date().toISOString().split("T")[0]}function io(t){fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({blogContext:t})}).catch(()=>{})}function LU({src:t,coverImages:e}){const[n,r]=x.useState(t?"display":"empty"),[s,i]=x.useState(t||""),[o,l]=x.useState(e||(t?[t]:[])),[d,f]=x.useState(""),[h,m]=x.useState(""),g=x.useRef(null);x.useEffect(()=>{t?(i(t),r("display")):(i(""),r("empty"),f(""),m(""))},[t]),x.useEffect(()=>{e&&e.length>0?l(e):l(t?[t]:[])},[e]);const v=s?o.indexOf(s):-1,b=o.length,k=b>1,w=x.useCallback(B=>{const z=o[B];z&&(i(z),io({coverImage:z,coverImages:o}))},[o]),S=x.useCallback(()=>{v>0&&w(v-1)},[v,w]),N=x.useCallback(()=>{v<b-1&&w(v+1)},[v,b,w]),T=x.useCallback(async()=>{if(d.trim()){r("loading"),m("");try{const B=await fetch("/api/image-gen/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:d.trim()})});if(!B.ok){const K=await B.json().catch(()=>null);m((K==null?void 0:K.error)||`Generation failed (${B.status})`),r("prompt");return}const z=await B.json();if(z.success&&z.src){const K=[...o,z.src];l(K),i(z.src),r("display"),f(""),io({coverImage:z.src,coverImages:K})}else m(z.error||"Generation failed"),r("prompt")}catch(B){m(B.message||"Network error"),r("prompt")}}},[d,o]),M=B=>{B.key==="Enter"&&T(),B.key==="Escape"&&(r("empty"),f(""),m(""))},_=()=>{r("prompt"),setTimeout(()=>{var B;return(B=g.current)==null?void 0:B.focus()},0)},R=()=>{const B=o.filter(z=>z!==s);if(l(B),B.length>0){const z=Math.min(v,B.length-1),K=B[z];i(K),io({coverImage:K,coverImages:B})}else i(""),r("empty"),io({coverImage:void 0,coverImages:void 0})},I=()=>{r("prompt"),setTimeout(()=>{var B;return(B=g.current)==null?void 0:B.focus()},0)},P=()=>{const B=document.createElement("a");B.href=s,B.download=`cover-${v+1}.png`,B.click()};return n==="display"&&s?c.jsxs("div",{className:"blog-cover blog-cover--display",children:[c.jsx("img",{className:"blog-cover-img",src:s,alt:"Cover"}),c.jsxs("div",{className:"blog-cover-overlay",children:[k&&c.jsx("button",{className:"blog-cover-arrow blog-cover-arrow--left",onClick:S,disabled:v<=0,children:c.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"15 18 9 12 15 6"})})}),c.jsxs("div",{className:"blog-cover-overlay-center",children:[c.jsxs("button",{className:"blog-cover-btn",onClick:I,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"23 4 23 10 17 10"}),c.jsx("polyline",{points:"1 20 1 14 7 14"}),c.jsx("path",{d:"M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15"})]}),"Regenerate"]}),c.jsxs("button",{className:"blog-cover-btn",onClick:P,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),c.jsx("polyline",{points:"7 10 12 15 17 10"}),c.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),"Save"]}),c.jsxs("button",{className:"blog-cover-btn blog-cover-btn--danger",onClick:R,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),"Remove"]})]}),k&&c.jsx("button",{className:"blog-cover-arrow blog-cover-arrow--right",onClick:N,disabled:v>=b-1,children:c.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})}),k&&c.jsxs("div",{className:"blog-cover-counter",children:[v+1," / ",b]})]})]}):n==="loading"?c.jsxs("div",{className:"blog-cover blog-cover--loading",children:[c.jsx("div",{className:"blog-cover-spinner"}),c.jsx("span",{className:"blog-cover-loading-text",children:"Generating cover image..."})]}):n==="prompt"?c.jsxs("div",{className:"blog-cover blog-cover--prompt",children:[c.jsxs("div",{className:"blog-cover-prompt-row",children:[c.jsx("input",{ref:g,className:"blog-cover-prompt-input",value:d,onChange:B=>f(B.target.value),onKeyDown:M,placeholder:"Describe your cover image...",spellCheck:!1}),c.jsx("button",{className:"blog-cover-prompt-btn",onClick:T,disabled:!d.trim(),children:"Generate"}),c.jsx("button",{className:"blog-cover-prompt-cancel",onClick:()=>{r(s?"display":"empty"),f(""),m("")},children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),h&&c.jsx("div",{className:"blog-cover-error",children:h})]}):c.jsxs("div",{className:"blog-cover blog-cover--empty",onClick:_,children:[c.jsxs("svg",{className:"blog-cover-icon",width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),c.jsx("polyline",{points:"21 15 16 10 5 21"})]}),c.jsx("span",{className:"blog-cover-hint",children:"Add a featured image"})]})}function DU({tags:t,onChange:e}){const[n,r]=x.useState(""),s=x.useRef(null),i=d=>{const f=d.trim().toLowerCase();f&&!t.includes(f)&&e([...t,f]),r("")},o=d=>e(t.filter(f=>f!==d)),l=d=>{(d.key==="Enter"||d.key===",")&&(d.preventDefault(),i(n)),d.key==="Backspace"&&!n&&t.length>0&&o(t[t.length-1])};return c.jsxs("div",{className:"blog-tags",onClick:()=>{var d;return(d=s.current)==null?void 0:d.focus()},children:[t.map(d=>c.jsxs("span",{className:"blog-tag",children:[d,c.jsx("button",{className:"blog-tag-remove",onClick:f=>{f.stopPropagation(),o(d)},children:c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},d)),c.jsx("input",{ref:s,className:"blog-tag-input",value:n,onChange:d=>r(d.target.value),onKeyDown:l,onBlur:()=>{n.trim()&&i(n)},placeholder:t.length===0?"Add tags...":"",spellCheck:!1})]})}function PU({children:t,title:e,onTitleChange:n,blogContext:r,filename:s,pendingTitle:i,docId:o}){var oe,Y;const l=r||{},d=!!(r!=null&&r.active),f=xE.has(e||"")?"":e||"",h=L2(f,A=>n==null?void 0:n(A||"Untitled")),[m,g]=x.useState(l.description||""),[v,b]=x.useState(l.date||wE()),[k,w]=x.useState(l.author||""),[S,N]=x.useState(l.slug||""),[T,M]=x.useState(!!l.slug),[_,R]=x.useState(!1),[I,P]=x.useState(!1),[B,z]=x.useState(!1),[K,F]=x.useState(!1),J=l.tags||OU,$=l.draft??!1;x.useEffect(()=>{g(l.description||""),b(l.date||wE()),w(l.author||""),N(l.slug||""),M(!!l.slug)},[s]),x.useEffect(()=>{fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"list_blog_sites",arguments:{}})}).then(A=>A.json()).then(A=>{var ee,ue;const L=(ue=(ee=A==null?void 0:A.content)==null?void 0:ee[0])!=null&&ue.text?JSON.parse(A.content[0].text):A;z(Array.isArray(L==null?void 0:L.sites)&&L.sites.length>0)}).catch(()=>{})},[]),x.useEffect(()=>{!T&&e&&!xE.has(e)&&N(IU(e))},[e,T]);const W=x.useCallback(()=>{d&&io({description:m,date:v,author:k,slug:S})},[d,m,v,k,S]),q=m.length,ne=q>160;return c.jsxs("div",{className:"blog-compose-wrapper",children:[c.jsx(LU,{src:l.coverImage,coverImages:l.coverImages}),c.jsxs("div",{className:"blog-compose-content",children:[((oe=l.lastPublish)==null?void 0:oe.publishedAt)&&c.jsxs("a",{className:"blog-published-status",href:l.lastPublish.publishedUrl,target:"_blank",rel:"noopener noreferrer",title:l.lastPublish.publishedUrl||"Published",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Published ",new Date(l.lastPublish.publishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})]}),c.jsx(D2,{pendingTitle:i,docId:o,baseClass:"blog-title-input",children:c.jsx("textarea",{className:"blog-title-input",ref:h.ref,value:f,onChange:h.onChange,onKeyDown:h.onKeyDown,placeholder:"Post title",rows:1,spellCheck:!1})}),c.jsxs("div",{className:"blog-description-wrap",children:[c.jsx("textarea",{className:`blog-description-input${ne?" over-limit":""}`,value:m,onChange:A=>g(A.target.value),onBlur:W,placeholder:"Write a short description for SEO and social previews...",rows:2,spellCheck:!1}),c.jsxs("span",{className:`blog-description-count${ne?" over-limit":""}`,children:[q,"/160"]})]}),c.jsxs("div",{className:"blog-meta-toggle",onClick:()=>P(A=>!A),children:[c.jsx("svg",{className:`blog-meta-chevron${I?" open":""}`,width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})}),c.jsx("span",{children:"Metadata"}),$&&c.jsx("span",{className:"blog-draft-badge",children:"Draft"})]}),I&&c.jsxs("div",{className:"blog-meta-fields",children:[c.jsxs("div",{className:"blog-meta-row",children:[c.jsx("label",{className:"blog-meta-label",children:"Date"}),c.jsx("input",{type:"date",className:"blog-meta-input",value:v,onChange:A=>b(A.target.value),onBlur:W})]}),c.jsxs("div",{className:"blog-meta-row",children:[c.jsx("label",{className:"blog-meta-label",children:"Author"}),c.jsx("input",{type:"text",className:"blog-meta-input",value:k,onChange:A=>w(A.target.value),onBlur:W,placeholder:"Author name",spellCheck:!1})]}),c.jsxs("div",{className:"blog-meta-row",children:[c.jsx("label",{className:"blog-meta-label",children:"Slug"}),c.jsx("input",{type:"text",className:"blog-meta-input",value:S,onChange:A=>{M(!0),N(A.target.value)},onBlur:W,placeholder:"auto-generated-from-title",spellCheck:!1})]}),c.jsxs("div",{className:"blog-meta-row",children:[c.jsx("label",{className:"blog-meta-label",children:"Tags"}),c.jsx(DU,{tags:J,onChange:A=>{d&&io({tags:A})}})]}),c.jsxs("div",{className:"blog-meta-row",children:[c.jsx("label",{className:"blog-meta-label",children:"Draft"}),c.jsx("button",{className:`blog-draft-toggle${$?" active":""}`,onClick:()=>{d&&io({draft:!$})},children:c.jsx("div",{className:"blog-draft-toggle-knob"})})]})]}),c.jsx("div",{className:"blog-compose-body",children:t})]}),c.jsx("div",{className:"blog-compose-footer",children:s&&c.jsxs("div",{className:"blog-footer-actions",children:[B&&c.jsxs("button",{className:"blog-footer-btn blog-footer-btn--primary",onClick:()=>F(!0),children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"})}),(Y=l.lastPublish)!=null&&Y.publishedUrl?"Republish":"Publish"]}),c.jsxs("button",{className:"blog-footer-btn",onClick:()=>R(!0),children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("polyline",{points:"12 6 12 12 16 14"})]}),"Schedule"]})]})}),_&&s&&c.jsx(Ul,{filename:s,title:e||"Untitled",onClose:()=>R(!1)}),K&&s&&c.jsx(LT,{filename:s,title:e||"Untitled",isActive:!0,onSwitchDocument:()=>{},onClose:()=>F(!1)})]})}function BU({connectionId:t,subject:e,filename:n,onBeforeSend:r,onClose:s}){const[i,o]=x.useState("confirm"),[l,d]=x.useState("html"),[f,h]=x.useState(""),[m,g]=x.useState(null),[v,b]=x.useState(null),[k,w]=x.useState(0),[S,N]=x.useState(null),[T,M]=x.useState(null),[_,R]=x.useState("all"),[I,P]=x.useState([]),[B,z]=x.useState(""),K=x.useRef(null),F=I.find(q=>q.id===B),J=_==="exclude_issue"&&F&&T!=null?Math.max(0,T-F.recipient_count):T;x.useEffect(()=>{fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"list_subscribers",arguments:{limit:1}})}).then(q=>q.json()).then(q=>{var V,oe;const ne=(oe=(V=q.content)==null?void 0:V[0])!=null&&oe.text?JSON.parse(q.content[0].text):q;ne.count!=null&&M(ne.count)}).catch(()=>{}),fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"list_newsletter_issues",arguments:{limit:10}})}).then(q=>q.json()).then(q=>{var V,oe;const ne=(oe=(V=q.content)==null?void 0:V[0])!=null&&oe.text?JSON.parse(q.content[0].text):q;ne.issues&&P(ne.issues)}).catch(()=>{})},[]);const $=()=>i==="sent"?{sentCount:k,issueId:S,sentAt:new Date().toISOString()}:void 0;x.useEffect(()=>{const q=ne=>{i!=="sending"&&i!=="testing"&&K.current&&!K.current.contains(ne.target)&&s($())};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[s,i,k,S]),x.useEffect(()=>{const q=ne=>{ne.key==="Escape"&&i!=="sending"&&i!=="testing"&&s($())};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[s,i,k,S]);async function W(q){var ne,V;o(q?"testing":"sending"),b(null);try{r&&await r();const oe={subject:e,connectionId:t,format:l};q&&(oe.test_email=q),!q&&_==="exclude_issue"&&B&&(oe.exclude_issue_id=B);const A=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"send_newsletter",arguments:oe})})).json(),L=(V=(ne=A.content)==null?void 0:ne[0])!=null&&V.text?JSON.parse(A.content[0].text):A;if(L.error){b(L.error),o("error");return}if(L.test){g(L.sent_to),o("confirm");return}const ee=L.sent||0,ue=L.issueId||null,be=new Date().toISOString();w(ee),N(ue),o("sent"),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({newsletterContext:{lastSend:{sentCount:ee,sentAt:be,issueId:ue||void 0}}})}).catch(()=>{})}catch(oe){b(oe.message),o("error")}}return c.jsx("div",{className:"newsletter-modal-overlay",children:c.jsxs("div",{className:"newsletter-modal",ref:K,children:[c.jsxs("div",{className:"newsletter-modal__header",children:[c.jsx("h3",{children:"Send Newsletter"}),c.jsx("button",{className:"newsletter-modal__close",onClick:()=>s($()),children:"×"})]}),c.jsxs("div",{className:"newsletter-modal__body",children:[i==="confirm"&&c.jsxs(c.Fragment,{children:[c.jsxs("p",{className:"newsletter-modal__confirm-text",style:J==null?{visibility:"hidden"}:void 0,children:['Send "',c.jsx("strong",{children:e}),'" to ',J!=null?J.toLocaleString():0," subscriber",J!==1?"s":"","?"]}),c.jsxs("div",{className:"newsletter-modal__audience",children:[c.jsx("label",{className:"newsletter-modal__label",children:"Audience"}),c.jsxs("select",{className:"newsletter-modal__select",value:_,onChange:q=>{const ne=q.target.value;R(ne),ne==="all"&&z("")},children:[c.jsx("option",{value:"all",children:"All subscribers"}),I.length>0&&c.jsx("option",{value:"exclude_issue",children:"Exclude who received..."})]}),_==="exclude_issue"&&c.jsxs("select",{className:"newsletter-modal__select",value:B,onChange:q=>z(q.target.value),children:[c.jsx("option",{value:"",children:"Select a past issue"}),I.map(q=>c.jsxs("option",{value:q.id,children:[q.subject," (",q.recipient_count," sent)"]},q.id))]})]}),c.jsxs("div",{className:"newsletter-modal__format-toggle",children:[c.jsx("button",{className:`newsletter-modal__format-btn${l==="html"?" active":""}`,onClick:()=>d("html"),children:"HTML"}),c.jsx("button",{className:`newsletter-modal__format-btn${l==="plaintext"?" active":""}`,onClick:()=>d("plaintext"),children:"Plaintext"})]}),c.jsxs("div",{className:"newsletter-modal__test-section",children:[c.jsxs("div",{className:"newsletter-modal__test-row",children:[c.jsx("input",{type:"email",className:"newsletter-modal__test-input",placeholder:"Test email address",value:f,onChange:q=>h(q.target.value),onKeyDown:q=>{q.key==="Enter"&&f.trim()&&W(f.trim())}}),c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--test",disabled:!f.trim(),onClick:()=>W(f.trim()),children:"Send Test"})]}),m&&c.jsxs("p",{className:"newsletter-modal__test-success",children:["Test sent to ",m]})]}),c.jsxs("div",{className:"newsletter-modal__actions",children:[c.jsx("button",{className:"newsletter-modal__btn",onClick:s,children:"Cancel"}),c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",disabled:_==="exclude_issue"&&!B,onClick:()=>W(),children:"Send Now"})]})]}),(i==="sending"||i==="testing")&&c.jsxs("div",{className:"newsletter-modal__status",children:[c.jsx("div",{className:"newsletter-modal__spinner"}),c.jsx("span",{children:i==="testing"?"Sending test...":"Sending..."})]}),i==="sent"&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"newsletter-modal__status newsletter-modal__status--success",children:["Sent to ",k," subscriber",k!==1?"s":"","!"]}),c.jsx("div",{className:"newsletter-modal__actions",children:c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>s({sentCount:k,issueId:S,sentAt:new Date().toISOString()}),children:"Done"})})]}),i==="error"&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"newsletter-modal__error",children:v}),c.jsxs("div",{className:"newsletter-modal__actions",children:[c.jsx("button",{className:"newsletter-modal__btn",onClick:s,children:"Cancel"}),c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>W(),children:"Retry"})]})]})]})]})})}function kE(t){fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({newsletterContext:t})}).catch(()=>{})}function $U({children:t,newsletterContext:e,filename:n,title:r,onTitleChange:s,onBeforeSend:i}){var $;const o=e||{},[l,d]=x.useState(o.subject||""),[f,h]=x.useState(o.previewText||""),[m,g]=x.useState([]),[v,b]=x.useState(null),[k,w]=x.useState(!1),[S,N]=x.useState(($=o.lastSend)!=null&&$.sentAt?{sentCount:o.lastSend.sentCount,issueId:o.lastSend.issueId||null,sentAt:o.lastSend.sentAt}:null),T=x.useRef(null),M=x.useRef(n),_=x.useRef(o.subject||""),R=x.useRef(o.previewText||"");x.useEffect(()=>{var W;if(M.current!==n)d(o.subject||""),h(o.previewText||""),_.current=o.subject||"",R.current=o.previewText||"",M.current=n;else{const q=o.subject||"",ne=o.previewText||"";q!==_.current&&(d(q),_.current=q),ne!==R.current&&(h(ne),R.current=ne)}N((W=o.lastSend)!=null&&W.sentAt?{sentCount:o.lastSend.sentCount,issueId:o.lastSend.issueId||null,sentAt:o.lastSend.sentAt}:null)},[e,n]),x.useEffect(()=>{fetch("/api/connections").then(W=>W.json()).then(W=>{const q=(W.connections||[]).filter(ne=>ne.provider==="newsletter"&&ne.status==="active");g(q)}).catch(()=>{})},[]);const I=!!(e!=null&&e.active),P=x.useRef();x.useEffect(()=>{if(P.current&&clearTimeout(P.current),!(!s||!l.trim()))return P.current=setTimeout(async()=>{const W=r,q=!W||W==="Untitled",ne=T.current!==null&&W===T.current;if(q||ne){try{await fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({newsletterContext:{subject:l}})})}catch{}s(l.trim()),T.current=l.trim()}},500),()=>{P.current&&clearTimeout(P.current)}},[l,r,s]);const B=x.useCallback(()=>{I&&(_.current=l,R.current=f,kE({subject:l,previewText:f}))},[I,l,f]),z=f.length,K=z>=90,F=z>150,J=()=>{m.length===1&&b(m[0].id),m.length>1&&b(m[0].id)};return c.jsxs("div",{className:"nl-compose-wrapper",children:[S&&c.jsxs("div",{className:"nl-sent-status",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Sent ",new Date(S.sentAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})," to ",S.sentCount," subscriber",S.sentCount!==1?"s":""]}),c.jsxs("div",{className:"nl-compose-content",children:[c.jsx("input",{className:"nl-subject-input",type:"text",value:l,onChange:W=>d(W.target.value),onBlur:B,placeholder:"Subject line (defaults to title if empty)",autoComplete:"off","data-lpignore":"true","data-1p-ignore":!0,spellCheck:!1}),c.jsxs("div",{className:"nl-preview-wrap",children:[c.jsx("textarea",{className:`nl-preview-input${F?" over-limit":""}`,value:f,onChange:W=>h(W.target.value),onBlur:B,placeholder:"Preview text shown in inbox before opening...",rows:2,spellCheck:!1}),c.jsxs("span",{className:`nl-preview-count${F?" over-limit":K?" full":""}`,children:[z,"/90"]})]}),c.jsx("div",{className:"nl-compose-body",children:t})]}),n&&c.jsxs("div",{className:"nl-compose-footer",children:[m.length>0&&c.jsxs("button",{className:"nl-footer-btn nl-footer-btn--primary",onClick:J,children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),c.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),"Send"]}),c.jsxs("button",{className:"nl-footer-btn",onClick:()=>w(!0),children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("polyline",{points:"12 6 12 12 16 14"})]}),"Schedule"]})]}),v&&n&&c.jsx(BU,{connectionId:v,subject:l||r||"Untitled",filename:n,onBeforeSend:i,onClose:W=>{b(null),W&&(N(W),kE({lastSend:{sentCount:W.sentCount,sentAt:W.sentAt,issueId:W.issueId||void 0}}))}}),k&&n&&c.jsx(Ul,{filename:n,title:r||"Untitled",onClose:()=>w(!1)})]})}const SE=600,FU=48;function Au(t){return t!=null&&typeof t=="object"&&Object.keys(t).length>0}function zU(t){const e=typeof(t==null?void 0:t.content_type)=="string"&&t.content_type||typeof(t==null?void 0:t.contentType)=="string"&&t.contentType||"";return e||(Au(t==null?void 0:t.blogContext)?"blog":t!=null&&t.newsletterContext&&(t.newsletterContext.active===!0||Au(t.newsletterContext))?"newsletter":Au(t==null?void 0:t.articleContext)?"article":t!=null&&t.tweetContext?t.tweetContext.mode||"tweet":Au(t==null?void 0:t.linkedinContext)?"linkedin":"document")}function UU(){var Tt,Mt,on;const t=x.useRef(null),e=x.useRef([]),[n,r]=x.useState(null),[s,i]=x.useState(null),[o,l]=x.useState([]),[d,f]=x.useState("Untitled"),[h,m]=x.useState(null),[g,v]=x.useState(void 0),[b,k]=x.useState(0),[w,S]=x.useState(!0),[N,T]=x.useState(0),[M,_]=x.useState(0),[R,I]=x.useState(0),[P,B]=x.useState({filenames:[],counts:{}}),[z,K]=x.useState({state:"unconfigured"}),[F,J]=x.useState(!1),[$,W]=x.useState({}),[q,ne]=x.useState(()=>localStorage.getItem("ow-toolbar")!=="hidden"),[V,oe]=x.useState(!1),Y=x.useRef(null),A=x.useRef(null),[L,ee]=x.useState(0),[ue,be]=x.useState(!1),[re,we]=x.useState(!1),[Ee,$e]=x.useState(()=>{try{const G=localStorage.getItem("ow-sidebar-width");if(G){const xe=parseInt(G,10);if(!isNaN(xe)&&xe>=BT&&xe<=$T)return xe}}catch{}return nv}),{open:Fe,width:Ze,visible:Re,setOverlay:tt,closeRail:gt}=Ll(),ut=$d()==="board";x.useEffect(()=>{const G=A.current;if(!G)return;ee(G.clientWidth);const xe=new ResizeObserver(He=>{for(const ht of He)ee(ht.contentRect.width)});return xe.observe(G),()=>xe.disconnect()},[]),x.useEffect(()=>{if(ut||L===0){be(!1);return}const G=L-(w?Ee:0)-(Fe?Ze:0);be(xe=>xe?G<SE+FU:G<SE)},[L,w,Ee,Fe,Ze,ut]),x.useLayoutEffect(()=>{tt(ue),we(!1)},[ue,tt]),x.useEffect(()=>{if(!ue)return;const G=xe=>{xe.key==="Escape"&&(re||Re)&&(we(!1),gt())};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[ue,re,Re,gt]);const ge=ue?re:w,[yt,Ct]=x.useState(null),[_t,Lt]=x.useState(null),[at,De]=x.useState(new Set),ve=x.useRef(0),Z=x.useRef(null),je=1500,Q=x.useCallback((G,xe)=>{Z.current&&(clearTimeout(Z.current),Z.current=null),ve.current=Date.now(),Ct(G),Lt(xe)},[]),he=x.useCallback(()=>{if(Z.current)return;const G=Date.now()-ve.current,xe=je-G;xe<=0?(Ct(null),Lt(null)):Z.current=setTimeout(()=>{Z.current=null,Ct(null),Lt(null)},xe)},[]),[,me]=x.useState(0),[Ue,Oe]=x.useState(null),Ve=x.useRef(null),et=x.useRef(null),ft=x.useRef(null),We=x.useRef([]),Ge=x.useRef(-1),vt=x.useRef(null),Et=x.useRef(!1),_e=x.useRef(""),[Ne,Ke]=x.useState(""),[st,Ye]=x.useState(!1),[jt,j]=x.useState(!1);function U(){const G=document.querySelector(".editor-container");return(G==null?void 0:G.scrollTop)||0}function ie(){if(Ge.current<0)return;const G=We.current[Ge.current];G&&(G.scrollTop=U())}const D=zU($),le=D==="article",fe=D==="blog",se=D==="newsletter",pe=D==="tweet"||D==="reply"||D==="quote";x.useEffect(()=>(le?document.documentElement.setAttribute("data-view","article"):fe?document.documentElement.setAttribute("data-view","blog"):se?document.documentElement.setAttribute("data-view","newsletter"):pe?document.documentElement.setAttribute("data-view","tweet"):document.documentElement.removeAttribute("data-view"),()=>document.documentElement.removeAttribute("data-view")),[pe,le,fe,se]),x.useEffect(()=>{const G=()=>me(xe=>xe+1);return window.addEventListener("ow-sidebar-mode-change",G),()=>window.removeEventListener("ow-sidebar-mode-change",G)},[]),x.useEffect(()=>{fetch("/api/document",{cache:"no-store"}).then(G=>G.json()).then(G=>{G.document&&(v(G.document),et.current=G.document),G.title&&f(G.title),G.metadata&&W(G.metadata)}).catch(()=>{v(void 0)}),fetch("/api/pending-docs").then(G=>G.json()).then(G=>B(G)).catch(()=>{}),fetch("/api/sync/status").then(G=>G.json()).then(G=>K(G)).catch(()=>{})},[]);const ye=x.useCallback(G=>{t.current=G,r(G),i(null),e.current=[G],l([G])},[]),Pe=x.useRef([]),Se=x.useCallback(G=>{if(e.current=G,l(G),Pe.current.length>0&&G.length>0){const xe=Pe.current;Pe.current=[];for(const He of G)He.isDestroyed||Rp(He,xe)}},[]),Vt=x.useCallback(G=>{var Cn,wr;const xe=performance.now(),He=window.__lastSwitch;He&&He.filename===G.filename?(He.tReceive=xe,console.log(`[Switch] RECEIVE filename=${G.filename} sendToReceive=${(xe-He.tSend).toFixed(1)}ms (server round-trip)`)):console.log(`[Switch] RECEIVE filename=${G.filename} (no matching CLICK — agent or initial-load switch)`),Ve.current&&(clearTimeout(Ve.current),Ve.current=null);const ht=_e.current==="",xt=G.filename===_e.current;_e.current=G.filename,et.current=G.document,ft.current=JSON.stringify(G.document),Ke(G.filename),v(G.document),f(G.title),W(G.metadata||{}),m(((Cn=G.pendingMetadata)==null?void 0:Cn.title)??null),!xt&&!ht&&((wr=G.metadata)!=null&&wr.tweetContext)&&k(tn=>tn+1),He&&He.filename===G.filename&&requestAnimationFrame(()=>{const tn=performance.now();He.tCommit=tn,console.log(`[Switch] COMMIT filename=${G.filename} receiveToCommit=${(tn-xe).toFixed(1)}ms totalClickToPaint=${(tn-He.tClick).toFixed(1)}ms`)});const Nn=vt.current??"push";if(vt.current=null,We.current.length===0?(We.current=[{filename:G.filename,scrollTop:0}],Ge.current=0):Nn==="back"?Ge.current=Math.max(0,Ge.current-1):Nn==="forward"?Ge.current=Math.min(We.current.length-1,Ge.current+1):xt||(We.current=We.current.slice(0,Ge.current+1),We.current.push({filename:G.filename,scrollTop:0}),Ge.current=We.current.length-1),!Et.current){const tn=`#${encodeURIComponent(G.filename)}`,kr={ow:{filename:G.filename,navIndex:Ge.current}};We.current.length===1||xt?window.history.replaceState(kr,"",tn):window.history.pushState(kr,"",tn)}if(Et.current=!1,Nn==="back"||Nn==="forward"){const tn=We.current[Ge.current];tn&&setTimeout(()=>{const kr=document.querySelector(".editor-container");kr&&(kr.scrollTop=tn.scrollTop)},50)}Ye(Ge.current>0),j(Ge.current<We.current.length-1)},[]),It=x.useCallback(G=>{Ve.current&&(clearTimeout(Ve.current),Ve.current=null),et.current=G.document,ft.current=JSON.stringify(G.document),v(G.document),f(G.title),W(G.metadata||{}),Oe(xe=>xe?{filename:G.filename,orphanCount:xe.orphanCount+G.orphanCount,staleBaselineCount:xe.staleBaselineCount+G.staleBaselineCount,reloadCount:xe.reloadCount+1}:{filename:G.filename,orphanCount:G.orphanCount,staleBaselineCount:G.staleBaselineCount,reloadCount:1})},[]),Sn=x.useCallback(()=>{T(G=>G+1),_(G=>G+1)},[]),yn=x.useCallback(()=>{I(G=>G+1)},[]),En=x.useCallback(G=>{B(G)},[]),{connected:qe,sendMessage:Nt,docVersionRef:bn}=hF({onNodeChanges:G=>{const xe=e.current;if(xe.length<=1){const He=t.current;if(!He)return;Rp(He,G)}else{if(xe.some(ht=>ht.isDestroyed)){Pe.current.push(...G);return}for(const ht of xe)Rp(ht,G)}},onDocumentSwitched:Vt,onDocumentReloaded:It,onDocumentsChanged:Sn,onWorkspacesChanged:yn,onPendingDocsChanged:En,onMetadataChanged:G=>W(G),onWritingStarted:(G,xe)=>Q(G,xe),onWritingFinished:()=>he(),onIdRewrites:G=>{const xe=e.current,He=xe.length>0?xe:t.current?[t.current]:[];for(const xt of He)xt.isDestroyed||e$(xt,G);const ht=et.current;if(ht&&Array.isArray(G)&&G.length>0){const xt=new Map(G.map(Cn=>[Cn.oldId,Cn.newId])),Nn=Cn=>{var wr;if(Array.isArray(Cn))for(const tn of Cn){const kr=(wr=tn==null?void 0:tn.attrs)==null?void 0:wr.id;kr&&xt.has(kr)&&(tn.attrs={...tn.attrs,id:xt.get(kr)}),tn!=null&&tn.content&&Nn(tn.content)}};Nn(ht.content||[])}},onPendingFilenamesChanged:G=>De(G),onSyncStatus:G=>K(G),onTitleChanged:G=>f(G),getEditorState:()=>{var xe;const G=et.current||((xe=t.current)==null?void 0:xe.getJSON());return G?{document:G}:null}}),Gt=x.useCallback(()=>{var He;Ve.current&&(clearTimeout(Ve.current),Ve.current=null);const G=et.current||((He=t.current)==null?void 0:He.getJSON());if(!G)return;const xe=JSON.stringify(G);xe!==ft.current&&(Nt({type:"doc-update",document:G,filename:_e.current,version:bn.current}),ft.current=xe)},[Nt,bn]),dr=x.useCallback(async()=>{var xe;const G=et.current||((xe=t.current)==null?void 0:xe.getJSON());G&&await fetch("/api/documents/sync-content",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({document:G,filename:_e.current})})},[]);x.useEffect(()=>{const G=()=>{var xt;Ve.current&&(clearTimeout(Ve.current),Ve.current=null);const He=et.current||((xt=t.current)==null?void 0:xt.getJSON());if(!He)return;const ht=JSON.stringify({type:"flush",document:He});navigator.sendBeacon("/api/flush",new Blob([ht],{type:"application/json"}))},xe=()=>{document.visibilityState==="hidden"&&G()};return window.addEventListener("beforeunload",G),document.addEventListener("visibilitychange",xe),()=>{window.removeEventListener("beforeunload",G),document.removeEventListener("visibilitychange",xe)}},[]);const ir=x.useCallback(()=>{Gt(),Nt({type:"create-document"})},[Gt,Nt]),Un=x.useCallback(G=>{if(G===_e.current)return;const xe=performance.now();window.__lastSwitch={filename:G,tClick:xe,tSend:0,tReceive:0,tCommit:0},console.log(`[Switch] CLICK filename=${G} t=${xe.toFixed(0)}`),ie(),vt.current="push",Gt(),Nt({type:"switch-document",filename:G});const He=performance.now();window.__lastSwitch.tSend=He,console.log(`[Switch] SEND filename=${G} clickToSend=${(He-xe).toFixed(1)}ms`)},[Gt,Nt]),Ar=x.useRef(null),un=x.useCallback(async G=>{let xe=null;if(G.docId)try{const He=await fetch("/api/documents").then(ht=>ht.json());if(Array.isArray(He)){const ht=He.find(xt=>xt.docId===G.docId);ht&&(xe=ht.filename)}}catch{}if(!xe&&G.filename&&(xe=G.filename),!xe){console.warn("[link] could not resolve doc: target",G);return}G.nodeId||G.quote?Ar.current={nodeId:G.nodeId||void 0,quote:G.quote||void 0}:Ar.current={toTop:!0},Un(xe),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ow-reveal-active-doc",{detail:{filename:xe}}))},0)},[Un]);x.useEffect(()=>{const G=xe=>{const He=xe.detail;He&&un(He)};return window.addEventListener("ow-navigate-to-link",G),()=>window.removeEventListener("ow-navigate-to-link",G)},[un]);const Ss=x.useRef(!1);x.useEffect(()=>{if(Ss.current)return;Ss.current=!0;const G=window.location.pathname.match(/^\/d\/([a-f0-9]{8})\/?$/);if(!G)return;const xe=G[1],He=window.location.hash.match(/^#node=([a-f0-9]{8})$/),ht=He?He[1]:null;un({docId:xe,filename:null,nodeId:ht,quote:null})},[un]),x.useEffect(()=>{if(!n||!Ar.current)return;const G=Ar.current;Ar.current=null,setTimeout(()=>{if(G.toTop){const ht=document.querySelector(".editor-container");ht&&(ht.scrollTop=0);return}let xe=null;if(G.nodeId&&n.state.doc.descendants((ht,xt)=>{var Nn;return xe!==null?!1:((Nn=ht.attrs)==null?void 0:Nn.id)===G.nodeId?(xe=xt+1,!1):!0}),xe===null&&G.quote){const ht=G.quote;n.state.doc.descendants((xt,Nn)=>{if(xe!==null)return!1;if(xt.isTextblock){const Cn=xt.textContent.indexOf(ht);if(Cn>=0)return xe=Nn+1+Cn,!1}return!0})}if(xe===null)return;n.chain().focus().setTextSelection({from:xe,to:xe}).scrollIntoView().run();const He=n.view.nodeDOM(xe-1);He!=null&&He.classList&&(He.classList.add("scroll-target-flash"),setTimeout(()=>He.classList.remove("scroll-target-flash"),1200))},100)},[n,Ne]);const us=x.useCallback(()=>{Ge.current<=0||window.history.back()},[]),Wt=x.useCallback(()=>{Ge.current>=We.current.length-1||window.history.forward()},[]);x.useEffect(()=>{const G=xe=>{const He=xe.state&&xe.state.ow;He!=null&&He.filename&&He.filename!==_e.current&&(ie(),vt.current=He.navIndex<Ge.current?"back":"forward",Et.current=!0,Gt(),Nt({type:"switch-document",filename:He.filename}))};return window.addEventListener("popstate",G),()=>window.removeEventListener("popstate",G)},[Gt,Nt]);const qs=x.useCallback(()=>{const G=_e.current,xe=t.current;if(!G||!xe)return;const He=()=>{const ht=e.current;if(ht.length>1)for(const xt of ht)xt!=null&&xt.view&&pk(xt.view);else xe!=null&&xe.view&&pk(xe.view)};fetch(`/api/comments/${encodeURIComponent(G)}`).then(ht=>ht.json()).then(ht=>{dk(ht.comments||[]),He()}).catch(()=>{dk([]),He()})},[]);x.useEffect(()=>{qs()},[Ne,n,qs]),x.useEffect(()=>{const G=xe=>{const He=xe.detail;(He==null?void 0:He.filename)===_e.current&&qs()};return window.addEventListener("ow-comments-changed",G),()=>window.removeEventListener("ow-comments-changed",G)},[qs]),x.useEffect(()=>{function G(xe){var xt;const He=xe.detail;if(!He)return;const ht=$==null?void 0:$.docId;ht&&He.docId&&He.docId!==ht||m(((xt=He.pendingMetadata)==null?void 0:xt.title)??null)}return window.addEventListener("ow-pending-metadata-changed",G),()=>window.removeEventListener("ow-pending-metadata-changed",G)},[$==null?void 0:$.docId]),x.useEffect(()=>{const G=$==null?void 0:$.docId;if(!G){mk([]);return}let xe=!1;return fetch(`/api/backlinks/${G}`).then(He=>He.ok?He.json():[]).then(He=>{if(xe)return;mk(Array.isArray(He)?He:[]);const ht=e.current.length>0?e.current:n?[n]:[];for(const xt of ht)xt!=null&&xt.view&&T5(xt.view)}).catch(()=>{}),()=>{xe=!0}},[$,n]),x.useEffect(()=>{const G=xe=>{xe.altKey&&xe.key==="ArrowLeft"&&(xe.preventDefault(),us()),xe.altKey&&xe.key==="ArrowRight"&&(xe.preventDefault(),Wt())};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[us,Wt]);const Jr=x.useCallback(G=>{et.current=G,Ve.current&&clearTimeout(Ve.current),Ve.current=setTimeout(()=>{const xe=et.current||G,He=JSON.stringify(xe);He!==ft.current&&(Nt({type:"doc-update",document:xe,filename:_e.current,version:bn.current}),ft.current=He)},1e3)},[Nt,bn]),Rr=x.useCallback(G=>{f(G),Nt({type:"title-update",title:G})},[Nt]),Es=x.useCallback(()=>{ne(G=>(localStorage.setItem("ow-toolbar",G?"hidden":"visible"),!G))},[]),Ie=x.useCallback(()=>{oe(G=>{if(!G)return Y.current={sidebarOpen:w,showToolbar:q},S(!1),we(!1),ne(!1),!0;const xe=Y.current;return xe&&(S(xe.sidebarOpen),ne(xe.showToolbar),Y.current=null),!1})},[w,q]),ot=x.useCallback(()=>{if(z.state==="unconfigured"){J(!0);return}Gt(),Nt({type:"save"}),fetch("/api/sync/push",{method:"POST"}).catch(()=>{})},[z.state,Gt,Nt]);return c.jsxs("div",{className:`app${ue?" app--overlay":""}`,ref:A,children:[!ut&&c.jsx(Dk,{open:ge,floating:ue,width:Ee,onWidthChange:$e,onSwitchDocument:Un,onCreateDocument:ir,refreshKey:N,docTagsRefreshKey:M,workspacesRefreshKey:R,pendingDocs:P,writingTitle:yt,writingTarget:_t,pendingWriteFilenames:at,activeFilename:Ne,onClose:()=>ue?we(!1):S(!1)}),c.jsxs("div",{className:"app-main",children:[c.jsx(J5,{title:d,onTitleChange:Rr,onToggleSidebar:!ut&&!ge?()=>ue?we(!0):S(!0):void 0,canGoBack:st,canGoForward:jt,onGoBack:us,onGoForward:Wt,editor:n,onToggleToolbar:Es,toolbarOpen:q,focusMode:V,onToggleFocusMode:Ie}),q&&n&&c.jsx(B5,{editor:s||n}),ut&&c.jsx(Dk,{open:!0,width:Ee,onWidthChange:$e,onSwitchDocument:Un,onCreateDocument:ir,refreshKey:N,docTagsRefreshKey:M,workspacesRefreshKey:R,pendingDocs:P,writingTitle:yt,writingTarget:_t,pendingWriteFilenames:at}),c.jsx(Y5,{}),!qe&&c.jsxs("div",{className:"connection-banner",children:[c.jsx("div",{className:"connection-banner-spinner"}),c.jsx("span",{children:"Reconnecting to server..."})]}),($==null?void 0:$.autoAccept)===!0&&c.jsxs("div",{className:"editor-auto-accept-banner",title:"Agent edits skip the review step. Right-click the doc in the sidebar to turn off.",children:[c.jsx("span",{className:"editor-auto-accept-dot"}),"Auto-accept on — agent edits skip review"]}),Ue&&c.jsxs("div",{className:"editor-reload-banner",role:"status","aria-live":"polite",children:[c.jsx("span",{className:"editor-reload-dot","aria-hidden":"true"}),c.jsx("span",{children:Ue.reloadCount>1?`Document reloaded from disk ${Ue.reloadCount}× since you last looked`:"Document reloaded from disk (external write detected)"}),(Ue.orphanCount>0||Ue.staleBaselineCount>0)&&c.jsxs("span",{className:"editor-reload-detail",children:[Ue.orphanCount>0&&c.jsxs("span",{className:"editor-reload-tag editor-reload-tag--orphan",children:[Ue.orphanCount," orphan",Ue.orphanCount===1?"":"s"]}),Ue.staleBaselineCount>0&&c.jsxs("span",{className:"editor-reload-tag editor-reload-tag--stale",children:[Ue.staleBaselineCount," stale-baseline"]})]}),c.jsx("button",{type:"button",className:"editor-reload-dismiss",onClick:()=>Oe(null),"aria-label":"Dismiss reload notification",children:"×"})]}),c.jsx("div",{className:"editor-container",children:le?c.jsx(RU,{title:d,onTitleChange:Rr,coverImage:(Tt=$==null?void 0:$.articleContext)==null?void 0:Tt.coverImage,coverImages:(Mt=$==null?void 0:$.articleContext)==null?void 0:Mt.coverImages,lastPost:(on=$==null?void 0:$.articleContext)==null?void 0:on.lastPost,pendingTitle:h,docId:($==null?void 0:$.docId)||void 0,autoplug:$==null?void 0:$.autoplug,children:c.jsx(xu,{initialContent:g,extensions:g5,onUpdate:Jr,onReady:ye,onLinkClick:un})}):fe?c.jsx(PU,{title:d,onTitleChange:Rr,blogContext:$==null?void 0:$.blogContext,filename:Ne,pendingTitle:h,docId:($==null?void 0:$.docId)||void 0,children:c.jsx(xu,{initialContent:g,onUpdate:Jr,onReady:ye,onLinkClick:un})}):se?c.jsx($U,{newsletterContext:$==null?void 0:$.newsletterContext,filename:Ne,title:d,onTitleChange:Rr,onBeforeSend:dr,children:c.jsx(xu,{initialContent:g,onUpdate:Jr,onReady:ye,onLinkClick:un})}):pe&&($!=null&&$.tweetContext)?c.jsx(CU,{tweetContext:$.tweetContext,initialContent:g,onUpdate:Jr,onEditorReady:ye,onEditorsChange:Se,onActiveEditorChange:i,filename:Ne,title:d,autoplug:$==null?void 0:$.autoplug},b):c.jsx(xu,{initialContent:g,onUpdate:Jr,onReady:ye,onLinkClick:un})})]}),ue&&(re||Re)&&c.jsx("div",{className:"ow-scrim",onClick:()=>{we(!1),gt()},"aria-hidden":"true"}),c.jsx(dF,{editors:o,pendingDocs:P,currentFilename:Ne,docId:($==null?void 0:$.docId)||null,pendingTitle:h,onSwitchDocument:Un,sendMessage:Nt,getDocument:()=>et.current,docVersionRef:bn,syncStatus:z,onSync:ot,onToggleToolbar:Es,toolbarOpen:q,focusMode:V,onToggleFocusMode:Ie}),c.jsx(u$,{editorRef:t,allEditors:o,documentId:Ne}),c.jsx(p$,{documentId:Ne}),F&&c.jsx(fF,{onClose:()=>J(!1),onSetupComplete:()=>{fetch("/api/sync/status").then(G=>G.json()).then(K).catch(()=>{})}})]})}_M();kM.createRoot(document.getElementById("root")).render(c.jsx(Ti.StrictMode,{children:c.jsx(AM,{children:c.jsx(UU,{})})}));
|
|
215
|
+
`)}function L2(t,e){const n=x.useRef(null),r=x.useCallback(()=>{const o=n.current;o&&(o.style.height="auto",o.style.height=`${o.scrollHeight}px`)},[]);x.useLayoutEffect(()=>{r()},[t,r]);const s=x.useCallback(o=>{e(o.target.value.replace(/[\r\n]+/g," ")),r()},[e,r]),i=x.useCallback(o=>{var l;o.key==="Enter"&&(o.preventDefault(),(l=n.current)==null||l.blur())},[]);return{ref:n,onChange:s,onKeyDown:i}}function D2({pendingTitle:t,docId:e,baseClass:n,children:r}){const[s,i]=x.useState(!1),[o,l]=x.useState(!1);return x.useEffect(()=>{function d(f){const h=f.detail;h&&(e&&h.docId&&h.docId!==e||(i(!!h.titleFocused),l(!!h.titleShowOriginal)))}return window.addEventListener("ow-pending-review-cursor",d),()=>window.removeEventListener("ow-pending-review-cursor",d)},[e]),t?o?c.jsx("div",{className:`${n} ${n}--pending${s?" pending-active pending-active--original":""}`,title:`Showing original title. Toggle back to Modified to see the agent's proposal "${t.to}".`,"aria-label":`Original title ${t.from} (agent proposed ${t.to})`,children:c.jsx("span",{className:"pending-original",children:t.from})}):c.jsx("div",{className:`${n} ${n}--pending${s?" pending-active pending-active--insert":""}`,title:`Agent proposed rename from "${t.from}". Accept or reject in the Review panel.`,"aria-label":`Pending title rename from ${t.from} to ${t.to}`,children:c.jsx("span",{className:"pending-insert",children:t.to})}):c.jsx(c.Fragment,{children:r})}const fg="ow-x-handle",bE="ow-x-name",MU=new Set(["Untitled","New Document","Article"]);function AU({src:t,coverImages:e}){const[n,r]=x.useState(t?"display":"empty"),[s,i]=x.useState(t||""),[o,l]=x.useState(e||(t?[t]:[])),[d,f]=x.useState(""),[h,m]=x.useState(""),g=x.useRef(null);x.useEffect(()=>{t?(i(t),r("display")):e&&e.length>0?(i(e[0]),r("display")):(i(""),r("empty"),f(""),m(""))},[t,e]),x.useEffect(()=>{e&&e.length>0?l(e):l(t?[t]:[])},[e]);const v=s?o.indexOf(s):-1,b=o.length,k=b>1,w=x.useCallback(B=>{const z=o[B];z&&(i(z),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({articleContext:{coverImage:z,coverImages:o}})}).catch(()=>{}))},[o]),S=x.useCallback(()=>{v>0&&w(v-1)},[v,w]),N=x.useCallback(()=>{v<b-1&&w(v+1)},[v,b,w]),T=x.useCallback(async()=>{if(d.trim()){r("loading"),m("");try{const B=await fetch("/api/image-gen/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:d.trim()})});if(!B.ok){const K=await B.json().catch(()=>null);m((K==null?void 0:K.error)||`Generation failed (${B.status})`),r("prompt");return}const z=await B.json();if(z.success&&z.src){const K=[...o,z.src];l(K),i(z.src),r("display"),f(""),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({articleContext:{coverImage:z.src,coverImages:K}})}).catch(()=>{})}else m(z.error||"Generation failed"),r("prompt")}catch(B){m(B.message||"Network error"),r("prompt")}}},[d,o]),M=B=>{B.key==="Enter"&&T(),B.key==="Escape"&&(r("empty"),f(""),m(""))},_=()=>{r("prompt"),setTimeout(()=>{var B;return(B=g.current)==null?void 0:B.focus()},0)},R=()=>{const B=o.filter(z=>z!==s);if(l(B),B.length>0){const z=Math.min(v,B.length-1),K=B[z];i(K),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({articleContext:{coverImage:K,coverImages:B}})}).catch(()=>{})}else i(""),r("empty"),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({articleContext:{coverImage:null,coverImages:null}})}).catch(()=>{})},I=()=>{r("prompt"),setTimeout(()=>{var B;return(B=g.current)==null?void 0:B.focus()},0)},P=()=>{const B=document.createElement("a");B.href=s,B.download=`cover-${v+1}.png`,B.click()};return n==="display"&&s?c.jsxs("div",{className:"article-cover article-cover--display",children:[c.jsx("img",{className:"article-cover-img",src:s,alt:"Cover"}),c.jsxs("div",{className:"article-cover-overlay",children:[k&&c.jsx("button",{className:"article-cover-arrow article-cover-arrow--left",onClick:S,disabled:v<=0,children:c.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"15 18 9 12 15 6"})})}),c.jsxs("div",{className:"article-cover-overlay-center",children:[c.jsxs("button",{className:"article-cover-overlay-btn",onClick:I,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"23 4 23 10 17 10"}),c.jsx("polyline",{points:"1 20 1 14 7 14"}),c.jsx("path",{d:"M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15"})]}),"Regenerate"]}),c.jsxs("button",{className:"article-cover-overlay-btn",onClick:P,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),c.jsx("polyline",{points:"7 10 12 15 17 10"}),c.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),"Save"]}),c.jsxs("button",{className:"article-cover-overlay-btn article-cover-overlay-btn--danger",onClick:R,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),"Remove"]})]}),k&&c.jsx("button",{className:"article-cover-arrow article-cover-arrow--right",onClick:N,disabled:v>=b-1,children:c.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})}),k&&c.jsxs("div",{className:"article-cover-counter",children:[v+1," / ",b]})]})]}):n==="loading"?c.jsxs("div",{className:"article-cover article-cover--loading",children:[c.jsx("div",{className:"article-cover-spinner"}),c.jsx("span",{className:"article-cover-loading-text",children:"Generating cover image..."})]}):n==="prompt"?c.jsxs("div",{className:"article-cover article-cover--prompt",children:[c.jsxs("div",{className:"article-cover-prompt-row",children:[c.jsx("input",{ref:g,className:"article-cover-prompt-input",value:d,onChange:B=>f(B.target.value),onKeyDown:M,placeholder:"Describe your cover image...",spellCheck:!1}),c.jsx("button",{className:"article-cover-prompt-btn",onClick:T,disabled:!d.trim(),children:"Generate"}),c.jsx("button",{className:"article-cover-prompt-cancel",onClick:()=>{r(s?"display":"empty"),f(""),m("")},children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),h&&c.jsx("div",{className:"article-cover-error",children:h})]}):c.jsxs("div",{className:"article-cover article-cover--empty",onClick:_,children:[c.jsxs("svg",{className:"article-cover-icon",width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),c.jsx("polyline",{points:"21 15 16 10 5 21"})]}),c.jsx("span",{className:"article-cover-hint",children:"We recommend an image with a 5:2 aspect ratio for best results."})]})}function RU(){const[t,e]=x.useState(()=>localStorage.getItem(fg)||""),[n,r]=x.useState(()=>localStorage.getItem(bE)||""),[s,i]=x.useState(!1),[o,l]=x.useState(""),d=x.useRef(null),f=x.useRef(null),h=()=>{const b=o.replace(/^@/,"").trim();b&&(localStorage.setItem(fg,b),e(b)),i(!1)},m=()=>{l(t),i(!0),setTimeout(()=>{var b;return(b=d.current)==null?void 0:b.focus()},0)};x.useEffect(()=>{if(!s)return;const b=k=>{f.current&&!f.current.contains(k.target)&&h()};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[s,o]),x.useEffect(()=>{const b=()=>{e(localStorage.getItem(fg)||""),r(localStorage.getItem(bE)||"")};return window.addEventListener("storage",b),()=>window.removeEventListener("storage",b)},[]);const g=t?`https://unavatar.io/twitter/${t}`:"",v=n||t||"Set your @handle";return c.jsxs("div",{className:"article-byline",ref:f,children:[c.jsxs("div",{className:"article-byline-row",onClick:m,title:t?`@${t} — click to change`:"Set your @handle",children:[t?c.jsx("img",{className:"article-byline-avatar",src:g,alt:`@${t}`}):c.jsx("div",{className:"article-byline-avatar article-byline-avatar--empty"}),c.jsx("span",{className:"article-byline-name",children:v}),t&&c.jsxs("span",{className:"article-byline-handle",children:["@",t]})]}),s&&c.jsx("div",{className:"article-byline-popover",children:c.jsx("input",{ref:d,className:"article-byline-input",value:o,onChange:b=>l(b.target.value),onKeyDown:b=>{b.key==="Enter"&&h(),b.key==="Escape"&&i(!1)},placeholder:"your_handle",spellCheck:!1})})]})}function OU({children:t,title:e,onTitleChange:n,coverImage:r,coverImages:s,lastPost:i,pendingTitle:o,docId:l,autoplug:d}){const{copyAsHtml:f,copyState:h}=TU(),[m,g]=x.useState(i?"done":"idle"),v=MU.has(e||"")?"":e||"",b=L2(v,z=>n==null?void 0:n(z||"Untitled")),[k,w]=x.useState(!1),[S,N]=x.useState(""),T=x.useRef(null),M=x.useRef(null);x.useEffect(()=>{g(i?"done":"idle")},[i]),x.useEffect(()=>{if(!k)return;setTimeout(()=>{var K;return(K=T.current)==null?void 0:K.focus()},0);const z=K=>{M.current&&!M.current.contains(K.target)&&(w(!1),N(""))};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[k]);const _=x.useCallback(()=>{const z=S.trim();if(!(!z||z.includes("x.com")||z.includes("twitter.com")))return;const F=(i==null?void 0:i.postedAt)??new Date().toISOString();fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({articleContext:{lastPost:z?{postedAt:F,tweetUrl:z}:{postedAt:F}}}),keepalive:!0}).catch(()=>{}),g("done"),w(!1),N("")},[S,i==null?void 0:i.postedAt]),R=x.useCallback(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({articleContext:{lastPost:null}}),keepalive:!0}).catch(()=>{}),g("idle")},[]),I=d!==!1,P=()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoplug:!I}),keepalive:!0}).catch(()=>{})},B=x.useCallback(()=>{if(m==="done"){R(),w(!1),N("");return}N((i==null?void 0:i.tweetUrl)??""),w(!0)},[m,i==null?void 0:i.tweetUrl,R]);return c.jsxs("div",{className:"article-compose-wrapper",children:[c.jsx(AU,{src:r,coverImages:s}),c.jsxs("div",{className:"article-compose-content",children:[c.jsx(D2,{pendingTitle:o,docId:l,baseClass:"article-title-input",children:c.jsx("textarea",{className:"article-title-input",ref:b.ref,value:v,onChange:b.onChange,onKeyDown:b.onKeyDown,placeholder:"Add a title",rows:1,spellCheck:!1})}),c.jsx(RU,{}),c.jsx("div",{className:"article-compose-body",children:t})]}),c.jsxs("div",{className:"article-compose-footer",children:[c.jsxs("div",{className:"article-mark-sent-wrap",ref:M,children:[c.jsx("button",{className:`article-mark-sent-btn${m==="done"?" article-mark-sent-btn--done":""}`,onClick:B,title:m==="done"?i!=null&&i.tweetUrl?`Posted — click to unmark (${i.tweetUrl})`:"Posted — click to unmark":"Mark as manually posted",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:m==="done"?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("polyline",{points:"8 12 11 15 16 9",stroke:m==="done"?"#fff":"currentColor"})]})}),k&&(()=>{const z=S.trim(),K=!z||z.includes("x.com")||z.includes("twitter.com");return c.jsxs("div",{className:"article-mark-sent-url",children:[c.jsx("input",{ref:T,type:"text",placeholder:"Paste posted tweet URL...",value:S,onChange:F=>N(F.target.value),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),_()),F.key==="Escape"&&(w(!1),N(""))}}),c.jsx("button",{onClick:_,disabled:!K,title:z?"Save URL":"Mark posted without URL",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})})]})})()]}),c.jsx("button",{className:`article-autoplug-toggle${I?" article-autoplug-toggle--on":""}`,onClick:P,title:I?"Auto-plug ON — engagement autoplugs may reply to this post with your configured promo. Click to opt out.":"Auto-plug OFF — this post is excluded from autoplugs. Click to opt in.",children:I?"Auto-plug on":"Auto-plug off"}),m==="done"&&i&&(i.tweetUrl?c.jsxs("a",{className:"article-sent-status",href:i.tweetUrl,target:"_blank",rel:"noopener noreferrer",children:["Posted ",new Date(i.postedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})]}):c.jsxs("span",{className:"article-sent-status",children:["Posted ",new Date(i.postedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})]})),c.jsx("button",{className:`article-copy-btn${h==="copied"?" article-copy-btn--copied":""}`,onClick:f,children:h==="copied"?c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Copied!"]}):c.jsxs(c.Fragment,{children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),c.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),"Copy as HTML"]})})]})]})}const xE=new Set(["Untitled","New Document","Blog"]),IU=[];function LU(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}function wE(){return new Date().toISOString().split("T")[0]}function io(t){fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({blogContext:t})}).catch(()=>{})}function DU({src:t,coverImages:e}){const[n,r]=x.useState(t?"display":"empty"),[s,i]=x.useState(t||""),[o,l]=x.useState(e||(t?[t]:[])),[d,f]=x.useState(""),[h,m]=x.useState(""),g=x.useRef(null);x.useEffect(()=>{t?(i(t),r("display")):(i(""),r("empty"),f(""),m(""))},[t]),x.useEffect(()=>{e&&e.length>0?l(e):l(t?[t]:[])},[e]);const v=s?o.indexOf(s):-1,b=o.length,k=b>1,w=x.useCallback(B=>{const z=o[B];z&&(i(z),io({coverImage:z,coverImages:o}))},[o]),S=x.useCallback(()=>{v>0&&w(v-1)},[v,w]),N=x.useCallback(()=>{v<b-1&&w(v+1)},[v,b,w]),T=x.useCallback(async()=>{if(d.trim()){r("loading"),m("");try{const B=await fetch("/api/image-gen/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:d.trim()})});if(!B.ok){const K=await B.json().catch(()=>null);m((K==null?void 0:K.error)||`Generation failed (${B.status})`),r("prompt");return}const z=await B.json();if(z.success&&z.src){const K=[...o,z.src];l(K),i(z.src),r("display"),f(""),io({coverImage:z.src,coverImages:K})}else m(z.error||"Generation failed"),r("prompt")}catch(B){m(B.message||"Network error"),r("prompt")}}},[d,o]),M=B=>{B.key==="Enter"&&T(),B.key==="Escape"&&(r("empty"),f(""),m(""))},_=()=>{r("prompt"),setTimeout(()=>{var B;return(B=g.current)==null?void 0:B.focus()},0)},R=()=>{const B=o.filter(z=>z!==s);if(l(B),B.length>0){const z=Math.min(v,B.length-1),K=B[z];i(K),io({coverImage:K,coverImages:B})}else i(""),r("empty"),io({coverImage:void 0,coverImages:void 0})},I=()=>{r("prompt"),setTimeout(()=>{var B;return(B=g.current)==null?void 0:B.focus()},0)},P=()=>{const B=document.createElement("a");B.href=s,B.download=`cover-${v+1}.png`,B.click()};return n==="display"&&s?c.jsxs("div",{className:"blog-cover blog-cover--display",children:[c.jsx("img",{className:"blog-cover-img",src:s,alt:"Cover"}),c.jsxs("div",{className:"blog-cover-overlay",children:[k&&c.jsx("button",{className:"blog-cover-arrow blog-cover-arrow--left",onClick:S,disabled:v<=0,children:c.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"15 18 9 12 15 6"})})}),c.jsxs("div",{className:"blog-cover-overlay-center",children:[c.jsxs("button",{className:"blog-cover-btn",onClick:I,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"23 4 23 10 17 10"}),c.jsx("polyline",{points:"1 20 1 14 7 14"}),c.jsx("path",{d:"M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15"})]}),"Regenerate"]}),c.jsxs("button",{className:"blog-cover-btn",onClick:P,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),c.jsx("polyline",{points:"7 10 12 15 17 10"}),c.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),"Save"]}),c.jsxs("button",{className:"blog-cover-btn blog-cover-btn--danger",onClick:R,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),"Remove"]})]}),k&&c.jsx("button",{className:"blog-cover-arrow blog-cover-arrow--right",onClick:N,disabled:v>=b-1,children:c.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})}),k&&c.jsxs("div",{className:"blog-cover-counter",children:[v+1," / ",b]})]})]}):n==="loading"?c.jsxs("div",{className:"blog-cover blog-cover--loading",children:[c.jsx("div",{className:"blog-cover-spinner"}),c.jsx("span",{className:"blog-cover-loading-text",children:"Generating cover image..."})]}):n==="prompt"?c.jsxs("div",{className:"blog-cover blog-cover--prompt",children:[c.jsxs("div",{className:"blog-cover-prompt-row",children:[c.jsx("input",{ref:g,className:"blog-cover-prompt-input",value:d,onChange:B=>f(B.target.value),onKeyDown:M,placeholder:"Describe your cover image...",spellCheck:!1}),c.jsx("button",{className:"blog-cover-prompt-btn",onClick:T,disabled:!d.trim(),children:"Generate"}),c.jsx("button",{className:"blog-cover-prompt-cancel",onClick:()=>{r(s?"display":"empty"),f(""),m("")},children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),h&&c.jsx("div",{className:"blog-cover-error",children:h})]}):c.jsxs("div",{className:"blog-cover blog-cover--empty",onClick:_,children:[c.jsxs("svg",{className:"blog-cover-icon",width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),c.jsx("polyline",{points:"21 15 16 10 5 21"})]}),c.jsx("span",{className:"blog-cover-hint",children:"Add a featured image"})]})}function PU({tags:t,onChange:e}){const[n,r]=x.useState(""),s=x.useRef(null),i=d=>{const f=d.trim().toLowerCase();f&&!t.includes(f)&&e([...t,f]),r("")},o=d=>e(t.filter(f=>f!==d)),l=d=>{(d.key==="Enter"||d.key===",")&&(d.preventDefault(),i(n)),d.key==="Backspace"&&!n&&t.length>0&&o(t[t.length-1])};return c.jsxs("div",{className:"blog-tags",onClick:()=>{var d;return(d=s.current)==null?void 0:d.focus()},children:[t.map(d=>c.jsxs("span",{className:"blog-tag",children:[d,c.jsx("button",{className:"blog-tag-remove",onClick:f=>{f.stopPropagation(),o(d)},children:c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},d)),c.jsx("input",{ref:s,className:"blog-tag-input",value:n,onChange:d=>r(d.target.value),onKeyDown:l,onBlur:()=>{n.trim()&&i(n)},placeholder:t.length===0?"Add tags...":"",spellCheck:!1})]})}function BU({children:t,title:e,onTitleChange:n,blogContext:r,filename:s,pendingTitle:i,docId:o}){var oe,Y;const l=r||{},d=!!(r!=null&&r.active),f=xE.has(e||"")?"":e||"",h=L2(f,A=>n==null?void 0:n(A||"Untitled")),[m,g]=x.useState(l.description||""),[v,b]=x.useState(l.date||wE()),[k,w]=x.useState(l.author||""),[S,N]=x.useState(l.slug||""),[T,M]=x.useState(!!l.slug),[_,R]=x.useState(!1),[I,P]=x.useState(!1),[B,z]=x.useState(!1),[K,F]=x.useState(!1),J=l.tags||IU,$=l.draft??!1;x.useEffect(()=>{g(l.description||""),b(l.date||wE()),w(l.author||""),N(l.slug||""),M(!!l.slug)},[s]),x.useEffect(()=>{fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"list_blog_sites",arguments:{}})}).then(A=>A.json()).then(A=>{var ee,ue;const L=(ue=(ee=A==null?void 0:A.content)==null?void 0:ee[0])!=null&&ue.text?JSON.parse(A.content[0].text):A;z(Array.isArray(L==null?void 0:L.sites)&&L.sites.length>0)}).catch(()=>{})},[]),x.useEffect(()=>{!T&&e&&!xE.has(e)&&N(LU(e))},[e,T]);const W=x.useCallback(()=>{d&&io({description:m,date:v,author:k,slug:S})},[d,m,v,k,S]),q=m.length,ne=q>160;return c.jsxs("div",{className:"blog-compose-wrapper",children:[c.jsx(DU,{src:l.coverImage,coverImages:l.coverImages}),c.jsxs("div",{className:"blog-compose-content",children:[((oe=l.lastPublish)==null?void 0:oe.publishedAt)&&c.jsxs("a",{className:"blog-published-status",href:l.lastPublish.publishedUrl,target:"_blank",rel:"noopener noreferrer",title:l.lastPublish.publishedUrl||"Published",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Published ",new Date(l.lastPublish.publishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})]}),c.jsx(D2,{pendingTitle:i,docId:o,baseClass:"blog-title-input",children:c.jsx("textarea",{className:"blog-title-input",ref:h.ref,value:f,onChange:h.onChange,onKeyDown:h.onKeyDown,placeholder:"Post title",rows:1,spellCheck:!1})}),c.jsxs("div",{className:"blog-description-wrap",children:[c.jsx("textarea",{className:`blog-description-input${ne?" over-limit":""}`,value:m,onChange:A=>g(A.target.value),onBlur:W,placeholder:"Write a short description for SEO and social previews...",rows:2,spellCheck:!1}),c.jsxs("span",{className:`blog-description-count${ne?" over-limit":""}`,children:[q,"/160"]})]}),c.jsxs("div",{className:"blog-meta-toggle",onClick:()=>P(A=>!A),children:[c.jsx("svg",{className:`blog-meta-chevron${I?" open":""}`,width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})}),c.jsx("span",{children:"Metadata"}),$&&c.jsx("span",{className:"blog-draft-badge",children:"Draft"})]}),I&&c.jsxs("div",{className:"blog-meta-fields",children:[c.jsxs("div",{className:"blog-meta-row",children:[c.jsx("label",{className:"blog-meta-label",children:"Date"}),c.jsx("input",{type:"date",className:"blog-meta-input",value:v,onChange:A=>b(A.target.value),onBlur:W})]}),c.jsxs("div",{className:"blog-meta-row",children:[c.jsx("label",{className:"blog-meta-label",children:"Author"}),c.jsx("input",{type:"text",className:"blog-meta-input",value:k,onChange:A=>w(A.target.value),onBlur:W,placeholder:"Author name",spellCheck:!1})]}),c.jsxs("div",{className:"blog-meta-row",children:[c.jsx("label",{className:"blog-meta-label",children:"Slug"}),c.jsx("input",{type:"text",className:"blog-meta-input",value:S,onChange:A=>{M(!0),N(A.target.value)},onBlur:W,placeholder:"auto-generated-from-title",spellCheck:!1})]}),c.jsxs("div",{className:"blog-meta-row",children:[c.jsx("label",{className:"blog-meta-label",children:"Tags"}),c.jsx(PU,{tags:J,onChange:A=>{d&&io({tags:A})}})]}),c.jsxs("div",{className:"blog-meta-row",children:[c.jsx("label",{className:"blog-meta-label",children:"Draft"}),c.jsx("button",{className:`blog-draft-toggle${$?" active":""}`,onClick:()=>{d&&io({draft:!$})},children:c.jsx("div",{className:"blog-draft-toggle-knob"})})]})]}),c.jsx("div",{className:"blog-compose-body",children:t})]}),c.jsx("div",{className:"blog-compose-footer",children:s&&c.jsxs("div",{className:"blog-footer-actions",children:[B&&c.jsxs("button",{className:"blog-footer-btn blog-footer-btn--primary",onClick:()=>F(!0),children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"})}),(Y=l.lastPublish)!=null&&Y.publishedUrl?"Republish":"Publish"]}),c.jsxs("button",{className:"blog-footer-btn",onClick:()=>R(!0),children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("polyline",{points:"12 6 12 12 16 14"})]}),"Schedule"]})]})}),_&&s&&c.jsx(Ul,{filename:s,title:e||"Untitled",onClose:()=>R(!1)}),K&&s&&c.jsx(LT,{filename:s,title:e||"Untitled",isActive:!0,onSwitchDocument:()=>{},onClose:()=>F(!1)})]})}function $U({connectionId:t,subject:e,filename:n,onBeforeSend:r,onClose:s}){const[i,o]=x.useState("confirm"),[l,d]=x.useState("html"),[f,h]=x.useState(""),[m,g]=x.useState(null),[v,b]=x.useState(null),[k,w]=x.useState(0),[S,N]=x.useState(null),[T,M]=x.useState(null),[_,R]=x.useState("all"),[I,P]=x.useState([]),[B,z]=x.useState(""),K=x.useRef(null),F=I.find(q=>q.id===B),J=_==="exclude_issue"&&F&&T!=null?Math.max(0,T-F.recipient_count):T;x.useEffect(()=>{fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"list_subscribers",arguments:{limit:1}})}).then(q=>q.json()).then(q=>{var V,oe;const ne=(oe=(V=q.content)==null?void 0:V[0])!=null&&oe.text?JSON.parse(q.content[0].text):q;ne.count!=null&&M(ne.count)}).catch(()=>{}),fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"list_newsletter_issues",arguments:{limit:10}})}).then(q=>q.json()).then(q=>{var V,oe;const ne=(oe=(V=q.content)==null?void 0:V[0])!=null&&oe.text?JSON.parse(q.content[0].text):q;ne.issues&&P(ne.issues)}).catch(()=>{})},[]);const $=()=>i==="sent"?{sentCount:k,issueId:S,sentAt:new Date().toISOString()}:void 0;x.useEffect(()=>{const q=ne=>{i!=="sending"&&i!=="testing"&&K.current&&!K.current.contains(ne.target)&&s($())};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[s,i,k,S]),x.useEffect(()=>{const q=ne=>{ne.key==="Escape"&&i!=="sending"&&i!=="testing"&&s($())};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[s,i,k,S]);async function W(q){var ne,V;o(q?"testing":"sending"),b(null);try{r&&await r();const oe={subject:e,connectionId:t,format:l};q&&(oe.test_email=q),!q&&_==="exclude_issue"&&B&&(oe.exclude_issue_id=B);const A=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"send_newsletter",arguments:oe})})).json(),L=(V=(ne=A.content)==null?void 0:ne[0])!=null&&V.text?JSON.parse(A.content[0].text):A;if(L.error){b(L.error),o("error");return}if(L.test){g(L.sent_to),o("confirm");return}const ee=L.sent||0,ue=L.issueId||null,be=new Date().toISOString();w(ee),N(ue),o("sent"),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({newsletterContext:{lastSend:{sentCount:ee,sentAt:be,issueId:ue||void 0}}})}).catch(()=>{})}catch(oe){b(oe.message),o("error")}}return c.jsx("div",{className:"newsletter-modal-overlay",children:c.jsxs("div",{className:"newsletter-modal",ref:K,children:[c.jsxs("div",{className:"newsletter-modal__header",children:[c.jsx("h3",{children:"Send Newsletter"}),c.jsx("button",{className:"newsletter-modal__close",onClick:()=>s($()),children:"×"})]}),c.jsxs("div",{className:"newsletter-modal__body",children:[i==="confirm"&&c.jsxs(c.Fragment,{children:[c.jsxs("p",{className:"newsletter-modal__confirm-text",style:J==null?{visibility:"hidden"}:void 0,children:['Send "',c.jsx("strong",{children:e}),'" to ',J!=null?J.toLocaleString():0," subscriber",J!==1?"s":"","?"]}),c.jsxs("div",{className:"newsletter-modal__audience",children:[c.jsx("label",{className:"newsletter-modal__label",children:"Audience"}),c.jsxs("select",{className:"newsletter-modal__select",value:_,onChange:q=>{const ne=q.target.value;R(ne),ne==="all"&&z("")},children:[c.jsx("option",{value:"all",children:"All subscribers"}),I.length>0&&c.jsx("option",{value:"exclude_issue",children:"Exclude who received..."})]}),_==="exclude_issue"&&c.jsxs("select",{className:"newsletter-modal__select",value:B,onChange:q=>z(q.target.value),children:[c.jsx("option",{value:"",children:"Select a past issue"}),I.map(q=>c.jsxs("option",{value:q.id,children:[q.subject," (",q.recipient_count," sent)"]},q.id))]})]}),c.jsxs("div",{className:"newsletter-modal__format-toggle",children:[c.jsx("button",{className:`newsletter-modal__format-btn${l==="html"?" active":""}`,onClick:()=>d("html"),children:"HTML"}),c.jsx("button",{className:`newsletter-modal__format-btn${l==="plaintext"?" active":""}`,onClick:()=>d("plaintext"),children:"Plaintext"})]}),c.jsxs("div",{className:"newsletter-modal__test-section",children:[c.jsxs("div",{className:"newsletter-modal__test-row",children:[c.jsx("input",{type:"email",className:"newsletter-modal__test-input",placeholder:"Test email address",value:f,onChange:q=>h(q.target.value),onKeyDown:q=>{q.key==="Enter"&&f.trim()&&W(f.trim())}}),c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--test",disabled:!f.trim(),onClick:()=>W(f.trim()),children:"Send Test"})]}),m&&c.jsxs("p",{className:"newsletter-modal__test-success",children:["Test sent to ",m]})]}),c.jsxs("div",{className:"newsletter-modal__actions",children:[c.jsx("button",{className:"newsletter-modal__btn",onClick:s,children:"Cancel"}),c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",disabled:_==="exclude_issue"&&!B,onClick:()=>W(),children:"Send Now"})]})]}),(i==="sending"||i==="testing")&&c.jsxs("div",{className:"newsletter-modal__status",children:[c.jsx("div",{className:"newsletter-modal__spinner"}),c.jsx("span",{children:i==="testing"?"Sending test...":"Sending..."})]}),i==="sent"&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"newsletter-modal__status newsletter-modal__status--success",children:["Sent to ",k," subscriber",k!==1?"s":"","!"]}),c.jsx("div",{className:"newsletter-modal__actions",children:c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>s({sentCount:k,issueId:S,sentAt:new Date().toISOString()}),children:"Done"})})]}),i==="error"&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"newsletter-modal__error",children:v}),c.jsxs("div",{className:"newsletter-modal__actions",children:[c.jsx("button",{className:"newsletter-modal__btn",onClick:s,children:"Cancel"}),c.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>W(),children:"Retry"})]})]})]})]})})}function kE(t){fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({newsletterContext:t})}).catch(()=>{})}function FU({children:t,newsletterContext:e,filename:n,title:r,onTitleChange:s,onBeforeSend:i}){var $;const o=e||{},[l,d]=x.useState(o.subject||""),[f,h]=x.useState(o.previewText||""),[m,g]=x.useState([]),[v,b]=x.useState(null),[k,w]=x.useState(!1),[S,N]=x.useState(($=o.lastSend)!=null&&$.sentAt?{sentCount:o.lastSend.sentCount,issueId:o.lastSend.issueId||null,sentAt:o.lastSend.sentAt}:null),T=x.useRef(null),M=x.useRef(n),_=x.useRef(o.subject||""),R=x.useRef(o.previewText||"");x.useEffect(()=>{var W;if(M.current!==n)d(o.subject||""),h(o.previewText||""),_.current=o.subject||"",R.current=o.previewText||"",M.current=n;else{const q=o.subject||"",ne=o.previewText||"";q!==_.current&&(d(q),_.current=q),ne!==R.current&&(h(ne),R.current=ne)}N((W=o.lastSend)!=null&&W.sentAt?{sentCount:o.lastSend.sentCount,issueId:o.lastSend.issueId||null,sentAt:o.lastSend.sentAt}:null)},[e,n]),x.useEffect(()=>{fetch("/api/connections").then(W=>W.json()).then(W=>{const q=(W.connections||[]).filter(ne=>ne.provider==="newsletter"&&ne.status==="active");g(q)}).catch(()=>{})},[]);const I=!!(e!=null&&e.active),P=x.useRef();x.useEffect(()=>{if(P.current&&clearTimeout(P.current),!(!s||!l.trim()))return P.current=setTimeout(async()=>{const W=r,q=!W||W==="Untitled",ne=T.current!==null&&W===T.current;if(q||ne){try{await fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({newsletterContext:{subject:l}})})}catch{}s(l.trim()),T.current=l.trim()}},500),()=>{P.current&&clearTimeout(P.current)}},[l,r,s]);const B=x.useCallback(()=>{I&&(_.current=l,R.current=f,kE({subject:l,previewText:f}))},[I,l,f]),z=f.length,K=z>=90,F=z>150,J=()=>{m.length===1&&b(m[0].id),m.length>1&&b(m[0].id)};return c.jsxs("div",{className:"nl-compose-wrapper",children:[S&&c.jsxs("div",{className:"nl-sent-status",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Sent ",new Date(S.sentAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})," to ",S.sentCount," subscriber",S.sentCount!==1?"s":""]}),c.jsxs("div",{className:"nl-compose-content",children:[c.jsx("input",{className:"nl-subject-input",type:"text",value:l,onChange:W=>d(W.target.value),onBlur:B,placeholder:"Subject line (defaults to title if empty)",autoComplete:"off","data-lpignore":"true","data-1p-ignore":!0,spellCheck:!1}),c.jsxs("div",{className:"nl-preview-wrap",children:[c.jsx("textarea",{className:`nl-preview-input${F?" over-limit":""}`,value:f,onChange:W=>h(W.target.value),onBlur:B,placeholder:"Preview text shown in inbox before opening...",rows:2,spellCheck:!1}),c.jsxs("span",{className:`nl-preview-count${F?" over-limit":K?" full":""}`,children:[z,"/90"]})]}),c.jsx("div",{className:"nl-compose-body",children:t})]}),n&&c.jsxs("div",{className:"nl-compose-footer",children:[m.length>0&&c.jsxs("button",{className:"nl-footer-btn nl-footer-btn--primary",onClick:J,children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),c.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),"Send"]}),c.jsxs("button",{className:"nl-footer-btn",onClick:()=>w(!0),children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("polyline",{points:"12 6 12 12 16 14"})]}),"Schedule"]})]}),v&&n&&c.jsx($U,{connectionId:v,subject:l||r||"Untitled",filename:n,onBeforeSend:i,onClose:W=>{b(null),W&&(N(W),kE({lastSend:{sentCount:W.sentCount,sentAt:W.sentAt,issueId:W.issueId||void 0}}))}}),k&&n&&c.jsx(Ul,{filename:n,title:r||"Untitled",onClose:()=>w(!1)})]})}const SE=600,zU=48;function Au(t){return t!=null&&typeof t=="object"&&Object.keys(t).length>0}function UU(t){const e=typeof(t==null?void 0:t.content_type)=="string"&&t.content_type||typeof(t==null?void 0:t.contentType)=="string"&&t.contentType||"";return e||(Au(t==null?void 0:t.blogContext)?"blog":t!=null&&t.newsletterContext&&(t.newsletterContext.active===!0||Au(t.newsletterContext))?"newsletter":Au(t==null?void 0:t.articleContext)?"article":t!=null&&t.tweetContext?t.tweetContext.mode||"tweet":Au(t==null?void 0:t.linkedinContext)?"linkedin":"document")}function HU(){var Tt,Mt,on;const t=x.useRef(null),e=x.useRef([]),[n,r]=x.useState(null),[s,i]=x.useState(null),[o,l]=x.useState([]),[d,f]=x.useState("Untitled"),[h,m]=x.useState(null),[g,v]=x.useState(void 0),[b,k]=x.useState(0),[w,S]=x.useState(!0),[N,T]=x.useState(0),[M,_]=x.useState(0),[R,I]=x.useState(0),[P,B]=x.useState({filenames:[],counts:{}}),[z,K]=x.useState({state:"unconfigured"}),[F,J]=x.useState(!1),[$,W]=x.useState({}),[q,ne]=x.useState(()=>localStorage.getItem("ow-toolbar")!=="hidden"),[V,oe]=x.useState(!1),Y=x.useRef(null),A=x.useRef(null),[L,ee]=x.useState(0),[ue,be]=x.useState(!1),[re,we]=x.useState(!1),[Ee,$e]=x.useState(()=>{try{const G=localStorage.getItem("ow-sidebar-width");if(G){const xe=parseInt(G,10);if(!isNaN(xe)&&xe>=BT&&xe<=$T)return xe}}catch{}return nv}),{open:Fe,width:Ze,visible:Re,setOverlay:tt,closeRail:gt}=Ll(),ut=$d()==="board";x.useEffect(()=>{const G=A.current;if(!G)return;ee(G.clientWidth);const xe=new ResizeObserver(He=>{for(const ht of He)ee(ht.contentRect.width)});return xe.observe(G),()=>xe.disconnect()},[]),x.useEffect(()=>{if(ut||L===0){be(!1);return}const G=L-(w?Ee:0)-(Fe?Ze:0);be(xe=>xe?G<SE+zU:G<SE)},[L,w,Ee,Fe,Ze,ut]),x.useLayoutEffect(()=>{tt(ue),we(!1)},[ue,tt]),x.useEffect(()=>{if(!ue)return;const G=xe=>{xe.key==="Escape"&&(re||Re)&&(we(!1),gt())};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[ue,re,Re,gt]);const ge=ue?re:w,[yt,Ct]=x.useState(null),[_t,Lt]=x.useState(null),[at,De]=x.useState(new Set),ve=x.useRef(0),Z=x.useRef(null),je=1500,Q=x.useCallback((G,xe)=>{Z.current&&(clearTimeout(Z.current),Z.current=null),ve.current=Date.now(),Ct(G),Lt(xe)},[]),he=x.useCallback(()=>{if(Z.current)return;const G=Date.now()-ve.current,xe=je-G;xe<=0?(Ct(null),Lt(null)):Z.current=setTimeout(()=>{Z.current=null,Ct(null),Lt(null)},xe)},[]),[,me]=x.useState(0),[Ue,Oe]=x.useState(null),Ve=x.useRef(null),et=x.useRef(null),ft=x.useRef(null),We=x.useRef([]),Ge=x.useRef(-1),vt=x.useRef(null),Et=x.useRef(!1),_e=x.useRef(""),[Ne,Ke]=x.useState(""),[st,Ye]=x.useState(!1),[jt,j]=x.useState(!1);function U(){const G=document.querySelector(".editor-container");return(G==null?void 0:G.scrollTop)||0}function ie(){if(Ge.current<0)return;const G=We.current[Ge.current];G&&(G.scrollTop=U())}const D=UU($),le=D==="article",fe=D==="blog",se=D==="newsletter",pe=D==="tweet"||D==="reply"||D==="quote";x.useEffect(()=>(le?document.documentElement.setAttribute("data-view","article"):fe?document.documentElement.setAttribute("data-view","blog"):se?document.documentElement.setAttribute("data-view","newsletter"):pe?document.documentElement.setAttribute("data-view","tweet"):document.documentElement.removeAttribute("data-view"),()=>document.documentElement.removeAttribute("data-view")),[pe,le,fe,se]),x.useEffect(()=>{const G=()=>me(xe=>xe+1);return window.addEventListener("ow-sidebar-mode-change",G),()=>window.removeEventListener("ow-sidebar-mode-change",G)},[]),x.useEffect(()=>{fetch("/api/document",{cache:"no-store"}).then(G=>G.json()).then(G=>{G.document&&(v(G.document),et.current=G.document),G.title&&f(G.title),G.metadata&&W(G.metadata)}).catch(()=>{v(void 0)}),fetch("/api/pending-docs").then(G=>G.json()).then(G=>B(G)).catch(()=>{}),fetch("/api/sync/status").then(G=>G.json()).then(G=>K(G)).catch(()=>{})},[]);const ye=x.useCallback(G=>{t.current=G,r(G),i(null),e.current=[G],l([G])},[]),Pe=x.useRef([]),Se=x.useCallback(G=>{if(e.current=G,l(G),Pe.current.length>0&&G.length>0){const xe=Pe.current;Pe.current=[];for(const He of G)He.isDestroyed||Rp(He,xe)}},[]),Vt=x.useCallback(G=>{var Cn,wr;const xe=performance.now(),He=window.__lastSwitch;He&&He.filename===G.filename?(He.tReceive=xe,console.log(`[Switch] RECEIVE filename=${G.filename} sendToReceive=${(xe-He.tSend).toFixed(1)}ms (server round-trip)`)):console.log(`[Switch] RECEIVE filename=${G.filename} (no matching CLICK — agent or initial-load switch)`),Ve.current&&(clearTimeout(Ve.current),Ve.current=null);const ht=_e.current==="",xt=G.filename===_e.current;_e.current=G.filename,et.current=G.document,ft.current=JSON.stringify(G.document),Ke(G.filename),v(G.document),f(G.title),W(G.metadata||{}),m(((Cn=G.pendingMetadata)==null?void 0:Cn.title)??null),!xt&&!ht&&((wr=G.metadata)!=null&&wr.tweetContext)&&k(tn=>tn+1),He&&He.filename===G.filename&&requestAnimationFrame(()=>{const tn=performance.now();He.tCommit=tn,console.log(`[Switch] COMMIT filename=${G.filename} receiveToCommit=${(tn-xe).toFixed(1)}ms totalClickToPaint=${(tn-He.tClick).toFixed(1)}ms`)});const Nn=vt.current??"push";if(vt.current=null,We.current.length===0?(We.current=[{filename:G.filename,scrollTop:0}],Ge.current=0):Nn==="back"?Ge.current=Math.max(0,Ge.current-1):Nn==="forward"?Ge.current=Math.min(We.current.length-1,Ge.current+1):xt||(We.current=We.current.slice(0,Ge.current+1),We.current.push({filename:G.filename,scrollTop:0}),Ge.current=We.current.length-1),!Et.current){const tn=`#${encodeURIComponent(G.filename)}`,kr={ow:{filename:G.filename,navIndex:Ge.current}};We.current.length===1||xt?window.history.replaceState(kr,"",tn):window.history.pushState(kr,"",tn)}if(Et.current=!1,Nn==="back"||Nn==="forward"){const tn=We.current[Ge.current];tn&&setTimeout(()=>{const kr=document.querySelector(".editor-container");kr&&(kr.scrollTop=tn.scrollTop)},50)}Ye(Ge.current>0),j(Ge.current<We.current.length-1)},[]),It=x.useCallback(G=>{Ve.current&&(clearTimeout(Ve.current),Ve.current=null),et.current=G.document,ft.current=JSON.stringify(G.document),v(G.document),f(G.title),W(G.metadata||{}),Oe(xe=>xe?{filename:G.filename,orphanCount:xe.orphanCount+G.orphanCount,staleBaselineCount:xe.staleBaselineCount+G.staleBaselineCount,reloadCount:xe.reloadCount+1}:{filename:G.filename,orphanCount:G.orphanCount,staleBaselineCount:G.staleBaselineCount,reloadCount:1})},[]),Sn=x.useCallback(()=>{T(G=>G+1),_(G=>G+1)},[]),yn=x.useCallback(()=>{I(G=>G+1)},[]),En=x.useCallback(G=>{B(G)},[]),{connected:qe,sendMessage:Nt,docVersionRef:bn}=pF({onNodeChanges:G=>{const xe=e.current;if(xe.length<=1){const He=t.current;if(!He)return;Rp(He,G)}else{if(xe.some(ht=>ht.isDestroyed)){Pe.current.push(...G);return}for(const ht of xe)Rp(ht,G)}},onDocumentSwitched:Vt,onDocumentReloaded:It,onDocumentsChanged:Sn,onWorkspacesChanged:yn,onPendingDocsChanged:En,onMetadataChanged:G=>W(G),onWritingStarted:(G,xe)=>Q(G,xe),onWritingFinished:()=>he(),onIdRewrites:G=>{const xe=e.current,He=xe.length>0?xe:t.current?[t.current]:[];for(const xt of He)xt.isDestroyed||e$(xt,G);const ht=et.current;if(ht&&Array.isArray(G)&&G.length>0){const xt=new Map(G.map(Cn=>[Cn.oldId,Cn.newId])),Nn=Cn=>{var wr;if(Array.isArray(Cn))for(const tn of Cn){const kr=(wr=tn==null?void 0:tn.attrs)==null?void 0:wr.id;kr&&xt.has(kr)&&(tn.attrs={...tn.attrs,id:xt.get(kr)}),tn!=null&&tn.content&&Nn(tn.content)}};Nn(ht.content||[])}},onPendingFilenamesChanged:G=>De(G),onSyncStatus:G=>K(G),onTitleChanged:G=>f(G),getEditorState:()=>{var xe;const G=et.current||((xe=t.current)==null?void 0:xe.getJSON());return G?{document:G}:null}}),Gt=x.useCallback(()=>{var He;Ve.current&&(clearTimeout(Ve.current),Ve.current=null);const G=et.current||((He=t.current)==null?void 0:He.getJSON());if(!G)return;const xe=JSON.stringify(G);xe!==ft.current&&(Nt({type:"doc-update",document:G,filename:_e.current,version:bn.current}),ft.current=xe)},[Nt,bn]),dr=x.useCallback(async()=>{var xe;const G=et.current||((xe=t.current)==null?void 0:xe.getJSON());G&&await fetch("/api/documents/sync-content",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({document:G,filename:_e.current})})},[]);x.useEffect(()=>{const G=()=>{var xt;Ve.current&&(clearTimeout(Ve.current),Ve.current=null);const He=et.current||((xt=t.current)==null?void 0:xt.getJSON());if(!He)return;const ht=JSON.stringify({type:"flush",document:He});navigator.sendBeacon("/api/flush",new Blob([ht],{type:"application/json"}))},xe=()=>{document.visibilityState==="hidden"&&G()};return window.addEventListener("beforeunload",G),document.addEventListener("visibilitychange",xe),()=>{window.removeEventListener("beforeunload",G),document.removeEventListener("visibilitychange",xe)}},[]);const ir=x.useCallback(()=>{Gt(),Nt({type:"create-document"})},[Gt,Nt]),Un=x.useCallback(G=>{if(G===_e.current)return;const xe=performance.now();window.__lastSwitch={filename:G,tClick:xe,tSend:0,tReceive:0,tCommit:0},console.log(`[Switch] CLICK filename=${G} t=${xe.toFixed(0)}`),ie(),vt.current="push",Gt(),Nt({type:"switch-document",filename:G});const He=performance.now();window.__lastSwitch.tSend=He,console.log(`[Switch] SEND filename=${G} clickToSend=${(He-xe).toFixed(1)}ms`)},[Gt,Nt]),Ar=x.useRef(null),un=x.useCallback(async G=>{let xe=null;if(G.docId)try{const He=await fetch("/api/documents").then(ht=>ht.json());if(Array.isArray(He)){const ht=He.find(xt=>xt.docId===G.docId);ht&&(xe=ht.filename)}}catch{}if(!xe&&G.filename&&(xe=G.filename),!xe){console.warn("[link] could not resolve doc: target",G);return}G.nodeId||G.quote?Ar.current={nodeId:G.nodeId||void 0,quote:G.quote||void 0}:Ar.current={toTop:!0},Un(xe),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ow-reveal-active-doc",{detail:{filename:xe}}))},0)},[Un]);x.useEffect(()=>{const G=xe=>{const He=xe.detail;He&&un(He)};return window.addEventListener("ow-navigate-to-link",G),()=>window.removeEventListener("ow-navigate-to-link",G)},[un]);const Ss=x.useRef(!1);x.useEffect(()=>{if(Ss.current)return;Ss.current=!0;const G=window.location.pathname.match(/^\/d\/([a-f0-9]{8})\/?$/);if(!G)return;const xe=G[1],He=window.location.hash.match(/^#node=([a-f0-9]{8})$/),ht=He?He[1]:null;un({docId:xe,filename:null,nodeId:ht,quote:null})},[un]),x.useEffect(()=>{if(!n||!Ar.current)return;const G=Ar.current;Ar.current=null,setTimeout(()=>{if(G.toTop){const ht=document.querySelector(".editor-container");ht&&(ht.scrollTop=0);return}let xe=null;if(G.nodeId&&n.state.doc.descendants((ht,xt)=>{var Nn;return xe!==null?!1:((Nn=ht.attrs)==null?void 0:Nn.id)===G.nodeId?(xe=xt+1,!1):!0}),xe===null&&G.quote){const ht=G.quote;n.state.doc.descendants((xt,Nn)=>{if(xe!==null)return!1;if(xt.isTextblock){const Cn=xt.textContent.indexOf(ht);if(Cn>=0)return xe=Nn+1+Cn,!1}return!0})}if(xe===null)return;n.chain().focus().setTextSelection({from:xe,to:xe}).scrollIntoView().run();const He=n.view.nodeDOM(xe-1);He!=null&&He.classList&&(He.classList.add("scroll-target-flash"),setTimeout(()=>He.classList.remove("scroll-target-flash"),1200))},100)},[n,Ne]);const us=x.useCallback(()=>{Ge.current<=0||window.history.back()},[]),Wt=x.useCallback(()=>{Ge.current>=We.current.length-1||window.history.forward()},[]);x.useEffect(()=>{const G=xe=>{const He=xe.state&&xe.state.ow;He!=null&&He.filename&&He.filename!==_e.current&&(ie(),vt.current=He.navIndex<Ge.current?"back":"forward",Et.current=!0,Gt(),Nt({type:"switch-document",filename:He.filename}))};return window.addEventListener("popstate",G),()=>window.removeEventListener("popstate",G)},[Gt,Nt]);const qs=x.useCallback(()=>{const G=_e.current,xe=t.current;if(!G||!xe)return;const He=()=>{const ht=e.current;if(ht.length>1)for(const xt of ht)xt!=null&&xt.view&&pk(xt.view);else xe!=null&&xe.view&&pk(xe.view)};fetch(`/api/comments/${encodeURIComponent(G)}`).then(ht=>ht.json()).then(ht=>{dk(ht.comments||[]),He()}).catch(()=>{dk([]),He()})},[]);x.useEffect(()=>{qs()},[Ne,n,qs]),x.useEffect(()=>{const G=xe=>{const He=xe.detail;(He==null?void 0:He.filename)===_e.current&&qs()};return window.addEventListener("ow-comments-changed",G),()=>window.removeEventListener("ow-comments-changed",G)},[qs]),x.useEffect(()=>{function G(xe){var xt;const He=xe.detail;if(!He)return;const ht=$==null?void 0:$.docId;ht&&He.docId&&He.docId!==ht||m(((xt=He.pendingMetadata)==null?void 0:xt.title)??null)}return window.addEventListener("ow-pending-metadata-changed",G),()=>window.removeEventListener("ow-pending-metadata-changed",G)},[$==null?void 0:$.docId]),x.useEffect(()=>{const G=$==null?void 0:$.docId;if(!G){mk([]);return}let xe=!1;return fetch(`/api/backlinks/${G}`).then(He=>He.ok?He.json():[]).then(He=>{if(xe)return;mk(Array.isArray(He)?He:[]);const ht=e.current.length>0?e.current:n?[n]:[];for(const xt of ht)xt!=null&&xt.view&&T5(xt.view)}).catch(()=>{}),()=>{xe=!0}},[$,n]),x.useEffect(()=>{const G=xe=>{xe.altKey&&xe.key==="ArrowLeft"&&(xe.preventDefault(),us()),xe.altKey&&xe.key==="ArrowRight"&&(xe.preventDefault(),Wt())};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[us,Wt]);const Jr=x.useCallback(G=>{et.current=G,Ve.current&&clearTimeout(Ve.current),Ve.current=setTimeout(()=>{const xe=et.current||G,He=JSON.stringify(xe);He!==ft.current&&(Nt({type:"doc-update",document:xe,filename:_e.current,version:bn.current}),ft.current=He)},1e3)},[Nt,bn]),Rr=x.useCallback(G=>{f(G),Nt({type:"title-update",title:G})},[Nt]),Es=x.useCallback(()=>{ne(G=>(localStorage.setItem("ow-toolbar",G?"hidden":"visible"),!G))},[]),Ie=x.useCallback(()=>{oe(G=>{if(!G)return Y.current={sidebarOpen:w,showToolbar:q},S(!1),we(!1),ne(!1),!0;const xe=Y.current;return xe&&(S(xe.sidebarOpen),ne(xe.showToolbar),Y.current=null),!1})},[w,q]),ot=x.useCallback(()=>{if(z.state==="unconfigured"){J(!0);return}Gt(),Nt({type:"save"}),fetch("/api/sync/push",{method:"POST"}).catch(()=>{})},[z.state,Gt,Nt]);return c.jsxs("div",{className:`app${ue?" app--overlay":""}`,ref:A,children:[!ut&&c.jsx(Dk,{open:ge,floating:ue,width:Ee,onWidthChange:$e,onSwitchDocument:Un,onCreateDocument:ir,refreshKey:N,docTagsRefreshKey:M,workspacesRefreshKey:R,pendingDocs:P,writingTitle:yt,writingTarget:_t,pendingWriteFilenames:at,activeFilename:Ne,onClose:()=>ue?we(!1):S(!1)}),c.jsxs("div",{className:"app-main",children:[c.jsx(J5,{title:d,onTitleChange:Rr,onToggleSidebar:!ut&&!ge?()=>ue?we(!0):S(!0):void 0,canGoBack:st,canGoForward:jt,onGoBack:us,onGoForward:Wt,editor:n,onToggleToolbar:Es,toolbarOpen:q,focusMode:V,onToggleFocusMode:Ie}),q&&n&&c.jsx(B5,{editor:s||n}),ut&&c.jsx(Dk,{open:!0,width:Ee,onWidthChange:$e,onSwitchDocument:Un,onCreateDocument:ir,refreshKey:N,docTagsRefreshKey:M,workspacesRefreshKey:R,pendingDocs:P,writingTitle:yt,writingTarget:_t,pendingWriteFilenames:at}),c.jsx(Y5,{}),!qe&&c.jsxs("div",{className:"connection-banner",children:[c.jsx("div",{className:"connection-banner-spinner"}),c.jsx("span",{children:"Reconnecting to server..."})]}),($==null?void 0:$.autoAccept)===!0&&c.jsxs("div",{className:"editor-auto-accept-banner",title:"Agent edits skip the review step. Right-click the doc in the sidebar to turn off.",children:[c.jsx("span",{className:"editor-auto-accept-dot"}),"Auto-accept on — agent edits skip review"]}),Ue&&c.jsxs("div",{className:"editor-reload-banner",role:"status","aria-live":"polite",children:[c.jsx("span",{className:"editor-reload-dot","aria-hidden":"true"}),c.jsx("span",{children:Ue.reloadCount>1?`Document reloaded from disk ${Ue.reloadCount}× since you last looked`:"Document reloaded from disk (external write detected)"}),(Ue.orphanCount>0||Ue.staleBaselineCount>0)&&c.jsxs("span",{className:"editor-reload-detail",children:[Ue.orphanCount>0&&c.jsxs("span",{className:"editor-reload-tag editor-reload-tag--orphan",children:[Ue.orphanCount," orphan",Ue.orphanCount===1?"":"s"]}),Ue.staleBaselineCount>0&&c.jsxs("span",{className:"editor-reload-tag editor-reload-tag--stale",children:[Ue.staleBaselineCount," stale-baseline"]})]}),c.jsx("button",{type:"button",className:"editor-reload-dismiss",onClick:()=>Oe(null),"aria-label":"Dismiss reload notification",children:"×"})]}),c.jsx("div",{className:"editor-container",children:le?c.jsx(OU,{title:d,onTitleChange:Rr,coverImage:(Tt=$==null?void 0:$.articleContext)==null?void 0:Tt.coverImage,coverImages:(Mt=$==null?void 0:$.articleContext)==null?void 0:Mt.coverImages,lastPost:(on=$==null?void 0:$.articleContext)==null?void 0:on.lastPost,pendingTitle:h,docId:($==null?void 0:$.docId)||void 0,autoplug:$==null?void 0:$.autoplug,children:c.jsx(xu,{initialContent:g,extensions:g5,onUpdate:Jr,onReady:ye,onLinkClick:un})}):fe?c.jsx(BU,{title:d,onTitleChange:Rr,blogContext:$==null?void 0:$.blogContext,filename:Ne,pendingTitle:h,docId:($==null?void 0:$.docId)||void 0,children:c.jsx(xu,{initialContent:g,onUpdate:Jr,onReady:ye,onLinkClick:un})}):se?c.jsx(FU,{newsletterContext:$==null?void 0:$.newsletterContext,filename:Ne,title:d,onTitleChange:Rr,onBeforeSend:dr,children:c.jsx(xu,{initialContent:g,onUpdate:Jr,onReady:ye,onLinkClick:un})}):pe&&($!=null&&$.tweetContext)?c.jsx(_U,{tweetContext:$.tweetContext,initialContent:g,onUpdate:Jr,onEditorReady:ye,onEditorsChange:Se,onActiveEditorChange:i,filename:Ne,title:d,autoplug:$==null?void 0:$.autoplug},b):c.jsx(xu,{initialContent:g,onUpdate:Jr,onReady:ye,onLinkClick:un})})]}),ue&&(re||Re)&&c.jsx("div",{className:"ow-scrim",onClick:()=>{we(!1),gt()},"aria-hidden":"true"}),c.jsx(fF,{editors:o,pendingDocs:P,currentFilename:Ne,docId:($==null?void 0:$.docId)||null,pendingTitle:h,onSwitchDocument:Un,sendMessage:Nt,getDocument:()=>et.current,docVersionRef:bn,syncStatus:z,onSync:ot,onToggleToolbar:Es,toolbarOpen:q,focusMode:V,onToggleFocusMode:Ie}),c.jsx(u$,{editorRef:t,allEditors:o,documentId:Ne}),c.jsx(p$,{documentId:Ne}),F&&c.jsx(hF,{onClose:()=>J(!1),onSetupComplete:()=>{fetch("/api/sync/status").then(G=>G.json()).then(K).catch(()=>{})}})]})}_M();kM.createRoot(document.getElementById("root")).render(c.jsx(Ti.StrictMode,{children:c.jsx(AM,{children:c.jsx(HU,{})})}));
|