openwriter 0.13.0 → 0.14.0

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.
@@ -202,9 +202,9 @@ https://github.com/highlightjs/highlight.js/issues/2277`),ln=Ce,St=Qe),bt===void
202
202
  `},f]}}const b6=t=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:t.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[t.APOS_STRING_MODE,t.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:t.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),x6=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],w6=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],k6=[...x6,...w6],S6=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),S_=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),E_=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),E6=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse(),N6=S_.concat(E_).sort().reverse();function C6(t){const e=b6(t),n=N6,r="and or not only",s="[\\w-]+",i="("+s+"|@\\{"+s+"\\})",o=[],l=[],d=function(O){return{className:"string",begin:"~?"+O+".*?"+O}},f=function(O,_,T){return{className:O,begin:_,relevance:T}},h={$pattern:/[a-z-]+/,keyword:r,attribute:S6.join(" ")},m={begin:"\\(",end:"\\)",contains:l,keywords:h,relevance:0};l.push(t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE,d("'"),d('"'),e.CSS_NUMBER_MODE,{begin:"(url|data-uri)\\(",starts:{className:"string",end:"[\\)\\n]",excludeEnd:!0}},e.HEXCOLOR,m,f("variable","@@?"+s,10),f("variable","@\\{"+s+"\\}"),f("built_in","~?`[^`]*?`"),{className:"attribute",begin:s+"\\s*:",end:":",returnBegin:!0,excludeEnd:!0},e.IMPORTANT,{beginKeywords:"and not"},e.FUNCTION_DISPATCH);const g=l.concat({begin:/\{/,end:/\}/,contains:o}),y={beginKeywords:"when",endsWithParent:!0,contains:[{beginKeywords:"and not"}].concat(l)},b={begin:i+"\\s*:",returnBegin:!0,end:/[;}]/,relevance:0,contains:[{begin:/-(webkit|moz|ms|o)-/},e.CSS_VARIABLE,{className:"attribute",begin:"\\b("+E6.join("|")+")\\b",end:/(?=:)/,starts:{endsWithParent:!0,illegal:"[<=$]",relevance:0,contains:l}}]},x={className:"keyword",begin:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",starts:{end:"[;{}]",keywords:h,returnEnd:!0,contains:l,relevance:0}},k={className:"variable",variants:[{begin:"@"+s+"\\s*:",relevance:15},{begin:"@"+s}],starts:{end:"[;}]",returnEnd:!0,contains:g}},E={variants:[{begin:"[\\.#:&\\[>]",end:"[;{}]"},{begin:i,end:/\{/}],returnBegin:!0,returnEnd:!0,illegal:`[<='$"]`,relevance:0,contains:[t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE,y,f("keyword","all\\b"),f("variable","@\\{"+s+"\\}"),{begin:"\\b("+k6.join("|")+")\\b",className:"selector-tag"},e.CSS_NUMBER_MODE,f("selector-tag",i,0),f("selector-id","#"+i),f("selector-class","\\."+i,0),f("selector-tag","&",0),e.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",begin:":("+S_.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+E_.join("|")+")"},{begin:/\(/,end:/\)/,relevance:0,contains:g},{begin:"!important"},e.FUNCTION_DISPATCH]},C={begin:s+`:(:)?(${n.join("|")})`,returnBegin:!0,contains:[E]};return o.push(t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE,x,k,C,b,E,y,e.FUNCTION_DISPATCH),{name:"Less",case_insensitive:!0,illegal:`[=>'/<($"]`,contains:o}}function _6(t){const e="\\[=*\\[",n="\\]=*\\]",r={begin:e,end:n,contains:["self"]},s=[t.COMMENT("--(?!"+e+")","$"),t.COMMENT("--"+e,n,{contains:[r],relevance:10})];return{name:"Lua",aliases:["pluto"],keywords:{$pattern:t.UNDERSCORE_IDENT_RE,literal:"true false nil",keyword:"and break do else elseif end for goto if in local not or repeat return then until while",built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"},contains:s.concat([{className:"function",beginKeywords:"function",end:"\\)",contains:[t.inherit(t.TITLE_MODE,{begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{className:"params",begin:"\\(",endsWithParent:!0,contains:s}].concat(s)},t.C_NUMBER_MODE,t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,{className:"string",begin:e,end:n,contains:[r],relevance:5}])}}function T6(t){const e={className:"variable",variants:[{begin:"\\$\\("+t.UNDERSCORE_IDENT_RE+"\\)",contains:[t.BACKSLASH_ESCAPE]},{begin:/\$[@%<?\^\+\*]/}]},n={className:"string",begin:/"/,end:/"/,contains:[t.BACKSLASH_ESCAPE,e]},r={className:"variable",begin:/\$\([\w-]+\s/,end:/\)/,keywords:{built_in:"subst patsubst strip findstring filter filter-out sort word wordlist firstword lastword dir notdir suffix basename addsuffix addprefix join wildcard realpath abspath error warning shell origin flavor foreach if or and call eval file value"},contains:[e,n]},s={begin:"^"+t.UNDERSCORE_IDENT_RE+"\\s*(?=[:+?]?=)"},i={className:"meta",begin:/^\.PHONY:/,end:/$/,keywords:{$pattern:/[\.\w]+/,keyword:".PHONY"}},o={className:"section",begin:/^[^\s]+:/,end:/$/,contains:[e]};return{name:"Makefile",aliases:["mk","mak","make"],keywords:{$pattern:/[\w-]+/,keyword:"define endef undefine ifdef ifndef ifeq ifneq else endif include -include sinclude override export unexport private vpath"},contains:[t.HASH_COMMENT_MODE,e,n,r,s,i,o]}}function M6(t){const e=t.regex,n={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},r={begin:"^[-\\*]{3,}",end:"$"},s={className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},i={className:"bullet",begin:"^[ ]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},o={begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},l=/[A-Za-z][A-Za-z0-9+.-]*/,d={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:e.concat(/\[.+?\]\(/,l,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},f={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},h={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},m=t.inherit(f,{contains:[]}),g=t.inherit(h,{contains:[]});f.contains.push(g),h.contains.push(m);let y=[n,d];return[f,h,m,g].forEach(E=>{E.contains=E.contains.concat(y)}),y=y.concat(f,h),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:y},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:y}]}]},n,i,f,h,{className:"quote",begin:"^>\\s+",contains:y,end:"$"},s,r,d,o,{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}function A6(t){const e={className:"built_in",begin:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},n=/[a-zA-Z@][a-zA-Z0-9_]*/,l={"variable.language":["this","super"],$pattern:n,keyword:["while","export","sizeof","typedef","const","struct","for","union","volatile","static","mutable","if","do","return","goto","enum","else","break","extern","asm","case","default","register","explicit","typename","switch","continue","inline","readonly","assign","readwrite","self","@synchronized","id","typeof","nonatomic","IBOutlet","IBAction","strong","weak","copy","in","out","inout","bycopy","byref","oneway","__strong","__weak","__block","__autoreleasing","@private","@protected","@public","@try","@property","@end","@throw","@catch","@finally","@autoreleasepool","@synthesize","@dynamic","@selector","@optional","@required","@encode","@package","@import","@defs","@compatibility_alias","__bridge","__bridge_transfer","__bridge_retained","__bridge_retain","__covariant","__contravariant","__kindof","_Nonnull","_Nullable","_Null_unspecified","__FUNCTION__","__PRETTY_FUNCTION__","__attribute__","getter","setter","retain","unsafe_unretained","nonnull","nullable","null_unspecified","null_resettable","class","instancetype","NS_DESIGNATED_INITIALIZER","NS_UNAVAILABLE","NS_REQUIRES_SUPER","NS_RETURNS_INNER_POINTER","NS_INLINE","NS_AVAILABLE","NS_DEPRECATED","NS_ENUM","NS_OPTIONS","NS_SWIFT_UNAVAILABLE","NS_ASSUME_NONNULL_BEGIN","NS_ASSUME_NONNULL_END","NS_REFINED_FOR_SWIFT","NS_SWIFT_NAME","NS_SWIFT_NOTHROW","NS_DURING","NS_HANDLER","NS_ENDHANDLER","NS_VALUERETURN","NS_VOIDRETURN"],literal:["false","true","FALSE","TRUE","nil","YES","NO","NULL"],built_in:["dispatch_once_t","dispatch_queue_t","dispatch_sync","dispatch_async","dispatch_once"],type:["int","float","char","unsigned","signed","short","long","double","wchar_t","unichar","void","bool","BOOL","id|0","_Bool"]},d={$pattern:n,keyword:["@interface","@class","@protocol","@implementation"]};return{name:"Objective-C",aliases:["mm","objc","obj-c","obj-c++","objective-c++"],keywords:l,illegal:"</",contains:[e,t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE,t.C_NUMBER_MODE,t.QUOTE_STRING_MODE,t.APOS_STRING_MODE,{className:"string",variants:[{begin:'@"',end:'"',illegal:"\\n",contains:[t.BACKSLASH_ESCAPE]}]},{className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},t.inherit(t.QUOTE_STRING_MODE,{className:"string"}),{className:"string",begin:/<.*?>/,end:/$/,illegal:"\\n"},t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE]},{className:"class",begin:"("+d.keyword.join("|")+")\\b",end:/(\{|$)/,excludeEnd:!0,keywords:d,contains:[t.UNDERSCORE_TITLE_MODE]},{begin:"\\."+t.UNDERSCORE_IDENT_RE,relevance:0}]}}function j6(t){const e=t.regex,n=["abs","accept","alarm","and","atan2","bind","binmode","bless","break","caller","chdir","chmod","chomp","chop","chown","chr","chroot","class","close","closedir","connect","continue","cos","crypt","dbmclose","dbmopen","defined","delete","die","do","dump","each","else","elsif","endgrent","endhostent","endnetent","endprotoent","endpwent","endservent","eof","eval","exec","exists","exit","exp","fcntl","field","fileno","flock","for","foreach","fork","format","formline","getc","getgrent","getgrgid","getgrnam","gethostbyaddr","gethostbyname","gethostent","getlogin","getnetbyaddr","getnetbyname","getnetent","getpeername","getpgrp","getpriority","getprotobyname","getprotobynumber","getprotoent","getpwent","getpwnam","getpwuid","getservbyname","getservbyport","getservent","getsockname","getsockopt","given","glob","gmtime","goto","grep","gt","hex","if","index","int","ioctl","join","keys","kill","last","lc","lcfirst","length","link","listen","local","localtime","log","lstat","lt","ma","map","method","mkdir","msgctl","msgget","msgrcv","msgsnd","my","ne","next","no","not","oct","open","opendir","or","ord","our","pack","package","pipe","pop","pos","print","printf","prototype","push","q|0","qq","quotemeta","qw","qx","rand","read","readdir","readline","readlink","readpipe","recv","redo","ref","rename","require","reset","return","reverse","rewinddir","rindex","rmdir","say","scalar","seek","seekdir","select","semctl","semget","semop","send","setgrent","sethostent","setnetent","setpgrp","setpriority","setprotoent","setpwent","setservent","setsockopt","shift","shmctl","shmget","shmread","shmwrite","shutdown","sin","sleep","socket","socketpair","sort","splice","split","sprintf","sqrt","srand","stat","state","study","sub","substr","symlink","syscall","sysopen","sysread","sysseek","system","syswrite","tell","telldir","tie","tied","time","times","tr","truncate","uc","ucfirst","umask","undef","unless","unlink","unpack","unshift","untie","until","use","utime","values","vec","wait","waitpid","wantarray","warn","when","while","write","x|0","xor","y|0"],r=/[dualxmsipngr]{0,12}/,s={$pattern:/[\w.]+/,keyword:n.join(" ")},i={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:s},o={begin:/->\{/,end:/\}/},l={scope:"attr",match:/\s+:\s*\w+(\s*\(.*?\))?/},d={scope:"variable",variants:[{begin:/\$\d/},{begin:e.concat(/[$%@](?!")(\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,"(?![A-Za-z])(?![@$%])")},{begin:/[$%@](?!")[^\s\w{=]|\$=/,relevance:0}],contains:[l]},f={className:"number",variants:[{match:/0?\.[0-9][0-9_]+\b/},{match:/\bv?(0|[1-9][0-9_]*(\.[0-9_]+)?|[1-9][0-9_]*)\b/},{match:/\b0[0-7][0-7_]*\b/},{match:/\b0x[0-9a-fA-F][0-9a-fA-F_]*\b/},{match:/\b0b[0-1][0-1_]*\b/}],relevance:0},h=[t.BACKSLASH_ESCAPE,i,d],m=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],g=(x,k,E="\\1")=>{const C=E==="\\1"?E:e.concat(E,k);return e.concat(e.concat("(?:",x,")"),k,/(?:\\.|[^\\\/])*?/,C,/(?:\\.|[^\\\/])*?/,E,r)},y=(x,k,E)=>e.concat(e.concat("(?:",x,")"),k,/(?:\\.|[^\\\/])*?/,E,r),b=[d,t.HASH_COMMENT_MODE,t.COMMENT(/^=\w/,/=cut/,{endsWithParent:!0}),o,{className:"string",contains:h,variants:[{begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[",end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*<",end:">",relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'",contains:[t.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`",contains:[t.BACKSLASH_ESCAPE]},{begin:/\{\w+\}/,relevance:0},{begin:"-?\\w+\\s*=>",relevance:0}]},f,{begin:"(\\/\\/|"+t.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*",keywords:"split return print reverse grep",relevance:0,contains:[t.HASH_COMMENT_MODE,{className:"regexp",variants:[{begin:g("s|tr|y",e.either(...m,{capture:!0}))},{begin:g("s|tr|y","\\(","\\)")},{begin:g("s|tr|y","\\[","\\]")},{begin:g("s|tr|y","\\{","\\}")}],relevance:2},{className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{begin:y("(?:m|qr)?",/\//,/\//)},{begin:y("m|qr",e.either(...m,{capture:!0}),/\1/)},{begin:y("m|qr",/\(/,/\)/)},{begin:y("m|qr",/\[/,/\]/)},{begin:y("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub method",end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[t.TITLE_MODE,l]},{className:"class",beginKeywords:"class",end:"[;{]",excludeEnd:!0,relevance:5,contains:[t.TITLE_MODE,l,f]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}]}];return i.contains=b,o.contains=b,{name:"Perl",aliases:["pl","pm"],keywords:s,contains:b}}function O6(t){const e=t.regex,n=/(?![A-Za-z0-9])(?![$])/,r=e.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,n),s=e.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,n),i=e.concat(/[A-Z]+/,n),o={scope:"variable",match:"\\$+"+r},l={scope:"meta",variants:[{begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{begin:/\?>/}]},d={scope:"subst",variants:[{begin:/\$\w+/},{begin:/\{\$/,end:/\}/}]},f=t.inherit(t.APOS_STRING_MODE,{illegal:null}),h=t.inherit(t.QUOTE_STRING_MODE,{illegal:null,contains:t.QUOTE_STRING_MODE.contains.concat(d)}),m={begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/,contains:t.QUOTE_STRING_MODE.contains.concat(d),"on:begin":(G,K)=>{K.data._beginMatch=G[1]||G[2]},"on:end":(G,K)=>{K.data._beginMatch!==G[1]&&K.ignoreMatch()}},g=t.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/}),y=`[
203
203
  ]`,b={scope:"string",variants:[h,f,m,g]},x={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},k=["false","null","true"],E=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],C=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],_={keyword:E,literal:(G=>{const K=[];return G.forEach(X=>{K.push(X),X.toLowerCase()===X?K.push(X.toUpperCase()):K.push(X.toLowerCase())}),K})(k),built_in:C},T=G=>G.map(K=>K.replace(/\|\d+$/,"")),R={variants:[{match:[/new/,e.concat(y,"+"),e.concat("(?!",T(C).join("\\b|"),"\\b)"),s],scope:{1:"keyword",4:"title.class"}}]},I=e.concat(r,"\\b(?!\\()"),B={variants:[{match:[e.concat(/::/,e.lookahead(/(?!class\b)/)),I],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[s,e.concat(/::/,e.lookahead(/(?!class\b)/)),I],scope:{1:"title.class",3:"variable.constant"}},{match:[s,e.concat("::",e.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[s,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},P={scope:"attr",match:e.concat(r,e.lookahead(":"),e.lookahead(/(?!::)/))},D={relevance:0,begin:/\(/,end:/\)/,keywords:_,contains:[P,o,B,t.C_BLOCK_COMMENT_MODE,b,x,R]},V={relevance:0,match:[/\b/,e.concat("(?!fn\\b|function\\b|",T(E).join("\\b|"),"|",T(C).join("\\b|"),"\\b)"),r,e.concat(y,"*"),e.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[D]};D.contains.push(V);const $=[P,B,t.C_BLOCK_COMMENT_MODE,b,x,R],Q={begin:e.concat(/#\[\s*\\?/,e.either(s,i)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:k,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:k,keyword:["new","array"]},contains:["self",...$]},...$,{scope:"meta",variants:[{match:s},{match:i}]}]};return{case_insensitive:!1,keywords:_,contains:[Q,t.HASH_COMMENT_MODE,t.COMMENT("//","$"),t.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:t.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},l,{scope:"variable.language",match:/\$this\b/},o,V,B,{match:[/const/,/\s/,r],scope:{1:"keyword",3:"variable.constant"}},R,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},t.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:_,contains:["self",Q,o,B,t.C_BLOCK_COMMENT_MODE,b,x]}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},t.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/,contains:[t.inherit(t.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{beginKeywords:"use",relevance:0,end:";",contains:[{match:/\b(as|const|function)\b/,scope:"keyword"},t.UNDERSCORE_TITLE_MODE]},b,x]}}function R6(t){return{name:"PHP template",subLanguage:"xml",contains:[{begin:/<\?(php|=)?/,end:/\?>/,subLanguage:"php",contains:[{begin:"/\\*",end:"\\*/",skip:!0},{begin:'b"',end:'"',skip:!0},{begin:"b'",end:"'",skip:!0},t.inherit(t.APOS_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0}),t.inherit(t.QUOTE_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0})]}]}}function I6(t){return{name:"Plain text",aliases:["text","txt"],disableAutodetect:!0}}function L6(t){const e=t.regex,n=new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*","u"),r=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],l={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:r,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},d={className:"meta",begin:/^(>>>|\.\.\.) /},f={className:"subst",begin:/\{/,end:/\}/,keywords:l,illegal:/#/},h={begin:/\{\{/,relevance:0},m={className:"string",contains:[t.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[t.BACKSLASH_ESCAPE,d],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[t.BACKSLASH_ESCAPE,d],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[t.BACKSLASH_ESCAPE,d,h,f]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[t.BACKSLASH_ESCAPE,d,h,f]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[t.BACKSLASH_ESCAPE,h,f]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[t.BACKSLASH_ESCAPE,h,f]},t.APOS_STRING_MODE,t.QUOTE_STRING_MODE]},g="[0-9](_?[0-9])*",y=`(\\b(${g}))?\\.(${g})|\\b(${g})\\.`,b=`\\b|${r.join("|")}`,x={className:"number",relevance:0,variants:[{begin:`(\\b(${g})|(${y}))[eE][+-]?(${g})[jJ]?(?=${b})`},{begin:`(${y})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${b})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${b})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${b})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${b})`},{begin:`\\b(${g})[jJ](?=${b})`}]},k={className:"comment",begin:e.lookahead(/# type:/),end:/$/,keywords:l,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},E={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:["self",d,x,m,t.HASH_COMMENT_MODE]}]};return f.contains=[m,x,d],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:l,illegal:/(<\/|\?)|=>/,contains:[d,x,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},m,k,t.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[E]},{variants:[{match:[/\bclass/,/\s+/,n,/\s*/,/\(\s*/,n,/\s*\)/]},{match:[/\bclass/,/\s+/,n]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[x,E,m]}]}}function D6(t){return{aliases:["pycon"],contains:[{className:"meta.prompt",starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}}function P6(t){const e=t.regex,n=/(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/,r=e.either(/0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,/0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,/(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/),s=/[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/,i=e.either(/[()]/,/[{}]/,/\[\[/,/[[\]]/,/\\/,/,/);return{name:"R",keywords:{$pattern:n,keyword:"function if in break next repeat else for while",literal:"NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10",built_in:"LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm"},contains:[t.COMMENT(/#'/,/$/,{contains:[{scope:"doctag",match:/@examples/,starts:{end:e.lookahead(e.either(/\n^#'\s*(?=@[a-zA-Z]+)/,/\n^(?!#')/)),endsParent:!0}},{scope:"doctag",begin:"@param",end:/$/,contains:[{scope:"variable",variants:[{match:n},{match:/`(?:\\.|[^`\\])+`/}],endsParent:!0}]},{scope:"doctag",match:/@[a-zA-Z]+/},{scope:"keyword",match:/\\[a-zA-Z]+/}]}),t.HASH_COMMENT_MODE,{scope:"string",contains:[t.BACKSLASH_ESCAPE],variants:[t.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\(/,end:/\)(-*)"/}),t.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\{/,end:/\}(-*)"/}),t.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\[/,end:/\](-*)"/}),t.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\(/,end:/\)(-*)'/}),t.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\{/,end:/\}(-*)'/}),t.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\[/,end:/\](-*)'/}),{begin:'"',end:'"',relevance:0},{begin:"'",end:"'",relevance:0}]},{relevance:0,variants:[{scope:{1:"operator",2:"number"},match:[s,r]},{scope:{1:"operator",2:"number"},match:[/%[^%]*%/,r]},{scope:{1:"punctuation",2:"number"},match:[i,r]},{scope:{2:"number"},match:[/[^a-zA-Z0-9._]|^/,r]}]},{scope:{3:"operator"},match:[n,/\s+/,/<-/,/\s+/]},{scope:"operator",relevance:0,variants:[{match:s},{match:/%[^%]*%/}]},{scope:"punctuation",relevance:0,match:i},{begin:"`",end:"`",contains:[{begin:/\\./}]}]}}function B6(t){const e=t.regex,n="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",r=e.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),s=e.concat(r,/(::\w+)*/),o={"variable.constant":["__FILE__","__LINE__","__ENCODING__"],"variable.language":["self","super"],keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield",...["include","extend","prepend","public","private","protected","raise","throw"]],built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"],literal:["true","false","nil"]},l={className:"doctag",begin:"@[A-Za-z]+"},d={begin:"#<",end:">"},f=[t.COMMENT("#","$",{contains:[l]}),t.COMMENT("^=begin","^=end",{contains:[l],relevance:10}),t.COMMENT("^__END__",t.MATCH_NOTHING_RE)],h={className:"subst",begin:/#\{/,end:/\}/,keywords:o},m={className:"string",contains:[t.BACKSLASH_ESCAPE,h],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?</,end:/>/},{begin:/%[qQwWx]?\//,end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{begin:e.concat(/<<[-~]?'?/,e.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)),contains:[t.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[t.BACKSLASH_ESCAPE,h]})]}]},g="[1-9](_?[0-9])*|0",y="[0-9](_?[0-9])*",b={className:"number",relevance:0,variants:[{begin:`\\b(${g})(\\.(${y}))?([eE][+-]?(${y})|r)?i?\\b`},{begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{begin:"\\b0(_?[0-7])+r?i?\\b"}]},x={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,keywords:o}]},R=[m,{variants:[{match:[/class\s+/,s,/\s+<\s+/,s]},{match:[/\b(class|module)\s+/,s]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:o},{match:[/(include|extend)\s+/,s],scope:{2:"title.class"},keywords:o},{relevance:0,match:[s,/\.new[. (]/],scope:{1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},{relevance:0,match:r,scope:"title.class"},{match:[/def/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[x]},{begin:t.IDENT_RE+"::"},{className:"symbol",begin:t.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[m,{begin:n}],relevance:0},b,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:o},{begin:"("+t.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[t.BACKSLASH_ESCAPE,h],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(d,f),relevance:0}].concat(d,f);h.contains=R,x.contains=R;const D=[{begin:/^\s*=>/,starts:{end:"$",contains:R}},{className:"meta.prompt",begin:"^("+"[>?]>"+"|"+"[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]"+"|"+"(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>"+")(?=[ ])",starts:{end:"$",keywords:o,contains:R}}];return f.unshift(d),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:o,illegal:/\/\*/,contains:[t.SHEBANG({binary:"ruby"})].concat(D).concat(f).concat(R)}}function z6(t){const e=t.regex,n=/(r#)?/,r=e.concat(n,t.UNDERSCORE_IDENT_RE),s=e.concat(n,t.IDENT_RE),i={className:"title.function.invoke",relevance:0,begin:e.concat(/\b/,/(?!let|for|while|if|else|match\b)/,s,e.lookahead(/\s*\(/))},o="([ui](8|16|32|64|128|size)|f(32|64))?",l=["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],d=["true","false","Some","None","Ok","Err"],f=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],h=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:t.IDENT_RE+"!?",type:h,keyword:l,literal:d,built_in:f},illegal:"</",contains:[t.C_LINE_COMMENT_MODE,t.COMMENT("/\\*","\\*/",{contains:["self"]}),t.inherit(t.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{className:"symbol",begin:/'[a-zA-Z_][a-zA-Z0-9_]*(?!')/},{scope:"string",variants:[{begin:/b?r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'/,end:/'/,contains:[{scope:"char.escape",match:/\\('|\w|x\w{2}|u\w{4}|U\w{8})/}]}]},{className:"number",variants:[{begin:"\\b0b([01_]+)"+o},{begin:"\\b0o([0-7_]+)"+o},{begin:"\\b0x([A-Fa-f0-9_]+)"+o},{begin:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+o}],relevance:0},{begin:[/fn/,/\s+/,r],className:{1:"keyword",3:"title.function"}},{className:"meta",begin:"#!?\\[",end:"\\]",contains:[{className:"string",begin:/"/,end:/"/,contains:[t.BACKSLASH_ESCAPE]}]},{begin:[/let/,/\s+/,/(?:mut\s+)?/,r],className:{1:"keyword",3:"keyword",4:"variable"}},{begin:[/for/,/\s+/,r,/\s+/,/in/],className:{1:"keyword",3:"variable",5:"keyword"}},{begin:[/type/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{begin:[/(?:trait|enum|struct|union|impl|for)/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{begin:t.IDENT_RE+"::",keywords:{keyword:"Self",built_in:f,type:h}},{className:"punctuation",begin:"->"},i]}}const $6=t=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:t.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[t.APOS_STRING_MODE,t.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:t.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),F6=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],U6=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],H6=[...F6,...U6],W6=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),q6=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),V6=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),K6=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function G6(t){const e=$6(t),n=V6,r=q6,s="@[a-z-]+",i="and or not only",l={className:"variable",begin:"(\\$"+"[a-zA-Z-][a-zA-Z0-9_-]*"+")\\b",relevance:0};return{name:"SCSS",case_insensitive:!0,illegal:"[=/|']",contains:[t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE,e.CSS_NUMBER_MODE,{className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0},e.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag",begin:"\\b("+H6.join("|")+")\\b",relevance:0},{className:"selector-pseudo",begin:":("+r.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+n.join("|")+")"},l,{begin:/\(/,end:/\)/,contains:[e.CSS_NUMBER_MODE]},e.CSS_VARIABLE,{className:"attribute",begin:"\\b("+K6.join("|")+")\\b"},{begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{begin:/:/,end:/[;}{]/,relevance:0,contains:[e.BLOCK_COMMENT,l,e.HEXCOLOR,e.CSS_NUMBER_MODE,t.QUOTE_STRING_MODE,t.APOS_STRING_MODE,e.IMPORTANT,e.FUNCTION_DISPATCH]},{begin:"@(page|font-face)",keywords:{$pattern:s,keyword:"@page @font-face"}},{begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/,keyword:i,attribute:W6.join(" ")},contains:[{begin:s,className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute"},l,t.QUOTE_STRING_MODE,t.APOS_STRING_MODE,e.HEXCOLOR,e.CSS_NUMBER_MODE]},e.FUNCTION_DISPATCH]}}function J6(t){return{name:"Shell Session",aliases:["console","shellsession"],contains:[{className:"meta.prompt",begin:/^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:"bash"}}]}}function Y6(t){const e=t.regex,n=t.COMMENT("--","$"),r={scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},s={begin:/"/,end:/"/,contains:[{match:/""/}]},i=["true","false","unknown"],o=["double precision","large object","with timezone","without timezone"],l=["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],d=["add","asc","collation","desc","final","first","last","view"],f=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year"],h=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],m=["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"],g=["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"],y=h,b=[...f,...d].filter(T=>!h.includes(T)),x={scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},k={scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0},E={match:e.concat(/\b/,e.either(...y),/\s*\(/),relevance:0,keywords:{built_in:y}};function C(T){return e.concat(/\b/,e.either(...T.map(R=>R.replace(/\s+/,"\\s+"))),/\b/)}const O={scope:"keyword",match:C(g),relevance:0};function _(T,{exceptions:R,when:I}={}){const B=I;return R=R||[],T.map(P=>P.match(/\|\d+$/)||R.includes(P)?P:B(P)?`${P}|0`:P)}return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:_(b,{when:T=>T.length<3}),literal:i,type:l,built_in:m},contains:[{scope:"type",match:C(o)},O,E,x,r,s,t.C_NUMBER_MODE,t.C_BLOCK_COMMENT_MODE,n,k]}}function N_(t){return t?typeof t=="string"?t:t.source:null}function Fa(t){return $t("(?=",t,")")}function $t(...t){return t.map(n=>N_(n)).join("")}function X6(t){const e=t[t.length-1];return typeof e=="object"&&e.constructor===Object?(t.splice(t.length-1,1),e):{}}function Gn(...t){return"("+(X6(t).capture?"":"?:")+t.map(r=>N_(r)).join("|")+")"}const Iv=t=>$t(/\b/,t,/\w$/.test(t)?/\b/:/\B/),Q6=["Protocol","Type"].map(Iv),P1=["init","self"].map(Iv),Z6=["Any","Self"],mp=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],B1=["false","nil","true"],eB=["assignment","associativity","higherThan","left","lowerThan","none","right"],tB=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],z1=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],C_=Gn(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),__=Gn(C_,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),gp=$t(C_,__,"*"),T_=Gn(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),md=Gn(T_,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),Qr=$t(T_,md,"*"),au=$t(/[A-Z]/,md,"*"),nB=["attached","autoclosure",$t(/convention\(/,Gn("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",$t(/objc\(/,Qr,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],rB=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];function sB(t){const e={match:/\s+/,relevance:0},n=t.COMMENT("/\\*","\\*/",{contains:["self"]}),r=[t.C_LINE_COMMENT_MODE,n],s={match:[/\./,Gn(...Q6,...P1)],className:{2:"keyword"}},i={match:$t(/\./,Gn(...mp)),relevance:0},o=mp.filter(Ke=>typeof Ke=="string").concat(["_|0"]),l=mp.filter(Ke=>typeof Ke!="string").concat(Z6).map(Iv),d={variants:[{className:"keyword",match:Gn(...l,...P1)}]},f={$pattern:Gn(/\b\w+/,/#\w+/),keyword:o.concat(tB),literal:B1},h=[s,i,d],m={match:$t(/\./,Gn(...z1)),relevance:0},g={className:"built_in",match:$t(/\b/,Gn(...z1),/(?=\()/)},y=[m,g],b={match:/->/,relevance:0},x={className:"operator",relevance:0,variants:[{match:gp},{match:`\\.(\\.|${__})+`}]},k=[b,x],E="([0-9]_*)+",C="([0-9a-fA-F]_*)+",O={className:"number",relevance:0,variants:[{match:`\\b(${E})(\\.(${E}))?([eE][+-]?(${E}))?\\b`},{match:`\\b0x(${C})(\\.(${C}))?([pP][+-]?(${E}))?\\b`},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},_=(Ke="")=>({className:"subst",variants:[{match:$t(/\\/,Ke,/[0\\tnr"']/)},{match:$t(/\\/,Ke,/u\{[0-9a-fA-F]{1,8}\}/)}]}),T=(Ke="")=>({className:"subst",match:$t(/\\/,Ke,/[\t ]*(?:[\r\n]|\r\n)/)}),R=(Ke="")=>({className:"subst",label:"interpol",begin:$t(/\\/,Ke,/\(/),end:/\)/}),I=(Ke="")=>({begin:$t(Ke,/"""/),end:$t(/"""/,Ke),contains:[_(Ke),T(Ke),R(Ke)]}),B=(Ke="")=>({begin:$t(Ke,/"/),end:$t(/"/,Ke),contains:[_(Ke),R(Ke)]}),P={className:"string",variants:[I(),I("#"),I("##"),I("###"),B(),B("#"),B("##"),B("###")]},D=[t.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[t.BACKSLASH_ESCAPE]}],V={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:D},$=Ke=>{const Et=$t(Ke,/\//),je=$t(/\//,Ke);return{begin:Et,end:je,contains:[...D,{scope:"comment",begin:`#(?!.*${je})`,end:/$/}]}},Q={scope:"regexp",variants:[$("###"),$("##"),$("#"),V]},G={match:$t(/`/,Qr,/`/)},K={className:"variable",match:/\$\d+/},X={className:"variable",match:`\\$${md}+`},re=[G,K,X],J={match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:rB,contains:[...k,O,P]}]}},oe={scope:"keyword",match:$t(/@/,Gn(...nB),Fa(Gn(/\(/,/\s+/)))},U={scope:"meta",match:$t(/@/,Qr)},A=[J,oe,U],L={match:Fa(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:$t(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,md,"+")},{className:"type",match:au,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:$t(/\s+&\s+/,Fa(au)),relevance:0}]},te={begin:/</,end:/>/,keywords:f,contains:[...r,...h,...A,b,L]};L.contains.push(te);const se={match:$t(Qr,/\s*:/),keywords:"_|0",relevance:0},be={begin:/\(/,end:/\)/,relevance:0,keywords:f,contains:["self",se,...r,Q,...h,...y,...k,O,P,...re,...A,L]},ee={begin:/</,end:/>/,keywords:"repeat each",contains:[...r,L]},ge={begin:Gn(Fa($t(Qr,/\s*:/)),Fa($t(Qr,/\s+/,Qr,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:Qr}]},fe={begin:/\(/,end:/\)/,keywords:f,contains:[ge,...r,...h,...k,O,P,...A,L,be],endsParent:!0,illegal:/["']/},Te={match:[/(func|macro)/,/\s+/,Gn(G.match,Qr,gp)],className:{1:"keyword",3:"title.function"},contains:[ee,fe,e],illegal:[/\[/,/%/]},Xe={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[ee,fe,e],illegal:/\[|%/},tt={match:[/operator/,/\s+/,gp],className:{1:"keyword",3:"title"}},st={begin:[/precedencegroup/,/\s+/,au],className:{1:"keyword",3:"title"},contains:[L],keywords:[...eB,...B1],end:/}/},nt={match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},Le={match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},yt={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,Qr,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:f,contains:[ee,...h,{begin:/:/,end:/\{/,keywords:f,contains:[{scope:"title.class.inherited",match:au},...h],relevance:0}]};for(const Ke of P.variants){const Et=Ke.contains.find(Je=>Je.label==="interpol");Et.keywords=f;const je=[...h,...y,...k,O,P,...re];Et.contains=[...je,{begin:/\(/,end:/\)/,contains:["self",...je]}]}return{name:"Swift",keywords:f,contains:[...r,Te,Xe,nt,Le,yt,tt,st,{beginKeywords:"import",end:/$/,contains:[...r],relevance:0},Q,...h,...y,...k,O,P,...re,...A,L,be]}}const gd="[A-Za-z$_][0-9A-Za-z$_]*",M_=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],A_=["true","false","null","undefined","NaN","Infinity"],j_=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],O_=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],R_=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],I_=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],L_=[].concat(R_,j_,O_);function iB(t){const e=t.regex,n=(J,{after:oe})=>{const U="</"+J[0].slice(1);return J.input.indexOf(U,oe)!==-1},r=gd,s={begin:"<>",end:"</>"},i=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(J,oe)=>{const U=J[0].length+J.index,A=J.input[U];if(A==="<"||A===","){oe.ignoreMatch();return}A===">"&&(n(J,{after:U})||oe.ignoreMatch());let L;const te=J.input.substring(U);if(L=te.match(/^\s*=/)){oe.ignoreMatch();return}if((L=te.match(/^\s+extends\s+/))&&L.index===0){oe.ignoreMatch();return}}},l={$pattern:gd,keyword:M_,literal:A_,built_in:L_,"variable.language":I_},d="[0-9](_?[0-9])*",f=`\\.(${d})`,h="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",m={className:"number",variants:[{begin:`(\\b(${h})((${f})|\\.)?|(${f}))[eE][+-]?(${d})\\b`},{begin:`\\b(${h})\\b((${f})\\b|\\.)?|(${f})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},g={className:"subst",begin:"\\$\\{",end:"\\}",keywords:l,contains:[]},y={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"xml"}},b={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"css"}},x={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"graphql"}},k={className:"string",begin:"`",end:"`",contains:[t.BACKSLASH_ESCAPE,g]},C={className:"comment",variants:[t.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:r+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),t.C_BLOCK_COMMENT_MODE,t.C_LINE_COMMENT_MODE]},O=[t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,y,b,x,k,{match:/\$\d+/},m];g.contains=O.concat({begin:/\{/,end:/\}/,keywords:l,contains:["self"].concat(O)});const _=[].concat(C,g.contains),T=_.concat([{begin:/(\s*)\(/,end:/\)/,keywords:l,contains:["self"].concat(_)}]),R={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:T},I={variants:[{match:[/class/,/\s+/,r,/\s+/,/extends/,/\s+/,e.concat(r,"(",e.concat(/\./,r),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,r],scope:{1:"keyword",3:"title.class"}}]},B={relevance:0,match:e.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...j_,...O_]}},P={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},D={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[R],illegal:/%/},V={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function $(J){return e.concat("(?!",J.join("|"),")")}const Q={match:e.concat(/\b/,$([...R_,"super","import"].map(J=>`${J}\\s*\\(`)),r,e.lookahead(/\s*\(/)),className:"title.function",relevance:0},G={begin:e.concat(/\./,e.lookahead(e.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},K={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},R]},X="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+t.UNDERSCORE_IDENT_RE+")\\s*=>",re={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,e.lookahead(X)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[R]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:l,exports:{PARAMS_CONTAINS:T,CLASS_REFERENCE:B},illegal:/#(?![$_A-z])/,contains:[t.SHEBANG({label:"shebang",binary:"node",relevance:5}),P,t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,y,b,x,k,C,{match:/\$\d+/},m,B,{scope:"attr",match:r+e.lookahead(":"),relevance:0},re,{begin:"("+t.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[C,t.REGEXP_MODE,{className:"function",begin:X,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:t.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:T}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:s.begin,end:s.end},{match:i},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},D,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+t.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[R,t.inherit(t.TITLE_MODE,{begin:r,className:"title.function"})]},{match:/\.\.\./,relevance:0},G,{match:"\\$"+r,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[R]},Q,V,I,K,{match:/\$[(.]/}]}}function oB(t){const e=t.regex,n=iB(t),r=gd,s=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],i={begin:[/namespace/,/\s+/,t.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},o={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:s},contains:[n.exports.CLASS_REFERENCE]},l={className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/},d=["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"],f={$pattern:gd,keyword:M_.concat(d),literal:A_,built_in:L_.concat(s),"variable.language":I_},h={className:"meta",begin:"@"+r},m=(x,k,E)=>{const C=x.contains.findIndex(O=>O.label===k);if(C===-1)throw new Error("can not find mode to replace");x.contains.splice(C,1,E)};Object.assign(n.keywords,f),n.exports.PARAMS_CONTAINS.push(h);const g=n.contains.find(x=>x.scope==="attr"),y=Object.assign({},g,{match:e.concat(r,e.lookahead(/\s*\?:/))});n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,g,y]),n.contains=n.contains.concat([h,i,o,y]),m(n,"shebang",t.SHEBANG()),m(n,"use_strict",l);const b=n.contains.find(x=>x.label==="func.def");return b.relevance=0,Object.assign(n,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),n}function aB(t){const e=t.regex,n={className:"string",begin:/"(""|[^/n])"C\b/},r={className:"string",begin:/"/,end:/"/,illegal:/\n/,contains:[{begin:/""/}]},s=/\d{1,2}\/\d{1,2}\/\d{4}/,i=/\d{4}-\d{1,2}-\d{1,2}/,o=/(\d|1[012])(:\d+){0,2} *(AM|PM)/,l=/\d{1,2}(:\d{1,2}){1,2}/,d={className:"literal",variants:[{begin:e.concat(/# */,e.either(i,s),/ *#/)},{begin:e.concat(/# */,l,/ *#/)},{begin:e.concat(/# */,o,/ *#/)},{begin:e.concat(/# */,e.either(i,s),/ +/,e.either(o,l),/ *#/)}]},f={className:"number",relevance:0,variants:[{begin:/\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/},{begin:/\b\d[\d_]*((U?[SIL])|[%&])?/},{begin:/&H[\dA-F_]+((U?[SIL])|[%&])?/},{begin:/&O[0-7_]+((U?[SIL])|[%&])?/},{begin:/&B[01_]+((U?[SIL])|[%&])?/}]},h={className:"label",begin:/^\w+:/},m=t.COMMENT(/'''/,/$/,{contains:[{className:"doctag",begin:/<\/?/,end:/>/}]}),g=t.COMMENT(null,/$/,{variants:[{begin:/'/},{begin:/([\t ]|^)REM(?=\s)/}]});return{name:"Visual Basic .NET",aliases:["vb"],case_insensitive:!0,classNameAliases:{label:"symbol"},keywords:{keyword:"addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield",built_in:"addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort",type:"boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort",literal:"true false nothing"},illegal:"//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",contains:[n,r,d,f,h,m,g,{className:"meta",begin:/[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/,end:/$/,keywords:{keyword:"const disable else elseif enable end externalsource if region then"},contains:[g]}]}}function lB(t){t.regex;const e=t.COMMENT(/\(;/,/;\)/);e.contains.push("self");const n=t.COMMENT(/;;/,/$/),r=["anyfunc","block","br","br_if","br_table","call","call_indirect","data","drop","elem","else","end","export","func","global.get","global.set","local.get","local.set","local.tee","get_global","get_local","global","if","import","local","loop","memory","memory.grow","memory.size","module","mut","nop","offset","param","result","return","select","set_global","set_local","start","table","tee_local","then","type","unreachable"],s={begin:[/(?:func|call|call_indirect)/,/\s+/,/\$[^\s)]+/],className:{1:"keyword",3:"title.function"}},i={className:"variable",begin:/\$[\w_]+/},o={match:/(\((?!;)|\))+/,className:"punctuation",relevance:0},l={className:"number",relevance:0,match:/[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/},d={match:/(i32|i64|f32|f64)(?!\.)/,className:"type"},f={className:"keyword",match:/\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/};return{name:"WebAssembly",keywords:{$pattern:/[\w.]+/,keyword:r},contains:[n,e,{match:[/(?:offset|align)/,/\s*/,/=/],className:{1:"keyword",3:"operator"}},i,o,s,t.QUOTE_STRING_MODE,d,f,l]}}function cB(t){const e=t.regex,n=e.concat(/[\p{L}_]/u,e.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),r=/[\p{L}0-9._:-]+/u,s={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},i={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},o=t.inherit(i,{begin:/\(/,end:/\)/}),l=t.inherit(t.APOS_STRING_MODE,{className:"string"}),d=t.inherit(t.QUOTE_STRING_MODE,{className:"string"}),f={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:"attr",begin:r,relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:"string",endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[s]},{begin:/'/,end:/'/,contains:[s]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,relevance:10,contains:[i,d,l,o,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,contains:[i,o,d,l]}]}]},t.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,relevance:10},s,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[d]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/<style(?=\s|>)/,end:/>/,keywords:{name:"style"},contains:[f],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/<script(?=\s|>)/,end:/>/,keywords:{name:"script"},contains:[f],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:e.concat(/</,e.lookahead(e.concat(n,e.either(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:n,relevance:0,starts:f}]},{className:"tag",begin:e.concat(/<\//,e.lookahead(e.concat(n,/>/))),contains:[{className:"name",begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}function uB(t){const e="true false yes no null",n="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},s={className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]},i={className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},o={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[t.BACKSLASH_ESCAPE,s]},l=t.inherit(o,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),g={className:"number",begin:"\\b"+"[0-9]{4}(-[0-9][0-9]){0,2}"+"([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?"+"(\\.[0-9]*)?"+"([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?"+"\\b"},y={end:",",endsWithParent:!0,excludeEnd:!0,keywords:e,relevance:0},b={begin:/\{/,end:/\}/,contains:[y],illegal:"\\n",relevance:0},x={begin:"\\[",end:"\\]",contains:[y],illegal:"\\n",relevance:0},k=[r,{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+n},{className:"type",begin:"!<"+n+">"},{className:"type",begin:"!"+n},{className:"type",begin:"!!"+n},{className:"meta",begin:"&"+t.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+t.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},t.HASH_COMMENT_MODE,{beginKeywords:e,keywords:{literal:e}},g,{className:"number",begin:t.C_NUMBER_RE+"\\b",relevance:0},b,x,i,o],E=[...k];return E.pop(),E.push(l),y.contains=E,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:k}}const dB={arduino:V4,bash:K4,c:G4,cpp:J4,csharp:Y4,css:i6,diff:o6,go:a6,graphql:l6,ini:c6,java:u6,javascript:m6,json:g6,kotlin:y6,less:C6,lua:_6,makefile:T6,markdown:M6,objectivec:A6,perl:j6,php:O6,"php-template":R6,plaintext:I6,python:L6,"python-repl":D6,r:P6,ruby:B6,rust:z6,scss:G6,shell:J6,sql:Y6,swift:sB,typescript:oB,vbnet:aB,wasm:lB,xml:cB,yaml:uB},$1={},fB="hljs-";function hB(t){const e=v_.newInstance();return t&&i(t),{highlight:n,highlightAuto:r,listLanguages:s,register:i,registerAlias:o,registered:l};function n(d,f,h){const m=h||$1,g=typeof m.prefix=="string"?m.prefix:fB;if(!e.getLanguage(d))throw new Error("Unknown language: `"+d+"` is not registered");e.configure({__emitter:pB,classPrefix:g});const y=e.highlight(f,{ignoreIllegals:!0,language:d});if(y.errorRaised)throw new Error("Could not highlight with `Highlight.js`",{cause:y.errorRaised});const b=y._emitter.root,x=b.data;return x.language=y.language,x.relevance=y.relevance,b}function r(d,f){const m=(f||$1).subset||s();let g=-1,y=0,b;for(;++g<m.length;){const x=m[g];if(!e.getLanguage(x))continue;const k=n(x,d,f);k.data&&k.data.relevance!==void 0&&k.data.relevance>y&&(y=k.data.relevance,b=k)}return b||{type:"root",children:[],data:{language:void 0,relevance:y}}}function s(){return e.listLanguages()}function i(d,f){if(typeof d=="string")e.registerLanguage(d,f);else{let h;for(h in d)Object.hasOwn(d,h)&&e.registerLanguage(h,d[h])}}function o(d,f){if(typeof d=="string")e.registerAliases(typeof f=="string"?f:[...f],{languageName:d});else{let h;for(h in d)if(Object.hasOwn(d,h)){const m=d[h];e.registerAliases(typeof m=="string"?m:[...m],{languageName:h})}}}function l(d){return!!e.getLanguage(d)}}class pB{constructor(e){this.options=e,this.root={type:"root",children:[],data:{language:void 0,relevance:0}},this.stack=[this.root]}addText(e){if(e==="")return;const n=this.stack[this.stack.length-1],r=n.children[n.children.length-1];r&&r.type==="text"?r.value+=e:n.children.push({type:"text",value:e})}startScope(e){this.openNode(String(e))}endScope(){this.closeNode()}__addSublanguage(e,n){const r=this.stack[this.stack.length-1],s=e.root.children;n?r.children.push({type:"element",tagName:"span",properties:{className:[n]},children:s}):r.children.push(...s)}openNode(e){const n=this,r=e.split(".").map(function(o,l){return l?o+"_".repeat(l):n.options.classPrefix+o}),s=this.stack[this.stack.length-1],i={type:"element",tagName:"span",properties:{className:r},children:[]};s.children.push(i),this.stack.push(i)}closeNode(){this.stack.pop()}finalize(){}toHTML(){return""}}const mB=new Bt("blurredLoadingNode"),Lv=Tt.create({name:"blurredLoadingNode",addStorage(){return{loadingNodes:{}}},addCommands(){return{applyLoadingEffect:(t,e,n,r="paragraph")=>({editor:s})=>{const i={...this.storage.loadingNodes};return i[t]={from:e,to:n,id:t,active:!0,type:r},this.storage.loadingNodes=i,s.view.dispatch(s.view.state.tr),setTimeout(()=>{s.isFocused&&s.commands.setTextSelection({from:e,to:e})},0),!0},removeLoadingEffect:t=>({editor:e})=>{const n={...this.storage.loadingNodes};return n[t]&&(delete n[t],this.storage.loadingNodes=n,e.view.dispatch(e.view.state.tr),e.isFocused||setTimeout(()=>{e.commands.focus()},0)),!0}}},addProseMirrorPlugins(){return[new Rt({key:mB,props:{decorations:t=>{const e=this.storage.loadingNodes,n=[];return Object.entries(e).forEach(([,r])=>{const s=r;if(!s.active)return;const{from:i,to:o,type:l}=s;l==="selection"?n.push(Lt.inline(i,o,{class:"node-blur-selection"})):t.doc.nodesBetween(i,o,(d,f)=>["paragraph","heading","blockquote","listItem","codeBlock"].includes(d.type.name)?(n.push(Lt.node(f,f+d.nodeSize,{class:"node-blur-effect"})),!1):!0)}),_t.create(t.doc,n)}}})]}}),Dv=vn.create({name:"imageLoading",group:"block",atom:!0,addAttributes(){return{id:{default:null}}},parseHTML(){return[{tag:'div[data-type="image-loading"]'}]},renderHTML(){return["div",{"data-type":"image-loading",class:"image-loading-placeholder",contenteditable:"false"}]}}),gB=new Bt("insertionLoadingNode"),lu=new Map,Pv=Tt.create({name:"insertionLoadingNode",addStorage(){return{insertionPoints:{}}},addCommands(){return{showInsertionLoading:(t,e)=>({editor:n})=>(this.storage.insertionPoints={},lu.clear(),this.storage.insertionPoints={[t]:{position:e,id:t,active:!0}},n.view.dom.classList.add("has-insertion-loading"),n.view.dispatch(n.view.state.tr),!0),removeInsertionLoading:t=>({editor:e})=>{const n={...this.storage.insertionPoints};return n[t]&&(delete n[t],this.storage.insertionPoints=n,lu.delete(t),Object.keys(n).length===0&&e.view.dom.classList.remove("has-insertion-loading"),e.view.dispatch(e.view.state.tr)),!0}}},addProseMirrorPlugins(){return[new Rt({key:gB,props:{decorations:t=>{const e=this.storage.insertionPoints,n=[];return Object.entries(e).forEach(([,r])=>{const s=r;s.active&&n.push(Lt.widget(s.position,()=>{const i=lu.get(s.id);if(i)return i;const o=document.createElement("span");o.className="inline-insertion-indicator";const l=document.createElement("span");l.className="inline-insertion-spinner";const d=document.createElement("div");d.className="bounce1";const f=document.createElement("div");f.className="bounce2";const h=document.createElement("div");return l.appendChild(d),l.appendChild(f),l.appendChild(h),o.appendChild(l),lu.set(s.id,o),o},{id:`insertion-${s.id}`}))}),_t.create(t.doc,n)}}})]}}),vB=["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","horizontalRule","table","taskList","taskItem","image"],Bv=Tt.create({name:"pendingAttributes",addGlobalAttributes(){return[{types:vB,attributes:{pendingStatus:{default:null,parseHTML:t=>t.getAttribute("data-pending-status")||null,renderHTML:t=>t.pendingStatus?{"data-pending-status":t.pendingStatus}:{}},pendingOriginalContent:{default:null,rendered:!1},pendingSelectionFrom:{default:null,rendered:!1},pendingSelectionTo:{default:null,rendered:!1},pendingOriginalFrom:{default:null,rendered:!1},pendingOriginalTo:{default:null,rendered:!1},pendingGroupId:{default:null,rendered:!1}}}]}});function yB({node:t,deleteNode:e}){return u.jsxs(KL,{as:"div",className:"tweet-image-card",draggable:!0,"data-drag-handle":!0,children:[u.jsx("img",{className:"tweet-image-card-img",src:t.attrs.src,alt:t.attrs.alt||"",draggable:!1}),u.jsx("button",{className:"tweet-image-card-remove",onClick:e,title:"Remove image",contentEditable:!1,children:"×"})]})}const bB=bv.extend({addNodeView(){return ZL(yB)}}),xB=hB(dB),zv=jD.extend({addAttributes(){var t;return{...(t=this.parent)==null?void 0:t.call(this),target:{default:null}}},renderHTML({HTMLAttributes:t}){var r;const{target:e,...n}=t;if((r=n.href)!=null&&r.startsWith("doc:")){const{href:s,...i}=n;return["span",{...i,"data-doc":s.slice(4),class:"doc-link"},0]}return["a",Dt(this.options.HTMLAttributes,n),0]}}),wB=[Rv.configure({codeBlock:!1,link:!1,underline:!1}),W4.configure({lowlight:xB}),zv.configure({openOnClick:!1,isAllowedUri:(t,e)=>t.startsWith("doc:")?!0:e.defaultValidate(t),HTMLAttributes:{rel:"noopener noreferrer nofollow"}}),p_,t4,sD,rP,iP,S3,k3.configure({nested:!0}),bv,e4,e_.configure({resizable:!1}),ZC,QC,XC,Lv,Dv,Pv,Bv,Pd.configure({placeholder:"Start writing..."}),Ov.configure({types:["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","horizontalRule","table","tableRow","tableHeader","tableCell","taskList","taskItem","image","imageLoading"],attributeName:"id",generateID:()=>crypto.randomUUID().replace(/-/g,"").slice(0,8)})],kB=[Rv.configure({codeBlock:!1,horizontalRule:!0,heading:{levels:[1,2,3]},link:!1,underline:!1}),zv.configure({openOnClick:!1,isAllowedUri:(t,e)=>t.startsWith("doc:")?!0:e.defaultValidate(t),HTMLAttributes:{rel:"noopener noreferrer nofollow"}}),bv,Lv,Dv,Pv,Bv,Pd.configure({placeholder:"Start writing..."}),Ov.configure({types:["paragraph","heading","bulletList","orderedList","listItem","blockquote","image","imageLoading","horizontalRule"],attributeName:"id",generateID:()=>crypto.randomUUID().replace(/-/g,"").slice(0,8)})],SB=Tt.create({name:"tweetEnterHardBreak",addKeyboardShortcuts(){return{Enter:()=>{const{state:t}=this.editor,{$from:e}=t.selection,n=e.pos,r=n>0?t.doc.resolve(n).nodeBefore:null;if((r==null?void 0:r.type.name)==="hardBreak"){const{tr:s}=t;return s.delete(n-r.nodeSize,n),s.split(s.mapping.map(n)),this.editor.view.dispatch(s),!0}return this.editor.commands.setHardBreak()}}}}),D_=[Rv.configure({codeBlock:!1,horizontalRule:!1,heading:!1,blockquote:!1,bulletList:!1,orderedList:!1,listItem:!1,link:!1,underline:!1}),zv.configure({openOnClick:!1,isAllowedUri:(t,e)=>t.startsWith("doc:")?!0:e.defaultValidate(t),HTMLAttributes:{rel:"noopener noreferrer nofollow"}}),bB,Lv,Dv,Pv,Bv,SB,Ov.configure({types:["paragraph","image","imageLoading"],attributeName:"id",generateID:()=>crypto.randomUUID().replace(/-/g,"").slice(0,8)})];[...D_,Pd.configure({placeholder:"What is happening?!"})];function Pr({onClick:t,active:e,disabled:n,title:r,children:s}){return u.jsx("button",{className:`floating-toolbar__btn${e?" active":""}${n?" disabled":""}`,onMouseDown:i=>{i.preventDefault(),t()},disabled:n,title:r,children:s})}function F1(){return u.jsx("div",{className:"floating-toolbar__divider"})}function EB({editor:t}){const[e,n]=S.useState(!1),[r,s]=S.useState({top:0,left:0}),[,i]=S.useState(0),o=S.useRef(-1),l=S.useRef(-1),d=S.useRef(!1);return S.useEffect(()=>{const f=t.view.dom,h=()=>{d.current=!0},m=()=>{if(!d.current)return;d.current=!1;const{from:g,to:y}=t.state.selection,b=g!==y&&t.state.selection.node;if(g!==y&&!b){const x=t.isActive("codeBlock"),k=!!document.querySelector(".context-menu");if(!x&&!k){o.current=g,l.current=y;const E=t.view.coordsAtPos(g),C=t.view.coordsAtPos(y,1),O=(E.left+C.right)/2;s({top:E.top,left:O}),n(!0)}}};return f.addEventListener("mousedown",h),document.addEventListener("mouseup",m),()=>{f.removeEventListener("mousedown",h),document.removeEventListener("mouseup",m)}},[t]),S.useEffect(()=>{const f=()=>{d.current=!1,n(!1),o.current=-1,l.current=-1};return t.on("blur",f),()=>{t.off("blur",f)}},[t]),S.useEffect(()=>{const f=()=>{const{from:h,to:m}=t.state.selection,g=h===m,y=t.isActive("codeBlock"),b=!!document.querySelector(".context-menu"),x=t.view.hasFocus(),k=!g&&t.state.selection.node;if(g||k||y||b||!x)n(!1),o.current=-1,l.current=-1;else if(!d.current&&(n(!0),h!==o.current||m!==l.current)){o.current=h,l.current=m;const E=t.view.coordsAtPos(h),C=t.view.coordsAtPos(m,1),O=(E.left+C.right)/2;s({top:E.top,left:O})}i(E=>E+1)};return t.on("transaction",f),()=>{t.off("transaction",f)}},[t]),e?u.jsxs("div",{className:"floating-toolbar",style:{position:"fixed",top:r.top,left:r.left,transform:"translate(-50%, -100%) translateY(-8px)",zIndex:1500},children:[u.jsx(Pr,{onClick:()=>t.chain().focus().toggleBold().run(),active:t.isActive("bold"),title:"Bold (Ctrl+B)",children:u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8"})})}),u.jsx(Pr,{onClick:()=>t.chain().focus().toggleItalic().run(),active:t.isActive("italic"),title:"Italic (Ctrl+I)",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("line",{x1:"19",x2:"10",y1:"4",y2:"4"}),u.jsx("line",{x1:"14",x2:"5",y1:"20",y2:"20"}),u.jsx("line",{x1:"15",x2:"9",y1:"4",y2:"20"})]})}),u.jsx(Pr,{onClick:()=>t.chain().focus().toggleUnderline().run(),active:t.isActive("underline"),title:"Underline (Ctrl+U)",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M6 4v6a6 6 0 0 0 12 0V4"}),u.jsx("line",{x1:"4",x2:"20",y1:"20",y2:"20"})]})}),u.jsx(Pr,{onClick:()=>t.chain().focus().toggleStrike().run(),active:t.isActive("strike"),title:"Strikethrough",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M16 4H9a3 3 0 0 0-2.83 4"}),u.jsx("path",{d:"M14 12a4 4 0 0 1 0 8H6"}),u.jsx("line",{x1:"4",x2:"20",y1:"12",y2:"12"})]})}),u.jsx(Pr,{onClick:()=>{const f=t.getAttributes("link").href||"",h=window.prompt("Link URL:",f);h!==null&&(h===""?t.chain().focus().unsetLink().run():t.chain().focus().setLink({href:h}).run())},active:t.isActive("link"),title:"Link (Ctrl+K)",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),u.jsx("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"})]})}),u.jsx(F1,{}),u.jsx(Pr,{onClick:()=>t.chain().focus().toggleHeading({level:1}).run(),active:t.isActive("heading",{level:1}),title:"Heading 1",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M4 12h8"}),u.jsx("path",{d:"M4 18V6"}),u.jsx("path",{d:"M12 18V6"}),u.jsx("path",{d:"m17 12 3-2v8"})]})}),u.jsx(Pr,{onClick:()=>t.chain().focus().toggleHeading({level:2}).run(),active:t.isActive("heading",{level:2}),title:"Heading 2",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M4 12h8"}),u.jsx("path",{d:"M4 18V6"}),u.jsx("path",{d:"M12 18V6"}),u.jsx("path",{d:"M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"})]})}),u.jsx(Pr,{onClick:()=>t.chain().focus().toggleHeading({level:3}).run(),active:t.isActive("heading",{level:3}),title:"Heading 3",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M4 12h8"}),u.jsx("path",{d:"M4 18V6"}),u.jsx("path",{d:"M12 18V6"}),u.jsx("path",{d:"M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2"}),u.jsx("path",{d:"M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2"})]})}),u.jsx(F1,{}),u.jsx(Pr,{onClick:()=>t.chain().focus().toggleBulletList().run(),active:t.isActive("bulletList"),title:"Bullet List",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M3 12h.01"}),u.jsx("path",{d:"M3 18h.01"}),u.jsx("path",{d:"M3 6h.01"}),u.jsx("path",{d:"M8 12h13"}),u.jsx("path",{d:"M8 18h13"}),u.jsx("path",{d:"M8 6h13"})]})}),u.jsx(Pr,{onClick:()=>t.chain().focus().toggleOrderedList().run(),active:t.isActive("orderedList"),title:"Ordered List",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M11 12h9"}),u.jsx("path",{d:"M11 18h9"}),u.jsx("path",{d:"M11 6h9"}),u.jsx("path",{d:"M4 10V4h1"}),u.jsx("path",{d:"M4 10h2"}),u.jsx("path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"})]})}),u.jsx(Pr,{onClick:()=>t.chain().focus().toggleBlockquote().run(),active:t.isActive("blockquote"),title:"Blockquote",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M17 6H3"}),u.jsx("path",{d:"M21 12H8"}),u.jsx("path",{d:"M21 18H8"}),u.jsx("path",{d:"M3 12v6"})]})})]}):null}const NB=new Bt("pendingDecoration");let P_=null,B_=null;function U1(t,e){P_=t,B_=e??null}let vd=!1,z_=null,$v=null,$_=null;function Fv(){return vd}function CB(){return $v}function _B(){return $_}function Dg(t,e,n,r){vd=t,z_=t?e??null:null,$v=t?r??null:null,$_=t?n??null:null}function TB(t){switch(t){case"insert":return"pending-insert";case"rewrite":return"pending-rewrite";case"delete":return"pending-delete";default:return""}}function H1(t,e,n){let r=0,s=e+1;for(let i=0;i<t.childCount;i++){const o=t.child(i);if(o.isText){if(r+o.text.length>=n)return s+(n-r);r+=o.text.length,s+=o.nodeSize}else{const l=o.type.name==="hardBreak"?1:o.type.spec.leafText?o.type.spec.leafText(o).length:0;if(l>0&&r+l>=n)return s;r+=l,s+=o.nodeSize}}return n===r?s:null}function W1(t){const e=[];return t.descendants((n,r)=>{var b,x,k,E,C,O,_;const s=(b=n.attrs)==null?void 0:b.pendingStatus;if(!s)return!0;const i=(x=n.attrs)==null?void 0:x.id,o=(k=n.attrs)==null?void 0:k.pendingGroupId,l=o&&o===B_,f=vd&&i===z_||o&&vd&&o===$v,h=f?(E=n.attrs)==null?void 0:E.pendingOriginalFrom:(C=n.attrs)==null?void 0:C.pendingSelectionFrom,m=f?(O=n.attrs)==null?void 0:O.pendingOriginalTo:(_=n.attrs)==null?void 0:_.pendingSelectionTo,g=h!=null&&m!=null,y=f?"pending-original":TB(s);if(g&&n.isTextblock&&y){const T=H1(n,r,h),R=H1(n,r,m);T!==null&&R!==null&&T<R&&e.push(Lt.inline(T,R,{class:y}))}else y&&(n.isTextblock&&r+1<r+n.nodeSize-1?e.push(Lt.inline(r+1,r+n.nodeSize-1,{class:y})):e.push(Lt.node(r,r+n.nodeSize,{class:y})));if(i&&(i===P_||l)){const T=f?"original":s;e.push(Lt.node(r,r+n.nodeSize,{class:`pending-active pending-active--${T}`}))}return!0}),_t.create(t,e)}function F_(){return new Rt({key:NB,state:{init(t,e){return W1(e.doc)},apply(t,e,n,r){return t.docChanged||t.getMeta("forceDecorationUpdate")?W1(r.doc):e.map(t.mapping,t.doc)}},props:{decorations(t){return this.getState(t)}}})}function Uv(t){const{state:e,dispatch:n}=t,r=e.tr.setMeta("forceDecorationUpdate",!0);n(r)}const MB=new Bt("markDecoration");let Uo=[];function q1(t){Uo=t}function AB(){return Uo}function U_(t){return{class:"agent-mark",title:t.note?`Agent Mark: ${t.note}`:"Agent Mark","data-mark-id":t.id}}function V1(t,e,n){const s=e.textContent.indexOf(t.text);if(s===-1)return null;const i=Ho(e,n,s),o=Ho(e,n,s+t.text.length);return i===null||o===null||i>=o?null:Lt.inline(i,o,U_(t))}function jB(t,e){const n=t.nodeIds,r=t.text.split(`
204
204
  `),s=U_(t),i=[];if(r.length===n.length)for(let o=0;o<n.length;o++){const l=r[o];if(!l)continue;const d=e.get(n[o]);if(!d)continue;const h=d.node.textContent.indexOf(l);if(h===-1)continue;const m=Ho(d.node,d.pos,h),g=Ho(d.node,d.pos,h+l.length);m!==null&&g!==null&&m<g&&i.push(Lt.inline(m,g,s))}else{let o=0;for(const l of n){if(o>=r.length)break;const d=e.get(l);if(!d)continue;const f=r[o];if(!f){o++;continue}const m=d.node.textContent.indexOf(f);if(m===-1)continue;const g=Ho(d.node,d.pos,m),y=Ho(d.node,d.pos,m+f.length);g!==null&&y!==null&&g<y&&(i.push(Lt.inline(g,y,s)),o++)}}return i}function K1(t){if(Uo.length===0)return _t.empty;const e=[],n=new Set,r=new Map;t.descendants((i,o)=>{var l;return i.isTextblock&&((l=i.attrs)!=null&&l.id)&&r.set(i.attrs.id,{node:i,pos:o}),!0});for(const i of Uo)if(i.nodeIds&&i.nodeIds.length>1){const o=jB(i,r);o.length>0&&(n.add(i.id),e.push(...o))}for(const i of Uo){if(n.has(i.id))continue;const o=r.get(i.nodeId);if(!o)continue;const l=V1(i,o.node,o.pos);l&&(n.add(i.id),e.push(l))}const s=Uo.filter(i=>!n.has(i.id));return s.length>0&&t.descendants((i,o)=>{if(!i.isTextblock)return!0;for(const l of s){if(n.has(l.id))continue;const d=V1(l,i,o);d&&(n.add(l.id),e.push(d))}return!0}),_t.create(t,e)}function Ho(t,e,n){let r=0,s=e+1;for(let i=0;i<t.childCount;i++){const o=t.child(i);if(o.isText){if(r+o.text.length>=n)return s+(n-r);r+=o.text.length,s+=o.nodeSize}else{const l=o.type.spec.leafText?o.type.spec.leafText(o).length:0;if(l>0&&r+l>=n)return s;r+=l,s+=o.nodeSize}}return n===r?s:null}function H_(){return new Rt({key:MB,state:{init(t,e){return K1(e.doc)},apply(t,e,n,r){return t.docChanged||t.getMeta("forceMarkUpdate")?K1(r.doc):e.map(t.mapping,t.doc)}},props:{decorations(t){return this.getState(t)}}})}function G1(t){const{state:e,dispatch:n}=t,r=e.tr.setMeta("forceMarkUpdate",!0);n(r)}const OB=new Bt("backlinkDecoration");let yd=[];function RB(t){yd=Array.isArray(t)?t:[]}function IB(t){const e=new Map;for(const n of t){if(!n.to_node)continue;const r=e.get(n.to_node)??[];r.push(n),e.set(n.to_node,r)}return e}function J1(t){if(yd.length===0)return _t.empty;const e=IB(yd);if(e.size===0)return _t.empty;const n=[];return t.descendants((r,s)=>{var l;if(!r.isTextblock)return!0;const i=(l=r.attrs)==null?void 0:l.id;if(!i)return!0;const o=e.get(i);return o&&n.push(Lt.node(s,s+r.nodeSize,{class:"linked-paragraph","data-backlinks-count":String(o.length),"data-backlinks-node":i})),!0}),_t.create(t,n)}function LB(){return new Rt({key:OB,state:{init(t,e){return J1(e.doc)},apply(t,e,n,r){return t.docChanged||t.getMeta("forceBacklinkUpdate")?J1(r.doc):e.map(t.mapping,t.doc)}},props:{decorations(t){return this.getState(t)}}})}function DB(t){const{state:e,dispatch:n}=t,r=e.tr.setMeta("forceBacklinkUpdate",!0);n(r)}function PB(t){return yd.filter(e=>e.to_node===t)}const Hv=new WeakMap;function BB(t,e){Hv.set(t,e)}async function W_(t,e){const n=new FormData;n.append("image",t);try{const r=await fetch("/api/upload-image",{method:"POST",body:n});if(!r.ok)return;const{src:s}=await r.json(),i=Hv.get(e);if(!i||i.getPreviewImages().length>=4)return;i.addToPreview(s)}catch{}}async function zB(t,e){try{const n=await fetch("/api/download-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:t})});if(!n.ok)return;const{src:r}=await n.json(),s=Hv.get(e);if(!s||s.getPreviewImages().length>=4)return;s.addToPreview(r)}catch{}}function $B(t){const e=[],n=/<img[^>]+src=["']([^"']+)["']/gi;let r;for(;(r=n.exec(t))!==null;){const s=r[1];(s.startsWith("http://")||s.startsWith("https://"))&&e.push(s)}return e}function q_(t,e){var s,i;const n=(s=e.clipboardData)==null?void 0:s.items;if(!n)return!1;for(const o of n)if(o.type.startsWith("image/")){e.preventDefault();const l=o.getAsFile();return l&&W_(l,t),!0}const r=(i=e.clipboardData)==null?void 0:i.getData("text/html");if(r){const o=$B(r);if(o.length>0){e.preventDefault();for(const l of o)zB(l,t);return!0}}return!1}function V_(t,e){var r;const n=(r=e.dataTransfer)==null?void 0:r.files;if(!(n!=null&&n.length))return!1;for(const s of n)if(s.type.startsWith("image/"))return e.preventDefault(),W_(s,t),!0;return!1}const Y1=/^[a-f0-9]{8}$/;function K_(t){if(!t.startsWith("doc:"))return null;const e=t.slice(4);let n=e,r=null;const s=e.indexOf("?q=");if(s>=0){n=e.slice(0,s);try{r=decodeURIComponent(e.slice(s+3))}catch{r=e.slice(s+3)}}let i=null;const o=n.indexOf("#");if(o>=0){const d=n.slice(o+1);i=Y1.test(d)?d:null,n=n.slice(0,o)}const l=Y1.test(n);return{docId:l?n:null,filename:l?null:n,nodeId:i,quote:r}}function vp(t){const e=t.docId||t.filename;if(!e)throw new Error("formatLinkHref: docId or filename required");let n=`doc:${e}`;return t.nodeId&&(n+=`#${t.nodeId}`),t.quote&&(n+=`?q=${encodeURIComponent(t.quote)}`),n}function FB(t){const e=K_(t);return e?e.docId||e.filename:null}function cu({initialContent:t,extensions:e,onUpdate:n,onReady:r,onLinkClick:s}){const i=S.useRef(s);i.current=s;const o=kC({extensions:e||wB,content:t||"<p></p>",onUpdate:({editor:l})=>{Fv()||n==null||n(l.getJSON())},editorProps:{attributes:{class:"tiptap"},handlePaste:q_,handleDrop:V_}},[t]);return S.useEffect(()=>{if(!o)return;const l=o.view.dom,d=f=>{var b;const h=f.target,m=h.closest("span.doc-link[data-doc]");if(m){const x=m.getAttribute("data-doc"),k=K_(`doc:${x}`);if(!k)return;(b=i.current)==null||b.call(i,k);return}const g=h.closest("a[href]");if(!g)return;const y=g.getAttribute("href")||"";/^(https?:|mailto:|tel:)/i.test(y)&&(f.metaKey||f.ctrlKey||f.shiftKey||f.button!==0||(f.preventDefault(),window.open(y,"_blank","noopener,noreferrer")))};return l.addEventListener("click",d,!0),()=>l.removeEventListener("click",d,!0)},[o]),S.useEffect(()=>{if(!o)return;const{state:l}=o.view;if(l.plugins.some(h=>h.key==="pendingDecoration$"))return;const d=F_(),f=l.reconfigure({plugins:[...l.plugins,d]});o.view.updateState(f)},[o]),S.useEffect(()=>{if(!o)return;const{state:l}=o.view;if(l.plugins.some(h=>h.key==="markDecoration$"))return;const d=H_(),f=l.reconfigure({plugins:[...l.plugins,d]});o.view.updateState(f)},[o]),S.useEffect(()=>{if(!o)return;const{state:l}=o.view;if(l.plugins.some(h=>h.key==="backlinkDecoration$"))return;const d=LB(),f=l.reconfigure({plugins:[...l.plugins,d]});o.view.updateState(f)},[o]),S.useEffect(()=>{o&&(r==null||r(o))},[o,r]),o?u.jsxs(u.Fragment,{children:[u.jsx(vv,{editor:o}),u.jsx(EB,{editor:o})]}):null}function dn({onClick:t,active:e,disabled:n,title:r,children:s}){return u.jsx("button",{className:`format-toolbar__btn${e?" active":""}${n?" disabled":""}`,onMouseDown:i=>{i.preventDefault(),t()},disabled:n,title:r,children:s})}function Lo(){return u.jsx("div",{className:"format-toolbar__divider"})}async function UB(t,e){const n=new FormData;n.append("image",t);try{const r=await fetch("/api/upload-image",{method:"POST",body:n});if(!r.ok)return;const{src:s}=await r.json();e.chain().focus().setImage({src:s,alt:t.name}).run()}catch{}}function HB({editor:t}){const[,e]=S.useState(0),n=S.useRef(null);S.useEffect(()=>{const s=()=>e(i=>i+1);return t.on("transaction",s),()=>{t.off("transaction",s)}},[t]);const r=s=>{var o;const i=(o=s.target.files)==null?void 0:o[0];i&&UB(i,t),s.target.value=""};return u.jsxs("div",{className:"format-toolbar",children:[u.jsxs("div",{className:"format-toolbar__group",children:[u.jsx(dn,{onClick:()=>t.chain().focus().toggleBold().run(),active:t.isActive("bold"),title:"Bold (Ctrl+B)",children:u.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8"})})}),u.jsx(dn,{onClick:()=>t.chain().focus().toggleItalic().run(),active:t.isActive("italic"),title:"Italic (Ctrl+I)",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("line",{x1:"19",x2:"10",y1:"4",y2:"4"}),u.jsx("line",{x1:"14",x2:"5",y1:"20",y2:"20"}),u.jsx("line",{x1:"15",x2:"9",y1:"4",y2:"20"})]})}),u.jsx(dn,{onClick:()=>t.chain().focus().toggleUnderline().run(),active:t.isActive("underline"),title:"Underline (Ctrl+U)",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M6 4v6a6 6 0 0 0 12 0V4"}),u.jsx("line",{x1:"4",x2:"20",y1:"20",y2:"20"})]})}),u.jsx(dn,{onClick:()=>t.chain().focus().toggleStrike().run(),active:t.isActive("strike"),title:"Strikethrough",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M16 4H9a3 3 0 0 0-2.83 4"}),u.jsx("path",{d:"M14 12a4 4 0 0 1 0 8H6"}),u.jsx("line",{x1:"4",x2:"20",y1:"12",y2:"12"})]})}),u.jsx(dn,{onClick:()=>t.chain().focus().toggleCode().run(),active:t.isActive("code"),title:"Inline Code",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"m16 18 6-6-6-6"}),u.jsx("path",{d:"m8 6-6 6 6 6"})]})})]}),u.jsx(Lo,{}),u.jsxs("div",{className:"format-toolbar__group",children:[u.jsx(dn,{onClick:()=>t.chain().focus().toggleHighlight().run(),active:t.isActive("highlight"),title:"Highlight",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"m9 11-6 6v3h9l3-3"}),u.jsx("path",{d:"m22 12-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"})]})}),u.jsx(dn,{onClick:()=>t.chain().focus().toggleSubscript().run(),active:t.isActive("subscript"),title:"Subscript",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"m4 5 8 8"}),u.jsx("path",{d:"m12 5-8 8"}),u.jsx("path",{d:"M20 19h-4c0-1.5.44-2 1.5-2.5S20 15.33 20 14c0-.47-.17-.93-.48-1.29a2.11 2.11 0 0 0-2.62-.44c-.42.24-.74.62-.9 1.07"})]})}),u.jsx(dn,{onClick:()=>t.chain().focus().toggleSuperscript().run(),active:t.isActive("superscript"),title:"Superscript",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"m4 19 8-8"}),u.jsx("path",{d:"m12 19-8-8"}),u.jsx("path",{d:"M20 12h-4c0-1.5.44-2 1.5-2.5S20 8.33 20 7c0-.47-.17-.93-.48-1.29a2.11 2.11 0 0 0-2.62-.44c-.42.24-.74.62-.9 1.07"})]})})]}),u.jsx(Lo,{}),u.jsxs("div",{className:"format-toolbar__group",children:[u.jsx(dn,{onClick:()=>t.chain().focus().toggleHeading({level:1}).run(),active:t.isActive("heading",{level:1}),title:"Heading 1",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M4 12h8"}),u.jsx("path",{d:"M4 18V6"}),u.jsx("path",{d:"M12 18V6"}),u.jsx("path",{d:"m17 12 3-2v8"})]})}),u.jsx(dn,{onClick:()=>t.chain().focus().toggleHeading({level:2}).run(),active:t.isActive("heading",{level:2}),title:"Heading 2",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M4 12h8"}),u.jsx("path",{d:"M4 18V6"}),u.jsx("path",{d:"M12 18V6"}),u.jsx("path",{d:"M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"})]})}),u.jsx(dn,{onClick:()=>t.chain().focus().toggleHeading({level:3}).run(),active:t.isActive("heading",{level:3}),title:"Heading 3",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M4 12h8"}),u.jsx("path",{d:"M4 18V6"}),u.jsx("path",{d:"M12 18V6"}),u.jsx("path",{d:"M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2"}),u.jsx("path",{d:"M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2"})]})}),u.jsx(dn,{onClick:()=>t.chain().focus().setParagraph().run(),active:t.isActive("paragraph")&&!t.isActive("heading"),title:"Paragraph",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M13 4v16"}),u.jsx("path",{d:"M17 4v16"}),u.jsx("path",{d:"M19 4H9.5a4.5 4.5 0 0 0 0 9H13"})]})})]}),u.jsx(Lo,{}),u.jsxs("div",{className:"format-toolbar__group",children:[u.jsx(dn,{onClick:()=>t.chain().focus().toggleBulletList().run(),active:t.isActive("bulletList"),title:"Bullet List",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M3 12h.01"}),u.jsx("path",{d:"M3 18h.01"}),u.jsx("path",{d:"M3 6h.01"}),u.jsx("path",{d:"M8 12h13"}),u.jsx("path",{d:"M8 18h13"}),u.jsx("path",{d:"M8 6h13"})]})}),u.jsx(dn,{onClick:()=>t.chain().focus().toggleOrderedList().run(),active:t.isActive("orderedList"),title:"Ordered List",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M11 12h9"}),u.jsx("path",{d:"M11 18h9"}),u.jsx("path",{d:"M11 6h9"}),u.jsx("path",{d:"M4 10V4h1"}),u.jsx("path",{d:"M4 10h2"}),u.jsx("path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"})]})}),u.jsx(dn,{onClick:()=>t.chain().focus().toggleTaskList().run(),active:t.isActive("taskList"),title:"Task List",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"m3 17 2 2 4-4"}),u.jsx("path",{d:"m3 7 2 2 4-4"}),u.jsx("path",{d:"M13 6h8"}),u.jsx("path",{d:"M13 12h8"}),u.jsx("path",{d:"M13 18h8"})]})})]}),u.jsx(Lo,{}),u.jsx("div",{className:"format-toolbar__group",children:u.jsx(dn,{onClick:()=>{const s=t.getAttributes("link").href||"",i=window.prompt("Link URL:",s);i!==null&&(i===""?t.chain().focus().unsetLink().run():t.chain().focus().setLink({href:i}).run())},active:t.isActive("link"),title:"Link (Ctrl+K)",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),u.jsx("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"})]})})}),u.jsx(Lo,{}),u.jsxs("div",{className:"format-toolbar__group",children:[u.jsx(dn,{onClick:()=>t.chain().focus().toggleBlockquote().run(),active:t.isActive("blockquote"),title:"Blockquote",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M17 6H3"}),u.jsx("path",{d:"M21 12H8"}),u.jsx("path",{d:"M21 18H8"}),u.jsx("path",{d:"M3 12v6"})]})}),u.jsx(dn,{onClick:()=>t.chain().focus().toggleCodeBlock().run(),active:t.isActive("codeBlock"),title:"Code Block",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),u.jsx("path",{d:"m10 9-3 3 3 3"}),u.jsx("path",{d:"m14 15 3-3-3-3"})]})}),u.jsx(dn,{onClick:()=>t.chain().focus().setHorizontalRule().run(),title:"Horizontal Rule",children:u.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M5 12h14"})})})]}),u.jsx(Lo,{}),u.jsxs("div",{className:"format-toolbar__group",children:[u.jsx(dn,{onClick:()=>{var s;return(s=n.current)==null?void 0:s.click()},title:"Insert Image",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}),u.jsx("circle",{cx:"9",cy:"9",r:"2"}),u.jsx("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]})}),u.jsx(dn,{onClick:()=>t.chain().focus().insertTable({rows:3,cols:3,withHeaderRow:!0}).run(),title:"Insert Table",children:u.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),u.jsx("path",{d:"M12 3v18"}),u.jsx("path",{d:"M3 9h18"}),u.jsx("path",{d:"M3 15h18"})]})})]}),u.jsx("input",{ref:n,type:"file",accept:"image/*",className:"format-toolbar__file-input",onChange:r})]})}const WB={tree:u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M3 3h7v7H3zM14 3h7v4h-7zM14 10h7v4h-7zM3 13h7v8H3z"})}),files:u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),u.jsx("polyline",{points:"14 2 14 8 20 8"})]}),timeline:u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("line",{x1:"12",y1:"2",x2:"12",y2:"22"}),u.jsx("circle",{cx:"12",cy:"6",r:"2"}),u.jsx("circle",{cx:"12",cy:"12",r:"2"}),u.jsx("circle",{cx:"12",cy:"18",r:"2"}),u.jsx("line",{x1:"14",y1:"6",x2:"20",y2:"6"}),u.jsx("line",{x1:"14",y1:"12",x2:"20",y2:"12"}),u.jsx("line",{x1:"14",y1:"18",x2:"20",y2:"18"})]}),board:u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{x:"3",y:"3",width:"5",height:"18",rx:"1"}),u.jsx("rect",{x:"10",y:"3",width:"5",height:"12",rx:"1"}),u.jsx("rect",{x:"17",y:"3",width:"5",height:"15",rx:"1"})]}),shelf:u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M4 19V5"}),u.jsx("path",{d:"M8 19V7"}),u.jsx("path",{d:"M12 19V4"}),u.jsx("path",{d:"M16 19V8"}),u.jsx("path",{d:"M20 19V6"}),u.jsx("line",{x1:"2",y1:"20",x2:"22",y2:"20"})]})};function qB(){const[t,e]=S.useState(!1),[n,r]=S.useState(rE),[s,i]=S.useState(sE),[o,l]=S.useState(kd),d=iE(),[f,h]=S.useState(aE),[m,g]=S.useState(lE),y=S.useRef(null),b=(_=n,T=s,R=o,I=d,B=f,P=m)=>{cE(_,T,R,I,B,P)},x=_=>{r(_),b(_)},k=()=>{const _=s==="light"?"dark":"light";i(_),b(void 0,_)},E=_=>{l(_),b(void 0,void 0,_),window.dispatchEvent(new CustomEvent("ow-sidebar-mode-change",{detail:_}))},C=_=>{h(_),b(void 0,void 0,void 0,void 0,_)},O=_=>{g(_),b(void 0,void 0,void 0,void 0,void 0,_)};return S.useEffect(()=>{if(!t)return;const _=T=>{y.current&&!y.current.contains(T.target)&&e(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[t]),u.jsxs("div",{className:"appearance-wrapper",ref:y,children:[u.jsx("button",{className:`titlebar-nav-btn${t?" titlebar-nav-btn--active":""}`,onClick:()=>e(!t),title:"Appearance",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z"}),u.jsx("circle",{cx:"13.5",cy:"6.5",r:"1",fill:"currentColor",stroke:"none"}),u.jsx("circle",{cx:"17.5",cy:"10.5",r:"1",fill:"currentColor",stroke:"none"}),u.jsx("circle",{cx:"6.5",cy:"12.5",r:"1",fill:"currentColor",stroke:"none"}),u.jsx("circle",{cx:"8.5",cy:"7.5",r:"1",fill:"currentColor",stroke:"none"})]})}),t&&u.jsxs("div",{className:"appearance-dropdown",children:[u.jsx("div",{className:"appearance-section",children:u.jsxs("div",{className:"appearance-section-header",children:[u.jsx("span",{className:"appearance-section-title",children:"Mode"}),u.jsxs("button",{className:"appearance-mode-btn",onClick:k,title:s==="light"?"Switch to dark":"Switch to light",children:[s==="light"?u.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"12",r:"5"}),u.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),u.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),u.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),u.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),u.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),u.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),u.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),u.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]}):u.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})}),u.jsx("span",{children:s==="light"?"Light":"Dark"})]})]})}),u.jsxs("div",{className:"appearance-section",children:[u.jsx("div",{className:"appearance-section-header",children:u.jsx("span",{className:"appearance-section-title",children:"Typography"})}),u.jsx("div",{className:"appearance-typeface-grid",children:ZS.map(_=>u.jsx("button",{className:`appearance-style-option ${n===_.id?"active":""}`,onClick:()=>x(_.id),title:_.description,children:_.label},_.id))})]}),u.jsxs("div",{className:"appearance-section",children:[u.jsx("div",{className:"appearance-section-header",children:u.jsx("span",{className:"appearance-section-title",children:"Spacing"})}),u.jsx("div",{className:"appearance-typography-grid",children:nE.map(_=>u.jsx("button",{className:`appearance-style-option ${f===_.id?"active":""}`,onClick:()=>C(_.id),children:_.label},_.id))})]}),u.jsxs("div",{className:"appearance-section",children:[u.jsx("div",{className:"appearance-section-header",children:u.jsx("span",{className:"appearance-section-title",children:"Canvas"})}),u.jsx("div",{className:"appearance-style-grid",children:tE.map(_=>u.jsx("button",{className:`appearance-style-option ${m===_.id?"active":""}`,onClick:()=>O(_.id),children:_.label},_.id))})]}),u.jsxs("div",{className:"appearance-section",children:[u.jsx("div",{className:"appearance-section-header",children:u.jsx("span",{className:"appearance-section-title",children:"Layout"})}),u.jsx("div",{className:"appearance-mode-grid",children:eE.map(_=>u.jsxs("button",{className:`appearance-mode-option ${o===_.id?"active":""}`,onClick:()=>E(_.id),children:[WB[_.icon],u.jsx("span",{children:_.label})]},_.id))})]})]})]})}const VB={none:"No Plan",free:"No Plan",creator:"Creator — $19/mo",growth:"Growth — $49/mo",publisher:"Publisher — $79/mo"},KB=[{plan:"creator",label:"Creator $19/mo"},{plan:"growth",label:"Growth $49/mo"}];function GB(){var d,f;const[t,e]=S.useState(null),[n,r]=S.useState(!0);S.useEffect(()=>{fetch("/api/billing").then(h=>h.json()).then(h=>e(h)).catch(()=>{}).finally(()=>r(!1))},[]);const s=S.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=S.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 u.jsx("div",{className:"billing-section",children:u.jsx("div",{className:"billing-loading",children:"Loading..."})});if(!(t!=null&&t.authenticated))return null;const o=t.plan||"free",l=KB.filter(h=>{const m=["free","creator","growth","publisher"];return m.indexOf(h.plan)>m.indexOf(o)});return u.jsxs("div",{className:"billing-section",children:[u.jsxs("div",{className:"billing-plan",children:[u.jsx("span",{className:"billing-plan-label",children:"Plan"}),u.jsx("span",{className:`billing-plan-badge billing-plan-badge--${o}`,children:VB[o]||o})]}),((d=t.billing)==null?void 0:d.paymentFailed)&&u.jsx("div",{className:"billing-warning",children:"Payment failed — update card to keep your plan."}),l.length>0&&u.jsx("div",{className:"billing-upgrades",children:l.map(h=>u.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)&&u.jsx("button",{className:"billing-manage-btn",onClick:i,children:"Manage Billing"})]})}function X1(t){return t.replace(/^@openwriter\/plugin-/,"").replace(/-/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function JB(){const[t,e]=S.useState(!1),[n,r]=S.useState([]),[s,i]=S.useState(null),[o,l]=S.useState(new Set),d=S.useRef(null),f=S.useCallback(()=>{fetch("/api/available-plugins").then(g=>g.json()).then(g=>r(g.plugins||[])).catch(()=>{})},[]);S.useEffect(()=>{t&&f()},[t,f]),S.useEffect(()=>{const g=()=>f();return window.addEventListener("ow-plugins-changed",g),()=>window.removeEventListener("ow-plugins-changed",g)},[f]),S.useEffect(()=>{if(!t)return;const g=y=>{d.current&&!d.current.contains(y.target)&&e(!1)};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[t]);const h=S.useCallback(async(g,y)=>{i(g);try{(await fetch(y?"/api/plugins/disable":"/api/plugins/enable",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:g})})).ok&&f()}catch{}finally{i(null)}},[f]),m=S.useCallback((g,y,b)=>{fetch("/api/plugins/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:g,config:{[y]:b}})}).catch(()=>{})},[]);return u.jsxs("div",{className:"plugin-wrapper",ref:d,children:[u.jsx("button",{className:`titlebar-nav-btn${t?" titlebar-nav-btn--active":""}`,onClick:()=>e(!t),title:"Plugins",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M12 22v-5"}),u.jsx("path",{d:"M9 8V2"}),u.jsx("path",{d:"M15 8V2"}),u.jsx("path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z"})]})}),t&&u.jsxs("div",{className:"plugin-dropdown",children:[u.jsx("div",{className:"plugin-dropdown-header",children:"Plugins"}),n.length===0?u.jsx("div",{className:"plugin-empty",children:"No plugins found"}):n.map(g=>u.jsxs("div",{className:"plugin-item",children:[u.jsxs("div",{className:"plugin-item-header",children:[u.jsxs("div",{className:"plugin-item-info",children:[u.jsxs("div",{className:"plugin-item-name",children:[X1(g.name),u.jsxs("span",{className:"plugin-item-version",children:["v",g.version]})]}),g.description&&u.jsx("div",{className:"plugin-item-desc",children:g.description})]}),u.jsxs("label",{className:`plugin-toggle${s===g.name?" loading":""}`,children:[u.jsx("input",{type:"checkbox",checked:g.enabled,disabled:s===g.name,onChange:()=>h(g.name,g.enabled)}),u.jsx("span",{className:"plugin-toggle-track"}),u.jsx("span",{className:"plugin-toggle-thumb"})]})]}),g.enabled&&g.name==="@openwriter/plugin-publish"&&u.jsx(GB,{}),g.enabled&&Object.keys(g.configSchema).length>0&&(()=>{const y=Object.entries(g.configSchema).some(([b,x])=>x.required&&!g.config[b]);return u.jsxs("div",{className:"plugin-config-section",children:[y&&u.jsxs("div",{className:"plugin-setup-hint",children:["Ask your agent: “set up ",X1(g.name),"”"]}),u.jsxs("button",{className:"plugin-config-toggle",onClick:()=>l(b=>{const x=new Set(b);return x.has(g.name)?x.delete(g.name):x.add(g.name),x}),children:[u.jsx("svg",{className:`plugin-config-chevron${o.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:u.jsx("polyline",{points:"9 18 15 12 9 6"})}),"Settings"]}),o.has(g.name)&&u.jsx("div",{className:"plugin-config",children:Object.entries(g.configSchema).map(([b,x])=>u.jsxs("div",{className:"plugin-config-field",children:[u.jsx("label",{className:"plugin-config-label",children:x.description||b}),u.jsx("input",{className:"plugin-config-input",type:b.toLowerCase().includes("key")||b.toLowerCase().includes("secret")||b.toLowerCase().includes("token")?"password":"text",defaultValue:g.config[b]||"",placeholder:x.env?`$${x.env}`:"",onBlur:k=>m(g.name,b,k.target.value)})]},b))})]})})()]},g.name))]})]})}function YB(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 XB(t){return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function QB(){const[t,e]=S.useState(!1),[n,r]=S.useState([]),[s,i]=S.useState(null),[o,l]=S.useState(!1),d=S.useRef(null),f=S.useCallback(()=>{fetch("/api/versions").then(m=>m.json()).then(m=>{r(Array.isArray(m)?m:[]),i(null)}).catch(()=>r([]))},[]);S.useEffect(()=>{t&&f()},[t,f]),S.useEffect(()=>{if(!t)return;const m=g=>{d.current&&!d.current.contains(g.target)&&e(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[t]);const h=S.useCallback(async m=>{if(s!==null){l(!0);try{(await fetch(`/api/versions/${s}/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:m})})).ok&&f()}catch{}l(!1)}},[s,f]);return u.jsxs("div",{className:"version-wrapper",ref:d,children:[u.jsx("button",{className:`titlebar-nav-btn${t?" titlebar-nav-btn--active":""}`,onClick:()=>e(!t),title:"Version history",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[u.jsx("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2"}),u.jsx("path",{d:"M12 7v5l3 3",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})}),t&&u.jsxs("div",{className:"version-dropdown",children:[u.jsx("div",{className:"version-dropdown__header",children:"Version History"}),u.jsx("div",{className:"version-dropdown__list",children:n.length===0?u.jsx("div",{className:"version-dropdown__empty",children:"No versions yet. Versions are created automatically when you save."}):n.map(m=>u.jsxs("div",{className:`version-dropdown__item${s===m.timestamp?" version-dropdown__item--selected":""}`,onClick:()=>i(m.timestamp===s?null:m.timestamp),children:[u.jsx("span",{className:"version-dropdown__item-time",children:YB(m.timestamp)}),u.jsxs("span",{className:"version-dropdown__item-meta",children:[m.wordCount.toLocaleString()," words · ",XB(m.size)]})]},m.timestamp))}),n.length>0&&u.jsxs("div",{className:"version-dropdown__footer",children:[u.jsx("button",{className:"version-dropdown__review-btn",disabled:s===null||o,onClick:()=>h("review"),children:"Review"}),u.jsx("button",{className:"version-dropdown__restore-btn",disabled:s===null||o,onClick:()=>h("full"),children:"Restore"})]})]})]})}const ZB=[{key:"md",label:"Markdown",desc:"Plain .md file",icon:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),u.jsx("path",{d:"M14 2v6h6"})]})},{key:"html",label:"HTML",desc:"Styled web page",icon:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("polyline",{points:"16 18 22 12 16 6"}),u.jsx("polyline",{points:"8 6 2 12 8 18"})]})},{key:"docx",label:"Word",desc:"Microsoft Word .docx",icon:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),u.jsx("path",{d:"M14 2v6h6"}),u.jsx("path",{d:"M16 13H8"}),u.jsx("path",{d:"M16 17H8"}),u.jsx("path",{d:"M10 9H8"})]})},{key:"txt",label:"Plain Text",desc:"Unformatted .txt file",icon:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M17 6.1H3"}),u.jsx("path",{d:"M21 12.1H3"}),u.jsx("path",{d:"M15.1 18H3"})]})},{key:"pdf",label:"PDF",desc:"Print preview for save as PDF",icon:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("polyline",{points:"6 9 6 2 18 2 18 9"}),u.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"}),u.jsx("rect",{x:"6",y:"14",width:"12",height:"8"})]})}];function e5(){const[t,e]=S.useState(!1),n=S.useRef(null);S.useEffect(()=>{if(!t)return;const s=i=>{n.current&&!n.current.contains(i.target)&&e(!1)};return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[t]);const r=s=>{if(e(!1),s==="pdf"){window.open("/api/export?format=pdf","_blank");return}const i=document.createElement("a");i.href=`/api/export?format=${s}`,i.download="",document.body.appendChild(i),i.click(),document.body.removeChild(i)};return u.jsxs("div",{className:"export-wrapper",ref:n,children:[u.jsx("button",{className:`titlebar-nav-btn${t?" titlebar-nav-btn--active":""}`,onClick:()=>e(!t),title:"Export document",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),u.jsx("polyline",{points:"7 10 12 15 17 10"}),u.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})}),t&&u.jsxs("div",{className:"export-dropdown",children:[u.jsx("div",{className:"export-dropdown__header",children:"Export"}),u.jsx("div",{className:"export-dropdown__list",children:ZB.map(s=>u.jsxs("div",{className:"export-dropdown__item",onClick:()=>r(s.key),children:[u.jsx("span",{className:"export-dropdown__item-icon",children:s.icon}),u.jsxs("span",{className:"export-dropdown__item-text",children:[u.jsx("span",{className:"export-dropdown__item-label",children:s.label}),u.jsx("span",{className:"export-dropdown__item-desc",children:s.desc})]})]},s.key))})]})]})}function t5({existingConnection:t,onClose:e,onSaved:n}){const[r,s]=S.useState("form"),[i,o]=S.useState(null),[l,d]=S.useState((t==null?void 0:t.domain)||""),[f,h]=S.useState(""),[m,g]=S.useState((t==null?void 0:t.from_name)||""),[y,b]=S.useState(""),[x,k]=S.useState((t==null?void 0:t.id)||""),[E,C]=S.useState({dns_verified:!1,sender_verified:!1}),O=S.useRef(null),_=S.useRef(null);S.useEffect(()=>{const V=$=>{r!=="submitting"&&r!=="verifying"&&_.current&&!_.current.contains($.target)&&e()};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[e,r]),S.useEffect(()=>{const V=$=>{$.key==="Escape"&&r!=="submitting"&&r!=="verifying"&&e()};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[e,r]),S.useEffect(()=>()=>{O.current&&clearInterval(O.current)},[]);async function T(){var V,$;s("submitting"),o(null);try{const G=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:y}})})).json(),K=($=(V=G.content)==null?void 0:V[0])!=null&&$.text?JSON.parse(G.content[0].text):G;if(K.error){o(K.error),s("error");return}const X=K.connectionId||K.connection_id||x;X&&k(X),I(X)}catch(Q){o(Q.message),s("error")}}async function R(){var V,$;s("submitting"),o(null);try{const G=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:y||void 0}})})).json(),K=($=(V=G.content)==null?void 0:V[0])!=null&&$.text?JSON.parse(G.content[0].text):G;if(K.error){o(K.error),s("error");return}s("done")}catch(Q){o(Q.message),s("error")}}function I(V){s("verifying"),O.current=setInterval(async()=>{var $,Q;try{const K=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"check_domain_status",arguments:{connectionId:V}})})).json(),X=(Q=($=K.content)==null?void 0:$[0])!=null&&Q.text?JSON.parse(K.content[0].text):K,re=!!X.dns_verified,J=!!X.sender_verified;C({dns_verified:re,sender_verified:J}),re&&J&&(O.current&&clearInterval(O.current),O.current=null,s("done"))}catch{}},5e3)}function B(){x&&fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"resend_domain_verification",arguments:{connectionId:x}})}).catch(()=>{})}const P=!!t,D=l.trim()&&f.trim()&&y.trim();return u.jsx("div",{className:"newsletter-modal-overlay",children:u.jsxs("div",{className:"newsletter-modal newsletter-modal--setup",ref:_,children:[u.jsxs("div",{className:"newsletter-modal__header",children:[u.jsx("h3",{children:P?"Newsletter Settings":"Set Up Newsletter"}),u.jsx("button",{className:"newsletter-modal__close",onClick:e,children:"×"})]}),u.jsxs("div",{className:"newsletter-modal__body",children:[r==="form"&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"newsletter-modal__field",children:[u.jsx("label",{className:"newsletter-modal__label",children:"Domain"}),u.jsx("input",{className:"newsletter-modal__input",type:"text",placeholder:"yourdomain.com",value:l,onChange:V=>d(V.target.value),disabled:P,autoComplete:"off"})]}),u.jsxs("div",{className:"newsletter-modal__field",children:[u.jsx("label",{className:"newsletter-modal__label",children:"From Email"}),u.jsx("input",{className:"newsletter-modal__input",type:"email",placeholder:"newsletter@yourdomain.com",value:f,onChange:V=>h(V.target.value),autoComplete:"off"})]}),u.jsxs("div",{className:"newsletter-modal__field",children:[u.jsxs("label",{className:"newsletter-modal__label",children:["From Name ",u.jsx("span",{className:"newsletter-modal__optional",children:"(optional)"})]}),u.jsx("input",{className:"newsletter-modal__input",type:"text",placeholder:"Your Name or Brand",value:m,onChange:V=>g(V.target.value),autoComplete:"off"})]}),u.jsxs("div",{className:"newsletter-modal__field",children:[u.jsxs("label",{className:"newsletter-modal__label",children:["Physical Address ",u.jsx("span",{className:"newsletter-modal__required",children:"*"})]}),u.jsx("textarea",{className:"newsletter-modal__input newsletter-modal__textarea",rows:2,placeholder:"123 Main St, City, State 12345",value:y,onChange:V=>b(V.target.value)}),u.jsx("span",{className:"newsletter-modal__hint",children:"Required by CAN-SPAM. Included in email footer."})]}),u.jsxs("div",{className:"newsletter-modal__actions",children:[u.jsx("button",{className:"newsletter-modal__btn",onClick:e,children:"Cancel"}),u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:P?R:T,disabled:!D,children:P?"Save":"Set Up Domain"})]})]}),r==="submitting"&&u.jsxs("div",{className:"newsletter-modal__status",children:[u.jsx("div",{className:"newsletter-modal__spinner"}),u.jsx("span",{children:P?"Saving...":"Setting up domain..."})]}),r==="verifying"&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"newsletter-modal__verify",children:[u.jsx("p",{className:"newsletter-modal__verify-title",children:"Verifying domain setup..."}),u.jsxs("div",{className:"newsletter-modal__verify-checks",children:[u.jsxs("div",{className:`newsletter-modal__verify-item${E.dns_verified?" newsletter-modal__verify-item--done":""}`,children:[E.dns_verified?"✓":u.jsx("span",{className:"newsletter-modal__spinner newsletter-modal__spinner--sm"}),u.jsx("span",{children:"DNS records"})]}),u.jsxs("div",{className:`newsletter-modal__verify-item${E.sender_verified?" newsletter-modal__verify-item--done":""}`,children:[E.sender_verified?"✓":u.jsx("span",{className:"newsletter-modal__spinner newsletter-modal__spinner--sm"}),u.jsx("span",{children:"Sender verification"})]})]}),u.jsx("p",{className:"newsletter-modal__hint",children:"This may take a few minutes. You can close and check back later."})]}),u.jsxs("div",{className:"newsletter-modal__actions",children:[u.jsx("button",{className:"newsletter-modal__btn",onClick:B,children:"Resend Verification"}),u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>{n(),e()},children:"Close"})]})]}),r==="done"&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"newsletter-modal__status newsletter-modal__status--success",children:P?"Settings saved!":"Newsletter domain configured!"}),u.jsx("div",{className:"newsletter-modal__actions",children:u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>{n(),e()},children:"Done"})})]}),r==="error"&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"newsletter-modal__error",children:i}),u.jsxs("div",{className:"newsletter-modal__actions",children:[u.jsx("button",{className:"newsletter-modal__btn",onClick:e,children:"Cancel"}),u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>s("form"),children:"Try Again"})]})]})]})]})})}const n5={github:[{key:"owner",label:"Owner",placeholder:"username or org",readonly:!0},{key:"repo",label:"Repository",placeholder:"my-blog",readonly:!0},{key:"branch",label:"Branch",placeholder:"main"},{key:"contentDir",label:"Content Directory",placeholder:"src/content/blog",required:!0},{key:"imageDir",label:"Image Directory",placeholder:"public/images/blog"}],x:[],linkedin:[]};function r5({connectionId:t,provider:e,displayName:n,onClose:r,onSaved:s}){const[i,o]=S.useState("loading"),[l,d]=S.useState({}),[f,h]=S.useState(null),m=S.useRef(null),g=n5[e]||[];S.useEffect(()=>{fetch(`/api/connections/${t}/config`).then(x=>x.json()).then(x=>{d(x.config||{}),o("form")}).catch(x=>{h(x.message),o("error")})},[t]),S.useEffect(()=>{const x=k=>{i!=="saving"&&m.current&&!m.current.contains(k.target)&&r()};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[r,i]),S.useEffect(()=>{const x=k=>{k.key==="Escape"&&i!=="saving"&&r()};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[r,i]);async function y(){o("saving"),h(null);try{const x=await fetch(`/api/connections/${t}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}),k=await x.json();if(!x.ok)throw new Error(k.error||"Failed to save");o("saved"),s(),setTimeout(r,800)}catch(x){h(x.message),o("error")}}function b(x){switch(x){case"x":return"X (Twitter)";case"linkedin":return"LinkedIn";case"github":return"GitHub";default:return x}}return u.jsx("div",{className:"conn-config-overlay",children:u.jsxs("div",{className:"conn-config-modal",ref:m,children:[u.jsxs("div",{className:"conn-config-modal__header",children:[u.jsxs("div",{className:"conn-config-modal__title",children:[b(e)," Settings"]}),u.jsx("div",{className:"conn-config-modal__subtitle",children:n})]}),i==="loading"&&u.jsxs("div",{className:"conn-config-modal__body conn-config-modal__center",children:[u.jsx("div",{className:"conn-config-spinner"}),u.jsx("span",{children:"Loading configuration..."})]}),(i==="form"||i==="error")&&g.length>0&&u.jsxs("div",{className:"conn-config-modal__body",children:[g.map(x=>u.jsxs("div",{className:"conn-config-field",children:[u.jsxs("label",{className:"conn-config-field__label",children:[x.label,x.readonly&&u.jsx("span",{className:"conn-config-field__badge",children:"read-only"})]}),u.jsx("input",{className:"conn-config-field__input",value:l[x.key]||"",placeholder:x.placeholder,readOnly:x.readonly,onChange:k=>d(E=>({...E,[x.key]:k.target.value}))})]},x.key)),f&&u.jsx("div",{className:"conn-config-modal__error",children:f})]}),(i==="form"||i==="error")&&g.length===0&&u.jsx("div",{className:"conn-config-modal__body conn-config-modal__center",children:u.jsxs("span",{className:"conn-config-modal__empty",children:["No configuration needed for ",b(e),"."]})}),i==="saving"&&u.jsxs("div",{className:"conn-config-modal__body conn-config-modal__center",children:[u.jsx("div",{className:"conn-config-spinner"}),u.jsx("span",{children:"Saving..."})]}),i==="saved"&&u.jsxs("div",{className:"conn-config-modal__body conn-config-modal__center",children:[u.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#22c55e",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"20 6 9 17 4 12"})}),u.jsx("span",{children:"Saved"})]}),u.jsxs("div",{className:"conn-config-modal__footer",children:[u.jsx("button",{className:"conn-config-btn conn-config-btn--secondary",onClick:r,children:i==="saved"?"Close":"Cancel"}),g.length>0&&(i==="form"||i==="error")&&u.jsx("button",{className:"conn-config-btn conn-config-btn--primary",onClick:y,children:"Save"})]})]})})}const s5=[{id:"x",label:"X (Twitter)",oauth:!0},{id:"linkedin",label:"LinkedIn",oauth:!0},{id:"github",label:"GitHub",oauth:!0},{id:"newsletter",label:"Newsletter",oauth:!1}];function i5(){const[t,e]=S.useState(!1),[n,r]=S.useState([]),[s,i]=S.useState(null),[o,l]=S.useState(null),[d,f]=S.useState(null),[h,m]=S.useState(null),[g,y]=S.useState(null),b=S.useRef(null),x=S.useRef(null);S.useEffect(()=>{fetch("/api/connections").then(I=>I.json()).then(I=>i(I.authenticated!==!1)).catch(()=>i(!1))},[]),S.useEffect(()=>{if(!t)return;const I=B=>{b.current&&!b.current.contains(B.target)&&(e(!1),l(null))};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[t]),S.useEffect(()=>{t&&k()},[t]),S.useEffect(()=>()=>{x.current&&clearInterval(x.current)},[]);async function k(){try{const B=await(await fetch("/api/connections")).json();i(B.authenticated!==!1);const P=(B.connections||[]).filter(D=>D&&D.id&&D.provider);return r(P),P}catch{return[]}}async function E(I){f(I);try{const B=await fetch(`/api/connections/oauth/${I}/start`,{method:"POST"}),P=await B.json();if(!B.ok||!P.url){f(null);return}window.open(P.url,"_blank","width=600,height=700"),x.current=setInterval(async()=>{try{const V=await(await fetch(`/api/connections/oauth/${I}/status/${P.state}`)).json();if(V.status==="completed"){x.current&&clearInterval(x.current),x.current=null,f(null);const $=await k();if(I==="x"){const Q=$.find(G=>G.provider==="x"&&G.status==="active");if(Q!=null&&Q.display_name){const G=Q.display_name.replace("@","");localStorage.setItem("ow-x-handle",G),window.dispatchEvent(new StorageEvent("storage",{key:"ow-x-handle",newValue:G}))}}}else V.status==="failed"&&(x.current&&clearInterval(x.current),x.current=null,f(null))}catch{}},2e3)}catch{f(null)}}async function C(I){try{const B=await fetch(`/api/connections/${I}`,{method:"DELETE"});if(!B.ok){const P=await B.json().catch(()=>({error:"Delete failed"}));console.error("[Connections] Delete failed:",P.error)}}catch(B){console.error("[Connections] Delete error:",B)}l(null),await k()}function O(I){return I==="active"?"connections-status--active":I==="expired"?"connections-status--expired":I==="revoked"?"connections-status--revoked":"connections-status--pending"}function _(I){switch(I){case"x":return u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:u.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 u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:u.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"github":return u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:u.jsx("path",{d:"M12 0C5.374 0 0 5.373 0 12c0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23A11.509 11.509 0 0112 5.803c1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576C20.566 21.797 24 17.3 24 12c0-6.627-5.373-12-12-12z"})});case"newsletter":return u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),u.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]});default:return u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),u.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"})]})}}const T=new Map;for(const I of n)T.set(I.provider,I);const R=s===!1;return u.jsxs("div",{className:"connections-wrapper",ref:b,children:[u.jsx("button",{className:`titlebar-nav-btn${t?" titlebar-nav-btn--active":""}${R?" titlebar-nav-btn--disabled":""}`,onClick:()=>e(!t),title:R?"Connect to the Publish platform to enable connections":"Connections",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"5",r:"3"}),u.jsx("circle",{cx:"5",cy:"19",r:"3"}),u.jsx("circle",{cx:"19",cy:"19",r:"3"}),u.jsx("line",{x1:"12",y1:"8",x2:"5",y2:"16"}),u.jsx("line",{x1:"12",y1:"8",x2:"19",y2:"16"})]})}),g&&u.jsx(r5,{connectionId:g.id,provider:g.provider,displayName:g.display_name,onClose:()=>y(null),onSaved:()=>k()}),h&&u.jsx(t5,{existingConnection:h==="edit"?T.get("newsletter"):null,onClose:()=>m(null),onSaved:()=>k()}),t&&R&&u.jsxs("div",{className:"connections-dropdown",children:[u.jsx("div",{className:"connections-dropdown__header",children:"Connections"}),u.jsxs("div",{className:"connections-dropdown__upsell",children:[u.jsx("p",{children:"Connect your X, LinkedIn, and other accounts to publish directly from OpenWriter."}),u.jsxs("p",{children:["Set up the ",u.jsx("strong",{children:"Publish"})," plugin to get started."]})]})]}),t&&!R&&u.jsxs("div",{className:"connections-dropdown",children:[u.jsx("div",{className:"connections-dropdown__header",children:"Connections"}),u.jsx("div",{className:"connections-dropdown__list",children:s5.map(I=>{const B=T.get(I.id);return B&&o===B.id?u.jsxs("div",{className:"connections-dropdown__confirm",children:[u.jsxs("span",{children:["Disconnect ",I.label,"?"]}),u.jsxs("div",{className:"connections-dropdown__confirm-btns",children:[u.jsx("button",{onClick:()=>C(B.id),children:"Yes"}),u.jsx("button",{onClick:()=>l(null),children:"No"})]})]},I.id):B?u.jsxs("div",{className:"connections-dropdown__item",children:[u.jsx("div",{className:"connections-dropdown__icon",children:_(I.id)}),u.jsxs("div",{className:"connections-dropdown__info",children:[u.jsx("div",{className:"connections-dropdown__name",children:B.display_name||B.domain||I.label}),u.jsxs("div",{className:"connections-dropdown__type",children:[u.jsx("span",{className:`connections-status ${O(B.status)}`}),"Connected"]})]}),u.jsxs("div",{className:"connections-dropdown__actions",children:[u.jsx("button",{className:"connections-dropdown__action-btn",onClick:()=>{I.id==="newsletter"?m("edit"):y({id:B.id,provider:I.id,display_name:B.display_name||I.label})},title:"Settings",children:u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.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"}),u.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),u.jsx("button",{className:"connections-dropdown__action-btn connections-dropdown__action-btn--delete",onClick:()=>l(B.id),title:"Disconnect",children:"×"})]})]},I.id):I.oauth?u.jsxs("div",{className:"connections-dropdown__item connections-dropdown__item--disconnected",children:[u.jsx("div",{className:"connections-dropdown__icon",children:_(I.id)}),u.jsxs("div",{className:"connections-dropdown__info",children:[u.jsx("div",{className:"connections-dropdown__name",children:I.label}),u.jsx("div",{className:"connections-dropdown__type",children:"Not connected"})]}),u.jsx("button",{className:"connections-dropdown__connect-inline-btn",onClick:()=>E(I.id),disabled:d!==null,children:d===I.id?"Connecting…":"Connect"})]},I.id):u.jsxs("div",{className:"connections-dropdown__item connections-dropdown__item--disconnected",children:[u.jsx("div",{className:"connections-dropdown__icon",children:_(I.id)}),u.jsxs("div",{className:"connections-dropdown__info",children:[u.jsx("div",{className:"connections-dropdown__name",children:I.label}),u.jsx("div",{className:"connections-dropdown__type",children:"Built-in · Not configured"})]}),u.jsx("button",{className:"connections-dropdown__connect-inline-btn",onClick:()=>m("new"),children:"Configure"})]},I.id)})})]})]})}const o5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:u.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"})}),a5=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[u.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"}),u.jsx("path",{d:"M9 14l2 2 4-4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),l5=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[u.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"}),u.jsx("path",{d:"M12 16v-5M9.5 13.5L12 11l2.5 2.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),c5=()=>u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[u.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"}),u.jsx("path",{d:"M14 14l-4 4M10 14l4 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]});function u5({title:t,onTitleChange:e,syncStatus:n,onSync:r,onToggleSidebar:s,canGoBack:i,canGoForward:o,onGoBack:l,onGoForward:d,editor:f,onToggleToolbar:h,toolbarOpen:m}){const[g,y]=S.useState(!1),[,b]=S.useState(0),x=S.useRef(null),[k,E]=S.useState(!1),[C,O]=S.useState([]),[_,T]=S.useState(!1),R=S.useRef(null),[I,B]=S.useState(null);S.useEffect(()=>{fetch("/api/update-info").then(Q=>Q.json()).then(Q=>{Q.updateAvailable&&B({currentVersion:Q.currentVersion,latestVersion:Q.updateAvailable})}).catch(()=>{})},[]);const P=S.useCallback(()=>{y(!0),setTimeout(()=>{var Q;return(Q=x.current)==null?void 0:Q.select()},0)},[]),D=S.useCallback(()=>{y(!1)},[]),V=S.useCallback(Q=>{Q.key==="Enter"&&y(!1),Q.key==="Escape"&&y(!1)},[]),$=S.useCallback(()=>{if(k){E(!1);return}E(!0),T(!0),fetch("/api/sync/pending").then(Q=>Q.json()).then(Q=>O(Q)).catch(()=>O([])).finally(()=>T(!1))},[k]);return S.useEffect(()=>{n.state!=="pending"&&E(!1)},[n.state]),S.useEffect(()=>{if(!k)return;const Q=G=>{R.current&&!R.current.contains(G.target)&&E(!1)};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[k]),S.useEffect(()=>{if(!f)return;const Q=()=>b(G=>G+1);return f.on("transaction",Q),()=>{f.off("transaction",Q)}},[f]),u.jsxs("div",{className:"titlebar",children:[u.jsxs("div",{className:"titlebar-left",children:[s&&u.jsx("button",{className:"titlebar-menu-btn",onClick:s,title:"Open sidebar",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[u.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",stroke:"currentColor",strokeWidth:"2"}),u.jsx("path",{d:"M9 3v18",stroke:"currentColor",strokeWidth:"2"}),u.jsx("path",{d:"M14 10l2 2-2 2",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})}),l&&u.jsx("button",{className:"titlebar-nav-btn",onClick:l,disabled:!i,title:"Go back (Alt+Left)",children:u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),d&&u.jsx("button",{className:"titlebar-nav-btn",onClick:d,disabled:!o,title:"Go forward (Alt+Right)",children:u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M6 3l5 5-5 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),f&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"titlebar-divider"}),u.jsx("button",{className:"titlebar-nav-btn",onClick:()=>f.chain().focus().undo().run(),disabled:!f.can().undo(),title:"Undo (Ctrl+Z)",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[u.jsx("path",{d:"M3 10h10a5 5 0 0 1 0 10H9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),u.jsx("path",{d:"M7 6L3 10l4 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})}),u.jsx("button",{className:"titlebar-nav-btn",onClick:()=>f.chain().focus().redo().run(),disabled:!f.can().redo(),title:"Redo (Ctrl+Y)",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[u.jsx("path",{d:"M21 10H11a5 5 0 0 0 0 10h4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),u.jsx("path",{d:"M17 6l4 4-4 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})]}),u.jsxs("div",{className:"titlebar-center",children:[g?u.jsx("input",{ref:x,className:"titlebar-input",value:t,onChange:Q=>e(Q.target.value),onBlur:D,onKeyDown:V,autoFocus:!0}):u.jsx("span",{className:"titlebar-title",onDoubleClick:P,children:t}),I&&u.jsxs("span",{className:"titlebar-update-badge",title:`Update available: v${I.currentVersion} → v${I.latestVersion}
205
- Run: npm update -g openwriter`,children:["v",I.latestVersion]})]}),u.jsxs("div",{className:"titlebar-right",children:[h&&u.jsx("button",{className:`titlebar-nav-btn${m?" titlebar-nav-btn--active":""}`,onClick:h,title:"Toggle format toolbar",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M4 20h16"}),u.jsx("path",{d:"m6 16 6-12 6 12"}),u.jsx("path",{d:"M8 12h8"})]})}),u.jsx(JB,{}),u.jsx(i5,{}),u.jsx(qB,{}),u.jsx(QB,{}),u.jsx(e5,{}),u.jsxs("div",{className:"sync-btn-group",ref:R,children:[u.jsxs("button",{className:`titlebar-btn sync-btn-state sync-${n.state}`,onClick:r,disabled:n.state==="syncing",title:n.lastSyncTime?`Last synced: ${new Date(n.lastSyncTime).toLocaleString()}`:"Sync to GitHub",children:[n.state==="unconfigured"&&u.jsxs(u.Fragment,{children:[u.jsx(o5,{})," Sync"]}),n.state==="synced"&&u.jsxs(u.Fragment,{children:[u.jsx(a5,{})," Synced"]}),n.state==="pending"&&u.jsxs(u.Fragment,{children:[u.jsx(l5,{})," Sync",n.pendingFiles?` (${n.pendingFiles})`:""]}),n.state==="syncing"&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"sync-btn-spinner"})," Syncing..."]}),n.state==="error"&&u.jsxs(u.Fragment,{children:[u.jsx(c5,{})," Retry"]})]}),n.state==="pending"&&n.pendingFiles&&n.pendingFiles>0&&u.jsx("button",{className:"sync-details-btn",onClick:$,title:"View pending changes",children:u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:u.jsx("path",{d:k?"M3 7.5L6 4.5L9 7.5":"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),k&&u.jsxs("div",{className:"sync-pending-dropdown",children:[u.jsx("div",{className:"sync-pending-header",children:"Changes to push"}),_?u.jsx("div",{className:"sync-pending-loading",children:"Loading..."}):C.length===0?u.jsx("div",{className:"sync-pending-loading",children:"No changes"}):u.jsx("div",{className:"sync-pending-list",children:C.map((Q,G)=>u.jsxs("div",{className:`sync-pending-item sync-file-${Q.status}`,children:[u.jsx("span",{className:"sync-file-badge",children:Q.status[0].toUpperCase()}),u.jsx("span",{className:"sync-file-name",children:Q.file})]},G))})]})]})]})]})}function Cn(t,e){let n=null;return t.state.doc.descendants((r,s)=>{var i;return((i=r.attrs)==null?void 0:i.id)===e?(n={node:r,pos:s},!1):!0}),n}function zd(t,e){const n=[];return t.state.doc.descendants((r,s)=>{var i;return((i=r.attrs)==null?void 0:i.pendingGroupId)===e&&n.push({nodeId:r.attrs.id,pos:s,node:r}),!0}),n}function Vo(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,"").slice(0,8):Math.random().toString(16).slice(2,10)}function bd(t){return t?Array.isArray(t)?t.map(bd).join(""):t.text?t.text:t.content&&Array.isArray(t.content)?t.content.map(e=>bd(e)).join(""):"":""}const d5=new Set(["paragraph","heading","codeBlock","horizontalRule","table","image"]);function xd(t,e){for(const n of t)n.type&&d5.has(n.type)?n.attrs={...n.attrs,pendingStatus:e}:n.content&&xd(n.content,e)}function Pg(t,e,n,r){const s=Array.isArray(n)?n:[n],i=(r==null?void 0:r.autoAccept)===!0;if(e.nodeId&&!e.afterNodeId&&!e.beforeNodeId){const m=Cn(t,e.nodeId);if(!m)return{success:!1,error:`Node ${e.nodeId} not found`};const g=s.map((y,b)=>{var x;return{...y,attrs:{...y.attrs,id:((x=y.attrs)==null?void 0:x.id)||(b===0?e.nodeId:Vo())}}});i||xd(g,"insert");try{return t.chain().deleteRange({from:m.pos,to:m.pos+m.node.nodeSize}).insertContentAt(m.pos,g).run(),{success:!0,nodeId:e.nodeId}}catch(y){return{success:!1,error:`Failed to replace empty node: ${y}`}}}if(!e.afterNodeId&&!e.beforeNodeId)return{success:!1,error:"Insert requires afterNodeId, beforeNodeId, or nodeId"};const o=e.afterNodeId||e.beforeNodeId,l=!!e.afterNodeId,d=Cn(t,o);if(!d)return{success:!1,error:`Anchor node ${o} not found`};if(!i){const m=bd(n),g=l?d.pos+d.node.nodeSize:0,y=l?d.pos+d.node.nodeSize+5e3:d.pos;let b=null;if(t.state.doc.nodesBetween(g,Math.min(y,t.state.doc.content.size),x=>{var k,E;return((k=x.attrs)==null?void 0:k.pendingStatus)==="insert"&&((E=x.attrs)!=null&&E.id)&&(x.textContent||"")===m?(b=x.attrs.id,!1):!0}),b)return{success:!0,nodeId:b}}const f=s.map(m=>{var g;return{...m,attrs:{...m.attrs,id:((g=m.attrs)==null?void 0:g.id)||Vo()}}});i||xd(f,"insert");const h=l?d.pos+d.node.nodeSize:d.pos;try{return t.chain().insertContentAt(h,f).run(),{success:!0,nodeId:f[0].attrs.id}}catch(m){return{success:!1,error:`Failed to insert content: ${m}`}}}function Wv(t,e,n,r,s){var x;const i=Cn(t,e);if(!i)return{success:!1,error:`Node ${e} not found`};const{node:o,pos:l}=i,d=Array.isArray(n)?n:[n],f=(s==null?void 0:s.autoAccept)===!0,m=!((x=o.attrs)!=null&&x.pendingOriginalContent)?o.toJSON():o.attrs.pendingOriginalContent,g={...d[0],attrs:f?{...d[0].attrs,id:e}:{...d[0].attrs,id:e,pendingStatus:"rewrite",pendingOriginalContent:m,...r?{pendingSelectionFrom:r.selectionFrom,pendingSelectionTo:r.selectionTo,pendingOriginalFrom:r.originalFrom,pendingOriginalTo:r.originalTo}:{}}},y=d.slice(1).map(k=>{var E;return{...k,attrs:{...k.attrs,id:((E=k.attrs)==null?void 0:E.id)||Vo()}}});f||xd(y,"insert");const b=[g,...y];try{return t.chain().command(({tr:k})=>{const E=b.map(C=>t.state.schema.nodeFromJSON(C));return k.replaceWith(l,l+o.nodeSize,E),!0}).run(),{success:!0,nodeId:e}}catch(k){return{success:!1,error:`Failed to rewrite: ${k}`}}}function f5(t,e,n){if(e.length===0)return{success:!1,error:"Range rewrite requires original IDs"};if(!n||n.length===0)return{success:!1,error:"Range rewrite requires new content (received empty)"};if(n.map(m=>bd(m)).join("").trim().length===0)return{success:!1,error:"Range rewrite content is empty (no text) — aborting"};const s=Cn(t,e[0]),i=Cn(t,e[e.length-1]);if(!s||!i)return{success:!1,error:"Could not find original nodes for range rewrite"};const o=[];for(const m of e){const g=Cn(t,m);g&&o.push(g.node.toJSON())}const l=s.pos,d=i.pos+i.node.nodeSize,f=Vo()+Vo(),h=n.map((m,g)=>{var y;return{...m,attrs:{...m.attrs,id:((y=m.attrs)==null?void 0:y.id)||Vo(),pendingStatus:"rewrite",pendingGroupId:f,...g===0?{pendingOriginalContent:o}:{}}}});try{return t.chain().deleteRange({from:l,to:d}).insertContentAt(l,h).run(),{success:!0,nodeId:h[0].attrs.id}}catch(m){return{success:!1,error:`Failed to apply range rewrite: ${m}`}}}function G_(t,e,n){var l;const r=Cn(t,e);if(!r)return{success:!1,error:`Node ${e} not found`};const{node:s,pos:i}=r,o=(n==null?void 0:n.autoAccept)===!0;if(!o&&((l=s.attrs)==null?void 0:l.pendingStatus)==="delete")return{success:!0,nodeId:e};try{return o?t.chain().deleteRange({from:i,to:i+s.nodeSize}).run():t.chain().command(({tr:d})=>(d.setNodeMarkup(i,void 0,{...s.attrs,pendingStatus:"delete"}),!0)).run(),{success:!0,nodeId:e}}catch(d){return{success:!1,error:`Failed to ${o?"delete":"mark for deletion"}: ${d}`}}}function h5(t,e){const n=e.autoAccept?{autoAccept:!0}:void 0;if(e.operation==="rewrite"&&e.nodeId&&e.content){const r=Wv(t,e.nodeId,e.content,null,n);return{success:r.success,error:r.error}}if(e.operation==="insert"&&e.content){let r=null;if(e.nodeId&&!e.afterNodeId?r={nodeId:e.nodeId}:e.afterNodeId&&(r={afterNodeId:e.afterNodeId}),!r)return{success:!1,error:"Insert requires afterNodeId or nodeId"};const s=Pg(t,r,e.content,n);return{success:s.success,error:s.error}}if(e.operation==="delete"&&e.nodeId){const r=G_(t,e.nodeId,n);return{success:r.success,error:r.error}}return{success:!1,error:`Invalid operation: ${e.operation}`}}function yp(t,e){if(e.length===0)return;if(e.length===1){h5(t,e[0]);return}const n=t.state.schema;t.chain().command(({tr:r})=>{var s;for(const i of e)try{const o=i.autoAccept===!0;if(i.operation==="rewrite"&&i.nodeId&&i.content){const l=Ua(r.doc,i.nodeId);if(!l)continue;const f=(Array.isArray(i.content)?i.content:[i.content]).map(h=>n.nodeFromJSON(h));r.replaceWith(l.pos,l.pos+l.node.nodeSize,f)}else if(i.operation==="insert"&&i.content){const d=(Array.isArray(i.content)?i.content:[i.content]).map(f=>n.nodeFromJSON(f));if(!o){const f=d.map(h=>h.textContent||"").join("");if(f&&i.afterNodeId){const h=Ua(r.doc,i.afterNodeId);if(h){const m=h.pos+h.node.nodeSize,g=Math.min(m+5e3,r.doc.content.size);let y=!1;if(r.doc.nodesBetween(m,g,b=>{var x;return y?!1:((x=b.attrs)==null?void 0:x.pendingStatus)==="insert"&&(b.textContent||"")===f?(y=!0,!1):!0}),y)continue}}}if(i.nodeId&&!i.afterNodeId){const f=Ua(r.doc,i.nodeId);if(!f)continue;r.replaceWith(f.pos,f.pos+f.node.nodeSize,d)}else if(i.afterNodeId){const f=Ua(r.doc,i.afterNodeId);if(!f)continue;const h=f.pos+f.node.nodeSize;r.insert(h,ye.fromArray(d))}}else if(i.operation==="delete"&&i.nodeId){const l=Ua(r.doc,i.nodeId);if(!l)continue;if(o)r.delete(l.pos,l.pos+l.node.nodeSize);else{if(((s=l.node.attrs)==null?void 0:s.pendingStatus)==="delete")continue;r.setNodeMarkup(l.pos,void 0,{...l.node.attrs,pendingStatus:"delete"})}}}catch{continue}return!0}).run()}function Ua(t,e){let n=null;return t.descendants((r,s)=>{var i;return((i=r.attrs)==null?void 0:i.id)===e?(n={node:r,pos:s},!1):!0}),n}function p5(t,e,n,r){const s=[];if(r==="delete"){for(const o of n)s.push(G_(t,o));return s}if(r==="insert"){const o=n[n.length-1];return o&&e.length>0&&s.push(Pg(t,{nodeId:o},e)),s}if(n.length>1){const o=f5(t,n,e);return s.push(o),s}const i=Wv(t,n[0],e[0]);if(s.push(i),e.length>1){const o=e.slice(1);s.push(Pg(t,{afterNodeId:n[0]},o))}return s}const Q1="[[START_SELECTION]]",Z1="[[END_SELECTION]]";function m5(t){if(!(t!=null&&t.content)||!Array.isArray(t.content))return 0;let e=0;for(const n of t.content)n.type==="text"&&typeof n.text=="string"?e+=n.text.length:n.type==="hardBreak"&&(e+=1);return e}function uu(t,e,n){if(!(t!=null&&t.content)||!Array.isArray(t.content))return;const r=m5(t);let s=Math.max(0,Math.min(e,r));for(let i=0;i<t.content.length;i++){const o=t.content[i];if(o.type==="text"&&typeof o.text=="string"){if(s<=o.text.length){const l=Math.max(0,Math.min(o.text.length,s));o.text=o.text.slice(0,l)+n+o.text.slice(l);return}s-=o.text.length;continue}if(o.type==="hardBreak"){if(s===0){t.content.splice(i+1,0,{type:"text",text:n});return}s-=1;continue}if(s===0){t.content.splice(i,0,{type:"text",text:n});return}}t.content.push({type:"text",text:n})}function g5(t,e,n){const r=JSON.parse(JSON.stringify(t));return r.length===0?r:r.length===1?(uu(r[0],n,Z1),uu(r[0],e,Q1),r):(uu(r[0],e,Q1),uu(r[r.length-1],n,Z1),r)}function v5(t){const e=r=>r.replace(/\[\[(START|END)_SELECTION]]/g,""),n=r=>{r.type==="text"&&typeof r.text=="string"&&(r.text=e(r.text)),r.content&&Array.isArray(r.content)&&r.content.forEach(n)};Array.isArray(t)?t.forEach(n):n(t)}function ew(t,e){return t.docId&&e.includes(t.docId)?!0:e.includes(t.filename)}const y5=[{action:"agent-mark",label:"Agent Mark",shortcut:"M",condition:"has-selection"},{action:"delete",label:"Delete",shortcut:"D"}];function b5({editorRef:t,allEditors:e,documentId:n}){const[r,s]=S.useState(!1),[i,o]=S.useState({x:0,y:0}),[l,d]=S.useState(!1),[f,h]=S.useState(""),[m,g]=S.useState(!1),[y,b]=S.useState(""),[x,k]=S.useState(!1),[E,C]=S.useState([]),[O,_]=S.useState([]),[T,R]=S.useState(!1),[I,B]=S.useState(""),[P,D]=S.useState([]),[V,$]=S.useState(!1),[Q,G]=S.useState(""),[K,X]=S.useState(null),[re,J]=S.useState(null),[oe,U]=S.useState(null),[A,L]=S.useState(!1),[te,se]=S.useState(null),be=S.useRef(null),ee=S.useRef(null),ge=S.useRef(null),fe=S.useCallback(ie=>{if(e&&e.length>0){for(const q of e)if(q.view.dom.contains(ie))return q}const H=t.current;return H&&H.view.dom.contains(ie)?H:null},[e,t]);S.useLayoutEffect(()=>{const ie=be.current;if(!ie||!r)return;const H=ie.getBoundingClientRect(),q=8;let{x:de,y:me}=i;me+H.height+q>window.innerHeight&&(me=i.y-H.height),de+H.width+q>window.innerWidth&&(de=i.x-H.width),me<q&&(me=q),de<q&&(de=q),(de!==i.x||me!==i.y)&&o({x:de,y:me})},[r,i]);const Te=S.useCallback(()=>{fetch("/api/plugins").then(ie=>ie.json()).then(ie=>{const H=[];for(const q of ie.plugins||[]){const de=q.displayName||void 0;for(const me of q.contextMenuItems||[])H.push({...me,pluginDisplayName:de})}D(H)}).catch(()=>{})},[]);S.useEffect(()=>{Te()},[Te]),S.useEffect(()=>{const ie=()=>Te();return window.addEventListener("ow-plugins-changed",ie),()=>window.removeEventListener("ow-plugins-changed",ie)},[Te]),S.useEffect(()=>{const ie=H=>{be.current&&!be.current.contains(H.target)&&(s(!1),g(!1),k(!1),$(!1),G(""),X(null),J(null))};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[]);const Xe=S.useCallback(()=>{const ie=ge.current||t.current;return ie?ie.isActive("link"):!1},[t]),tt=S.useCallback(()=>{const ie=ge.current||t.current,H=ee.current;if(!ie||!H)return!1;const{from:q,to:de}=H;let me=!1;return ie.state.doc.nodesBetween(q,de,Ee=>{var De;return(De=Ee.attrs)!=null&&De.pendingStatus&&(me=!0),!me}),me},[t]),st=S.useCallback(()=>{const ie=ge.current||t.current,H=ee.current,q=(H==null?void 0:H.from)??0,de=(H==null?void 0:H.to)??0,me=q!==de,Ee=(()=>{if(!ie)return!1;try{return ie.state.doc.resolve(q).parent.content.size===0}catch{return!1}})(),De=tt(),$e=[];for(const qe of P)qe.condition==="has-selection"&&!me||qe.condition==="empty-node"&&!Ee||$e.push({action:qe.action,label:qe.label,shortcut:qe.shortcut,isPlugin:!0,promptForInput:qe.promptForInput,pluginDisplayName:qe.pluginDisplayName});for(const qe of y5)qe.condition==="has-selection"&&(!me||De)||$e.push(qe);return me&&$e.push({action:"link",label:"Link to doc",shortcut:"L"}),Xe()&&$e.push({action:"unlink",label:"Unlink"}),oe&&oe.entries.length>0&&$e.unshift({action:"see-connections",label:`See connections (${oe.entries.length})`}),$e},[t,Xe,P,tt,oe]);S.useEffect(()=>{const ie=q=>{var qe;if(q.button!==2)return;const de=fe(q.target);if(!de)return;ge.current=de;const{from:me,to:Ee}=de.state.selection,De=[],$e=[];if(me!==Ee&&de.state.doc.nodesBetween(me,Ee,W=>{W.isBlock&&W.type.name!=="doc"&&(De.push(W.toJSON()),W.attrs.id&&$e.push(W.attrs.id))}),De.length===0){const{$from:W}=de.state.selection,pe=W.parent;pe&&pe.type.name!=="doc"&&(De.push(pe.toJSON()),(qe=pe.attrs)!=null&&qe.id&&$e.push(pe.attrs.id))}ee.current={from:me,to:Ee,nodes:De,nodeIds:$e}},H=q=>{var qe,W,pe,xe;if(!fe(q.target)||q.shiftKey)return;const me=(W=(qe=q.target)==null?void 0:qe.closest)==null?void 0:W.call(qe,"[data-mark-id]"),Ee=(me==null?void 0:me.getAttribute("data-mark-id"))||null,De=(xe=(pe=q.target)==null?void 0:pe.closest)==null?void 0:xe.call(pe,".linked-paragraph[data-backlinks-node]"),$e=(De==null?void 0:De.getAttribute("data-backlinks-node"))||null;if(q.preventDefault(),o({x:q.clientX,y:q.clientY}),s(!0),g(!1),k(!1),L(!1),$(!1),G(""),X(null),Ee){const Ye=AB().find(it=>it.id===Ee);if(Ye){J({id:Ye.id,text:Ye.text,note:Ye.note}),U(null);return}}if(J(null),$e){const Ye=PB($e);U(Ye.length>0?{nodeId:$e,entries:Ye}:null)}else U(null)};return document.addEventListener("mousedown",ie,!0),document.addEventListener("contextmenu",H),()=>{document.removeEventListener("mousedown",ie,!0),document.removeEventListener("contextmenu",H)}},[fe]);const nt=S.useCallback(async(ie,H)=>{var xe,Ye,it,ot,Re;const q=ge.current||t.current;if(!q)return;const de=ee.current;if(!de||de.nodes.length===0){console.warn("[ContextMenu] No captured selection for action:",ie);return}let{nodes:me,nodeIds:Ee}=de;const{from:De,to:$e}=de;d(!0),s(!1),g(!1);const qe=`ctx-${Date.now()}`,W=ie.includes(":")?ie.split(":").slice(1).join(":"):ie,pe=["insert","fill","fill-sentence"].includes(W);if(pe)q.commands.showInsertionLoading(qe,De);else{const vt=q.state.doc.resolve(De),ht=q.state.doc.resolve($e),zt=vt.sameParent(ht)&&De!==$e;q.commands.applyLoadingEffect(qe,De,$e,zt?"selection":"paragraph")}try{const vt=[],ht=[],zt=new Set(Ee);let Ut=!1;const Jt=q.state.doc;for(let We=0;We<Jt.childCount;We++){const Mt=Jt.child(We),ut=(xe=Mt.attrs)==null?void 0:xe.id;if(ut&&zt.has(ut))Ut=!0;else if(Ut){const yn=Mt.textContent.trim();yn&&ht.push(yn)}else{const yn=Mt.textContent.trim();yn&&vt.push(yn)}}let M=me,ne=!1,ue=0,Me=0;const ct=De!==$e?q.state.doc.resolve(De):null,gt=De!==$e?q.state.doc.resolve($e):null;if((ct&&gt?ct.sameParent(gt):!1)&&ct&&me.length===1){const We=ct.start(ct.depth);ue=De-We,Me=$e-We;const Mt=((it=(Ye=me[0])==null?void 0:Ye.content)==null?void 0:it.reduce((ut,yn)=>{var qr;return ut+(((qr=yn.text)==null?void 0:qr.length)||(yn.type==="hardBreak"?1:0))},0))??0;(ue>0||Me<Mt)&&(M=g5(me,ue,Me),ne=!0)}const z=q.state.doc.textContent,he={nodes:M,action:W,nodeIds:Ee,contextBefore:vt.slice(-3),contextAfter:ht.slice(0,3),fullDocument:z,documentId:n,debug:!0};ne&&(he.hasSelectionMarkers=!0),H&&(he.instruction=H);const Ie=await fetch(`${window.location.origin}/api/voice/apply-editor`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(he)});if(!Ie.ok){const We=await Ie.json().catch(()=>({}));console.error("[ContextMenu] API error:",Ie.status,We);return}const He=await Ie.json();if(He.success&&He.nodes){let We=He.nodes;if(We.length===1&&Array.isArray(We[0])&&(We=We[0]),v5(We),ne&&We.length===1&&Ee.length===1){const Mt=yi=>(yi==null?void 0:yi.reduce((Mr,bi)=>{var Ts;return Mr+(((Ts=bi.text)==null?void 0:Ts.length)||(bi.type==="hardBreak"?1:0))},0))??0,ut=Mt((ot=me[0])==null?void 0:ot.content),yn=Mt((Re=We[0])==null?void 0:Re.content),qr={selectionFrom:ue,selectionTo:yn-(ut-Me),originalFrom:ue,originalTo:Me};Wv(q,Ee[0],We[0],qr)}else p5(q,We,Ee,W)}else console.warn("[ContextMenu] Unexpected response:",He)}catch(vt){console.error("[ContextMenu] Plugin action failed:",vt)}finally{pe?q.commands.removeInsertionLoading(qe):q.commands.removeLoadingEffect(qe),d(!1)}},[t]),Le=S.useCallback(async ie=>{const H=ge.current||t.current;if(!H)return;const{$from:q}=H.state.selection,de=q.before(q.depth),me=q.after(q.depth),Ee=q.parent.content.size===0;d(!0),s(!1),g(!1),Ee?H.chain().focus().deleteRange({from:de,to:me}).insertContentAt(de,{type:"imageLoading"}).run():H.chain().focus().insertContentAt(me,{type:"imageLoading"}).run();let De=-1;H.state.doc.descendants(($e,qe)=>{if($e.type.name==="imageLoading"&&De===-1)return De=qe,$e.nodeSize,!1});try{const $e=await fetch("/api/image-gen/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:ie})}),qe=await $e.json().catch(()=>({success:!1,error:`Generation failed (${$e.status})`}));if(qe.success&&qe.src){let W=-1,pe=0;if(H.state.doc.descendants((xe,Ye)=>{if(xe.type.name==="imageLoading"&&W===-1)return W=Ye,pe=xe.nodeSize,!1}),W>=0){const{tr:xe}=H.state;xe.replaceWith(W,W+pe,H.schema.nodes.image.create({src:qe.src,alt:ie})),H.view.dispatch(xe)}}else{console.error("[ContextMenu] Image generation failed:",qe.error);let W=-1,pe=0;if(H.state.doc.descendants((xe,Ye)=>{if(xe.type.name==="imageLoading"&&W===-1)return W=Ye,pe=xe.nodeSize,!1}),W>=0){const{tr:xe}=H.state;xe.delete(W,W+pe),H.view.dispatch(xe)}}}catch($e){console.error("[ContextMenu] Image generation failed:",$e);let qe=-1,W=0;if(H.state.doc.descendants((pe,xe)=>{if(pe.type.name==="imageLoading"&&qe===-1)return qe=xe,W=pe.nodeSize,!1}),qe>=0){const{tr:pe}=H.state;pe.delete(qe,qe+W),H.view.dispatch(pe)}}finally{d(!1)}},[t]),yt=S.useCallback(ie=>{const{action:H,isPlugin:q,promptForInput:de}=ie;if(q&&de){b(H),g(!0);return}if(q){if(H.startsWith("img:"))return;nt(H);return}if(H==="agent-mark"){$(!0);return}if(H==="delete"){const me=ge.current||t.current,Ee=ee.current;if(me&&Ee&&Ee.nodeIds.length>0){const{tr:De}=me.state,$e=new Set(Ee.nodeIds),qe=[];me.state.doc.descendants((W,pe)=>{var xe;if((xe=W.attrs)!=null&&xe.id&&$e.has(W.attrs.id))return qe.push({from:pe,to:pe+W.nodeSize}),!1});for(const W of qe.reverse())De.delete(W.from,W.to);qe.length>0&&me.view.dispatch(De)}s(!1);return}if(H==="link"){const me=ge.current||t.current;if(me){const Ee=[];me.state.doc.descendants(De=>{var $e;($e=De.marks)==null||$e.forEach(qe=>{var W,pe;if(qe.type.name==="link"&&((pe=(W=qe.attrs)==null?void 0:W.href)!=null&&pe.startsWith("doc:"))){const xe=FB(qe.attrs.href);xe&&!Ee.includes(xe)&&Ee.push(xe)}})}),_(Ee)}fetch("/api/documents").then(Ee=>Ee.json()).then(Ee=>{Array.isArray(Ee)&&C(Ee.map(De=>({filename:De.filename,title:De.title,docId:De.docId}))),R(!1),B(""),k(!0)}).catch(()=>{});return}if(H==="unlink"){const me=ge.current||t.current;me&&me.chain().focus().unsetLink().run(),s(!1);return}if(H==="see-connections"){fetch("/api/documents").then(me=>me.json()).then(me=>{Array.isArray(me)&&C(me.map(Ee=>({filename:Ee.filename,title:Ee.title,docId:Ee.docId})))}).catch(()=>{}),L(!0);return}},[nt,t]),Ke=S.useCallback(()=>{f.trim()&&(y.startsWith("img:")?Le(f.trim()):nt(y,f.trim()),h(""),b(""))},[nt,Le,y,f]),Et=S.useCallback(()=>{if(!n)return;if(K){fetch("/api/marks",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:n,id:K.id,note:Q.trim()})}).then(()=>{s(!1),$(!1),G(""),X(null)}).catch(De=>{console.error("[ContextMenu] Agent mark edit failed:",De)});return}const ie=ge.current||t.current,H=ee.current;if(!ie||!H)return;const{from:q,to:de,nodeIds:me}=H;if(q===de||me.length===0)return;const Ee=ie.state.doc.textBetween(q,de,`
205
+ Run: npm update -g openwriter`,children:["v",I.latestVersion]})]}),u.jsxs("div",{className:"titlebar-right",children:[h&&u.jsx("button",{className:`titlebar-nav-btn${m?" titlebar-nav-btn--active":""}`,onClick:h,title:"Toggle format toolbar",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M4 20h16"}),u.jsx("path",{d:"m6 16 6-12 6 12"}),u.jsx("path",{d:"M8 12h8"})]})}),u.jsx(JB,{}),u.jsx(i5,{}),u.jsx(qB,{}),u.jsx(QB,{}),u.jsx(e5,{}),u.jsxs("div",{className:"sync-btn-group",ref:R,children:[u.jsxs("button",{className:`titlebar-btn sync-btn-state sync-${n.state}`,onClick:r,disabled:n.state==="syncing",title:n.lastSyncTime?`Last synced: ${new Date(n.lastSyncTime).toLocaleString()}`:"Sync to GitHub",children:[n.state==="unconfigured"&&u.jsxs(u.Fragment,{children:[u.jsx(o5,{})," Sync"]}),n.state==="synced"&&u.jsxs(u.Fragment,{children:[u.jsx(a5,{})," Synced"]}),n.state==="pending"&&u.jsxs(u.Fragment,{children:[u.jsx(l5,{})," Sync",n.pendingFiles?` (${n.pendingFiles})`:""]}),n.state==="syncing"&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"sync-btn-spinner"})," Syncing..."]}),n.state==="error"&&u.jsxs(u.Fragment,{children:[u.jsx(c5,{})," Retry"]})]}),n.state==="pending"&&n.pendingFiles&&n.pendingFiles>0&&u.jsx("button",{className:"sync-details-btn",onClick:$,title:"View pending changes",children:u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:u.jsx("path",{d:k?"M3 7.5L6 4.5L9 7.5":"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),k&&u.jsxs("div",{className:"sync-pending-dropdown",children:[u.jsx("div",{className:"sync-pending-header",children:"Changes to push"}),_?u.jsx("div",{className:"sync-pending-loading",children:"Loading..."}):C.length===0?u.jsx("div",{className:"sync-pending-loading",children:"No changes"}):u.jsx("div",{className:"sync-pending-list",children:C.map((Q,G)=>u.jsxs("div",{className:`sync-pending-item sync-file-${Q.status}`,children:[u.jsx("span",{className:"sync-file-badge",children:Q.status[0].toUpperCase()}),u.jsx("span",{className:"sync-file-name",children:Q.file})]},G))})]})]})]})]})}function Cn(t,e){let n=null;return t.state.doc.descendants((r,s)=>{var i;return((i=r.attrs)==null?void 0:i.id)===e?(n={node:r,pos:s},!1):!0}),n}function zd(t,e){const n=[];return t.state.doc.descendants((r,s)=>{var i;return((i=r.attrs)==null?void 0:i.pendingGroupId)===e&&n.push({nodeId:r.attrs.id,pos:s,node:r}),!0}),n}function Vo(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,"").slice(0,8):Math.random().toString(16).slice(2,10)}function bd(t){return t?Array.isArray(t)?t.map(bd).join(""):t.text?t.text:t.content&&Array.isArray(t.content)?t.content.map(e=>bd(e)).join(""):"":""}const d5=new Set(["paragraph","heading","codeBlock","horizontalRule","table","image"]);function xd(t,e){for(const n of t)n.type&&d5.has(n.type)?n.attrs={...n.attrs,pendingStatus:e}:n.content&&xd(n.content,e)}function Pg(t,e,n,r){const s=Array.isArray(n)?n:[n],i=(r==null?void 0:r.autoAccept)===!0;if(e.nodeId&&!e.afterNodeId&&!e.beforeNodeId){const m=Cn(t,e.nodeId);if(!m)return{success:!1,error:`Node ${e.nodeId} not found`};const g=s.map((y,b)=>{var x;return{...y,attrs:{...y.attrs,id:((x=y.attrs)==null?void 0:x.id)||(b===0?e.nodeId:Vo())}}});i||xd(g,"insert");try{return t.chain().deleteRange({from:m.pos,to:m.pos+m.node.nodeSize}).insertContentAt(m.pos,g).run(),{success:!0,nodeId:e.nodeId}}catch(y){return{success:!1,error:`Failed to replace empty node: ${y}`}}}if(!e.afterNodeId&&!e.beforeNodeId)return{success:!1,error:"Insert requires afterNodeId, beforeNodeId, or nodeId"};const o=e.afterNodeId||e.beforeNodeId,l=!!e.afterNodeId,d=Cn(t,o);if(!d)return{success:!1,error:`Anchor node ${o} not found`};if(!i){const m=bd(n),g=l?d.pos+d.node.nodeSize:0,y=l?d.pos+d.node.nodeSize+5e3:d.pos;let b=null;if(t.state.doc.nodesBetween(g,Math.min(y,t.state.doc.content.size),x=>{var k,E;return((k=x.attrs)==null?void 0:k.pendingStatus)==="insert"&&((E=x.attrs)!=null&&E.id)&&(x.textContent||"")===m?(b=x.attrs.id,!1):!0}),b)return{success:!0,nodeId:b}}const f=s.map(m=>{var g;return{...m,attrs:{...m.attrs,id:((g=m.attrs)==null?void 0:g.id)||Vo()}}});i||xd(f,"insert");const h=l?d.pos+d.node.nodeSize:d.pos;try{return t.chain().insertContentAt(h,f).run(),{success:!0,nodeId:f[0].attrs.id}}catch(m){return{success:!1,error:`Failed to insert content: ${m}`}}}function Wv(t,e,n,r,s){var k,E,C,O,_,T;const i=Cn(t,e);if(!i)return{success:!1,error:`Node ${e} not found`};const{node:o,pos:l}=i,d=Array.isArray(n)?n:[n],f=(s==null?void 0:s.autoAccept)===!0,m=!((k=o.attrs)!=null&&k.pendingOriginalContent)?o.toJSON():o.attrs.pendingOriginalContent,y=((E=d[0])==null?void 0:E.type)==="listItem"&&((T=(_=(O=(C=d[0])==null?void 0:C.content)==null?void 0:O[0])==null?void 0:_.attrs)==null?void 0:T.pendingStatus)!=null?{...d[0],attrs:{...d[0].attrs,id:e}}:{...d[0],attrs:f?{...d[0].attrs,id:e}:{...d[0].attrs,id:e,pendingStatus:"rewrite",pendingOriginalContent:m,...r?{pendingSelectionFrom:r.selectionFrom,pendingSelectionTo:r.selectionTo,pendingOriginalFrom:r.originalFrom,pendingOriginalTo:r.originalTo}:{}}},b=d.slice(1).map(R=>{var I;return{...R,attrs:{...R.attrs,id:((I=R.attrs)==null?void 0:I.id)||Vo()}}});f||xd(b,"insert");const x=[y,...b];try{return t.chain().command(({tr:R})=>{const I=x.map(B=>t.state.schema.nodeFromJSON(B));return R.replaceWith(l,l+o.nodeSize,I),!0}).run(),{success:!0,nodeId:e}}catch(R){return{success:!1,error:`Failed to rewrite: ${R}`}}}function f5(t,e,n){if(e.length===0)return{success:!1,error:"Range rewrite requires original IDs"};if(!n||n.length===0)return{success:!1,error:"Range rewrite requires new content (received empty)"};if(n.map(m=>bd(m)).join("").trim().length===0)return{success:!1,error:"Range rewrite content is empty (no text) — aborting"};const s=Cn(t,e[0]),i=Cn(t,e[e.length-1]);if(!s||!i)return{success:!1,error:"Could not find original nodes for range rewrite"};const o=[];for(const m of e){const g=Cn(t,m);g&&o.push(g.node.toJSON())}const l=s.pos,d=i.pos+i.node.nodeSize,f=Vo()+Vo(),h=n.map((m,g)=>{var y;return{...m,attrs:{...m.attrs,id:((y=m.attrs)==null?void 0:y.id)||Vo(),pendingStatus:"rewrite",pendingGroupId:f,...g===0?{pendingOriginalContent:o}:{}}}});try{return t.chain().deleteRange({from:l,to:d}).insertContentAt(l,h).run(),{success:!0,nodeId:h[0].attrs.id}}catch(m){return{success:!1,error:`Failed to apply range rewrite: ${m}`}}}function G_(t,e,n){var l;const r=Cn(t,e);if(!r)return{success:!1,error:`Node ${e} not found`};const{node:s,pos:i}=r,o=(n==null?void 0:n.autoAccept)===!0;if(!o&&((l=s.attrs)==null?void 0:l.pendingStatus)==="delete")return{success:!0,nodeId:e};try{return o?t.chain().deleteRange({from:i,to:i+s.nodeSize}).run():t.chain().command(({tr:d})=>(d.setNodeMarkup(i,void 0,{...s.attrs,pendingStatus:"delete"}),!0)).run(),{success:!0,nodeId:e}}catch(d){return{success:!1,error:`Failed to ${o?"delete":"mark for deletion"}: ${d}`}}}function h5(t,e){const n=e.autoAccept?{autoAccept:!0}:void 0;if(e.operation==="rewrite"&&e.nodeId&&e.content){const r=Wv(t,e.nodeId,e.content,null,n);return{success:r.success,error:r.error}}if(e.operation==="insert"&&e.content){let r=null;if(e.nodeId&&!e.afterNodeId?r={nodeId:e.nodeId}:e.afterNodeId&&(r={afterNodeId:e.afterNodeId}),!r)return{success:!1,error:"Insert requires afterNodeId or nodeId"};const s=Pg(t,r,e.content,n);return{success:s.success,error:s.error}}if(e.operation==="delete"&&e.nodeId){const r=G_(t,e.nodeId,n);return{success:r.success,error:r.error}}return{success:!1,error:`Invalid operation: ${e.operation}`}}function yp(t,e){if(e.length===0)return;if(e.length===1){h5(t,e[0]);return}const n=t.state.schema;t.chain().command(({tr:r})=>{var s;for(const i of e)try{const o=i.autoAccept===!0;if(i.operation==="rewrite"&&i.nodeId&&i.content){const l=Ua(r.doc,i.nodeId);if(!l)continue;const f=(Array.isArray(i.content)?i.content:[i.content]).map(h=>n.nodeFromJSON(h));r.replaceWith(l.pos,l.pos+l.node.nodeSize,f)}else if(i.operation==="insert"&&i.content){const d=(Array.isArray(i.content)?i.content:[i.content]).map(f=>n.nodeFromJSON(f));if(!o){const f=d.map(h=>h.textContent||"").join("");if(f&&i.afterNodeId){const h=Ua(r.doc,i.afterNodeId);if(h){const m=h.pos+h.node.nodeSize,g=Math.min(m+5e3,r.doc.content.size);let y=!1;if(r.doc.nodesBetween(m,g,b=>{var x;return y?!1:((x=b.attrs)==null?void 0:x.pendingStatus)==="insert"&&(b.textContent||"")===f?(y=!0,!1):!0}),y)continue}}}if(i.nodeId&&!i.afterNodeId){const f=Ua(r.doc,i.nodeId);if(!f)continue;r.replaceWith(f.pos,f.pos+f.node.nodeSize,d)}else if(i.afterNodeId){const f=Ua(r.doc,i.afterNodeId);if(!f)continue;const h=f.pos+f.node.nodeSize;r.insert(h,ye.fromArray(d))}}else if(i.operation==="delete"&&i.nodeId){const l=Ua(r.doc,i.nodeId);if(!l)continue;if(o)r.delete(l.pos,l.pos+l.node.nodeSize);else{if(((s=l.node.attrs)==null?void 0:s.pendingStatus)==="delete")continue;r.setNodeMarkup(l.pos,void 0,{...l.node.attrs,pendingStatus:"delete"})}}}catch{continue}return!0}).run()}function Ua(t,e){let n=null;return t.descendants((r,s)=>{var i;return((i=r.attrs)==null?void 0:i.id)===e?(n={node:r,pos:s},!1):!0}),n}function p5(t,e,n,r){const s=[];if(r==="delete"){for(const o of n)s.push(G_(t,o));return s}if(r==="insert"){const o=n[n.length-1];return o&&e.length>0&&s.push(Pg(t,{nodeId:o},e)),s}if(n.length>1){const o=f5(t,n,e);return s.push(o),s}const i=Wv(t,n[0],e[0]);if(s.push(i),e.length>1){const o=e.slice(1);s.push(Pg(t,{afterNodeId:n[0]},o))}return s}const Q1="[[START_SELECTION]]",Z1="[[END_SELECTION]]";function m5(t){if(!(t!=null&&t.content)||!Array.isArray(t.content))return 0;let e=0;for(const n of t.content)n.type==="text"&&typeof n.text=="string"?e+=n.text.length:n.type==="hardBreak"&&(e+=1);return e}function uu(t,e,n){if(!(t!=null&&t.content)||!Array.isArray(t.content))return;const r=m5(t);let s=Math.max(0,Math.min(e,r));for(let i=0;i<t.content.length;i++){const o=t.content[i];if(o.type==="text"&&typeof o.text=="string"){if(s<=o.text.length){const l=Math.max(0,Math.min(o.text.length,s));o.text=o.text.slice(0,l)+n+o.text.slice(l);return}s-=o.text.length;continue}if(o.type==="hardBreak"){if(s===0){t.content.splice(i+1,0,{type:"text",text:n});return}s-=1;continue}if(s===0){t.content.splice(i,0,{type:"text",text:n});return}}t.content.push({type:"text",text:n})}function g5(t,e,n){const r=JSON.parse(JSON.stringify(t));return r.length===0?r:r.length===1?(uu(r[0],n,Z1),uu(r[0],e,Q1),r):(uu(r[0],e,Q1),uu(r[r.length-1],n,Z1),r)}function v5(t){const e=r=>r.replace(/\[\[(START|END)_SELECTION]]/g,""),n=r=>{r.type==="text"&&typeof r.text=="string"&&(r.text=e(r.text)),r.content&&Array.isArray(r.content)&&r.content.forEach(n)};Array.isArray(t)?t.forEach(n):n(t)}function ew(t,e){return t.docId&&e.includes(t.docId)?!0:e.includes(t.filename)}const y5=[{action:"agent-mark",label:"Agent Mark",shortcut:"M",condition:"has-selection"},{action:"delete",label:"Delete",shortcut:"D"}];function b5({editorRef:t,allEditors:e,documentId:n}){const[r,s]=S.useState(!1),[i,o]=S.useState({x:0,y:0}),[l,d]=S.useState(!1),[f,h]=S.useState(""),[m,g]=S.useState(!1),[y,b]=S.useState(""),[x,k]=S.useState(!1),[E,C]=S.useState([]),[O,_]=S.useState([]),[T,R]=S.useState(!1),[I,B]=S.useState(""),[P,D]=S.useState([]),[V,$]=S.useState(!1),[Q,G]=S.useState(""),[K,X]=S.useState(null),[re,J]=S.useState(null),[oe,U]=S.useState(null),[A,L]=S.useState(!1),[te,se]=S.useState(null),be=S.useRef(null),ee=S.useRef(null),ge=S.useRef(null),fe=S.useCallback(ie=>{if(e&&e.length>0){for(const q of e)if(q.view.dom.contains(ie))return q}const H=t.current;return H&&H.view.dom.contains(ie)?H:null},[e,t]);S.useLayoutEffect(()=>{const ie=be.current;if(!ie||!r)return;const H=ie.getBoundingClientRect(),q=8;let{x:de,y:me}=i;me+H.height+q>window.innerHeight&&(me=i.y-H.height),de+H.width+q>window.innerWidth&&(de=i.x-H.width),me<q&&(me=q),de<q&&(de=q),(de!==i.x||me!==i.y)&&o({x:de,y:me})},[r,i]);const Te=S.useCallback(()=>{fetch("/api/plugins").then(ie=>ie.json()).then(ie=>{const H=[];for(const q of ie.plugins||[]){const de=q.displayName||void 0;for(const me of q.contextMenuItems||[])H.push({...me,pluginDisplayName:de})}D(H)}).catch(()=>{})},[]);S.useEffect(()=>{Te()},[Te]),S.useEffect(()=>{const ie=()=>Te();return window.addEventListener("ow-plugins-changed",ie),()=>window.removeEventListener("ow-plugins-changed",ie)},[Te]),S.useEffect(()=>{const ie=H=>{be.current&&!be.current.contains(H.target)&&(s(!1),g(!1),k(!1),$(!1),G(""),X(null),J(null))};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[]);const Xe=S.useCallback(()=>{const ie=ge.current||t.current;return ie?ie.isActive("link"):!1},[t]),tt=S.useCallback(()=>{const ie=ge.current||t.current,H=ee.current;if(!ie||!H)return!1;const{from:q,to:de}=H;let me=!1;return ie.state.doc.nodesBetween(q,de,Ee=>{var De;return(De=Ee.attrs)!=null&&De.pendingStatus&&(me=!0),!me}),me},[t]),st=S.useCallback(()=>{const ie=ge.current||t.current,H=ee.current,q=(H==null?void 0:H.from)??0,de=(H==null?void 0:H.to)??0,me=q!==de,Ee=(()=>{if(!ie)return!1;try{return ie.state.doc.resolve(q).parent.content.size===0}catch{return!1}})(),De=tt(),$e=[];for(const qe of P)qe.condition==="has-selection"&&!me||qe.condition==="empty-node"&&!Ee||$e.push({action:qe.action,label:qe.label,shortcut:qe.shortcut,isPlugin:!0,promptForInput:qe.promptForInput,pluginDisplayName:qe.pluginDisplayName});for(const qe of y5)qe.condition==="has-selection"&&(!me||De)||$e.push(qe);return me&&$e.push({action:"link",label:"Link to doc",shortcut:"L"}),Xe()&&$e.push({action:"unlink",label:"Unlink"}),oe&&oe.entries.length>0&&$e.unshift({action:"see-connections",label:`See connections (${oe.entries.length})`}),$e},[t,Xe,P,tt,oe]);S.useEffect(()=>{const ie=q=>{var qe;if(q.button!==2)return;const de=fe(q.target);if(!de)return;ge.current=de;const{from:me,to:Ee}=de.state.selection,De=[],$e=[];if(me!==Ee&&de.state.doc.nodesBetween(me,Ee,W=>{W.isBlock&&W.type.name!=="doc"&&(De.push(W.toJSON()),W.attrs.id&&$e.push(W.attrs.id))}),De.length===0){const{$from:W}=de.state.selection,pe=W.parent;pe&&pe.type.name!=="doc"&&(De.push(pe.toJSON()),(qe=pe.attrs)!=null&&qe.id&&$e.push(pe.attrs.id))}ee.current={from:me,to:Ee,nodes:De,nodeIds:$e}},H=q=>{var qe,W,pe,xe;if(!fe(q.target)||q.shiftKey)return;const me=(W=(qe=q.target)==null?void 0:qe.closest)==null?void 0:W.call(qe,"[data-mark-id]"),Ee=(me==null?void 0:me.getAttribute("data-mark-id"))||null,De=(xe=(pe=q.target)==null?void 0:pe.closest)==null?void 0:xe.call(pe,".linked-paragraph[data-backlinks-node]"),$e=(De==null?void 0:De.getAttribute("data-backlinks-node"))||null;if(q.preventDefault(),o({x:q.clientX,y:q.clientY}),s(!0),g(!1),k(!1),L(!1),$(!1),G(""),X(null),Ee){const Ye=AB().find(it=>it.id===Ee);if(Ye){J({id:Ye.id,text:Ye.text,note:Ye.note}),U(null);return}}if(J(null),$e){const Ye=PB($e);U(Ye.length>0?{nodeId:$e,entries:Ye}:null)}else U(null)};return document.addEventListener("mousedown",ie,!0),document.addEventListener("contextmenu",H),()=>{document.removeEventListener("mousedown",ie,!0),document.removeEventListener("contextmenu",H)}},[fe]);const nt=S.useCallback(async(ie,H)=>{var xe,Ye,it,ot,Re;const q=ge.current||t.current;if(!q)return;const de=ee.current;if(!de||de.nodes.length===0){console.warn("[ContextMenu] No captured selection for action:",ie);return}let{nodes:me,nodeIds:Ee}=de;const{from:De,to:$e}=de;d(!0),s(!1),g(!1);const qe=`ctx-${Date.now()}`,W=ie.includes(":")?ie.split(":").slice(1).join(":"):ie,pe=["insert","fill","fill-sentence"].includes(W);if(pe)q.commands.showInsertionLoading(qe,De);else{const vt=q.state.doc.resolve(De),ht=q.state.doc.resolve($e),zt=vt.sameParent(ht)&&De!==$e;q.commands.applyLoadingEffect(qe,De,$e,zt?"selection":"paragraph")}try{const vt=[],ht=[],zt=new Set(Ee);let Ut=!1;const Jt=q.state.doc;for(let We=0;We<Jt.childCount;We++){const Mt=Jt.child(We),ut=(xe=Mt.attrs)==null?void 0:xe.id;if(ut&&zt.has(ut))Ut=!0;else if(Ut){const yn=Mt.textContent.trim();yn&&ht.push(yn)}else{const yn=Mt.textContent.trim();yn&&vt.push(yn)}}let M=me,ne=!1,ue=0,Me=0;const ct=De!==$e?q.state.doc.resolve(De):null,gt=De!==$e?q.state.doc.resolve($e):null;if((ct&&gt?ct.sameParent(gt):!1)&&ct&&me.length===1){const We=ct.start(ct.depth);ue=De-We,Me=$e-We;const Mt=((it=(Ye=me[0])==null?void 0:Ye.content)==null?void 0:it.reduce((ut,yn)=>{var qr;return ut+(((qr=yn.text)==null?void 0:qr.length)||(yn.type==="hardBreak"?1:0))},0))??0;(ue>0||Me<Mt)&&(M=g5(me,ue,Me),ne=!0)}const z=q.state.doc.textContent,he={nodes:M,action:W,nodeIds:Ee,contextBefore:vt.slice(-3),contextAfter:ht.slice(0,3),fullDocument:z,documentId:n,debug:!0};ne&&(he.hasSelectionMarkers=!0),H&&(he.instruction=H);const Ie=await fetch(`${window.location.origin}/api/voice/apply-editor`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(he)});if(!Ie.ok){const We=await Ie.json().catch(()=>({}));console.error("[ContextMenu] API error:",Ie.status,We);return}const He=await Ie.json();if(He.success&&He.nodes){let We=He.nodes;if(We.length===1&&Array.isArray(We[0])&&(We=We[0]),v5(We),ne&&We.length===1&&Ee.length===1){const Mt=yi=>(yi==null?void 0:yi.reduce((Mr,bi)=>{var Ts;return Mr+(((Ts=bi.text)==null?void 0:Ts.length)||(bi.type==="hardBreak"?1:0))},0))??0,ut=Mt((ot=me[0])==null?void 0:ot.content),yn=Mt((Re=We[0])==null?void 0:Re.content),qr={selectionFrom:ue,selectionTo:yn-(ut-Me),originalFrom:ue,originalTo:Me};Wv(q,Ee[0],We[0],qr)}else p5(q,We,Ee,W)}else console.warn("[ContextMenu] Unexpected response:",He)}catch(vt){console.error("[ContextMenu] Plugin action failed:",vt)}finally{pe?q.commands.removeInsertionLoading(qe):q.commands.removeLoadingEffect(qe),d(!1)}},[t]),Le=S.useCallback(async ie=>{const H=ge.current||t.current;if(!H)return;const{$from:q}=H.state.selection,de=q.before(q.depth),me=q.after(q.depth),Ee=q.parent.content.size===0;d(!0),s(!1),g(!1),Ee?H.chain().focus().deleteRange({from:de,to:me}).insertContentAt(de,{type:"imageLoading"}).run():H.chain().focus().insertContentAt(me,{type:"imageLoading"}).run();let De=-1;H.state.doc.descendants(($e,qe)=>{if($e.type.name==="imageLoading"&&De===-1)return De=qe,$e.nodeSize,!1});try{const $e=await fetch("/api/image-gen/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:ie})}),qe=await $e.json().catch(()=>({success:!1,error:`Generation failed (${$e.status})`}));if(qe.success&&qe.src){let W=-1,pe=0;if(H.state.doc.descendants((xe,Ye)=>{if(xe.type.name==="imageLoading"&&W===-1)return W=Ye,pe=xe.nodeSize,!1}),W>=0){const{tr:xe}=H.state;xe.replaceWith(W,W+pe,H.schema.nodes.image.create({src:qe.src,alt:ie})),H.view.dispatch(xe)}}else{console.error("[ContextMenu] Image generation failed:",qe.error);let W=-1,pe=0;if(H.state.doc.descendants((xe,Ye)=>{if(xe.type.name==="imageLoading"&&W===-1)return W=Ye,pe=xe.nodeSize,!1}),W>=0){const{tr:xe}=H.state;xe.delete(W,W+pe),H.view.dispatch(xe)}}}catch($e){console.error("[ContextMenu] Image generation failed:",$e);let qe=-1,W=0;if(H.state.doc.descendants((pe,xe)=>{if(pe.type.name==="imageLoading"&&qe===-1)return qe=xe,W=pe.nodeSize,!1}),qe>=0){const{tr:pe}=H.state;pe.delete(qe,qe+W),H.view.dispatch(pe)}}finally{d(!1)}},[t]),yt=S.useCallback(ie=>{const{action:H,isPlugin:q,promptForInput:de}=ie;if(q&&de){b(H),g(!0);return}if(q){if(H.startsWith("img:"))return;nt(H);return}if(H==="agent-mark"){$(!0);return}if(H==="delete"){const me=ge.current||t.current,Ee=ee.current;if(me&&Ee&&Ee.nodeIds.length>0){const{tr:De}=me.state,$e=new Set(Ee.nodeIds),qe=[];me.state.doc.descendants((W,pe)=>{var xe;if((xe=W.attrs)!=null&&xe.id&&$e.has(W.attrs.id))return qe.push({from:pe,to:pe+W.nodeSize}),!1});for(const W of qe.reverse())De.delete(W.from,W.to);qe.length>0&&me.view.dispatch(De)}s(!1);return}if(H==="link"){const me=ge.current||t.current;if(me){const Ee=[];me.state.doc.descendants(De=>{var $e;($e=De.marks)==null||$e.forEach(qe=>{var W,pe;if(qe.type.name==="link"&&((pe=(W=qe.attrs)==null?void 0:W.href)!=null&&pe.startsWith("doc:"))){const xe=FB(qe.attrs.href);xe&&!Ee.includes(xe)&&Ee.push(xe)}})}),_(Ee)}fetch("/api/documents").then(Ee=>Ee.json()).then(Ee=>{Array.isArray(Ee)&&C(Ee.map(De=>({filename:De.filename,title:De.title,docId:De.docId}))),R(!1),B(""),k(!0)}).catch(()=>{});return}if(H==="unlink"){const me=ge.current||t.current;me&&me.chain().focus().unsetLink().run(),s(!1);return}if(H==="see-connections"){fetch("/api/documents").then(me=>me.json()).then(me=>{Array.isArray(me)&&C(me.map(Ee=>({filename:Ee.filename,title:Ee.title,docId:Ee.docId})))}).catch(()=>{}),L(!0);return}},[nt,t]),Ke=S.useCallback(()=>{f.trim()&&(y.startsWith("img:")?Le(f.trim()):nt(y,f.trim()),h(""),b(""))},[nt,Le,y,f]),Et=S.useCallback(()=>{if(!n)return;if(K){fetch("/api/marks",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:n,id:K.id,note:Q.trim()})}).then(()=>{s(!1),$(!1),G(""),X(null)}).catch(De=>{console.error("[ContextMenu] Agent mark edit failed:",De)});return}const ie=ge.current||t.current,H=ee.current;if(!ie||!H)return;const{from:q,to:de,nodeIds:me}=H;if(q===de||me.length===0)return;const Ee=ie.state.doc.textBetween(q,de,`
206
206
  `);Ee.trim()&&fetch("/api/marks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:n,text:Ee,note:Q.trim(),nodeId:me[me.length-1],nodeIds:me})}).then(()=>{s(!1),$(!1),G("")}).catch(De=>{console.error("[ContextMenu] Agent mark failed:",De)})},[t,n,Q,K]),je=S.useCallback(()=>{re&&(X({id:re.id,text:re.text}),G(re.note),$(!0),J(null))},[re]),Je=S.useCallback(()=>{re&&fetch("/api/marks",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[re.id]})}).then(()=>{s(!1),J(null)}).catch(ie=>{console.error("[ContextMenu] Agent mark resolve failed:",ie)})},[re]),Fe=S.useCallback((ie,H)=>{const q=ge.current||t.current;if(q){const de=ie.docId?vp({docId:ie.docId,nodeId:H==null?void 0:H.nodeId,quote:H==null?void 0:H.quote}):vp({filename:ie.filename});q.chain().focus().setLink({href:de}).run()}fetch("/api/auto-tag-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetFile:ie.filename})}).catch(()=>{}),s(!1),k(!1),se(null)},[t]),Nt=S.useCallback(ie=>{if(!ie.docId){Fe(ie);return}se({docId:ie.docId,filename:ie.filename,title:ie.title,paragraphs:[],loading:!0}),fetch(`/api/documents/by-doc-id/${ie.docId}/paragraphs`).then(H=>H.json()).then(H=>{se(q=>q&&q.docId===ie.docId?{...q,paragraphs:Array.isArray(H.paragraphs)?H.paragraphs:[],loading:!1}:q)}).catch(()=>{se(H=>H&&H.docId===ie.docId?{...H,paragraphs:[],loading:!1}:H)})},[Fe]),qt=S.useCallback(()=>{const ie=I.trim();if(!ie)return;const H=ge.current||t.current;H&&(fetch("/api/create-link-doc",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:ie})}).then(q=>q.json()).then(q=>{if(q.filename){const de=vp(q.docId?{docId:q.docId}:{filename:q.filename});H.chain().focus().setLink({href:de}).run()}}).catch(()=>{}),s(!1),k(!1),R(!1),B(""))},[t,I]);return r?u.jsx("div",{ref:be,className:"context-menu",style:{left:i.x,top:i.y},children:l?u.jsx("div",{className:"context-menu-loading",children:"Applying..."}):V?u.jsxs("div",{className:"context-menu-mark-editor",children:[(()=>{const ie=(K==null?void 0:K.text)??(()=>{const H=ge.current||t.current,q=ee.current;return!H||!q||q.from===q.to?"":H.state.doc.textBetween(q.from,q.to,`
207
- `)})();return ie?u.jsx("div",{className:"context-menu-mark-quote",children:ie}):null})(),u.jsx("textarea",{autoFocus:!0,className:"context-menu-mark-textarea",value:Q,onChange:ie=>G(ie.target.value),onKeyDown:ie=>{ie.key==="Enter"&&(ie.metaKey||ie.ctrlKey)&&(ie.preventDefault(),Et()),ie.key==="Escape"&&(s(!1),$(!1),G(""),X(null))},placeholder:"Note for agent (optional)...",rows:4}),u.jsxs("div",{className:"context-menu-mark-actions",children:[u.jsx("span",{className:"context-menu-mark-hint",children:"⌘↵ to save · Esc to cancel"}),u.jsx("button",{onClick:Et,children:K?"Save":"Mark"})]})]}):re?u.jsxs(u.Fragment,{children:[u.jsx("button",{className:"context-menu-item",onClick:je,children:u.jsx("span",{children:"Edit mark"})}),u.jsx("button",{className:"context-menu-item",onClick:Je,children:u.jsx("span",{children:"Resolve mark"})})]}):m?u.jsxs("div",{className:"context-menu-custom",children:[u.jsx("input",{autoFocus:!0,value:f,onChange:ie=>h(ie.target.value),onKeyDown:ie=>{ie.key==="Enter"&&Ke(),ie.key==="Escape"&&s(!1)},placeholder:"Custom instruction..."}),u.jsx("button",{onClick:Ke,children:"Apply"})]}):te?u.jsxs("div",{className:"context-menu-link-picker",children:[u.jsxs("div",{className:"context-menu-link-header",children:[u.jsx("button",{className:"context-menu-link-back",onClick:()=>se(null),title:"Back to doc list",children:"←"}),u.jsxs("span",{children:['Pick paragraph in "',te.title,'"']})]}),u.jsx("button",{className:"context-menu-item context-menu-new-link",onClick:()=>Fe({filename:te.filename,docId:te.docId}),children:u.jsx("span",{children:"Link whole doc"})}),u.jsx("div",{className:"context-menu-link-list",children:te.loading?u.jsx("div",{className:"context-menu-loading",children:"Loading…"}):te.paragraphs.length===0?u.jsx("div",{className:"context-menu-loading",children:"No paragraphs"}):te.paragraphs.map(ie=>{const H=ie.preview.replace(/…$/,"").slice(0,50),q=ie.type==="heading"?Math.max(0,(ie.level||1)-1)*12:12;return u.jsx("button",{className:`context-menu-item context-menu-paragraph-row context-menu-paragraph-row--${ie.type}`,style:{paddingLeft:8+q},onClick:()=>Fe({filename:te.filename,docId:te.docId},{nodeId:ie.nodeId,quote:H}),children:u.jsx("span",{children:ie.preview})},ie.nodeId)})})]}):A&&oe?u.jsxs("div",{className:"context-menu-link-picker",children:[u.jsxs("div",{className:"context-menu-link-header",children:["Linked from ",oe.entries.length," ",oe.entries.length===1?"place":"places"]}),u.jsx("div",{className:"context-menu-link-list",children:oe.entries.map((ie,H)=>{const q=E.find(me=>me.docId===ie.from_doc),de=(q==null?void 0:q.title)||ie.from_doc;return u.jsxs("button",{className:"context-menu-item",onClick:()=>{window.dispatchEvent(new CustomEvent("ow-navigate-to-link",{detail:{docId:ie.from_doc,nodeId:ie.from_node,filename:null,quote:null}})),s(!1),L(!1)},children:[u.jsx("span",{children:de}),u.jsxs("span",{className:"context-menu-shortcut",children:['"',ie.text,'"']})]},`${ie.from_doc}-${ie.from_node}-${H}`)})})]}):x?u.jsxs("div",{className:"context-menu-link-picker",children:[u.jsx("div",{className:"context-menu-link-header",children:"Link to document"}),T?u.jsxs("div",{className:"context-menu-custom",children:[u.jsx("input",{autoFocus:!0,value:I,onChange:ie=>B(ie.target.value),onKeyDown:ie=>{ie.key==="Enter"&&qt(),ie.key==="Escape"&&R(!1)},placeholder:"New document title..."}),u.jsx("button",{onClick:qt,children:"Create"})]}):u.jsx("button",{className:"context-menu-item context-menu-new-link",onClick:()=>R(!0),children:u.jsx("span",{children:"+ New link doc"})}),u.jsxs("div",{className:"context-menu-link-list",children:[O.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-section-header",children:"Linked in this doc"}),E.filter(ie=>ew(ie,O)).map(ie=>u.jsxs("div",{className:"context-menu-link-row",children:[u.jsx("button",{className:"context-menu-item context-menu-link-row__main",onClick:()=>Fe(ie),children:u.jsx("span",{children:ie.title})}),ie.docId&&u.jsx("button",{className:"context-menu-link-row__drill",title:"Pick a paragraph in this doc",onClick:()=>Nt(ie),children:"▸"})]},`linked-${ie.filename}`))]}),u.jsx("div",{className:"context-menu-section-header",children:"All documents"}),E.filter(ie=>!ew(ie,O)).map(ie=>u.jsxs("div",{className:"context-menu-link-row",children:[u.jsx("button",{className:"context-menu-item context-menu-link-row__main",onClick:()=>Fe(ie),children:u.jsx("span",{children:ie.title})}),ie.docId&&u.jsx("button",{className:"context-menu-link-row__drill",title:"Pick a paragraph in this doc",onClick:()=>Nt(ie),children:"▸"})]},ie.filename)),E.length===0&&u.jsx("div",{className:"context-menu-loading",children:"No documents"})]})]}):(()=>{const ie=st();let H;return ie.map((q,de)=>{const me=q.isPlugin&&q.pluginDisplayName&&q.pluginDisplayName!==H,Ee=H!==void 0;q.isPlugin?H=q.pluginDisplayName:H=void 0;const De=!q.isPlugin&&Ee;return u.jsxs("span",{children:[me&&u.jsx("div",{className:"context-menu-section-header",children:q.pluginDisplayName}),De&&u.jsx("div",{className:"context-menu-divider"}),u.jsxs("button",{className:"context-menu-item",onClick:()=>yt(q),children:[u.jsx("span",{children:q.label}),q.shortcut&&u.jsx("span",{className:"context-menu-shortcut",children:q.shortcut})]})]},q.action)})})()}):null}function qv(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 x5(t,e){const n=Cn(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 w5(t,e){const n=Cn(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 k5(t,e){var o;const n=Cn(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=qv(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function S5(t,e){var o;const n=Cn(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=qv(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function E5(t,e){var o,l;const n=Cn(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=qv(t.state.doc,s,s+r.nodeSize);t.chain().deleteRange(d).run()}return!0}function N5(t,e){var i;const n=Cn(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 C5(t,e){const n=zd(t,e);if(n.length===0)return!1;for(const r of[...n].reverse()){const s=Cn(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 _5(t,e){var l;const n=zd(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 J_(t,e){var i,o;const n=Cn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return C5(t,r);switch((o=n.node.attrs)==null?void 0:o.pendingStatus){case"insert":return x5(t,e);case"rewrite":return w5(t,e);case"delete":return k5(t,e);default:return!1}}function Y_(t,e){var i,o;const n=Cn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return _5(t,r);switch((o=n.node.attrs)==null?void 0:o.pendingStatus){case"insert":return S5(t,e);case"rewrite":return E5(t,e);case"delete":return N5(t,e);default:return!1}}function T5(t){const e=X_(t).reverse();for(const n of e)J_(t,n);t.view&&Uv(t.view)}function M5(t){const e=X_(t).reverse();for(const n of e)Y_(t,n);t.view&&Uv(t.view)}function Vv(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 bp(t){const e=[];for(const n of t)n&&!n.isDestroyed&&e.push(...Vv(n));return e}function X_(t){return Vv(t).map(e=>e.nodeId)}function A5(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 Ha(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 j5(t){const[e,n]=S.useState([]),[r,s]=S.useState(0),i=S.useRef(),o=S.useRef(new Set),l=S.useCallback(()=>{const E=t.filter(R=>R&&!R.isDestroyed);if(E.length===0){n([]),o.current=new Set;return}const C=bp(E);n(C);const O=o.current,_=new Set(C.map(R=>R.nodeId));let T=-1;if(O.size>0){for(let R=0;R<C.length;R++)if(!O.has(C[R].nodeId)){T=R;break}}o.current=_,T>=0?(s(T),Ha(C[T].editor,C[T].nodeId)):C.length===0?s(0):s(R=>Math.min(R,C.length-1))},[t]);S.useEffect(()=>{const E=t.filter(_=>_&&!_.isDestroyed);if(E.length===0)return;const C=()=>{clearTimeout(i.current),i.current=setTimeout(l,50)};for(const _ of E)_.on("transaction",C);l();const O=setTimeout(()=>{const _=bp(E.filter(T=>!T.isDestroyed));_.length>0&&Ha(_[0].editor,_[0].nodeId)},150);return()=>{for(const _ of E)_.isDestroyed||_.off("transaction",C);clearTimeout(i.current),clearTimeout(O)}},[t,l]),S.useEffect(()=>{const E=e[r]??null;return U1((E==null?void 0:E.nodeId)??null,(E==null?void 0:E.groupId)??null),E!=null&&E.editor&&!E.editor.isDestroyed&&E.editor.view&&Uv(E.editor.view),()=>{U1(null)}},[r,e]);const d=A5(e),f=e[r]??null,h=S.useCallback(()=>{if(e.length===0)return;const E=(r+1)%e.length;s(E),e[E]&&Ha(e[E].editor,e[E].nodeId)},[e,r]),m=S.useCallback(()=>{if(e.length===0)return;const E=(r-1+e.length)%e.length;s(E),e[E]&&Ha(e[E].editor,e[E].nodeId)},[e,r]),g=S.useCallback(()=>{const E=t.filter(_=>_&&!_.isDestroyed),C=bp(E);if(C.length===0)return;const O=Math.min(r,C.length-1);Ha(C[O].editor,C[O].nodeId)},[t,r]),y=S.useCallback(()=>{f&&(J_(f.editor,f.nodeId),l(),g())},[f,l,g]),b=S.useCallback(()=>{f&&(Y_(f.editor,f.nodeId),l(),g())},[f,l,g]),x=S.useCallback(()=>{const E=t.filter(C=>C&&!C.isDestroyed);for(const C of E)T5(C);l()},[t,l]),k=S.useCallback(()=>{const E=t.filter(C=>C&&!C.isDestroyed);for(const C of E)M5(C);l()},[t,l]);return{pendingNodes:e,counts:d,currentNode:f,currentIndex:r,hasPending:d.total>0,goToNext:h,goToPrevious:m,acceptCurrent:y,rejectCurrent:b,acceptAll:x,rejectAll:k,refresh:l}}const na={strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},O5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",...na})}),R5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M6 3l5 5-5 5",stroke:"currentColor",...na})}),I5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M3 10l5-5 5 5",stroke:"currentColor",...na})}),L5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M3 6l5 5 5-5",stroke:"currentColor",...na})}),tw=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M3 8.5l3.5 3.5L13 5",stroke:"currentColor",...na})}),nw=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor",...na})});function Q_(t,e,n){const r=Cn(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 Z_(t,e,n){const r=zd(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 du(t,e){if(!Fv()||!e)return!1;const n=_B(),r=CB();return r&&n&&Array.isArray(n)?Z_(t,r,n):n&&Q_(t,e,n),Dg(!1),!0}function D5({editors:t,pendingDocs:e,currentFilename:n,onSwitchDocument:r,sendMessage:s,getDocument:i,docVersionRef:o}){const{counts:l,currentNode:d,currentIndex:f,hasPending:h,goToNext:m,goToPrevious:g,acceptCurrent:y,rejectCurrent:b,acceptAll:x,rejectAll:k}=j5(t),[E,C]=S.useState(!1),O=S.useRef(null),_=S.useRef(null),T=e.filenames.length,R=P5(e.filenames,n),I=(d==null?void 0:d.pendingStatus)==="rewrite",B=!!(d!=null&&d.groupId),P=I,D=S.useCallback(()=>{var A,L;const U=d==null?void 0:d.editor;if(!(!U||!d||d.pendingStatus!=="rewrite"))if(E)_.current&&du(_.current,O.current),O.current=null,_.current=null,C(!1);else if(B&&d.groupId){const te=zd(U,d.groupId);if(te.length===0)return;const se=(A=te[0].node.attrs)==null?void 0:A.pendingOriginalContent;if(!se||!Array.isArray(se))return;const be=te.map(fe=>fe.node.toJSON()),ee=se.map((fe,Te)=>({...fe,attrs:{...fe.attrs||{},pendingStatus:"rewrite",pendingGroupId:d.groupId,...Te===0?{pendingOriginalContent:se}:{}}}));if(!Z_(U,d.groupId,ee))return;Dg(!0,d.nodeId,be,d.groupId),O.current=d.nodeId,_.current=U,C(!0)}else{const te=Cn(U,d.nodeId);if(!te)return;const{node:se}=te,be=(L=se.attrs)==null?void 0:L.pendingOriginalContent;if(!be)return;const ee=se.toJSON();if(!Q_(U,d.nodeId,be))return;Dg(!0,d.nodeId,ee),O.current=d.nodeId,_.current=U,C(!0)}},[d,E,B]);S.useEffect(()=>{if(!E)return;const U=O.current,A=_.current;U&&A&&(d==null?void 0:d.nodeId)!==U&&(du(A,U),O.current=null,_.current=null,C(!1))},[d==null?void 0:d.nodeId,E]),S.useEffect(()=>{if(t.length!==0)return()=>{Fv()&&O.current&&_.current&&(du(_.current,O.current),O.current=null,_.current=null)}},[t]);const V=S.useCallback(U=>{if(!n)return;if(!t.some(L=>!L||L.isDestroyed?!1:Vv(L).length>0)){const L=i==null?void 0:i();L&&s({type:"doc-update",document:L,filename:n,version:(o==null?void 0:o.current)??0}),s({type:"pending-resolved",filename:n,action:U})}},[t,n,s,i,o]),$=S.useCallback(()=>{_.current&&E&&O.current&&(du(_.current,O.current),O.current=null,_.current=null,C(!1))},[E]),Q=S.useCallback(()=>{$(),y(),V("accept")},[$,y,V]),G=S.useCallback(()=>{$(),b(),V("reject")},[$,b,V]),K=S.useCallback(()=>{$(),x(),V("accept")},[$,x,V]);S.useEffect(()=>{const U=()=>K();return window.addEventListener("ow-accept-all",U),()=>window.removeEventListener("ow-accept-all",U)},[K]);const X=S.useCallback(()=>{$(),k(),V("reject")},[$,k,V]),re=S.useCallback(()=>{if(T===0||T===1&&R===0)return;const U=R<=0?T-1:R-1;r(e.filenames[U])},[T,R,e.filenames,r]),J=S.useCallback(()=>{if(T===0||T===1&&R===0)return;const U=R>=T-1?0:R+1;r(e.filenames[U])},[T,R,e.filenames,r]);if(S.useEffect(()=>{if(!h)return;const U=A=>{if(!(A.target instanceof HTMLInputElement||A.target instanceof HTMLTextAreaElement)&&!(A.target instanceof HTMLElement&&A.target.closest("[contenteditable]")))switch(A.key){case"j":case"ArrowDown":!A.metaKey&&!A.ctrlKey&&(A.preventDefault(),m());break;case"k":case"ArrowUp":!A.metaKey&&!A.ctrlKey&&(A.preventDefault(),g());break;case"h":case"ArrowLeft":!A.metaKey&&!A.ctrlKey&&!A.altKey&&(A.preventDefault(),re());break;case"l":case"ArrowRight":!A.metaKey&&!A.ctrlKey&&!A.altKey&&(A.preventDefault(),J());break;case"a":!A.metaKey&&!A.ctrlKey&&!A.shiftKey&&(A.preventDefault(),Q());break;case"r":!A.metaKey&&!A.ctrlKey&&(A.preventDefault(),G());break;case"A":A.shiftKey&&!A.metaKey&&!A.ctrlKey&&(A.preventDefault(),K());break;case"R":A.shiftKey&&!A.metaKey&&!A.ctrlKey&&(A.preventDefault(),X());break;case"o":!A.metaKey&&!A.ctrlKey&&!A.shiftKey&&(A.preventDefault(),D());break}};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[h,m,g,re,J,Q,G,K,X,D]),!h)return null;const oe=R>=0?R+1:"?";return u.jsxs("div",{className:"review-panel",children:[T>1&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"review-panel__nav",children:[u.jsx("button",{className:"review-panel__btn",onClick:re,title:"Previous doc (h)",children:u.jsx(O5,{})}),u.jsx("button",{className:"review-panel__btn",onClick:J,title:"Next doc (l)",children:u.jsx(R5,{})}),u.jsxs("span",{className:"review-panel__counter",children:[oe,"/",T]})]}),u.jsx("div",{className:"review-panel__divider"})]}),u.jsxs("div",{className:"review-panel__nav",children:[u.jsx("button",{className:"review-panel__btn",onClick:g,disabled:l.total===0,title:"Previous (k)",children:u.jsx(I5,{})}),u.jsx("button",{className:"review-panel__btn",onClick:m,disabled:l.total===0,title:"Next (j)",children:u.jsx(L5,{})}),u.jsxs("span",{className:"review-panel__counter",children:[f+1,"/",l.total]})]}),u.jsx("div",{className:"review-panel__divider"}),u.jsxs("div",{className:"review-panel__toggle",children:[u.jsx("button",{className:`review-panel__toggle-btn${P&&!E?" review-panel__toggle-btn--active":""}`,onClick:()=>P&&E&&D(),disabled:!P,title:"Show modified (o)",children:"Modified"}),u.jsx("button",{className:`review-panel__toggle-btn${P&&E?" review-panel__toggle-btn--active":""}`,onClick:()=>P&&!E&&D(),disabled:!P,title:"Show original (o)",children:"Original"})]}),u.jsx("div",{className:"review-panel__divider"}),u.jsxs("div",{className:"review-panel__actions",children:[u.jsx("button",{className:"review-panel__accept",onClick:Q,title:"Accept (a)",children:u.jsx(tw,{})}),u.jsx("button",{className:"review-panel__reject",onClick:G,title:"Reject (r)",children:u.jsx(nw,{})}),u.jsxs("button",{className:"review-panel__accept-all",onClick:K,title:"Accept all (Shift+A)",children:[u.jsx(tw,{}),u.jsx("span",{children:"All"})]}),u.jsxs("button",{className:"review-panel__reject-all",onClick:X,title:"Reject all (Shift+R)",children:[u.jsx(nw,{}),u.jsx("span",{children:"All"})]})]})]})}function P5(t,e){return t.indexOf(e)}function fu(t){return t.type==="doc"?t.file:t.id}function yl(t,e){for(const n of t)n.type==="doc"?e.add(n.file):n.type==="container"&&yl(n.items,e)}function ea(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 ks(t){return/^[A-Z]:[/\\]|^\//.test(t)}function e2(t){const e=t.replace(/\\/g,"/").split("/");return e.length>=2?e[e.length-2]:""}function B5(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 z5(t,e){const[n,r]=S.useState([]),[s,i]=S.useState([]),o=S.useRef(null),l=S.useRef(new Set),d=S.useCallback(g=>{l.current.add(g)},[]),f=S.useMemo(()=>{const g=new Set;for(const y of s)y.workspace&&yl(y.workspace.root,g);return g},[s]),h=S.useCallback(()=>{fetch("/api/documents").then(g=>g.json()).then(g=>{if(!Array.isArray(g))return;const y=l.current;if(y.size>0){const x=new Set(g.map(k=>k.filename));for(const k of[...y])x.has(k)||y.delete(k)}const b=y.size>0?g.filter(x=>!y.has(x.filename)):g;r(b)}).catch(()=>{})},[]),m=S.useCallback(()=>{fetch("/api/workspaces").then(g=>g.json()).then(async g=>{if(!Array.isArray(g))return;const y=await Promise.all(g.map(async b=>{try{const k=await(await fetch(`/api/workspaces/${encodeURIComponent(b.filename)}`)).json();return{...b,workspace:k}}catch{return b}}));i(y)}).catch(()=>{})},[]);return S.useEffect(()=>{h()},[h,t]),S.useEffect(()=>{m()},[m,e]),S.useEffect(()=>{const g=requestAnimationFrame(()=>{var b;const y=(b=o.current)==null?void 0:b.querySelector(".sidebar-item.active");y==null||y.scrollIntoView({block:"nearest",behavior:"instant"})});return()=>cancelAnimationFrame(g)},[n]),{docs:n,setDocs:r,workspaces:s,setWorkspaces:i,assignedFiles:f,fetchDocs:h,fetchWorkspaces:m,scrollRef:o,markPendingDelete:d}}function Bg(t,e){return t.filter(n=>!e(n)).map(n=>n.type==="container"?{...n,items:Bg(n.items,e)}:n)}function t2(t,e,n){return t.map(r=>r.type==="container"&&r.id===e?{...r,name:n}:r.type==="container"?{...r,items:t2(r.items,e,n)}:r)}function $5(t,e,n,r,s,i){const o=S.useCallback(B=>{n(P=>P.filter(D=>D.filename!==B)),i==null||i(B),fetch(`/api/documents/${encodeURIComponent(B)}`,{method:"DELETE"}).catch(()=>t())},[n,t]),l=S.useCallback(B=>{n(P=>P.filter(D=>D.filename!==B)),fetch(`/api/documents/${encodeURIComponent(B)}/archive`,{method:"POST"}).catch(()=>t())},[n,t]),d=S.useCallback(B=>{n(P=>P.filter(D=>D.filename!==B)),fetch(`/api/documents/${encodeURIComponent(B)}/unarchive`,{method:"POST"}).catch(()=>t())},[n,t]),f=S.useCallback((B,P,D)=>{!D.trim()||D.trim()===P||(n(V=>V.map($=>$.filename===B?{...$,title:D.trim()}:$)),fetch(`/api/documents/${encodeURIComponent(B)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:D.trim()})}).catch(()=>t()))},[n,t]),h=S.useCallback(B=>{r(P=>P.filter(D=>D.filename!==B)),fetch(`/api/workspaces/${encodeURIComponent(B)}`,{method:"DELETE"}).catch(()=>e())},[r,e]),m=S.useCallback((B,P)=>{P.trim()&&(r(D=>D.map(V=>V.filename===B?{...V,title:P.trim()}:V)),fetch(`/api/workspaces/${encodeURIComponent(B)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:P.trim()})}).catch(()=>e()))},[r,e]),g=S.useCallback((B,P)=>{r(D=>D.map(V=>V.filename!==B||!V.workspace?V:{...V,docCount:Math.max(0,V.docCount-1),workspace:{...V.workspace,root:Bg(V.workspace.root,$=>$.type==="doc"&&$.file===P)}})),fetch(`/api/workspaces/${encodeURIComponent(B)}/docs/${encodeURIComponent(P)}`,{method:"DELETE"}).catch(()=>e())},[r,e]),y=S.useCallback((B,P,D=!1)=>{r($=>$.map(Q=>Q.filename!==B||!Q.workspace?Q:{...Q,workspace:{...Q.workspace,root:Bg(Q.workspace.root,G=>G.type==="container"&&G.id===P)}}));const V=`/api/workspaces/${encodeURIComponent(B)}/containers/${encodeURIComponent(P)}${D?"?cascade=true":""}`;fetch(V,{method:"DELETE"}).then(()=>{D&&t()}).catch(()=>e())},[r,e,t]),b=S.useCallback((B,P,D)=>{D.trim()&&(r(V=>V.map($=>$.filename!==B||!$.workspace?$:{...$,workspace:{...$.workspace,root:t2($.workspace.root,P,D.trim())}})),fetch(`/api/workspaces/${encodeURIComponent(B)}/containers/${encodeURIComponent(P)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:D.trim()})}).catch(()=>e()))},[r,e]),x=S.useCallback(()=>{fetch("/api/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:"Untitled Workspace"})}).catch(()=>{})},[]),k=S.useCallback((B,P,D)=>{fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D?{metadata:D}:{})}).then(V=>V.json()).then(V=>{if(V.filename)return fetch(`/api/workspaces/${encodeURIComponent(B)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:V.filename,title:V.title||"Untitled",containerId:P})})}).catch(()=>{})},[]),E=S.useCallback((B,P)=>{fetch(`/api/workspaces/${encodeURIComponent(B)}/containers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:"Untitled",parentContainerId:P})}).catch(()=>{})},[]),[C,O]=S.useState({}),_=S.useRef(-1);S.useEffect(()=>{s!==_.current&&(_.current=s??0,fetch("/api/documents").then(B=>B.json()).then(B=>{const P={};return Promise.all(B.map(D=>fetch(`/api/doc-tags/${encodeURIComponent(D.filename)}`).then(V=>V.json()).then(V=>{var $;($=V.tags)!=null&&$.length&&(P[D.filename]=V.tags)}).catch(()=>{}))).then(()=>O(P))}).catch(()=>{}))},[s]);const T=S.useCallback(B=>C[B]||[],[C]),R=S.useCallback((B,P)=>{P.trim()&&(O(D=>{const V=D[B]||[];return V.includes(P.trim())?D:{...D,[B]:[...V,P.trim()]}}),fetch(`/api/doc-tags/${encodeURIComponent(B)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag:P.trim()})}).catch(()=>{}))},[]),I=S.useCallback((B,P)=>{O(D=>{const $=(D[B]||[]).filter(Q=>Q!==P);if($.length===0){const Q={...D};return delete Q[B],Q}return{...D,[B]:$}}),fetch(`/api/doc-tags/${encodeURIComponent(B)}/${encodeURIComponent(P)}`,{method:"DELETE"}).catch(()=>{})},[]);return{fetchDocs:t,handleDelete:o,handleArchive:l,handleUnarchive:d,handleRename:f,handleCreateWorkspace:x,handleDeleteWorkspace:h,handleCreateInWorkspace:k,handleRemoveFromWorkspace:g,handleCreateContainer:E,handleDeleteContainer:y,handleRenameContainer:b,handleRenameWorkspace:m,getDocTags:T,handleAddTag:R,handleRemoveTag:I}}function n2({docs:t,workspaces:e,assignedFiles:n,scrollRef:r,setCollapsedSections:s}){const[i,o]=S.useState(null),[l,d]=S.useState(null),f=S.useRef(null),h=S.useRef(null),m=S.useRef(null),g=S.useRef(null),y=S.useRef(null),b=5,x=(D,V,$)=>$==="before"?V>0?fu(D[V-1]):null:fu(D[V]),k=S.useCallback((D,V)=>{if(V===null){const G=t.filter(X=>!n.has(X.filename)).map(X=>({type:"doc",file:X.filename,title:X.title})),K=G.findIndex(X=>fu(X)===D);return K>=0?{siblings:G,index:K,containerId:null}:null}const $=e.find(G=>G.filename===V);if(!($!=null&&$.workspace))return null;const Q=(G,K)=>{for(let X=0;X<G.length;X++){if(fu(G[X])===D)return{siblings:G,index:X,containerId:K};if(G[X].type==="container"){const re=Q(G[X].items,G[X].id);if(re)return re}}return null};return Q($.workspace.root,null)},[t,n,e]),E=S.useCallback(()=>{o(null),d(null),y.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=""},[]),C=S.useCallback((D,V)=>{if(!D||!V)return;if(D.type==="workspace"){const J=V.itemId;if(J===D.filename)return;const oe=e.map(L=>L.filename),U=oe.indexOf(D.filename);if(U<0)return;oe.splice(U,1);let A=oe.indexOf(J);if(A<0)return;V.position==="after"&&(A+=1),oe.splice(A,0,D.filename),fetch("/api/workspaces/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:oe})}).catch(()=>{});return}const{wsFilename:$,containerId:Q,afterId:G}=V,K=D.type==="doc"?D.file:D.id,X=D.sourceWs;if(V.itemId===K)return;if(D.type==="container"){if($===null&&Q===null&&V.itemId!=="__section__"){const J=V.itemId,oe=V.position==="after"?J:(()=>{const U=e.findIndex(A=>A.filename===J);return U>0?e[U-1].filename:null})();fetch("/api/workspaces/promote-container",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:X,containerId:K,afterWorkspaceFilename:oe})}).catch(()=>{});return}if(X!==$&&$){fetch(`/api/workspaces/${encodeURIComponent($)}/containers/${encodeURIComponent(K)}/cross-move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:X,targetContainerId:Q??null,afterIdentifier:G})}).catch(()=>{});return}if(!$)return;fetch(`/api/workspaces/${encodeURIComponent($)}/docs/${encodeURIComponent(K)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:Q??null,afterFile:G})}).catch(()=>{});return}const re=D.file;if(X===null&&$===null){const J=t.filter(te=>!n.has(te.filename)).map(te=>te.filename),oe=J.indexOf(re);if(oe<0)return;J.splice(oe,1);let U=G?J.indexOf(G):-1;U>=0?U+=1:U=0,J.splice(U,0,re);const A=[];let L=0;for(const te of t)n.has(te.filename)?A.push(te.filename):A.push(J[L++]);fetch("/api/documents/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:A})}).catch(()=>{});return}if(X===null&&$!==null){fetch(`/api/workspaces/${encodeURIComponent($)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:re,title:re.replace(/\.md$/,""),containerId:Q??null,afterFile:G})}).catch(()=>{});return}if(X!==null&&$===null){fetch(`/api/workspaces/${encodeURIComponent(X)}/docs/${encodeURIComponent(re)}`,{method:"DELETE"}).catch(()=>{});return}if(X===$&&$!==null){fetch(`/api/workspaces/${encodeURIComponent($)}/docs/${encodeURIComponent(re)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:Q??null,afterFile:G})}).catch(()=>{});return}X!==null&&$!==null&&fetch(`/api/workspaces/${encodeURIComponent($)}/docs/${encodeURIComponent(re)}/cross-move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:X,containerId:Q??null,afterFile:G,title:re.replace(/\.md$/,"")})}).catch(()=>{})},[e,t,n]),O=S.useCallback((D,V)=>{const $=m.current;$&&($.style.display="none");const Q=document.elementFromPoint(D,V);if($&&($.style.display=""),!Q)return null;if((i==null?void 0:i.type)==="workspace"||(i==null?void 0:i.type)==="container"){const te=Q.closest("[data-ws-drag]");if(te){const se=te.dataset.wsDrag,be=te.getBoundingClientRect(),ee=(V-be.top)/be.height;return{itemId:se,position:ee<.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 te=Q.closest("[data-ws-drag]");if(te)return{itemId:"__section__",position:"inside",wsFilename:te.dataset.wsDrag,containerId:null,afterId:null}}const G=Q.closest("[data-drag-id]");if(!G){const te=Q.closest("[data-drop-ws]");return te?{itemId:"__section__",position:"inside",wsFilename:te.dataset.dropWs==="__docs__"?null:te.dataset.dropWs,containerId:te.dataset.dropContainer||null,afterId:null}:null}const K=G.dataset.dragId,X=G.dataset.dragType,re=G.dataset.dragWs==="__docs__"?null:G.dataset.dragWs,J=G.getBoundingClientRect(),oe=(V-J.top)/J.height;if(X==="container-header"){const te=K,se=G.dataset.dragParent||null,be=k(te,re);if(!be)return null;const ee=(i==null?void 0:i.type)==="container"?.33:.25;return oe<ee?{itemId:te,position:"before",wsFilename:re,containerId:se,afterId:x(be.siblings,be.index,"before")}:oe>1-ee?{itemId:te,position:"after",wsFilename:re,containerId:se,afterId:x(be.siblings,be.index,"after")}:{itemId:te,position:"inside",wsFilename:re,containerId:te,afterId:null}}const U=G.dataset.dragContainer||null,A=k(K,re);if(!A)return null;const L=oe<.5?"before":"after";return{itemId:K,position:L,wsFilename:re,containerId:U,afterId:x(A.siblings,A.index,L)}},[k,i]),_=S.useCallback(D=>{const V=r.current;if(!V)return;const $=V.getBoundingClientRect(),Q=80,G=18;let K=0;if(D<$.top+Q?K=-G*Math.max(0,1-(D-$.top)/Q):D>$.bottom-Q&&(K=G*Math.max(0,1-($.bottom-D)/Q)),h.current&&(cancelAnimationFrame(h.current),h.current=null),K!==0){const X=()=>{V.scrollTop+=K,h.current=requestAnimationFrame(X)};h.current=requestAnimationFrame(X)}},[r]),T=S.useCallback((D,V)=>{const $=m.current;$&&($.style.display="none");const Q=document.elementFromPoint(D,V);$&&($.style.display="");const G=Q==null?void 0:Q.closest("[data-section-key]");if(!G){f.current&&(clearTimeout(f.current),f.current=null);return}const K=G.dataset.sectionKey;f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{s(X=>{if(!X.has(K))return X;const re=new Set(X);return re.delete(K),re})},500)},[s]);S.useEffect(()=>{if(!i)return;const D=$=>{m.current&&(m.current.style.left=`${$.clientX+12}px`,m.current.style.top=`${$.clientY-8}px`),d(O($.clientX,$.clientY)),_($.clientY),T($.clientX,$.clientY)},V=$=>{C(i,O($.clientX,$.clientY)),E()};return window.addEventListener("pointermove",D),window.addEventListener("pointerup",V),()=>{window.removeEventListener("pointermove",D),window.removeEventListener("pointerup",V)}},[i,O,C,E,_,T]);const R=S.useCallback((D,V,$)=>{if(D.button!==0||D.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:D.clientX,y:D.clientY},y.current=V;const G=X=>{if(!g.current||!y.current)return;const re=X.clientX-g.current.x,J=X.clientY-g.current.y;if(Math.abs(re)+Math.abs(J)>=b){document.body.style.userSelect="none",window.removeEventListener("pointermove",G),window.removeEventListener("pointerup",K),o(y.current),y.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=$,document.body.appendChild(oe),m.current=oe,oe.style.left=`${X.clientX+12}px`,oe.style.top=`${X.clientY-8}px`}},K=()=>{window.removeEventListener("pointermove",G),window.removeEventListener("pointerup",K),g.current=null,y.current=null,document.body.style.userSelect=""};window.addEventListener("pointermove",G),window.addEventListener("pointerup",K)},[]);return{draggedItem:i,dropIndicator:l,handlePointerDown:R,dropClass:D=>!l||l.itemId!==D?"":l.position==="before"?"drop-before":l.position==="after"?"drop-after":l.position==="inside"?"drop-inside":"",isDragging:D=>i?i.type==="doc"?i.file===D:i.type==="workspace"?i.filename===D:i.id===D:!1,isContainerDropTarget:D=>!l||!i?!1:l.containerId===D}}function F5({items:t,onAction:e,menuRef:n}){const[r,s]=S.useState(null),i=S.useRef(null),o=S.useMemo(()=>{const h=new Map;for(const m of t){const g=m.pluginDisplayName||"_ungrouped",y=h.get(g)||[];y.push(m),h.set(g,y)}return h},[t]),[l,d]=S.useState({});S.useLayoutEffect(()=>{if(!r||!i.current||!n.current)return;const h=n.current.getBoundingClientRect(),m=i.current.getBoundingClientRect(),g=8;let y=h.right-4,b=i.current.offsetTop+h.top-4;y+m.width+g>window.innerWidth&&(y=h.left-m.width+4),b+m.height+g>window.innerHeight&&(b=window.innerHeight-m.height-g),b<g&&(b=g),d({position:"fixed",left:y,top:b})},[r,n]);const f=[];for(const[h,m]of o)if(h!=="_ungrouped"&&m.length>=3)f.push(u.jsxs("span",{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsxs("button",{className:"context-menu-item context-menu-submenu-trigger",onMouseEnter:()=>s(h),onClick:()=>s(r===h?null:h),children:[u.jsx("span",{children:"Transform"}),u.jsx("span",{className:"context-menu-submenu-arrow",children:"▸"})]}),r===h&&u.jsx("div",{ref:i,className:"context-menu context-menu-submenu",style:l,onMouseLeave:()=>s(null),children:m.map(g=>u.jsx("button",{className:"context-menu-item",onClick:()=>e(g),children:u.jsx("span",{children:g.label})},g.action))})]},`sub-${h}`));else{let g=!0;for(const y of m){const b=g&&h!=="_ungrouped";g=!1,f.push(u.jsxs("span",{children:[b&&u.jsx("div",{className:"context-menu-divider"}),b&&u.jsx("div",{className:"context-menu-section-header",children:h}),u.jsx("button",{className:"context-menu-item",onClick:()=>e(y),children:u.jsx("span",{children:y.label})})]},y.action))}}return u.jsx(u.Fragment,{children:f})}function wd({x:t,y:e,filename:n,title:r,onClose:s,onDuplicate:i,onRename:o,onArchive:l,onDelete:d,onPluginAction:f,pluginItems:h,onSchedulePost:m,onViewAnalytics:g,viewAnalyticsLabel:y,onMarkSent:b,isAlreadySent:x,isApproved:k,onToggleApprove:E,isAutoAccept:C,onToggleAutoAccept:O,folderMode:_,onNewDoc:T,onNewContainer:R,onAcceptAll:I,onRejectAll:B,folderAutoAccept:P,onToggleFolderAutoAccept:D,folderAutoAcceptLabel:V,folderDocCount:$,onDeleteWithDocs:Q,bulkCount:G,onBulkDelete:K}){const X=S.useRef(null),[re,J]=S.useState(!1),[oe,U]=S.useState(!1),[A,L]=S.useState({left:t,top:e});S.useLayoutEffect(()=>{const se=X.current;if(!se)return;const be=se.getBoundingClientRect(),ee=8;let ge=t,fe=e;e+be.height+ee>window.innerHeight&&(fe=e-be.height),t+be.width+ee>window.innerWidth&&(ge=t-be.width),fe<ee&&(fe=ee),ge<ee&&(ge=ee),L({left:ge,top:fe})},[t,e]),S.useEffect(()=>{const se=be=>{X.current&&!X.current.contains(be.target)&&s()};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[s]),S.useEffect(()=>{const se=be=>{be.key==="Escape"&&s()};return document.addEventListener("keydown",se),()=>document.removeEventListener("keydown",se)},[s]);const te=S.useCallback(se=>{f(se.action,se),s()},[f,s]);return G&&G>1&&K?u.jsxs("div",{ref:X,className:"context-menu",style:{left:A.left,top:A.top},children:[u.jsxs("div",{className:"context-menu-section-header",children:[G," selected"]}),re?u.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:se=>se.stopPropagation(),children:[u.jsxs("span",{children:["Delete ",G,"?"]}),u.jsx("button",{onClick:()=>{K(),s()},children:"Yes"}),u.jsx("button",{onClick:()=>J(!1),children:"No"})]}):u.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>J(!0),children:u.jsxs("span",{children:["Delete (",G,")"]})})]}):_?u.jsxs("div",{ref:X,className:"context-menu",style:{left:A.left,top:A.top},children:[u.jsx("button",{className:"context-menu-item",onClick:()=>{o(),s()},children:u.jsx("span",{children:"Rename"})}),T&&u.jsx("button",{className:"context-menu-item",onClick:se=>{T(se),s()},children:u.jsx("span",{children:"New Document"})}),R&&u.jsx("button",{className:"context-menu-item",onClick:()=>{R(),s()},children:u.jsx("span",{children:"New Container"})}),(I||B)&&u.jsx("div",{className:"context-menu-divider"}),I&&u.jsx("button",{className:"context-menu-item",onClick:()=>{I(),s()},children:u.jsx("span",{children:"Accept All Changes"})}),B&&u.jsx("button",{className:"context-menu-item",onClick:()=>{B(),s()},children:u.jsx("span",{children:"Reject All Changes"})}),D&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{D(),s()},children:u.jsx("span",{children:P?`Turn off auto-accept${V?" "+V:""}`:`Turn on auto-accept${V?" "+V:""}`})})]}),u.jsx("div",{className:"context-menu-divider"}),re?$&&$>0&&Q?u.jsxs("div",{className:"sidebar-ctx-folder-delete",onClick:se=>se.stopPropagation(),children:[u.jsx("div",{className:"sidebar-ctx-folder-delete-prompt",children:"Delete this folder?"}),u.jsxs("button",{className:"context-menu-item sidebar-ctx-delete-option",onClick:()=>{d(),s()},children:[u.jsx("span",{children:"Folder only"}),u.jsxs("span",{className:"sidebar-ctx-delete-hint",children:[$," doc",$===1?"":"s"," → Documents"]})]}),u.jsxs("button",{className:"context-menu-item sidebar-ctx-delete-option sidebar-ctx-delete",onClick:()=>{Q(),s()},children:[u.jsxs("span",{children:["Folder + ",$," doc",$===1?"":"s"]}),u.jsx("span",{className:"sidebar-ctx-delete-hint",children:"permanently deletes files"})]}),u.jsx("button",{className:"context-menu-item sidebar-ctx-delete-cancel",onClick:()=>J(!1),children:u.jsx("span",{children:"Cancel"})})]}):u.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:se=>se.stopPropagation(),children:[u.jsx("span",{children:"Delete?"}),u.jsx("button",{onClick:()=>{d(),s()},children:"Yes"}),u.jsx("button",{onClick:()=>J(!1),children:"No"})]}):u.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>J(!0),children:u.jsx("span",{children:"Delete"})})]}):u.jsxs("div",{ref:X,className:"context-menu",style:{left:A.left,top:A.top},children:[u.jsx("button",{className:"context-menu-item",onClick:()=>{i(),s()},children:u.jsx("span",{children:"Duplicate"})}),u.jsx("button",{className:"context-menu-item",onClick:()=>{o(),s()},children:u.jsx("span",{children:"Rename"})}),oe?u.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:se=>se.stopPropagation(),children:[u.jsx("span",{children:"Archive?"}),u.jsx("button",{onClick:()=>{l(),s()},children:"Yes"}),u.jsx("button",{onClick:()=>U(!1),children:"No"})]}):u.jsx("button",{className:"context-menu-item",onClick:()=>U(!0),children:u.jsx("span",{children:"Archive"})}),re?u.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:se=>se.stopPropagation(),children:[u.jsx("span",{children:ks(n)?"Remove?":"Delete?"}),u.jsx("button",{onClick:()=>{d(),s()},children:"Yes"}),u.jsx("button",{onClick:()=>J(!1),children:"No"})]}):u.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>J(!0),children:u.jsx("span",{children:ks(n)?"Remove":"Delete"})}),E&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{E(),s()},children:u.jsx("span",{children:k?"Remove Approval":"Approve"})})]}),O&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{O(),s()},children:u.jsx("span",{children:C?"Turn off auto-accept":"Turn on auto-accept"})})]}),m&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{m(),s()},children:u.jsx("span",{children:"Schedule Post"})})]}),b&&!x&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{b(),s()},children:u.jsx("span",{children:"Mark as Sent"})})]}),g&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{g(),s()},children:u.jsx("span",{children:y||"View Analytics"})})]}),h.length>0&&u.jsx(F5,{items:h,onAction:te,menuRef:X})]})}function r2({actionLabel:t,docTitle:e,onConfirm:n,onClose:r}){const[s,i]=S.useState(""),o=S.useRef(null);S.useEffect(()=>{var d;(d=o.current)==null||d.focus()},[]),S.useEffect(()=>{const d=f=>{f.key==="Escape"&&r()};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const l=S.useCallback(()=>{n(s.trim())},[s,n]);return u.jsx("div",{className:"focus-modal-overlay",onClick:r,children:u.jsxs("div",{className:"focus-modal",onClick:d=>d.stopPropagation(),children:[u.jsxs("div",{className:"focus-modal-header",children:[u.jsx("h2",{children:t}),u.jsx("button",{className:"focus-modal-close",onClick:r,children:"×"})]}),u.jsxs("div",{className:"focus-modal-body",children:[u.jsxs("label",{children:['Focus instructions for "',e,'"',u.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()}})]}),u.jsxs("div",{className:"focus-modal-hint",children:[s.length,"/500"]}),u.jsxs("div",{className:"focus-modal-actions",children:[u.jsx("button",{className:"focus-modal-btn secondary",onClick:r,children:"Cancel"}),u.jsx("button",{className:"focus-modal-btn primary",onClick:l,children:"Go"})]})]})]})})}function xp(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(u.jsx("mark",{children:t.slice(o,o+e.length)},o)),i=o+e.length}return n}function rw({r:t,query:e,onClick:n}){return u.jsxs("div",{className:`sidebar-item search-result-item ${t.isActive?"active":""} ${t.isArchived?"search-result-archived":""}`,onClick:n,children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-item-title-text",children:t.matchType==="title"?xp(t.title,e):t.title}),t.isArchived&&u.jsx("span",{className:"search-archived-badge",children:"archived"})]}),t.matchType==="tag"&&t.matchedTag&&u.jsxs("div",{className:"search-result-tag",children:["Tag: ",xp(t.matchedTag,e)]}),t.matchType==="content"&&t.snippet&&u.jsx("div",{className:"search-result-snippet",children:xp(t.snippet,e)}),u.jsxs("div",{className:"sidebar-item-meta",children:[t.wordCount.toLocaleString()," words · ",ea(t.lastModified)]})]})}function $d({results:t,query:e,onSwitchDocument:n,actions:r}){if(t.length===0)return u.jsx("div",{className:"sidebar-scroll",children:u.jsxs("div",{className:"search-empty",children:['No results for "',e,'"']})});const s=t.filter(o=>!o.isArchived),i=t.filter(o=>o.isArchived);return u.jsx("div",{className:"sidebar-scroll",children:u.jsxs("div",{className:"search-results",children:[s.map(o=>u.jsx(rw,{r:o,query:e,onClick:()=>n(o.filename)},o.filename)),i.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"search-archived-divider",children:u.jsx("span",{children:"Archived"})}),i.map(o=>u.jsx(rw,{r:o,query:e,onClick:()=>r.handleUnarchive(o.filename)},o.filename))]})]})})}async function wp(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 kp(t,e){return e?(t/e*100).toFixed(1)+"%":"0%"}function sw(t){return new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function iw(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 s2({docId:t,title:e,onClose:n}){const[r,s]=S.useState("loading"),[i,o]=S.useState([]),[l,d]=S.useState(""),[f,h]=S.useState(null),[m,g]=S.useState(null),[y,b]=S.useState("links"),[x,k]=S.useState("all"),[E,C]=S.useState(!1),[O,_]=S.useState(!1),[T,R]=S.useState(""),[I,B]=S.useState(!1),[P,D]=S.useState(null),V=S.useRef(null);S.useEffect(()=>{let ee=!1;return(async()=>{try{const ge=await wp("list_newsletter_issues",{limit:20});if(ee)return;if(!ge.issues||ge.issues.length===0){s("no-data");return}o(ge.issues);const fe=ge.issues[0].id;d(fe)}catch(ge){ee||(g(ge.message),s("error"))}})(),()=>{ee=!0}},[]),S.useEffect(()=>{if(!l)return;let ee=!1;return C(!0),_(!1),D(null),R(""),(async()=>{try{const ge=await wp("get_newsletter_analytics",{issue_id:l});if(ee)return;if(ge.error){g(ge.error),s("error");return}h(ge),s("loaded")}catch(ge){ee||(g(ge.message),s("error"))}finally{ee||C(!1)}})(),()=>{ee=!0}},[l]),S.useEffect(()=>{const ee=ge=>{V.current&&!V.current.contains(ge.target)&&n()};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[n]),S.useEffect(()=>{const ee=ge=>{ge.key==="Escape"&&n()};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[n]);const $=f?H5(f.subscriber_events):[],Q=(f==null?void 0:f.issue.recipient_count)??0,G=f?f.stats.delivered||Q-f.stats.bounces:0,K=f?new Set(f.subscriber_events.filter(ee=>{var ge;return ee.event_type==="click"&&((ge=ee.url)==null?void 0:ge.includes("/newsletter/unsubscribe/"))}).map(ee=>ee.email)).size:0,X=f?f.stats.unsubscribes||K:0,re=f?f.subscriber_events.filter(ee=>ee.event_type==="dropped").length:0,J=f?Math.max(0,Q-f.stats.unique_opens):0,oe=f!=null&&f.issue.sent_at?Date.now()-new Date(f.issue.sent_at).getTime():0,U=Math.floor(oe/36e5),A=!!(f!=null&&f.issue.resent_at||P),L=ee=>{const ge=Math.floor(ee/36e5);return ge<1?"just now":ge<24?`${ge}h ago`:`${Math.floor(ge/24)}d ${ge%24}h ago`},te=async()=>{if(!(!T.trim()||I)){B(!0);try{const ee=await wp("resend_to_unopened",{issue_id:l,subject:T});ee.error?(g(ee.error),s("error")):(D({sent:ee.sent,failed:ee.failed}),_(!1))}catch(ee){g(ee.message),s("error")}finally{B(!1)}}},se=ee=>{var ge;return ee.event_type==="unsubscribe"||ee.event_type==="click"&&!!((ge=ee.url)!=null&&ge.includes("/newsletter/unsubscribe/"))},be=f?U5(f.subscriber_events.filter(ee=>x==="all"?!0:x==="unsubscribe"?se(ee):ee.event_type===x)):[];return u.jsx("div",{className:"newsletter-modal-overlay",children:u.jsxs("div",{className:"na-modal",ref:V,children:[u.jsxs("div",{className:"na-header",children:[u.jsx("h3",{children:"Newsletter Analytics"}),u.jsx("button",{className:"newsletter-modal__close",onClick:n,children:"×"})]}),r==="loading"&&!f&&u.jsx("div",{className:"na-body",children:u.jsxs("div",{className:"newsletter-modal__status",children:[u.jsx("div",{className:"newsletter-modal__spinner"}),u.jsx("span",{children:"Loading analytics..."})]})}),r==="no-data"&&u.jsxs("div",{className:"na-body",children:[u.jsx("div",{className:"newsletter-modal__status",children:u.jsx("span",{children:"No newsletter sends found yet."})}),u.jsx("div",{className:"newsletter-modal__actions",children:u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:n,children:"Done"})})]}),r==="error"&&u.jsxs("div",{className:"na-body",children:[u.jsx("div",{className:"newsletter-modal__error",children:m}),u.jsx("div",{className:"newsletter-modal__actions",children:u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:n,children:"Done"})})]}),r==="loaded"&&f&&u.jsxs("div",{className:"na-body",children:[i.length>1&&u.jsx("select",{className:"newsletter-modal__select na-issue-select",value:l,onChange:ee=>d(ee.target.value),children:i.map(ee=>u.jsxs("option",{value:ee.id,children:[ee.subject," — ",sw(ee.sent_at)]},ee.id))}),E?u.jsxs("div",{className:"newsletter-modal__status",children:[u.jsx("div",{className:"newsletter-modal__spinner"}),u.jsx("span",{children:"Loading..."})]}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"na-kpi-row",children:[u.jsxs("div",{className:"na-kpi",children:[u.jsx("div",{className:"na-kpi__value",children:G.toLocaleString()}),u.jsx("div",{className:"na-kpi__label",children:"Delivered"}),u.jsxs("div",{className:"na-kpi__sub",children:[Q.toLocaleString()," sent"]})]}),u.jsxs("div",{className:"na-kpi",children:[u.jsx("div",{className:"na-kpi__value",children:kp(f.stats.unique_opens,G)}),u.jsx("div",{className:"na-kpi__label",children:"Open rate"}),u.jsxs("div",{className:"na-kpi__sub",children:[f.stats.unique_opens.toLocaleString()," opens"]})]}),u.jsxs("div",{className:"na-kpi",children:[u.jsx("div",{className:"na-kpi__value",children:kp(f.stats.unique_clicks,G)}),u.jsx("div",{className:"na-kpi__label",children:"Click rate"}),u.jsxs("div",{className:"na-kpi__sub",children:[f.stats.unique_clicks.toLocaleString()," clicks"]})]})]}),u.jsxs("div",{className:"na-kpi-row na-kpi-row--secondary",children:[u.jsxs("div",{className:"na-kpi na-kpi--sm",children:[u.jsx("span",{className:"na-kpi__value--sm",children:f.stats.bounces}),u.jsx("span",{className:"na-kpi__label--sm",children:"Bounces"})]}),u.jsxs("div",{className:"na-kpi na-kpi--sm",children:[u.jsx("span",{className:"na-kpi__value--sm",children:X}),u.jsx("span",{className:"na-kpi__label--sm",children:"Unsubs"})]}),u.jsxs("div",{className:"na-kpi na-kpi--sm",children:[u.jsx("span",{className:"na-kpi__value--sm",children:re}),u.jsx("span",{className:"na-kpi__label--sm",children:"Dropped"})]}),f.stats.complaints>0&&u.jsxs("div",{className:"na-kpi na-kpi--sm",children:[u.jsx("span",{className:"na-kpi__value--sm",children:f.stats.complaints}),u.jsx("span",{className:"na-kpi__label--sm",children:"Spam"})]})]}),J>0&&!A&&u.jsx("div",{className:"na-resend",children:O?u.jsxs("div",{className:"na-resend-panel",children:[u.jsxs("div",{className:"na-resend-label-row",children:[u.jsx("span",{className:"na-resend-label",children:"New subject line"}),u.jsxs("span",{className:"na-resend-meta",children:["sent ",L(oe),U<48?" · consider waiting 48h":""]})]}),u.jsx("input",{className:"na-resend-input",type:"text",value:T,onChange:ee=>R(ee.target.value),placeholder:"Try a different angle"}),u.jsxs("div",{className:"na-resend-actions",children:[u.jsx("button",{className:"na-resend-cancel",onClick:()=>_(!1),children:"Cancel"}),u.jsx("button",{className:"na-resend-send",onClick:te,disabled:I||!T.trim(),children:I?"Sending...":`Send to ${J.toLocaleString()}`})]})]}):u.jsxs("button",{className:"na-resend-toggle",onClick:()=>{_(!0),R(f.issue.subject)},children:["Resend to ",J.toLocaleString()," non-openers ",u.jsx("span",{style:{float:"right"},children:"›"})]})}),A&&u.jsxs("div",{className:"na-resend-done",children:["Resent ",f.issue.resent_at?L(Date.now()-new Date(f.issue.resent_at).getTime()):"just now",P?` — ${P.sent} sent`:"",f.issue.resend_subject?` — "${f.issue.resend_subject}"`:""]}),u.jsxs("div",{className:"na-tabs",children:[u.jsxs("button",{className:`na-tab${y==="links"?" active":""}`,onClick:()=>b("links"),children:["Links (",$.length,")"]}),u.jsxs("button",{className:`na-tab${y==="activity"?" active":""}`,onClick:()=>b("activity"),children:["Activity (",f.subscriber_events.length,")"]})]}),y==="links"&&u.jsx("div",{className:"na-table-wrap",children:$.length===0?u.jsx("div",{className:"na-empty",children:"No link clicks recorded yet."}):u.jsxs("table",{className:"na-table",children:[u.jsx("thead",{children:u.jsxs("tr",{children:[u.jsx("th",{children:"Link"}),u.jsx("th",{children:"Unique"}),u.jsx("th",{children:"Total"}),u.jsx("th",{children:"CTR"})]})}),u.jsx("tbody",{children:$.map(ee=>u.jsxs("tr",{children:[u.jsx("td",{className:"na-table__url",title:ee.url,children:u.jsx("a",{href:ee.url,target:"_blank",rel:"noopener noreferrer",children:iw(ee.url)})}),u.jsx("td",{children:ee.uniqueClicks}),u.jsx("td",{children:ee.totalClicks}),u.jsx("td",{children:kp(ee.uniqueClicks,G)})]},ee.url))})]})}),y==="activity"&&u.jsxs("div",{className:"na-activity",children:[u.jsx("div",{className:"na-filter-row",children:["all","open","click","bounce","dropped","unsubscribe"].map(ee=>u.jsx("button",{className:`na-filter-btn${x===ee?" active":""}`,onClick:()=>k(ee),children:ee==="all"?"All":ee.charAt(0).toUpperCase()+ee.slice(1)+"s"},ee))}),u.jsxs("div",{className:"na-table-wrap",children:[be.length===0?u.jsxs("div",{className:"na-empty",children:["No ",x==="all"?"":x+" ","events recorded."]}):u.jsxs("table",{className:"na-table",children:[u.jsx("thead",{children:u.jsxs("tr",{children:[u.jsx("th",{children:"Email"}),u.jsx("th",{children:"Event"}),u.jsx("th",{children:"Detail"}),u.jsx("th",{children:"Time"})]})}),u.jsx("tbody",{children:be.slice(0,100).map(ee=>u.jsxs("tr",{children:[u.jsx("td",{className:"na-table__email",children:ee.email}),u.jsxs("td",{children:[u.jsx("span",{className:`na-badge na-badge--${ee.event_type}`,children:ee.event_type}),ee.count>1&&u.jsxs("span",{className:"na-count",children:[ee.count,"x"]})]}),u.jsx("td",{className:"na-table__url",children:ee.url?u.jsx("a",{href:ee.url,target:"_blank",rel:"noopener noreferrer",children:iw(ee.url,35)}):"—"}),u.jsx("td",{className:"na-table__time",children:sw(ee.latestTimestamp)})]},ee.key))})]}),be.length>100&&u.jsxs("div",{className:"na-truncated",children:["Showing 100 of ",be.length," events"]})]})]})]})]})]})})}function U5(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 H5(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 W5(t){return t.tweetContext?"tweet":t.articleContext?"article":t.linkedinContext?"linkedin":t.newsletterContext?"newsletter":t.blogContext?"blog":"tweet"}function Cl({filename:t,title:e,onClose:n}){const[r,s]=S.useState("queue"),[i,o]=S.useState(null),[l,d]=S.useState(null),[f,h]=S.useState(""),[m,g]=S.useState(!1),[y,b]=S.useState(null),[x,k]=S.useState(null);S.useEffect(()=>{fetch(`/api/documents/${encodeURIComponent(t)}/text`).then(O=>{if(!O.ok)throw new Error("Failed to load document");return O.json()}).then(O=>{d(O.text||""),o(W5(O.meta||{}))}).catch(O=>k(O.message))},[t]);const E=async()=>{var O;if(!(!l||!i)){g(!0);try{const _={content:l,content_type:i,mode:r};r==="custom"&&f&&(_.scheduled_at=new Date(f).toISOString());const T=await fetch("/api/scheduler/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)}),R=await T.json();if(T.ok){const I=(O=R.item)!=null&&O.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(_){b({success:!1,message:_.message})}finally{g(!1)}}},C=i===null&&!x;return u.jsx("div",{className:"schedule-post-overlay",onClick:n,children:u.jsxs("div",{className:"schedule-post-modal",onClick:O=>O.stopPropagation(),children:[u.jsxs("div",{className:"schedule-post-modal-header",children:[u.jsx("h3",{children:"Schedule Post"}),u.jsx("button",{className:"schedule-post-modal-close",onClick:n,children:"×"})]}),u.jsx("div",{className:"schedule-post-modal-doc",children:e}),x?u.jsxs("div",{className:"schedule-post-modal-result error",children:[x,u.jsx("button",{className:"schedule-post-modal-done",onClick:n,children:"Done"})]}):y?u.jsxs("div",{className:`schedule-post-modal-result ${y.success?"success":"error"}`,children:[y.message,u.jsx("button",{className:"schedule-post-modal-done",onClick:n,children:"Done"})]}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"schedule-post-modal-field",children:[u.jsx("label",{children:"Content Type"}),u.jsx("div",{className:"schedule-post-modal-type",children:C?"...":i})]}),u.jsxs("div",{className:"schedule-post-modal-field",children:[u.jsx("label",{children:"Mode"}),u.jsxs("div",{className:"schedule-post-modal-modes",children:[u.jsx("button",{className:`schedule-post-mode ${r==="queue"?"active":""}`,onClick:()=>s("queue"),children:"Queue Next"}),u.jsx("button",{className:`schedule-post-mode ${r==="now"?"active":""}`,onClick:()=>s("now"),children:"Post Now"}),u.jsx("button",{className:`schedule-post-mode ${r==="custom"?"active":""}`,onClick:()=>s("custom"),children:"Custom Time"})]})]}),r==="custom"&&u.jsxs("div",{className:"schedule-post-modal-field",children:[u.jsx("label",{children:"Date & Time"}),u.jsx("input",{type:"datetime-local",value:f,onChange:O=>h(O.target.value)})]}),u.jsxs("div",{className:"schedule-post-modal-actions",children:[u.jsx("button",{className:"schedule-post-modal-cancel",onClick:n,children:"Cancel"}),u.jsx("button",{className:"schedule-post-modal-submit",onClick:E,disabled:m||C||r==="custom"&&!f,children:m?"Scheduling...":r==="now"?"Post Now":"Schedule"})]})]})]})})}const ow=[{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 i2({anchorRect:t,onSelect:e,onClose:n}){const r=S.useRef(null),[s,i]=S.useState(null),[o,l]=S.useState(""),d=S.useRef(null),[f,h]=S.useState({left:t.left,top:t.bottom+4});S.useLayoutEffect(()=>{const b=r.current;if(!b)return;const x=b.getBoundingClientRect(),k=8;let E=t.left,C=t.bottom+4;C+x.height+k>window.innerHeight&&(C=t.top-x.height-4),E+x.width+k>window.innerWidth&&(E=t.right-x.width),C<k&&(C=k),E<k&&(E=k),h({left:E,top:C})},[t]),S.useEffect(()=>{const b=x=>{r.current&&!r.current.contains(x.target)&&n()};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[n]),S.useEffect(()=>{const b=x=>{x.key==="Escape"&&n()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[n]),S.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 x=ow.find(E=>E.key===s);if(!(x!=null&&x.metadata))return;const k=JSON.parse(JSON.stringify(x.metadata));k.tweetContext&&(k.tweetContext.url=b),e(k)},y=o.trim().includes("x.com")||o.trim().includes("twitter.com");return u.jsx("div",{ref:r,className:"create-doc-dropdown",style:{left:f.left,top:f.top},children:ow.map(b=>u.jsxs("div",{children:[u.jsx("button",{className:`create-doc-dropdown-item${s===b.key?" active":""}`,onClick:()=>m(b),children:b.label}),s===b.key&&u.jsxs("div",{className:"create-doc-dropdown-url",children:[u.jsx("input",{ref:d,type:"text",placeholder:b.urlPlaceholder,value:o,onChange:x=>l(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),g()),x.key==="Escape"&&(i(null),l(""))}}),u.jsx("button",{onClick:g,disabled:!y,children:u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"9 18 15 12 9 6"})})})]})]},b.key))})}const q5=[{id:"full",label:"Full"},{id:"compact",label:"Compact"},{id:"minimal",label:"Minimal"}];function o2(t,e){if(!e)return!0;for(const n of t)if(n.type==="container"&&(n.id===e||o2(n.items,e)))return!0;return!1}function a2(t,e){for(const n of t){if(n.type==="doc"&&n.file===e)return[];if(n.type==="container"){const r=a2(n.items,e);if(r)return[n.id,...r]}}return null}function V5({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:y,onSearchChange:b}){var Jt;const x=M=>!!m&&m.has(M),[k,E]=S.useState(null),[C,O]=S.useState(""),[_,T]=S.useState(null),[R,I]=S.useState(()=>{try{const M=localStorage.getItem("ow-collapsed-sections");return M?new Set(JSON.parse(M)):new Set}catch{return new Set}}),[B,P]=S.useState(null),[D,V]=S.useState(null),[$,Q]=S.useState(""),[G,K]=S.useState(null),[X,re]=S.useState(""),[J,oe]=S.useState(null),[U,A]=S.useState(""),[L,te]=S.useState(null),[se,be]=S.useState(null),[ee,ge]=S.useState([]),[fe,Te]=S.useState(null),[Xe,tt]=S.useState(null),[st,nt]=S.useState(null),[Le,yt]=S.useState(null),[Ke,Et]=S.useState(null),[je,Je]=S.useState(oE),Fe=S.useRef(null);S.useEffect(()=>{if(!Ke)return;const M=ne=>{Fe.current&&!Fe.current.contains(ne.target)&&Et(null)};return document.addEventListener("mousedown",M),()=>document.removeEventListener("mousedown",M)},[Ke]);const Nt=M=>{Je(M),zM(M),Et(null)},qt=M=>{M.preventDefault(),Et({x:M.clientX,y:M.clientY})},ie=S.useCallback((M,ne)=>{fetch("/api/documents/batch-resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filenames:M,action:ne})}).catch(()=>{})},[]),{draggedItem:H,dropIndicator:q,handlePointerDown:de,dropClass:me,isDragging:Ee,isContainerDropTarget:De}=n2({docs:t,workspaces:n,assignedFiles:r,scrollRef:d,setCollapsedSections:I}),$e=S.useCallback(()=>{fetch("/api/plugins").then(M=>M.json()).then(M=>{const ne=[];for(const ue of M.plugins||[]){const Me=ue.displayName||void 0;for(const ct of ue.sidebarMenuItems||[])ne.push({...ct,pluginDisplayName:Me})}ge(ne)}).catch(()=>{})},[]);S.useEffect(()=>{$e()},[$e]),S.useEffect(()=>{const M=()=>$e();return window.addEventListener("ow-plugins-changed",M),()=>window.removeEventListener("ow-plugins-changed",M)},[$e]);const{variantsByMaster:qe,variantFilenames:W}=S.useMemo(()=>{const M=new Map,ne=new Set;for(const ue of t)if(ue.masterDocId){const Me=M.get(ue.masterDocId)||[];Me.push(ue),M.set(ue.masterDocId,Me),ne.add(ue.filename)}return{variantsByMaster:M,variantFilenames:ne}},[t]),pe=S.useCallback((M,ne)=>{M.preventDefault(),M.stopPropagation(),te({x:M.clientX,y:M.clientY,filename:ne.filename,title:ne.title,docId:ne.docId,lastSent:ne.lastSent,postedUrl:ne.postedUrl,isNewsletter:ne.isNewsletter})},[]),xe=S.useCallback(M=>{fetch("/api/documents/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:M})}).catch(()=>{})},[]),Ye=S.useCallback((M,ne,ue,Me,ct)=>{if(ne.promptForFocus&&ct===void 0){Te({action:M,label:ne.label,filename:ue,title:Me});return}fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:M,filename:ue,title:Me,instructions:ct||"",label:ne.label})}).catch(()=>{})},[]),it=M=>{I(ne=>{const ue=new Set(ne);return ue.has(M)?ue.delete(M):ue.add(M),localStorage.setItem("ow-collapsed-sections",JSON.stringify([...ue])),ue})},ot=t.find(M=>M.isActive),Re=S.useRef(n);if(Re.current=n,S.useEffect(()=>{var M;if(ot)for(const ne of Re.current){const ue=a2(((M=ne.workspace)==null?void 0:M.root)||[],ot.filename);if(ue){I(Me=>{const ct=[ne.filename,...ue.map(ve=>`container-${ve}`)];if(ct.every(ve=>!Me.has(ve)))return Me;const gt=new Set(Me);for(const ve of ct)gt.delete(ve);return localStorage.setItem("ow-collapsed-sections",JSON.stringify([...gt])),gt});break}}},[ot==null?void 0:ot.filename]),y!==null)return u.jsx($d,{results:y,query:g,onSwitchDocument:i,actions:l});const vt=t.filter(M=>!r.has(M.filename)&&!W.has(M.filename)),ht=(M,ne,ue,Me,ct,gt=!1)=>u.jsxs("div",{className:`sidebar-item ${M.isActive?"active":""} ${Ee(M.filename)?"dragging":""} ${me(M.filename)}`,"data-drag-id":M.filename,"data-drag-type":"doc","data-drag-ws":ne||"__docs__","data-drag-container":ue||"",onPointerDown:ve=>de(ve,{type:"doc",file:M.filename,sourceWs:ne||null},M.title),onClick:()=>!M.isActive&&!H&&i(M.filename),onDoubleClick:()=>{E(M.filename),O(M.title)},onContextMenu:ve=>pe(ve,M),children:[k===M.filename?u.jsx("input",{className:"sidebar-rename-input",value:C,onChange:ve=>O(ve.target.value),onBlur:()=>{l.handleRename(M.filename,M.title,C),E(null)},onKeyDown:ve=>{ve.key==="Enter"&&(l.handleRename(M.filename,M.title,C),E(null)),ve.key==="Escape"&&E(null)},autoFocus:!0,onClick:ve=>ve.stopPropagation()}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-item-title-text",children:M.title}),M.variantType&&u.jsx("span",{className:"files-badge-variant",children:M.variantType}),l.getDocTags(M.filename).includes("✓")&&u.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:u.jsx("polyline",{points:"20 6 9 17 4 12"})}),M.lastSent&&u.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:u.jsx("polyline",{points:"20 6 9 17 4 12"})}),(M.autoAccept||gt)&&u.jsx("span",{className:"sidebar-auto-accept-dot",title:M.autoAccept?"Auto-accept on":"Auto-accept inherited"}),s.filenames.includes(M.filename)&&u.jsx("span",{className:"sidebar-pending-dot"})]}),ks(M.filename)&&u.jsx("div",{className:"sidebar-item-context",children:e2(M.filename)}),u.jsxs("div",{className:"sidebar-item-meta",children:[M.wordCount.toLocaleString()," words · ",ea(M.lastModified)]}),u.jsxs("div",{className:"sidebar-tags",children:[l.getDocTags(M.filename).filter(ve=>ve!=="✓").map(ve=>u.jsxs("span",{className:"sidebar-tag",onClick:z=>z.stopPropagation(),children:[ve,u.jsx("span",{className:"sidebar-tag-remove",onClick:z=>{z.stopPropagation(),l.handleRemoveTag(M.filename,ve)},children:"×"})]},ve)),J===M.filename?u.jsx("input",{className:"sidebar-tag-input",value:U,onChange:ve=>A(ve.target.value),onBlur:()=>{U.trim()&&l.handleAddTag(M.filename,U),oe(null)},onKeyDown:ve=>{ve.key==="Enter"&&(l.handleAddTag(M.filename,U),oe(null),A("")),ve.key==="Escape"&&(oe(null),A(""))},autoFocus:!0,onClick:ve=>ve.stopPropagation(),placeholder:"tag..."}):u.jsx("button",{className:"sidebar-tag-add",onClick:ve=>{ve.stopPropagation(),oe(M.filename),A("")},children:"+"})]})]}),_===M.filename?u.jsxs("div",{className:"sidebar-confirm-delete",onClick:ve=>ve.stopPropagation(),children:[u.jsx("span",{children:ks(M.filename)?"Remove?":"Delete?"}),u.jsx("button",{onClick:()=>{l.handleDelete(M.filename),T(null)},children:"Yes"}),u.jsx("button",{onClick:()=>T(null),children:"No"})]}):u.jsx("button",{className:"sidebar-delete-btn",onClick:ve=>{ve.stopPropagation(),T(M.filename)},title:ks(M.filename)?"Remove document":"Delete document",children:"×"})]},M.filename),zt=(M,ne,ue,Me,ct,gt=!1)=>{const ve=M.docId?qe.get(M.docId):void 0,z=f&&(h==null?void 0:h.parentDocId)&&h.parentDocId===M.docId;if(!(ve&&ve.length>0||z))return ht(M,ne,ue,Me,ct,gt);const Ie=`variants-${M.docId}`,He=!R.has(Ie);return u.jsxs("div",{className:"sidebar-variant-group",children:[u.jsxs("div",{className:"sidebar-variant-master",onClick:We=>{We.target.closest(".sidebar-variant-chevron")&&(We.stopPropagation(),it(Ie))},children:[ht(M,ne,ue,Me,ct,gt),u.jsx("span",{className:`sidebar-variant-chevron${He?"":" collapsed"}`,children:u.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"6 9 12 15 18 9"})})})]}),He&&u.jsxs("div",{className:"sidebar-variant-children",children:[ve==null?void 0:ve.map((We,Mt)=>ht(We,ne,ue,Me,Mt,gt)),z&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:f})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]})]})]},`vg-${M.filename}`)},Ut=(M,ne,ue,Me,ct,gt,ve=!1)=>{if(M.type==="doc"){const ut=t.find(yn=>yn.filename===M.file);return ut?W.has(ut.filename)?u.jsx(u.Fragment,{}):zt(ut,ue,Me,ct,gt,ve):ks(M.file)?u.jsx("div",{className:"sidebar-item sidebar-unavailable",children:u.jsxs("div",{className:"sidebar-item-title",children:[M.title||M.file," (unavailable)"]})},M.file):u.jsxs("div",{className:"sidebar-item sidebar-missing",children:[u.jsxs("div",{className:"sidebar-item-title",children:[M.title||M.file," (missing)"]}),u.jsx("button",{className:"sidebar-delete-btn",onClick:()=>l.handleRemoveFromWorkspace(ue,M.file),title:"Remove",children:"×"})]},M.file)}const z=M,he=`container-${z.id}`,Ie=R.has(he),He=ne<=2?`depth-${ne}`:"depth-2",We=z.autoAccept===!0,Mt=We||ve;return u.jsxs("div",{className:`sidebar-container ${He} ${Ie?"collapsed":""} ${me(z.id)} ${De(z.id)?"drop-inside":""}`,children:[u.jsxs("div",{className:`sidebar-container-header ${(q==null?void 0:q.itemId)===z.id&&q.position==="inside"?"drop-inside":""}`,"data-drag-id":z.id,"data-drag-type":"container-header","data-drag-ws":ue,"data-drag-parent":Me||"","data-section-key":he,onPointerDown:ut=>de(ut,{type:"container",id:z.id,sourceWs:ue},z.name),onClick:()=>!H&&it(he),onContextMenu:ut=>{ut.preventDefault(),ut.stopPropagation(),yt({x:ut.clientX,y:ut.clientY,type:"container",wsFilename:ue,containerId:z.id,title:z.name,nodes:z.items,autoAccept:We})},children:[u.jsx("span",{className:`sidebar-chevron ${Ie?"collapsed":""}`,children:"▾"}),D===z.id?u.jsx("input",{className:"sidebar-rename-input",value:$,onChange:ut=>Q(ut.target.value),onBlur:()=>{l.handleRenameContainer(ue,z.id,$),V(null)},onKeyDown:ut=>{ut.key==="Enter"&&(l.handleRenameContainer(ue,z.id,$),V(null)),ut.key==="Escape"&&V(null)},autoFocus:!0,onClick:ut=>ut.stopPropagation()}):u.jsx("span",{className:"sidebar-container-name",onDoubleClick:ut=>{ut.stopPropagation(),V(z.id),Q(z.name)},children:z.name}),Mt&&u.jsx("span",{className:"sidebar-auto-accept-dot",title:We?"Auto-accept on for this container":"Auto-accept inherited from workspace"}),u.jsxs("div",{className:"sidebar-container-actions",children:[u.jsx("button",{className:"sidebar-new-btn",onClick:ut=>{ut.stopPropagation(),nt({anchor:ut.target.getBoundingClientRect(),wsFilename:ue,containerId:z.id})},title:"New doc",children:"+"}),ne<2&&u.jsx("button",{className:"sidebar-new-btn",onClick:ut=>{ut.stopPropagation(),l.handleCreateContainer(ue,z.id)},title:"New sub-container",children:"☐"}),u.jsx("button",{className:"sidebar-new-btn sidebar-container-delete",onClick:ut=>{ut.stopPropagation(),l.handleDeleteContainer(ue,z.id)},title:"Delete container",children:"×"})]})]}),!Ie&&u.jsxs("div",{className:"sidebar-container-list","data-drop-ws":ue,"data-drop-container":z.id,children:[f&&!(h!=null&&h.parentDocId)&&(h==null?void 0:h.wsFilename)===ue&&h.containerId===z.id&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:f})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),z.items.filter(ut=>ut.type!=="doc"?!0:!(x(ut.file)||f&&(h==null?void 0:h.wsFilename)===ue&&h.containerId===z.id&&ut.title===f)).map((ut,yn)=>Ut(ut,ne+1,ue,z.id,z.items,yn,Mt)),z.items.length===0&&!f&&u.jsx("div",{className:"sidebar-empty",children:H?"Drop here":"Empty"})]})]},z.id)};return u.jsxs("div",{className:"sidebar-scroll",ref:d,children:[u.jsxs("div",{className:`sidebar-section sidebar-docs-section ${R.has("docs")?"docs-collapsed":""}`,children:[u.jsxs("div",{className:"sidebar-section-header","data-section-key":"docs",onClick:()=>it("docs"),onContextMenu:qt,children:[u.jsx("span",{className:`sidebar-chevron ${R.has("docs")?"collapsed":""}`,children:"▾"}),u.jsx("span",{className:"sidebar-label",children:"Documents"}),u.jsx("button",{className:"sidebar-new-btn",onClick:M=>{M.stopPropagation(),nt({anchor:M.target.getBoundingClientRect()})},title:"New document",children:"+"})]}),!R.has("docs")&&u.jsxs("div",{className:"sidebar-section-list","data-drop-ws":"__docs__",children:[f&&!(h!=null&&h.parentDocId)&&(!h||!n.some(M=>M.filename===(h==null?void 0:h.wsFilename)))&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:f})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),vt.filter(M=>!x(M.filename)&&(!f||M.title!==f)).map((M,ne)=>{const ue=vt.map(Me=>({type:"doc",file:Me.filename,title:Me.title}));return zt(M,void 0,null,ue,ne)}),vt.length===0&&u.jsx("div",{className:"sidebar-empty",children:H?"Drop here to unassign":"No unassigned documents"})]})]}),n.map(M=>{var ct,gt,ve;const ne=((ct=M.workspace)==null?void 0:ct.root)||[],ue=R.has(M.filename),Me=((gt=M.workspace)==null?void 0:gt.autoAccept)===!0||M.autoAccept===!0;return u.jsxs("div",{className:`sidebar-section sidebar-workspace-section ${ue?"ws-collapsed":""} ${Ee(M.filename)?"dragging":""} ${(q==null?void 0:q.itemId)===M.filename?q.position==="before"?"drop-before":"drop-after":""}`,children:[u.jsxs("div",{className:"sidebar-section-header","data-section-key":M.filename,"data-ws-drag":M.filename,onPointerDown:z=>de(z,{type:"workspace",filename:M.filename},M.title),onClick:()=>!H&&it(M.filename),onContextMenu:z=>{var he;z.preventDefault(),z.stopPropagation(),yt({x:z.clientX,y:z.clientY,type:"workspace",wsFilename:M.filename,title:M.title,nodes:ne,autoAccept:((he=M.workspace)==null?void 0:he.autoAccept)===!0||M.autoAccept===!0})},children:[u.jsx("span",{className:`sidebar-chevron ${ue?"collapsed":""}`,children:"▾"}),G===M.filename?u.jsx("input",{className:"sidebar-rename-input",value:X,onChange:z=>re(z.target.value),onBlur:()=>{l.handleRenameWorkspace(M.filename,X),K(null)},onKeyDown:z=>{z.key==="Enter"&&(l.handleRenameWorkspace(M.filename,X),K(null)),z.key==="Escape"&&K(null)},autoFocus:!0,onClick:z=>z.stopPropagation()}):u.jsx("span",{className:"sidebar-label sidebar-workspace-label",onDoubleClick:z=>{z.stopPropagation(),K(M.filename),re(M.title)},children:M.title}),(((ve=M.workspace)==null?void 0:ve.autoAccept)===!0||M.autoAccept===!0)&&u.jsx("span",{className:"sidebar-auto-accept-dot",title:"Auto-accept on for this workspace"}),u.jsxs("div",{className:"sidebar-workspace-actions",children:[u.jsx("button",{className:"sidebar-new-btn",onClick:z=>{z.stopPropagation(),nt({anchor:z.target.getBoundingClientRect(),wsFilename:M.filename,containerId:null})},title:"New document",children:"+"}),u.jsx("button",{className:"sidebar-new-btn",onClick:z=>{z.stopPropagation(),l.handleCreateContainer(M.filename,null)},title:"New container",children:"☐"}),B===M.filename?u.jsxs("span",{className:"sidebar-inline-confirm",onClick:z=>z.stopPropagation(),children:[u.jsx("button",{onClick:()=>{l.handleDeleteWorkspace(M.filename),P(null)},children:"Yes"}),u.jsx("button",{onClick:()=>P(null),children:"No"})]}):u.jsx("button",{className:"sidebar-new-btn sidebar-workspace-delete",onClick:z=>{z.stopPropagation(),P(M.filename)},title:"Delete workspace",children:"×"})]})]}),!ue&&u.jsxs("div",{className:"sidebar-section-list","data-drop-ws":M.filename,children:[f&&!(h!=null&&h.parentDocId)&&(h==null?void 0:h.wsFilename)===M.filename&&(h.containerId===null||!o2(ne,h.containerId))&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:f})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),ne.filter(z=>z.type!=="doc"?!0:!(x(z.file)||f&&(h==null?void 0:h.wsFilename)===M.filename&&h.containerId===null&&z.title===f)).map((z,he)=>Ut(z,0,M.filename,null,ne,he,Me)),ne.length===0&&!f&&u.jsx("div",{className:"sidebar-empty",children:H?"Drop here to add":"Empty workspace"})]})]},M.filename)}),u.jsx("div",{className:"sidebar-new-workspace",children:u.jsx("button",{onClick:l.handleCreateWorkspace,children:"+ New Workspace"})}),Le&&u.jsx(wd,{x:Le.x,y:Le.y,filename:Le.wsFilename,title:Le.title,onClose:()=>yt(null),onDuplicate:()=>{},onRename:()=>{Le.type==="workspace"?(K(Le.wsFilename),re(Le.title)):Le.containerId&&(V(Le.containerId),Q(Le.title)),yt(null)},onArchive:()=>{},onDelete:()=>{Le.type==="workspace"?l.handleDeleteWorkspace(Le.wsFilename):Le.containerId&&l.handleDeleteContainer(Le.wsFilename,Le.containerId)},onPluginAction:()=>{},pluginItems:[],folderMode:!0,onNewDoc:M=>{nt({anchor:M.target.getBoundingClientRect(),wsFilename:Le.wsFilename,containerId:Le.type==="container"?Le.containerId:null}),yt(null)},onNewContainer:()=>{l.handleCreateContainer(Le.wsFilename,Le.type==="container"?Le.containerId:null),yt(null)},onAcceptAll:()=>{const M=new Set;yl(Le.nodes,M),M.size&&ie([...M],"accept"),yt(null)},onRejectAll:()=>{const M=new Set;yl(Le.nodes,M),M.size&&ie([...M],"reject"),yt(null)},folderAutoAccept:Le.autoAccept,folderAutoAcceptLabel:Le.type==="workspace"?"for workspace":"for container",onToggleFolderAutoAccept:()=>{fetch("/api/auto-accept/inherit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wsFile:Le.wsFilename,...Le.type==="container"?{containerId:Le.containerId}:{},enabled:!Le.autoAccept})}).catch(()=>{})}}),L&&u.jsx(wd,{x:L.x,y:L.y,filename:L.filename,title:L.title,onClose:()=>te(null),onDuplicate:()=>xe(L.filename),onRename:()=>{E(L.filename),O(L.title)},onArchive:()=>l.handleArchive(L.filename),onDelete:()=>l.handleDelete(L.filename),onPluginAction:(M,ne)=>Ye(M,ne,L.filename,L.title),pluginItems:ee,onSchedulePost:()=>{tt({filename:L.filename,title:L.title}),te(null)},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"),te(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:((Jt=t.find(M=>M.filename===L.filename))==null?void 0:Jt.autoAccept)===!0,onToggleAutoAccept:()=>{var ne;const M=((ne=t.find(ue=>ue.filename===L.filename))==null?void 0:ne.autoAccept)===!0;fetch("/api/auto-accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:L.filename,enabled:!M})}).then(()=>l.fetchDocs()).catch(()=>{})},isAlreadySent:!!L.lastSent,onMarkSent:()=>{const M=L.filename;l.getDocTags(M).includes("✓")&&l.handleRemoveTag(M,"✓"),i(M),setTimeout(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualPost:{postedAt:new Date().toISOString()}})}).then(()=>l.fetchDocs()).catch(()=>{})},100),te(null)}}),fe&&u.jsx(r2,{actionLabel:fe.label,docTitle:fe.title,onClose:()=>Te(null),onConfirm:M=>{const ne=ee.find(ue=>ue.action===fe.action);ne&&Ye(fe.action,ne,fe.filename,fe.title,M),Te(null)}}),se&&u.jsx(s2,{docId:se.docId,title:se.title,onClose:()=>be(null)}),Xe&&u.jsx(Cl,{filename:Xe.filename,title:Xe.title,onClose:()=>tt(null)}),st&&u.jsx(i2,{anchorRect:st.anchor,onClose:()=>nt(null),onSelect:M=>{nt(null),st.wsFilename?l.handleCreateInWorkspace(st.wsFilename,st.containerId??null,M):M?fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:M})}).catch(()=>{}):o()}}),Ke&&u.jsx("div",{ref:Fe,className:"sidebar-density-dropdown",style:{position:"fixed",left:Ke.x,top:Ke.y,zIndex:200},children:q5.map(M=>u.jsx("button",{className:`sidebar-density-option ${je===M.id?"active":""}`,onClick:()=>Nt(M.id),children:M.label},M.id))})]})}function K5({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,onCreateDocument:i,actions:o,scrollRef:l,searchQuery:d,searchResults:f}){const[h,m]=S.useState(null);if(f!==null)return u.jsx($d,{results:f,query:d,onSwitchDocument:s});const g=[...t].sort((k,E)=>new Date(E.lastModified).getTime()-new Date(k.lastModified).getTime()),y=[];let b="";for(const k of g){const E=B5(k.lastModified);E!==b&&(y.push({label:E,docs:[]}),b=E),y[y.length-1].docs.push(k)}const x=k=>{for(const E of e){if(!E.workspace)continue;const C=O=>{for(const _ of O)if(_.type==="doc"&&_.file===k||_.type==="container"&&C(_.items))return!0;return!1};if(C(E.workspace.root))return E.title}return null};return u.jsxs("div",{className:"sidebar-scroll tl-scroll",ref:l,children:[u.jsxs("div",{className:"tl-header",children:[u.jsx("span",{className:"tl-title",children:"Timeline"}),u.jsx("button",{className:"sidebar-new-btn",onClick:i,title:"New document",children:"+"})]}),y.map(k=>u.jsxs("div",{className:"tl-group",children:[u.jsx("div",{className:"tl-date",children:k.label}),k.docs.map(E=>{const C=x(E.filename);return u.jsxs("div",{className:`tl-item ${E.isActive?"active":""}`,onClick:()=>!E.isActive&&s(E.filename),children:[u.jsx("div",{className:"tl-dot"}),u.jsxs("div",{className:"tl-content",children:[u.jsxs("div",{className:"tl-item-title",children:[u.jsx("span",{children:E.title}),r.filenames.includes(E.filename)&&u.jsx("span",{className:"sidebar-pending-dot"})]}),ks(E.filename)&&u.jsx("div",{className:"tl-item-context",children:e2(E.filename)}),u.jsxs("div",{className:"tl-item-meta",children:[E.wordCount.toLocaleString()," words · ",ea(E.lastModified)]}),C&&u.jsx("div",{className:"tl-badge",children:C})]}),h===E.filename?u.jsxs("div",{className:"sidebar-confirm-delete",onClick:O=>O.stopPropagation(),children:[u.jsx("span",{children:ks(E.filename)?"Remove?":"Delete?"}),u.jsx("button",{onClick:()=>{o.handleDelete(E.filename),m(null)},children:"Yes"}),u.jsx("button",{onClick:()=>m(null),children:"No"})]}):u.jsx("button",{className:"sidebar-delete-btn",onClick:O=>{O.stopPropagation(),m(E.filename)},title:ks(E.filename)?"Remove":"Delete",children:"×"})]},E.filename)})]},k.label)),t.length===0&&u.jsx("div",{className:"sidebar-empty",children:"No documents yet"})]})}function G5({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:o,searchQuery:l,searchResults:d,onSearchChange:f}){const[h,m]=S.useState([]),[g,y]=S.useState(null),[b,x]=S.useState(null),k=S.useRef(null);S.useEffect(()=>{if(!g)return;const A=L=>{k.current&&!k.current.contains(L.target)&&y(null)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[g]);const E=(A,L)=>{for(const te of A)if(te.type==="container"){if(te.id===L)return te;const se=E(te.items,L);if(se)return se}return null},C=A=>{let L=0;for(const te of A)te.type==="doc"?L++:te.type==="container"&&(L+=C(te.items));return L},O=A=>{const L=[];for(const te of A)te.type==="doc"?L.push(te.file):te.type==="container"&&L.push(...O(te.items));return L},_=S.useMemo(()=>{if(h.length===0)return[];const A=h[h.length-1],L=e.find(se=>se.filename===A.wsFilename);if(!(L!=null&&L.workspace))return[];if(A.type==="workspace")return L.workspace.root;const te=E(L.workspace.root,A.key);return te?te.items:[]},[h,e]),T=_.filter(A=>A.type==="container"),R=S.useMemo(()=>{const A=_.filter(L=>L.type==="doc").map(L=>L.file);return t.filter(L=>A.includes(L.filename))},[_,t]),I=A=>{const L=O(A.items);return t.filter(te=>L.includes(te.filename))},B=A=>{const L=e.find(se=>se.filename===A);if(!(L!=null&&L.workspace))return[];const te=O(L.workspace.root);return t.filter(se=>te.includes(se.filename))},P=S.useMemo(()=>t.filter(A=>!n.has(A.filename)),[t,n]),D=A=>{m(L=>[...L,A]),y(null)},V=()=>{m(A=>A.slice(0,-1)),y(null)},$=(A,L)=>{if(g===A){y(null);return}const se=L.currentTarget.getBoundingClientRect();x({top:se.bottom+4,left:se.left}),y(A)},Q=A=>{s(A),y(null)},G=h.length>1?h[h.length-2].title:"All",K=S.useRef(null),X=S.useRef(null),[re,J]=S.useState(null),oe=S.useCallback(A=>{const te=A.currentTarget.getBoundingClientRect();J({top:te.bottom+4,left:te.left})},[]);S.useEffect(()=>{if(!d)return;const A=L=>{X.current&&!X.current.contains(L.target)&&K.current&&!K.current.contains(L.target)&&f("")};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[d,f]);const U=()=>{if(!g)return[];if(g==="__unassigned__")return P;if(g==="__level-docs__")return R;const A=e.find(L=>L.filename===g);if(A)return B(A.filename);for(const L of e){if(!L.workspace)continue;const te=E(L.workspace.root,g);if(te)return I(te)}return[]};return u.jsxs("div",{className:"board-scroll",ref:o,children:[u.jsxs("div",{className:"board-search-pill",children:[u.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:[u.jsx("circle",{cx:"11",cy:"11",r:"8"}),u.jsx("path",{d:"m21 21-4.3-4.3"})]}),u.jsx("input",{ref:K,className:"board-search-input",type:"text",placeholder:"Search...",value:l,onChange:A=>f(A.target.value),onFocus:oe}),l&&u.jsx("button",{className:"board-search-clear",onClick:()=>f(""),children:"×"})]}),h.length===0?u.jsx("button",{className:"board-back board-back--static",tabIndex:-1,children:"All"}):u.jsxs("button",{className:"board-back",onClick:V,title:`Back to ${G}`,children:["← ",G]}),h.length===0&&u.jsxs(u.Fragment,{children:[P.length>0&&u.jsxs("button",{className:`board-chip ${g==="__unassigned__"?"open":""}`,onClick:A=>$("__unassigned__",A),children:["Documents ",u.jsx("span",{className:"board-chip-count",children:P.length})]}),e.map(A=>{var te;const L=(te=A.workspace)==null?void 0:te.root.some(se=>se.type==="container");return u.jsxs("button",{className:`board-chip ${g===A.filename?"open":""}`,onClick:se=>L?D({type:"workspace",key:A.filename,title:A.title,wsFilename:A.filename}):$(A.filename,se),children:[A.title," ",u.jsx("span",{className:"board-chip-count",children:A.docCount}),L&&u.jsx("span",{className:"board-chip-arrow",children:"›"})]},A.filename)}),u.jsx("button",{className:"board-chip board-chip-add",onClick:i.handleCreateWorkspace,title:"New workspace",children:"+"})]}),h.length>0&&u.jsxs(u.Fragment,{children:[R.length>0&&u.jsxs("button",{className:`board-chip board-chip-docs ${g==="__level-docs__"?"open":""}`,onClick:A=>$("__level-docs__",A),children:["Docs ",u.jsx("span",{className:"board-chip-count",children:R.length})]}),T.map(A=>{const L=A.items.some(te=>te.type==="container");return u.jsxs("button",{className:`board-chip ${g===A.id?"open":""}`,onClick:te=>L?D({type:"container",key:A.id,title:A.name,wsFilename:h[h.length-1].wsFilename}):$(A.id,te),children:[A.name," ",u.jsx("span",{className:"board-chip-count",children:C(A.items)}),L&&u.jsx("span",{className:"board-chip-arrow",children:"›"})]},A.id)})]}),g&&b&&(()=>{const A=U();return u.jsxs("div",{className:"board-dropdown",ref:k,style:{position:"fixed",top:b.top,left:b.left},children:[A.map(L=>u.jsxs("div",{className:`board-dropdown-item ${L.isActive?"active":""}`,onClick:()=>Q(L.filename),children:[u.jsxs("span",{className:"board-dropdown-title",children:[L.title,r.filenames.includes(L.filename)&&u.jsx("span",{className:"board-pending-dot"})]}),u.jsxs("span",{className:"board-dropdown-meta",children:[L.wordCount.toLocaleString()," words · ",ea(L.lastModified)]})]},L.filename)),A.length===0&&u.jsx("div",{className:"board-dropdown-empty",children:"No documents"})]})})(),d&&re&&u.jsxs("div",{className:"board-dropdown board-search-dropdown",ref:X,style:{position:"fixed",top:re.top,left:re.left},children:[d.map(A=>u.jsxs("div",{className:`board-dropdown-item ${A.isActive?"active":""}`,onClick:()=>{s(A.filename),f("")},children:[u.jsx("span",{className:"board-dropdown-title",children:A.title}),A.matchType==="tag"&&A.matchedTag&&u.jsxs("span",{className:"board-dropdown-meta",children:["Tag: ",A.matchedTag]}),A.matchType==="content"&&A.snippet&&u.jsx("span",{className:"board-dropdown-meta board-search-snippet",children:A.snippet}),u.jsxs("span",{className:"board-dropdown-meta",children:[A.wordCount.toLocaleString()," words · ",ea(A.lastModified)]})]},A.filename)),d.length===0&&u.jsx("div",{className:"board-dropdown-empty",children:"No results"})]})]})}function J5({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:o,searchQuery:l,searchResults:d}){const[f,h]=S.useState([]);if(d!==null)return u.jsx($d,{results:d,query:l,onSwitchDocument:s});const m=(_,T)=>{for(const R of _)if(R.type==="container"){if(R.id===T)return R;const I=m(R.items,T);if(I)return I}return null},g=_=>{let T=0;for(const R of _)R.type==="doc"?T++:R.type==="container"&&(T+=g(R.items));return T},y=S.useMemo(()=>{if(f.length===0)return[];const _=f[f.length-1],T=e.find(I=>I.filename===_.wsFilename);if(!(T!=null&&T.workspace))return[];if(_.type==="workspace")return T.workspace.root;const R=m(T.workspace.root,_.key);return R?R.items:[]},[f,e]),b=y.filter(_=>_.type==="container"),x=S.useMemo(()=>{if(f.length===0)return t.filter(T=>!n.has(T.filename));const _=y.filter(T=>T.type==="doc").map(T=>T.file);return t.filter(T=>_.includes(T.filename))},[f,y,t,n]),k=_=>h(T=>[...T,_]),E=()=>h(_=>_.slice(0,-1)),C=f.length>1?f[f.length-2].title:"Shelf",O=f.length>0?f[f.length-1].title:"Documents";return u.jsxs("div",{className:"shelf-wrapper",children:[u.jsxs("div",{className:"shelf-spines",ref:o,children:[f.length>0&&u.jsxs("button",{className:"shelf-back",onClick:E,title:`Back to ${C}`,children:[u.jsx("span",{className:"shelf-back-arrow",children:"←"}),u.jsx("span",{className:"shelf-back-label",children:C})]}),f.length===0&&u.jsxs(u.Fragment,{children:[e.map(_=>u.jsxs("div",{className:"shelf-section-spine",onClick:()=>k({type:"workspace",key:_.filename,title:_.title,wsFilename:_.filename}),title:_.title,children:[u.jsx("span",{className:"shelf-section-title",children:_.title}),u.jsx("span",{className:"shelf-section-count",children:_.docCount})]},_.filename)),u.jsx("button",{className:"shelf-add",onClick:i.handleCreateWorkspace,title:"New workspace",children:"+"})]}),f.length>0&&b.map(_=>u.jsxs("div",{className:"shelf-section-spine shelf-section-container",onClick:()=>k({type:"container",key:_.id,title:_.name,wsFilename:f[f.length-1].wsFilename}),title:_.name,children:[u.jsx("span",{className:"shelf-section-title",children:_.name}),u.jsx("span",{className:"shelf-section-count",children:g(_.items)})]},_.id))]}),u.jsxs("div",{className:"shelf-docs",children:[u.jsx("div",{className:"shelf-docs-header",children:O}),u.jsxs("div",{className:"shelf-docs-list",children:[x.map(_=>u.jsxs("div",{className:`shelf-doc-item ${_.isActive?"active":""}`,onClick:()=>s(_.filename),children:[u.jsxs("div",{className:"shelf-doc-title",children:[u.jsx("span",{children:_.title}),r.filenames.includes(_.filename)&&u.jsx("span",{className:"shelf-pending-dot"})]}),u.jsxs("div",{className:"shelf-doc-meta",children:[_.wordCount.toLocaleString()," words · ",ea(_.lastModified)]})]},_.filename)),x.length===0&&u.jsx("div",{className:"shelf-docs-empty",children:"No documents"})]})]})]})}const Y5=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.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"}),u.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14",opacity:"0.5"})]}),X5=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),u.jsx("polyline",{points:"14 2 14 8 20 8"}),u.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),u.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]}),Q5=()=>u.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:u.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"})}),Z5=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[u.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"}),u.jsx("path",{d:"M7 15l-4-3.5L7 8",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),e8=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[u.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"}),u.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"})]}),t8=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[u.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"}),u.jsx("rect",{x:"2",y:"16",width:"8",height:"7",rx:"1.5",fill:"none",stroke:"currentColor",strokeWidth:"1.5"}),u.jsx("line",{x1:"4",y1:"18.5",x2:"8",y2:"18.5",stroke:"currentColor",strokeWidth:"1",opacity:"0.7"}),u.jsx("line",{x1:"4",y1:"20.5",x2:"7",y2:"20.5",stroke:"currentColor",strokeWidth:"1",opacity:"0.7"})]}),n8=()=>u.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:u.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"})}),r8=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),u.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),s8=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("path",{d:"M2 12h20"}),u.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"})]}),aw=()=>u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"20 6 9 17 4 12"})});function i8({type:t}){switch(t){case"tweet":return u.jsx(Q5,{});case"reply":return u.jsx(Z5,{});case"quote":return u.jsx(e8,{});case"article":return u.jsx(t8,{});case"linkedin":return u.jsx(n8,{});case"newsletter":return u.jsx(r8,{});case"blog":return u.jsx(s8,{});default:return u.jsx(X5,{})}}function Eu(t){let e=0;for(const n of t)n.type==="doc"?e++:n.type==="container"&&(e+=Eu(n.items));return e}function l2(t,e){for(const n of t){if(n.type==="doc"&&n.file===e)return[];if(n.type==="container"){const r=l2(n.items,e);if(r)return[n.id,...r]}}return null}function lw(t){const e=new Set;return yl(t,e),[...e]}function c2(t,e,n=0){for(const r of t)if(r.type==="container"){if(r.id===e)return n;const s=c2(r.items,e,n+1);if(s>=0)return s}return-1}function o8(t,e){if(!e)return 12;for(const n of t){if(!n.workspace)continue;const r=c2(n.workspace.root,e);if(r>=0)return 12+(r+1)*16}return 12}function a8({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:y}){var qe;const b=W=>!!h&&h.has(W),[x,k]=S.useState(()=>{try{const W=localStorage.getItem("ow-files-collapsed");return W?new Set(JSON.parse(W)):new Set}catch{return new Set}}),{draggedItem:E,dropIndicator:C,handlePointerDown:O,dropClass:_,isDragging:T,isContainerDropTarget:R}=n2({docs:t,workspaces:e,assignedFiles:n,scrollRef:l,setCollapsedSections:k}),I=W=>!C||C.itemId!==W||C.position==="inside"?void 0:{"--drop-indent":`${o8(e,C.containerId)}px`},{variantsByMaster:B,variantFilenames:P}=S.useMemo(()=>{const W=new Map,pe=new Set;for(const xe of t)if(xe.masterDocId){const Ye=W.get(xe.masterDocId)||[];Ye.push(xe),W.set(xe.masterDocId,Ye),pe.add(xe.filename)}return{variantsByMaster:W,variantFilenames:pe}},[t]),[D,V]=S.useState(null),[$,Q]=S.useState(null),[G,K]=S.useState(new Set),[X,re]=S.useState(null),[J,oe]=S.useState([]),[U,A]=S.useState(null),[L,te]=S.useState(null),[se,be]=S.useState(null),[ee,ge]=S.useState(null),[fe,Te]=S.useState(null),[Xe,tt]=S.useState(new Set);S.useEffect(()=>{tt(new Set)},[r]);const st=S.useCallback(()=>{fetch("/api/plugins").then(W=>W.json()).then(W=>{const pe=[];for(const xe of W.plugins||[]){const Ye=xe.displayName||void 0;for(const it of xe.sidebarMenuItems||[])pe.push({...it,pluginDisplayName:Ye})}oe(pe)}).catch(()=>{})},[]);S.useEffect(()=>{st()},[st]),S.useEffect(()=>{const W=()=>st();return window.addEventListener("ow-plugins-changed",W),()=>window.removeEventListener("ow-plugins-changed",W)},[st]);const nt=S.useCallback((W,pe)=>{if(W.preventDefault(),W.stopPropagation(),G.has(pe.filename)&&G.size>1){Q({x:W.clientX,y:W.clientY,filename:pe.filename,title:pe.title,bulkCount:G.size});return}G.size>0&&!G.has(pe.filename)&&K(new Set),Q({x:W.clientX,y:W.clientY,filename:pe.filename,title:pe.title,docId:pe.docId,lastSent:pe.lastSent,postedUrl:pe.postedUrl,isNewsletter:pe.isNewsletter})},[G]),Le=S.useCallback(W=>{fetch("/api/documents/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:W})}).catch(()=>{})},[]),yt=S.useCallback((W,pe,xe,Ye,it)=>{if(pe.promptForFocus&&it===void 0){A({action:W,label:pe.label,filename:xe,title:Ye});return}fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:W,filename:xe,title:Ye,instructions:it||"",label:pe.label})}).catch(()=>{})},[]),Ke=S.useCallback((W,pe)=>{tt(xe=>{const Ye=new Set(xe);for(const it of W)Ye.add(it);return Ye}),fetch("/api/documents/batch-resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filenames:W,action:pe})}).catch(()=>{})},[]),Et=W=>{k(pe=>{const xe=new Set(pe);return xe.has(W)?xe.delete(W):xe.add(W),localStorage.setItem("ow-files-collapsed",JSON.stringify([...xe])),xe})},je=(W,pe,xe,Ye)=>{V({type:W,key:pe,value:xe,wsFilename:Ye})},Je=()=>{if(!D)return;const{type:W,key:pe,value:xe,wsFilename:Ye}=D;W==="doc"?o.handleRename(pe,"",xe):W==="workspace"?o.handleRenameWorkspace(pe,xe):W==="container"&&Ye&&o.handleRenameContainer(Ye,pe,xe),V(null)},Fe=t.find(W=>W.isActive),Nt=S.useRef(e);Nt.current=e,S.useEffect(()=>{var W;if(Fe)for(const pe of Nt.current){const xe=l2(((W=pe.workspace)==null?void 0:W.root)||[],Fe.filename);if(xe){k(Ye=>{const it=[pe.filename,...xe.map(Re=>`container-${Re}`)];if(it.every(Re=>!Ye.has(Re)))return Ye;const ot=new Set(Ye);for(const Re of it)ot.delete(Re);return localStorage.setItem("ow-files-collapsed",JSON.stringify([...ot])),ot});break}}},[Fe==null?void 0:Fe.filename]);const qt=S.useMemo(()=>t.filter(W=>!n.has(W.filename)&&!P.has(W.filename)&&!b(W.filename)),[t,n,P,h]),ie=S.useMemo(()=>{var Ye;const W=[],pe=it=>{W.push(it.filename);const ot=it.docId?B.get(it.docId):void 0,Re=it.docId&&!x.has(`variants-${it.docId}`);if(ot&&Re)for(const vt of ot)W.push(vt.filename)},xe=it=>{for(const ot of it)if(ot.type==="doc"){const Re=t.find(vt=>vt.filename===ot.file);Re&&!P.has(Re.filename)&&pe(Re)}else x.has(`container-${ot.id}`)||xe(ot.items)};x.has("docs")||qt.forEach(pe);for(const it of e)x.has(it.filename)||xe(((Ye=it.workspace)==null?void 0:Ye.root)||[]);return W},[t,e,qt,P,B,x]),H=S.useCallback(()=>{K(new Set)},[]),q=S.useCallback((W,pe)=>{if(E)return;const xe=W.shiftKey,Ye=W.ctrlKey||W.metaKey;if(xe){const ot=X||(Fe==null?void 0:Fe.filename)||pe,Re=ie.indexOf(ot),vt=ie.indexOf(pe);if(Re<0||vt<0){K(new Set([pe])),re(pe);return}const[ht,zt]=Re<vt?[Re,vt]:[vt,Re];K(new Set(ie.slice(ht,zt+1)));return}if(Ye){K(ot=>{const Re=new Set(ot);return Re.has(pe)?Re.delete(pe):Re.add(pe),Re}),re(pe);return}K(new Set),re(pe);const it=t.find(ot=>ot.filename===pe);it&&!it.isActive&&s(pe)},[E,X,Fe==null?void 0:Fe.filename,ie,s,t]);S.useEffect(()=>{if(G.size===0)return;const W=pe=>{pe.key==="Escape"&&H()};return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[G.size,H]);const de=S.useCallback(()=>{for(const W of G)o.handleDelete(W);K(new Set),re(null)},[G,o]);if(g!==null)return u.jsx($d,{results:g,query:m,onSwitchDocument:s,actions:o});const me=W=>u.jsx("input",{className:"sidebar-rename-input",value:D.value,onChange:pe=>V(xe=>xe?{...xe,value:pe.target.value}:null),onBlur:W,onKeyDown:pe=>{pe.key==="Enter"&&W(),pe.key==="Escape"&&V(null)},autoFocus:!0,onClick:pe=>pe.stopPropagation()}),Ee=(W,pe,xe,Ye,it,ot=!1)=>u.jsxs("div",{className:`files-row${W.isActive?" active":""}${G.has(W.filename)?" selected":""} ${T(W.filename)?"dragging":""} ${_(W.filename)}${W.masterDocId?" is-variant":""}`,style:{paddingLeft:pe,...I(W.filename)},"data-drag-id":W.filename,"data-drag-type":"doc","data-drag-ws":xe||"__docs__","data-drag-container":Ye||"",onPointerDown:Re=>O(Re,{type:"doc",file:W.filename,sourceWs:xe||null},W.title),onClick:Re=>q(Re,W.filename),onDoubleClick:()=>je("doc",W.filename,W.title),onContextMenu:Re=>nt(Re,W),children:[u.jsx("span",{className:"files-row-icon",children:u.jsx(i8,{type:W.contentType})}),(D==null?void 0:D.type)==="doc"&&D.key===W.filename?me(Je):u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"files-row-label",children:W.title}),W.variantType&&u.jsx("span",{className:"files-badge-variant",children:W.variantType}),(W.autoAccept||ot)&&u.jsx("span",{className:"sidebar-auto-accept-dot",title:W.autoAccept?"Auto-accept on":"Auto-accept inherited"}),r.filenames.includes(W.filename)&&!Xe.has(W.filename)&&u.jsx("span",{className:"files-badge-pending"}),o.getDocTags(W.filename).includes("✓")&&u.jsx("span",{className:"files-badge-approved",children:u.jsx(aw,{})}),W.lastSent&&u.jsx("span",{className:"files-badge-sent",children:u.jsx(aw,{})}),it&&u.jsx("span",{className:`files-row-chevron${x.has(`variants-${W.docId}`)?" collapsed":""}`,onClick:Re=>{Re.stopPropagation(),Et(`variants-${W.docId}`)},children:u.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"6 9 12 15 18 9"})})})]})]},W.filename),De=(W,pe,xe,Ye,it=!1)=>{const ot=W.docId?B.get(W.docId):void 0,Re=!!(ot&&ot.length>0),vt=d&&(f==null?void 0:f.parentDocId)&&f.parentDocId===W.docId,ht=Re||vt,zt=!x.has(`variants-${W.docId}`);return ht?u.jsxs("div",{className:"files-variant-group",children:[Ee(W,pe,xe,Ye,Re,it),zt&&(ot==null?void 0:ot.map(Ut=>Ee(Ut,pe+16,xe,Ye,!1,it))),vt&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:pe+16},children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:d})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]})]},`vg-${W.filename}`):Ee(W,pe,xe,Ye,!1,it)},$e=(W,pe,xe,Ye,it=!1)=>{const ot=12+pe*16;if(W.type==="doc"){const M=t.find(ne=>ne.filename===W.file);return!M||P.has(M.filename)?null:De(M,ot,xe,Ye,it)}const Re=W,vt=`container-${Re.id}`,ht=x.has(vt),zt=Eu(Re.items),Ut=Re.autoAccept===!0,Jt=Ut||it;return u.jsxs("div",{className:`${_(Re.id)} ${R(Re.id)?"files-drop-inside":""}`,children:[u.jsxs("div",{className:`files-row is-container ${T(Re.id)?"dragging":""} ${_(Re.id)}`,style:{paddingLeft:ot,...I(Re.id)},"data-drag-id":Re.id,"data-drag-type":"container-header","data-drag-ws":xe,"data-drag-parent":Ye||"","data-section-key":vt,onPointerDown:M=>O(M,{type:"container",id:Re.id,sourceWs:xe},Re.name),onClick:()=>!E&&Et(vt),onDoubleClick:M=>{M.stopPropagation(),je("container",Re.id,Re.name,xe)},onContextMenu:M=>{M.preventDefault(),M.stopPropagation(),Te({x:M.clientX,y:M.clientY,type:"container",wsFilename:xe,containerId:Re.id,title:Re.name,nodes:Re.items,autoAccept:Ut})},children:[u.jsx("span",{className:"files-row-icon",children:u.jsx(Y5,{})}),(D==null?void 0:D.type)==="container"&&D.key===Re.id?me(Je):u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"files-row-label",children:Re.name}),Jt&&u.jsx("span",{className:"sidebar-auto-accept-dot",title:Ut?"Auto-accept on for this container":"Auto-accept inherited from workspace"}),u.jsx("span",{className:"files-row-count",children:zt})]})]}),u.jsxs("div",{className:`files-children${ht?" collapsed":""}`,"data-drop-ws":xe,"data-drop-container":Re.id,children:[d&&!(f!=null&&f.parentDocId)&&(f==null?void 0:f.wsFilename)===xe&&f.containerId===Re.id&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:d})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),Re.items.filter(M=>M.type!=="doc"||!b(M.file)).map(M=>$e(M,pe+1,xe,Re.id,Jt))]})]},Re.id)};return u.jsxs("div",{className:"files-scroll",ref:l,children:[u.jsxs("div",{className:"files-section",children:[u.jsxs("div",{className:"files-row is-section","data-section-key":"docs",onClick:()=>Et("docs"),children:[u.jsx("span",{className:`files-row-chevron leading${x.has("docs")?" collapsed":""}`,children:u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"6 9 12 15 18 9"})})}),u.jsx("span",{className:"files-row-label",children:"Documents"}),u.jsx("button",{className:"files-section-btn",onClick:W=>{W.stopPropagation(),ge({anchor:W.target.getBoundingClientRect()})},title:"New document",children:"+"})]}),u.jsxs("div",{className:`files-section-list files-children${x.has("docs")?" collapsed":""}`,"data-drop-ws":"__docs__",children:[d&&!(f!=null&&f.parentDocId)&&(!f||!e.some(W=>W.filename===(f==null?void 0:f.wsFilename)))&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:d})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),qt.map(W=>De(W,28))]})]}),e.map(W=>{var ot,Re,vt;const pe=((ot=W.workspace)==null?void 0:ot.root)||[],xe=x.has(W.filename),Ye=Eu(pe),it=((Re=W.workspace)==null?void 0:Re.autoAccept)===!0||W.autoAccept===!0;return u.jsxs("div",{className:`files-section ${T(W.filename)?"dragging":""} ${(C==null?void 0:C.itemId)===W.filename?C.position==="before"?"files-ws-drop-before":"files-ws-drop-after":""}`,children:[u.jsx("div",{className:`files-row is-section${(C==null?void 0:C.itemId)==="__section__"&&C.wsFilename===W.filename&&C.position==="inside"?" files-ws-drop-target":""}`,"data-section-key":W.filename,"data-ws-drag":W.filename,onPointerDown:ht=>O(ht,{type:"workspace",filename:W.filename},W.title),onClick:()=>!E&&Et(W.filename),onDoubleClick:ht=>{ht.stopPropagation(),je("workspace",W.filename,W.title)},onContextMenu:ht=>{var zt;ht.preventDefault(),ht.stopPropagation(),Te({x:ht.clientX,y:ht.clientY,type:"workspace",wsFilename:W.filename,title:W.title,nodes:pe,autoAccept:((zt=W.workspace)==null?void 0:zt.autoAccept)===!0||W.autoAccept===!0})},children:(D==null?void 0:D.type)==="workspace"&&D.key===W.filename?u.jsxs(u.Fragment,{children:[u.jsx("span",{className:`files-row-chevron leading${xe?" collapsed":""}`,children:u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"6 9 12 15 18 9"})})}),me(Je)]}):u.jsxs(u.Fragment,{children:[u.jsx("span",{className:`files-row-chevron leading${xe?" collapsed":""}`,children:u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"6 9 12 15 18 9"})})}),u.jsx("span",{className:"files-row-label",children:W.title}),(((vt=W.workspace)==null?void 0:vt.autoAccept)===!0||W.autoAccept===!0)&&u.jsx("span",{className:"sidebar-auto-accept-dot",title:"Auto-accept on for this workspace"}),u.jsx("span",{className:"files-row-count",children:Ye}),u.jsxs("div",{className:"files-section-actions",children:[u.jsx("button",{className:"files-section-btn",onClick:ht=>{ht.stopPropagation(),ge({anchor:ht.target.getBoundingClientRect(),wsFilename:W.filename,containerId:null})},title:"New document",children:"+"}),u.jsx("button",{className:"files-section-btn",onClick:ht=>{ht.stopPropagation(),o.handleCreateContainer(W.filename,null)},title:"New container",children:"☐"})]})]})}),u.jsxs("div",{className:`files-section-list files-children${xe?" collapsed":""}`,"data-drop-ws":W.filename,children:[d&&!(f!=null&&f.parentDocId)&&(f==null?void 0:f.wsFilename)===W.filename&&(f.containerId===null||!pe.some(ht=>ht.type==="container"&&ht.id===f.containerId))&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:d})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),pe.filter(ht=>ht.type!=="doc"||!b(ht.file)).map(ht=>$e(ht,1,W.filename,null,it))]})]},W.filename)}),u.jsx("div",{className:"files-new-ws",children:u.jsx("button",{onClick:o.handleCreateWorkspace,children:"+ New Workspace"})}),fe&&u.jsx(wd,{x:fe.x,y:fe.y,filename:fe.wsFilename,title:fe.title,onClose:()=>Te(null),onDuplicate:()=>{},onRename:()=>{fe.type==="workspace"?je("workspace",fe.wsFilename,fe.title):fe.containerId&&je("container",fe.containerId,fe.title,fe.wsFilename),Te(null)},onArchive:()=>{},onDelete:()=>{fe.type==="workspace"?o.handleDeleteWorkspace(fe.wsFilename):fe.containerId&&o.handleDeleteContainer(fe.wsFilename,fe.containerId,!1)},folderDocCount:fe.type==="container"?Eu(fe.nodes):0,onDeleteWithDocs:fe.type==="container"&&fe.containerId?()=>{o.handleDeleteContainer(fe.wsFilename,fe.containerId,!0)}:void 0,onPluginAction:()=>{},pluginItems:[],folderMode:!0,onNewDoc:W=>{ge({anchor:W.target.getBoundingClientRect(),wsFilename:fe.wsFilename,containerId:fe.type==="container"?fe.containerId:null}),Te(null)},onNewContainer:()=>{o.handleCreateContainer(fe.wsFilename,fe.type==="container"?fe.containerId:null),Te(null)},onAcceptAll:()=>{const W=lw(fe.nodes);W.length&&Ke(W,"accept"),Te(null)},onRejectAll:()=>{const W=lw(fe.nodes);W.length&&Ke(W,"reject"),Te(null)},folderAutoAccept:fe.autoAccept,folderAutoAcceptLabel:fe.type==="workspace"?"for workspace":"for container",onToggleFolderAutoAccept:()=>{fetch("/api/auto-accept/inherit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wsFile:fe.wsFilename,...fe.type==="container"?{containerId:fe.containerId}:{},enabled:!fe.autoAccept})}).catch(()=>{})}}),$&&u.jsx(wd,{x:$.x,y:$.y,filename:$.filename,title:$.title,bulkCount:$.bulkCount,onBulkDelete:de,onClose:()=>Q(null),onDuplicate:()=>Le($.filename),onRename:()=>{je("doc",$.filename,$.title),Q(null)},onArchive:()=>o.handleArchive($.filename),onDelete:()=>o.handleDelete($.filename),onPluginAction:(W,pe)=>yt(W,pe,$.filename,$.title),pluginItems:J,onSchedulePost:()=>{te({filename:$.filename,title:$.title}),Q(null)},onViewAnalytics:$.docId&&$.lastSent&&($.postedUrl||$.isNewsletter)?()=>{$.isNewsletter?be({docId:$.docId,title:$.title}):$.postedUrl&&window.open($.postedUrl,"_blank"),Q(null)}:void 0,viewAnalyticsLabel:$.isNewsletter?"View Analytics":$.postedUrl?"View on X":"View Analytics",isApproved:o.getDocTags($.filename).includes("✓"),onToggleApprove:()=>{o.getDocTags($.filename).includes("✓")?o.handleRemoveTag($.filename,"✓"):(o.handleAddTag($.filename,"✓"),setTimeout(()=>window.dispatchEvent(new CustomEvent("ow-accept-all")),50))},isAutoAccept:((qe=t.find(W=>W.filename===$.filename))==null?void 0:qe.autoAccept)===!0,onToggleAutoAccept:()=>{var pe;const W=((pe=t.find(xe=>xe.filename===$.filename))==null?void 0:pe.autoAccept)===!0;fetch("/api/auto-accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:$.filename,enabled:!W})}).then(()=>o.fetchDocs()).catch(()=>{})},isAlreadySent:!!$.lastSent,onMarkSent:()=>{const W=$.filename;o.getDocTags(W).includes("✓")&&o.handleRemoveTag(W,"✓"),s(W),setTimeout(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualPost:{postedAt:new Date().toISOString()}})}).then(()=>o.fetchDocs()).catch(()=>{})},100),Q(null)}}),U&&u.jsx(r2,{actionLabel:U.label,docTitle:U.title,onClose:()=>A(null),onConfirm:W=>{const pe=J.find(xe=>xe.action===U.action);pe&&yt(U.action,pe,U.filename,U.title,W),A(null)}}),se&&u.jsx(s2,{docId:se.docId,title:se.title,onClose:()=>be(null)}),L&&u.jsx(Cl,{filename:L.filename,title:L.title,onClose:()=>te(null)}),ee&&u.jsx(i2,{anchorRect:ee.anchor,onClose:()=>ge(null),onSelect:W=>{ge(null),ee.wsFilename?o.handleCreateInWorkspace(ee.wsFilename,ee.containerId??null,W):W?fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:W})}).catch(()=>{}):i()}})]})}const l8=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],c8=[{value:"any",label:"Any"},{value:"content_type",label:"Content Type"},{value:"connection",label:"Connection"}],u2=["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 cw(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 u8(t){if(t.length>0)return t[0].timezone;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;if(u2.includes(e))return e}catch{}return"America/New_York"}function d8({slots:t,onBack:e}){const[n,r]=S.useState(t),[s,i]=S.useState(()=>u8(t)),[o,l]=S.useState(!1),[d,f]=S.useState("09:00"),[h,m]=S.useState(["default"]),[g,y]=S.useState("any"),[b,x]=S.useState(!1),k=S.useRef(null);S.useEffect(()=>{if(!o)return;function T(R){k.current&&!k.current.contains(R.target)&&l(!1)}return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[o]);async function E(T){i(T);const R=[];for(const I of n){const B=await fetch(`/api/scheduler/slots/${I.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({timezone:T})});if(B.ok){const P=await B.json();R.push(P.slot)}else R.push(I)}R.length>0&&r(R)}async function C(){const T=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(T.ok){const R=await T.json();r(I=>[...I,R.slot]),x(!1),f("09:00"),m(["default"]),y("any")}}async function O(T){(await fetch(`/api/scheduler/slots/${T}`,{method:"DELETE"})).ok&&r(I=>I.filter(B=>B.id!==T))}function _(T){m(R=>{if(T==="default")return["default"];const I=R.filter(B=>B!=="default");if(I.includes(T)){const B=I.filter(P=>P!==T);return B.length===0?["default"]:B}return[...I,T]})}return u.jsxs("div",{className:"sidebar-schedule",children:[u.jsxs("div",{className:"sidebar-schedule-header",children:[u.jsx("button",{className:"sidebar-schedule-btn",onClick:e,title:"Back",children:u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"m15 18-6-6 6-6"})})}),u.jsx("h3",{children:"Slot Settings"}),u.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>x(!b),children:b?"Cancel":"+ Add"})]}),u.jsxs("div",{className:"slot-tz",ref:k,children:[u.jsx("label",{className:"slot-tz-label",children:"Timezone"}),u.jsxs("button",{className:"slot-tz-trigger",onClick:()=>l(!o),children:[u.jsx("span",{children:cw(s)}),u.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:u.jsx("path",{d:"m6 9 6 6 6-6"})})]}),o&&u.jsx("div",{className:"slot-tz-dropdown",children:u2.map(T=>u.jsx("div",{className:`slot-tz-option ${T===s?"active":""}`,onClick:()=>{E(T),l(!1)},children:cw(T)},T))})]}),b&&u.jsxs("div",{className:"slot-add-form",children:[u.jsxs("div",{className:"slot-add-row",children:[u.jsx("input",{type:"time",className:"slot-input",value:d,onChange:T=>f(T.target.value)}),u.jsx("select",{className:"slot-input",value:g,onChange:T=>y(T.target.value),children:c8.map(T=>u.jsx("option",{value:T.value,children:T.label},T.value))})]}),u.jsxs("div",{className:"slot-add-days",children:[u.jsx("button",{className:`sidebar-schedule-btn slot-day-btn ${h.includes("default")?"sidebar-schedule-btn--active":""}`,onClick:()=>_("default"),children:"Every day"}),l8.map(T=>u.jsx("button",{className:`sidebar-schedule-btn slot-day-btn ${h.includes(T.toLowerCase())?"sidebar-schedule-btn--active":""}`,onClick:()=>_(T.toLowerCase()),children:T},T))]}),u.jsx("button",{className:"sidebar-schedule-btn sidebar-schedule-btn--active slot-create-btn",onClick:C,children:"Create Slot"})]}),u.jsx("div",{className:"slot-list",children:n.length===0?u.jsxs("div",{className:"schedule-empty",children:[u.jsx("div",{className:"schedule-empty-title",children:"No slots"}),u.jsx("div",{className:"schedule-empty-desc",children:"Create time slots to define your posting schedule."})]}):n.map(T=>u.jsxs("div",{className:"schedule-item slot-item",children:[u.jsx("div",{className:"schedule-item-time slot-item-time",children:f8(T.time)}),u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:T.days.includes("default")?"Every day":T.days.join(", ")}),u.jsxs("div",{className:"schedule-item-meta",children:[u.jsxs("span",{children:["Filter: ",T.filter_type]}),T.filter_value&&u.jsxs("span",{children:["(",T.filter_value,")"]})]})]}),u.jsx("button",{className:"schedule-item-action schedule-item-action--danger slot-delete-btn",onClick:()=>O(T.id),title:"Delete slot",children:"×"})]},T.id))})]})}function f8(t){const[e,n]=t.split(":").map(Number),r=e>=12?"PM":"AM";return`${e%12||12}:${String(n).padStart(2,"0")} ${r}`}function h8({onBack:t}){const[e,n]=S.useState([]),[r,s]=S.useState([]),[i,o]=S.useState(null),[l,d]=S.useState(!1),[f,h]=S.useState(!0),m=S.useCallback(async()=>{try{const[E,C]=await Promise.all([fetch("/api/scheduler/autoplugs/goals"),fetch("/api/scheduler/autoplugs/tracking")]);if(E.ok){const O=await E.json();n(O.goals||[])}if(C.ok){const O=await C.json();s(O.tracking||[])}}catch{}h(!1)},[]);S.useEffect(()=>{m()},[m]);const g=async E=>{(await fetch(`/api/scheduler/autoplugs/goals/${E.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!E.enabled})})).ok&&n(O=>O.map(_=>_.id===E.id?{..._,enabled:!_.enabled}:_))},y=async E=>{(await fetch(`/api/scheduler/autoplugs/goals/${E}`,{method:"DELETE"})).ok&&(n(O=>O.filter(_=>_.id!==E)),o(null))},b=async E=>{(await fetch(`/api/scheduler/autoplugs/tracking/${E}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({skipped:!0})})).ok&&s(O=>O.map(_=>_.id===E?{..._,skipped:!0}:_))},x=e.reduce((E,C)=>C.rule&&C.enabled?Math.min(E,C.rule.threshold):E,1/0),k=x===1/0?50:x;return u.jsxs("div",{className:"sidebar-schedule",children:[u.jsxs("div",{className:"sidebar-schedule-header",children:[u.jsx("button",{className:"sidebar-schedule-back",onClick:t,title:"Back",children:u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"m15 18-6-6 6-6"})})}),u.jsx("h3",{children:"Autoplugs"}),u.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>d(!l),children:l?"Cancel":"+ Add"})]}),l&&u.jsx(m8,{onCreated:E=>{n(C=>[...C,E]),d(!1)}}),f?null:u.jsxs(u.Fragment,{children:[e.length===0?u.jsxs("div",{className:"schedule-empty",children:[u.jsx("div",{className:"schedule-empty-title",children:"No goals"}),u.jsx("div",{className:"schedule-empty-desc",children:"Create a goal to start autoplugging your tweets."})]}):e.map(E=>u.jsxs("div",{children:[u.jsxs("div",{className:"schedule-item",onClick:()=>o(i===E.id?null:E.id),children:[u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:E.name}),u.jsx("div",{className:"schedule-item-meta",children:p8(E).map((C,O)=>u.jsx("span",{children:C},O))})]}),u.jsx("button",{className:`autoplug-toggle ${E.enabled?"autoplug-toggle--on":"autoplug-toggle--off"}`,onClick:C=>{C.stopPropagation(),g(E)},title:E.enabled?"Disable":"Enable"})]}),i===E.id&&u.jsx(g8,{goal:E,onSaved:C=>{n(O=>O.map(_=>_.id===C.id?C:_))},onDeleted:()=>y(E.id),onRefresh:m})]},E.id)),u.jsx("div",{className:"schedule-day-header",children:"Tracking"}),r.length===0?u.jsxs("div",{className:"schedule-empty",children:[u.jsx("div",{className:"schedule-empty-title",children:"No tracked tweets"}),u.jsx("div",{className:"schedule-empty-desc",children:"Tweets will appear here after posting."})]}):r.map(E=>u.jsxs("div",{className:"schedule-item",children:[u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:E.original_text||`Tweet ${E.tweet_id}`}),u.jsxs("div",{className:"schedule-item-meta",children:[u.jsx("span",{children:v8(E.posted_at)}),u.jsxs("span",{children:[E.likes," likes"]}),u.jsxs("span",{children:[E.retweets," RTs"]}),E.views>0&&u.jsxs("span",{children:[y8(E.views)," views"]})]}),E.triggered?u.jsxs("div",{className:"autoplug-tracking-triggered",children:[u.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Autoplugged ",E.goal_name?`→ ${E.goal_name}`:""]}):E.skipped?u.jsx("div",{className:"autoplug-tracking-skipped",children:"Skipped"}):u.jsx("div",{className:"autoplug-tracking-bar",children:u.jsx("div",{className:"autoplug-tracking-bar-fill",style:{width:`${Math.min(100,E.likes/k*100)}%`}})})]}),!E.triggered&&!E.skipped&&u.jsx("button",{className:"autoplug-tracking-skip",onClick:()=>b(E.id),title:"Skip autoplug for this tweet",children:"×"})]},E.id))]})]})}function p8(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 m8({onCreated:t}){const[e,n]=S.useState(""),[r,s]=S.useState(""),[i,o]=S.useState(""),[l,d]=S.useState("likes"),[f,h]=S.useState(50),[m,g]=S.useState(30),[y,b]=S.useState("static"),[x,k]=S.useState(!1),E=async()=>{if(e.trim()){k(!0);try{const C=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(!C.ok){k(!1);return}const{goal:O}=await C.json();await fetch("/api/scheduler/autoplugs/rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({goal_id:O.id,metric:l,threshold:f,delay_minutes:m,mode:y})});const _=await fetch("/api/scheduler/autoplugs/goals");if(_.ok){const R=((await _.json()).goals||[]).find(I=>I.id===O.id);if(R){t(R);return}}t({...O,rule_count:1,pool_count:0,rule:{metric:l,threshold:f,delay_minutes:m,mode:y,id:""}})}finally{k(!1)}}};return u.jsxs("div",{className:"autoplug-editor",children:[u.jsxs("label",{children:["Name",u.jsx("input",{value:e,onChange:C=>n(C.target.value),placeholder:"Newsletter, Course..."})]}),u.jsxs("label",{children:["Link",u.jsx("input",{value:r,onChange:C=>s(C.target.value),placeholder:"https://..."})]}),u.jsxs("label",{children:["Description (context for LLM)",u.jsx("textarea",{value:i,onChange:C=>o(C.target.value),placeholder:"Weekly engineering insights...",rows:2})]}),u.jsxs("div",{className:"autoplug-editor-row",children:[u.jsx("input",{type:"number",value:f,onChange:C=>h(Number(C.target.value)),min:1}),u.jsxs("select",{value:l,onChange:C=>d(C.target.value),children:[u.jsx("option",{value:"likes",children:"likes"}),u.jsx("option",{value:"retweets",children:"retweets"}),u.jsx("option",{value:"views",children:"views"})]}),u.jsx("span",{className:"autoplug-editor-row-label",children:"wait"}),u.jsx("input",{type:"number",value:m,onChange:C=>g(Number(C.target.value)),min:0,className:"autoplug-delay-input"}),u.jsx("span",{className:"autoplug-editor-row-label",children:"min"})]}),u.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map(C=>u.jsx("button",{className:y===C?"active":"",onClick:()=>b(C),children:C==="llm"?"LLM":C.charAt(0).toUpperCase()+C.slice(1)},C))}),u.jsx("button",{className:"sidebar-schedule-btn sidebar-schedule-btn--active autoplug-create-btn",onClick:E,disabled:x||!e.trim(),children:x?"Creating...":"Create Goal"})]})}function g8({goal:t,onSaved:e,onDeleted:n,onRefresh:r}){var V,$,Q,G;const[s,i]=S.useState(t.name),[o,l]=S.useState(t.link||""),[d,f]=S.useState(t.description||""),[h,m]=S.useState(((V=t.rule)==null?void 0:V.metric)||"likes"),[g,y]=S.useState((($=t.rule)==null?void 0:$.threshold)||50),[b,x]=S.useState(((Q=t.rule)==null?void 0:Q.delay_minutes)||30),[k,E]=S.useState(((G=t.rule)==null?void 0:G.mode)||"static"),[C,O]=S.useState([]),[_,T]=S.useState(""),[R,I]=S.useState(!1);S.useEffect(()=>{fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`).then(K=>K.json()).then(K=>O(K.pool||[])).catch(()=>{})},[t.id]);const B=async()=>{var K;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})}),(K=t.rule)!=null&&K.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:k})}):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:k})}),r()}finally{I(!1)}},P=async()=>{if(!_.trim())return;const K=await fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:_.trim()})});if(K.ok){const X=await K.json();O(re=>[...re,X.message]),T("")}},D=async K=>{(await fetch(`/api/scheduler/autoplugs/pool/${K}`,{method:"DELETE"})).ok&&O(re=>re.filter(J=>J.id!==K))};return u.jsxs("div",{className:"autoplug-editor",children:[u.jsxs("label",{children:["Name",u.jsx("input",{value:s,onChange:K=>i(K.target.value)})]}),u.jsxs("label",{children:["Link",u.jsx("input",{value:o,onChange:K=>l(K.target.value),placeholder:"https://..."})]}),u.jsxs("label",{children:["Description",u.jsx("textarea",{value:d,onChange:K=>f(K.target.value),rows:2})]}),u.jsx("div",{className:"autoplug-editor-section-label",children:"Trigger"}),u.jsxs("div",{className:"autoplug-editor-row",children:[u.jsx("input",{type:"number",value:g,onChange:K=>y(Number(K.target.value)),min:1}),u.jsxs("select",{value:h,onChange:K=>m(K.target.value),children:[u.jsx("option",{value:"likes",children:"likes"}),u.jsx("option",{value:"retweets",children:"retweets"}),u.jsx("option",{value:"views",children:"views"})]}),u.jsx("span",{className:"autoplug-editor-row-label",children:"wait"}),u.jsx("input",{type:"number",value:b,onChange:K=>x(Number(K.target.value)),min:0,className:"autoplug-delay-input"}),u.jsx("span",{className:"autoplug-editor-row-label",children:"min"})]}),u.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map(K=>u.jsx("button",{className:k===K?"active":"",onClick:()=>E(K),children:K==="llm"?"LLM":K.charAt(0).toUpperCase()+K.slice(1)},K))}),u.jsxs("div",{className:"autoplug-pool-section",children:[u.jsx("div",{className:"autoplug-editor-section-label",children:"Static Pool"}),C.map(K=>u.jsxs("div",{className:"autoplug-pool-item",children:[u.jsx("span",{children:K.content}),u.jsx("button",{onClick:()=>D(K.id),title:"Remove",children:"×"})]},K.id)),u.jsxs("div",{className:"autoplug-pool-add",children:[u.jsx("input",{value:_,onChange:K=>T(K.target.value),placeholder:"Add message... (use {{link}} for link)",onKeyDown:K=>K.key==="Enter"&&P()}),u.jsx("button",{onClick:P,children:"+"})]})]}),(k==="llm"||k==="hybrid")&&u.jsx("div",{className:"autoplug-llm-hint",children:"LLM mode uses Author's Voice to generate contextual replies referencing the original tweet."}),u.jsxs("div",{className:"autoplug-editor-actions",children:[u.jsx("button",{className:"schedule-item-action",onClick:B,disabled:R,children:R?"Saving...":"Save"}),u.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:n,children:"Delete"})]})]})}function v8(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 y8(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function b8({onBack:t}){const[e,n]=S.useState([]),[r,s]=S.useState([]),[i,o]=S.useState(!1),[l,d]=S.useState(!1),[f,h]=S.useState(null),[m,g]=S.useState(!0),y=S.useCallback(async()=>{try{const[k,E]=await Promise.all([fetch("/api/scheduler/queue"),fetch("/api/scheduler/slots"),fetch("/api/scheduler/sync",{method:"POST"})]);if(k.ok){const C=await k.json();n(C.items||[])}if(E.ok){const C=await E.json();s(C.slots||[])}}catch{}g(!1)},[]);S.useEffect(()=>{y()},[y]);const b=async k=>{(await fetch(`/api/scheduler/queue/${k}`,{method:"DELETE"})).ok&&(n(C=>C.filter(O=>O.id!==k)),h(null))};if(l)return u.jsx(h8,{onBack:()=>{d(!1),y()}});if(i)return u.jsx(d8,{slots:r,onBack:()=>{o(!1),y()}});const x=x8(r,e);return u.jsxs("div",{className:"sidebar-schedule",children:[u.jsxs("div",{className:"sidebar-schedule-header",children:[u.jsx("button",{className:"sidebar-schedule-back",onClick:t,title:"Back to documents",children:u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"m15 18-6-6 6-6"})})}),u.jsx("h3",{children:"Schedule"}),u.jsxs("div",{className:"sidebar-schedule-actions",children:[u.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>d(!0),title:"Autoplugs",children:u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}),u.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>o(!0),title:"Manage slots",children:u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.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"}),u.jsx("circle",{cx:"12",cy:"12",r:"3"})]})})]})]}),m?null:r.length===0?u.jsxs("div",{className:"schedule-empty",children:[u.jsx("div",{className:"schedule-empty-title",children:"No time slots"}),u.jsx("div",{className:"schedule-empty-desc",children:"Create time slots to define your posting schedule."})]}):x.map(({label:k,entries:E})=>u.jsxs("div",{className:"schedule-day",children:[u.jsx("div",{className:"schedule-day-header",children:k}),E.map((C,O)=>{var _,T,R,I,B;return C.type==="empty"?u.jsxs("div",{className:"schedule-slot-empty",children:[u.jsx("div",{className:"schedule-item-time",children:dw(C.time)}),u.jsx("div",{className:"schedule-slot-empty-label",children:((_=C.slot)==null?void 0:_.filter_type)==="any"?"Open slot":`${(T=C.slot)==null?void 0:T.filter_type}: ${((R=C.slot)==null?void 0:R.filter_value)||"any"}`})]},`empty-${O}`):u.jsxs("div",{children:[u.jsxs("div",{className:"schedule-item",onClick:()=>h(f===C.item.id?null:C.item.id),children:[u.jsx("div",{className:"schedule-item-time",children:dw(C.time)}),u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:((I=C.item.content)==null?void 0:I.text)||JSON.stringify(C.item.content)}),u.jsxs("div",{className:"schedule-item-meta",children:[u.jsx("span",{className:`schedule-item-status schedule-item-status--${C.item.status}`}),u.jsx("span",{children:C.item.status}),C.item.connection_name&&u.jsx("span",{children:C.item.connection_name}),C.item.provider&&u.jsx("span",{children:C.item.provider})]})]})]}),f===C.item.id&&u.jsxs("div",{className:"schedule-item-expanded",children:[u.jsx("div",{className:"schedule-item-full-text",children:((B=C.item.content)==null?void 0:B.text)||JSON.stringify(C.item.content,null,2)}),u.jsx("div",{className:"schedule-item-actions",children:u.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:()=>b(C.item.id),children:"Cancel"})})]})]},C.item.id)})]},k))]})}function x8(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 y of t){if(!(y.days.includes("default")||y.days.includes(g)))continue;const[x,k]=y.time.split(":").map(Number),E=new Date(d);if(E.setHours(x,k,0,0),uw(d,n)&&E<n)continue;const C=`${E.getFullYear()}-${E.getMonth()}-${E.getDate()}-${x}-${k}`,O=s.get(C);O?(f.push({type:"filled",time:E,item:O,slot:y}),i.add(O.id)):f.push({type:"empty",time:E,slot:y})}for(const y of e){if(i.has(y.id))continue;const b=new Date(y.scheduled_at);uw(b,d)&&(f.push({type:"filled",time:b,item:y}),i.add(y.id))}f.sort((y,b)=>y.time.getTime()-b.time.getTime()),f.length>0&&o.push({label:l,entries:f})}return o}function uw(t,e){return t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate()}function dw(t){return t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function w8({onBack:t}){const[e,n]=S.useState([]),[r,s]=S.useState(""),[i,o]=S.useState(null),[l,d]=S.useState(!1),f=S.useRef(null),h=S.useCallback(async()=>{try{const k=await fetch("/api/tasks");if(k.ok){const E=await k.json();n(E.tasks||[])}}catch{}},[]);S.useEffect(()=>{h()},[h]);const m=async()=>{const k=r.trim();if(k){s("");try{const E=await fetch("/api/tasks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:k})});if(E.ok){const C=await E.json();n(O=>[...O,C.task])}}catch{}}},g=k=>{o(k),fetch(`/api/tasks/${k}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({completed:!0})}).catch(()=>{}),setTimeout(()=>{n(E=>E.filter(C=>C.id!==k)),o(null)},400)},y=async k=>{try{(await fetch(`/api/tasks/${k}`,{method:"DELETE"})).ok&&n(C=>C.filter(O=>O.id!==k))}catch{}},b=()=>{d(!0),setTimeout(()=>{var k;return(k=f.current)==null?void 0:k.focus()},0)},x=e.filter(k=>!k.completed);return u.jsxs("div",{className:"sidebar-tasks",children:[u.jsxs("div",{className:"sidebar-tasks-header",children:[u.jsx("button",{className:"sidebar-tasks-back",onClick:t,title:"Back to documents",children:u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"m15 18-6-6 6-6"})})}),u.jsx("h3",{children:"Tasks"}),u.jsx("button",{className:"sidebar-tasks-add-btn",onClick:b,title:"Add task",children:"+"})]}),x.length===0&&!l?u.jsxs("div",{className:"sidebar-tasks-empty",children:[u.jsx("div",{className:"sidebar-tasks-empty-title",children:"No tasks"}),u.jsx("div",{className:"sidebar-tasks-empty-desc",children:"Add tasks to track your checklist."})]}):u.jsx("div",{className:"sidebar-tasks-list",children:x.map(k=>u.jsxs("div",{className:`sidebar-tasks-item${i===k.id?" completing":""}`,children:[u.jsx("input",{type:"checkbox",className:"sidebar-tasks-checkbox",checked:i===k.id,onChange:()=>g(k.id)}),u.jsx("span",{className:`sidebar-tasks-text${i===k.id?" completed":""}`,children:k.text}),u.jsx("button",{className:"sidebar-tasks-delete",onClick:()=>y(k.id),title:"Remove",children:"×"})]},k.id))}),l&&u.jsx("div",{className:"sidebar-tasks-add",children:u.jsx("input",{ref:f,type:"text",placeholder:"New task...",value:r,onChange:k=>s(k.target.value),onKeyDown:k=>{k.key==="Enter"&&m(),k.key==="Escape"&&(d(!1),s(""))},onBlur:()=>{r.trim()||d(!1)}})})]})}function k8({profiles:t,activeProfile:e,trashedProfiles:n,onSwitch:r,onCreate:s,onDelete:i,onRestore:o}){const[l,d]=S.useState(!1),[f,h]=S.useState(!1),[m,g]=S.useState(""),[y,b]=S.useState(null),x=S.useRef(null),k=S.useRef(null);S.useEffect(()=>{if(!l)return;const C=O=>{x.current&&!x.current.contains(O.target)&&(d(!1),h(!1),g(""),b(null))};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[l]),S.useEffect(()=>{f&&k.current&&k.current.focus()},[f]);const E=()=>{const C=m.trim();C&&(s(C),g(""),h(!1))};return u.jsxs("div",{className:"sidebar-profile-wrapper",ref:x,children:[u.jsx("button",{className:"sidebar-collapse-btn",onClick:()=>d(!l),title:`Profile: ${e}`,children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"8",r:"4"}),u.jsx("path",{d:"M5.5 21a8.38 8.38 0 0 1 13 0"})]})}),l&&u.jsxs("div",{className:"sidebar-profile-dropdown",children:[t.map(C=>u.jsxs("div",{className:"sidebar-profile-row",children:[y===C?u.jsxs("div",{className:"sidebar-profile-confirm",children:[u.jsx("span",{children:"Delete?"}),u.jsxs("div",{className:"sidebar-inline-confirm",children:[u.jsx("button",{onClick:()=>{i(C),b(null)},children:"Yes"}),u.jsx("button",{onClick:()=>b(null),children:"No"})]})]}):u.jsx(u.Fragment,{children:u.jsxs("button",{className:`sidebar-profile-option ${C===e?"active":""}`,onClick:()=>{C!==e&&r(C),d(!1)},children:[u.jsx("span",{className:"sidebar-profile-check",children:C===e?"✓":""}),u.jsx("span",{children:C})]})}),C!=="Default"&&C!==e&&y!==C&&u.jsx("button",{className:"sidebar-profile-delete-btn",onClick:O=>{O.stopPropagation(),b(C)},title:"Delete profile",children:"×"})]},C)),n.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"sidebar-profile-divider"}),u.jsx("div",{className:"sidebar-profile-trash-label",children:"Trash"}),n.map(C=>u.jsxs("div",{className:"sidebar-profile-row sidebar-profile-trashed",children:[u.jsx("span",{className:"sidebar-profile-trash-name",children:C}),u.jsx("button",{className:"sidebar-profile-restore-btn",onClick:()=>o(C),children:"Restore"})]},C))]}),u.jsx("div",{className:"sidebar-profile-divider"}),f?u.jsx("div",{className:"sidebar-profile-add-input",children:u.jsx("input",{ref:k,type:"text",value:m,onChange:C=>g(C.target.value),onKeyDown:C=>{C.key==="Enter"&&E(),C.key==="Escape"&&(h(!1),g(""))},placeholder:"Profile name..."})}):u.jsxs("button",{className:"sidebar-profile-option sidebar-profile-add",onClick:()=>h(!0),children:[u.jsx("span",{className:"sidebar-profile-check",children:"+"}),u.jsx("span",{children:"New Profile"})]})]})]})}const fw=200,hw=600,Sp=260;function pw({open:t,onSwitchDocument:e,onCreateDocument:n,refreshKey:r,workspacesRefreshKey:s,pendingDocs:i,writingTitle:o,writingTarget:l,pendingWriteFilenames:d,onClose:f}){const{docs:h,setDocs:m,workspaces:g,setWorkspaces:y,assignedFiles:b,fetchDocs:x,fetchWorkspaces:k,scrollRef:E,markPendingDelete:C}=z5(r,s),O=$5(x,k,m,y,r,C),_=kd(),[T,R]=S.useState(()=>{try{const Je=localStorage.getItem("ow-sidebar-width");if(Je){const Fe=parseInt(Je,10);if(!isNaN(Fe)&&Fe>=fw&&Fe<=hw)return Fe}}catch{}return Sp}),I=S.useRef(!1),B=S.useCallback(Je=>{Je.preventDefault(),I.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const Fe=qt=>{if(!I.current)return;const ie=Math.min(hw,Math.max(fw,qt.clientX));R(ie)},Nt=()=>{I.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("pointermove",Fe),window.removeEventListener("pointerup",Nt);try{localStorage.setItem("ow-sidebar-width",String(P.current))}catch{}};window.addEventListener("pointermove",Fe),window.addEventListener("pointerup",Nt)},[]),P=S.useRef(T);P.current=T;const D=S.useCallback(Je=>{m(Fe=>Fe.map(Nt=>({...Nt,isActive:Nt.filename===Je}))),e(Je)},[m,e]),[V,$]=S.useState(!1),[Q,G]=S.useState(!1),[K,X]=S.useState([]),[re,J]=S.useState("Default"),oe=S.useCallback(async()=>{try{const Je=await fetch("/api/profiles");if(Je.ok){const Fe=await Je.json();X(Fe.profiles),J(Fe.active)}}catch{}},[]);S.useEffect(()=>{oe()},[oe]);const U=S.useCallback(async Je=>{try{(await fetch("/api/profiles/switch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Je})})).ok&&(J(Je),oe())}catch{}},[oe]),A=S.useCallback(async Je=>{try{(await fetch("/api/profiles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Je})})).ok&&oe()}catch{}},[oe]),[L,te]=S.useState([]),se=S.useCallback(async()=>{try{const Je=await fetch("/api/profiles/trash");if(Je.ok){const Fe=await Je.json();te(Fe.profiles)}}catch{}},[]);S.useEffect(()=>{se()},[se]);const be=S.useCallback(async Je=>{try{(await fetch(`/api/profiles/${encodeURIComponent(Je)}`,{method:"DELETE"})).ok&&(oe(),se())}catch{}},[oe,se]),ee=S.useCallback(async Je=>{try{(await fetch("/api/profiles/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Je})})).ok&&(oe(),se())}catch{}},[oe,se]),[ge,fe]=S.useState(""),[Te,Xe]=S.useState(null),tt=S.useRef(),st=S.useRef(null),nt=S.useCallback(Je=>{if(fe(Je),tt.current&&clearTimeout(tt.current),!Je.trim()){Xe(null);return}tt.current=setTimeout(async()=>{try{const Fe=await fetch(`/api/documents/search?q=${encodeURIComponent(Je.trim())}&archived=true`);Fe.ok&&Xe(await Fe.json())}catch{}},250)},[]);S.useEffect(()=>()=>{tt.current&&clearTimeout(tt.current)},[]);const Le={docs:h,archivedDocs:[],workspaces:g,assignedFiles:b,pendingDocs:i,writingTitle:o,writingTarget:l,pendingWriteFilenames:d,onSwitchDocument:D,onCreateDocument:n,actions:O,scrollRef:E,searchQuery:ge,searchResults:Te,onSearchChange:nt},yt=()=>{switch(_){case"files":return u.jsx(a8,{...Le});case"timeline":return u.jsx(K5,{...Le});case"board":return u.jsx(G5,{...Le});case"shelf":return u.jsx(J5,{...Le});default:return u.jsx(V5,{...Le})}},Ke=u.jsxs("div",{className:"sidebar-search",children:[u.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:[u.jsx("circle",{cx:"10.5",cy:"10.5",r:"7"}),u.jsx("path",{d:"m20 20-4.5-4.5"})]}),u.jsx("input",{ref:st,className:"sidebar-search-input",type:"text",placeholder:"Search...",value:ge,onChange:Je=>nt(Je.target.value)}),ge&&u.jsx("button",{className:"sidebar-search-clear",onClick:()=>nt(""),title:"Clear search",children:"×"})]}),Et=t?{width:`${T}px`,minWidth:`${T}px`}:void 0,je=t?u.jsx("div",{className:"sidebar-resize-handle",onPointerDown:B,onDoubleClick:()=>{R(Sp);try{localStorage.setItem("ow-sidebar-width",String(Sp))}catch{}},title:"Drag to resize · double-click to reset"}):null;return _==="board"?u.jsxs("div",{className:`sidebar sidebar-board-mode ${t?"open":""}`,style:Et,children:[yt(),je]}):u.jsxs("div",{className:`sidebar ${t?"open":""}`,style:Et,children:[u.jsxs("div",{className:"sidebar-topbar",children:[u.jsxs("div",{className:"sidebar-logo",children:[u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[u.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"}),u.jsx("path",{d:"M15 5l4 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),u.jsx("span",{className:"sidebar-logo-text",children:"OpenWriter"})]}),u.jsxs("div",{className:"sidebar-topbar-actions",children:[u.jsx(k8,{profiles:K,activeProfile:re,trashedProfiles:L,onSwitch:U,onCreate:A,onDelete:be,onRestore:ee}),u.jsx("button",{className:`sidebar-collapse-btn${V?" sidebar-collapse-btn--active":""}`,onClick:()=>{$(!V),G(!1)},title:"Schedule",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),u.jsx("line",{x1:"16",x2:"16",y1:"1",y2:"5"}),u.jsx("line",{x1:"8",x2:"8",y1:"1",y2:"5"}),u.jsx("line",{x1:"3",x2:"21",y1:"9",y2:"9"})]})}),u.jsx("button",{className:`sidebar-collapse-btn${Q?" sidebar-collapse-btn--active":""}`,onClick:()=>{G(!Q),$(!1)},title:"Tasks",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),u.jsx("path",{d:"m9 12 2 2 4-4"})]})}),f&&u.jsx("button",{className:"sidebar-collapse-btn",onClick:f,title:"Close sidebar",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[u.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",stroke:"currentColor",strokeWidth:"2"}),u.jsx("path",{d:"M9 3v18",stroke:"currentColor",strokeWidth:"2"}),u.jsx("path",{d:"M15 10l-2 2 2 2",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})]}),Q?u.jsx(w8,{onBack:()=>G(!1)}):V?u.jsx(b8,{onBack:()=>$(!1)}):u.jsxs(u.Fragment,{children:[Ke,yt()]}),je]})}function S8({onClose:t,onSetupComplete:e}){const[n,r]=S.useState("detecting"),[s,i]=S.useState(null),[o,l]=S.useState("gh"),[d,f]=S.useState("openwriter-docs"),[h,m]=S.useState(!0),[g,y]=S.useState(""),[b,x]=S.useState(""),[k,E]=S.useState(""),[C,O]=S.useState("");S.useEffect(()=>{fetch("/api/sync/capabilities").then(T=>T.json()).then(T=>{i(T),T.ghAuthenticated?l("gh"):(T.gitInstalled,l("pat")),r("setup")}).catch(()=>{E("Failed to detect git capabilities"),r("error")})},[]);const _=S.useCallback(async()=>{r("progress"),O(o==="connect"?"Connecting to repository...":"Creating repository and syncing...");try{const T={method:o,repoName:d,isPrivate:h};o==="pat"&&(T.pat=g),o==="connect"&&(T.remoteUrl=b,T.pat=g||void 0);const R=await fetch("/api/sync/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(T)});if(!R.ok){const I=await R.json().catch(()=>({}));throw new Error(I.error||`Setup failed (${R.status})`)}r("done"),e()}catch(T){E(T.message),r("error")}},[o,d,h,g,b,e]);return u.jsx("div",{className:"sync-modal-overlay",onClick:t,children:u.jsxs("div",{className:"sync-modal",onClick:T=>T.stopPropagation(),children:[u.jsxs("div",{className:"sync-modal-header",children:[u.jsx("h2",{children:"Sync to GitHub"}),u.jsx("button",{className:"sync-modal-close",onClick:t,children:"×"})]}),n==="detecting"&&u.jsxs("div",{className:"sync-modal-body",children:[u.jsx("div",{className:"sync-spinner"}),u.jsx("p",{children:"Detecting git configuration..."})]}),n==="setup"&&s&&u.jsxs("div",{className:"sync-modal-body",children:[!s.gitInstalled&&u.jsxs("div",{className:"sync-warning",children:["Git is not installed. Please ",u.jsx("a",{href:"https://git-scm.com/downloads",target:"_blank",rel:"noreferrer",children:"install git"})," first."]}),s.gitInstalled&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"sync-tabs",children:[s.ghAuthenticated&&u.jsx("button",{className:`sync-tab${o==="gh"?" active":""}`,onClick:()=>l("gh"),children:"GitHub CLI"}),u.jsx("button",{className:`sync-tab${o==="pat"?" active":""}`,onClick:()=>l("pat"),children:"Personal Access Token"}),u.jsx("button",{className:`sync-tab${o==="connect"?" active":""}`,onClick:()=>l("connect"),children:"Connect Existing"})]}),o==="gh"&&u.jsxs("div",{className:"sync-form",children:[u.jsxs("label",{children:["Repository name",u.jsx("input",{type:"text",value:d,onChange:T=>f(T.target.value),placeholder:"openwriter-docs"})]}),u.jsxs("label",{className:"sync-checkbox",children:[u.jsx("input",{type:"checkbox",checked:h,onChange:T=>m(T.target.checked)}),"Private repository"]})]}),o==="pat"&&u.jsxs("div",{className:"sync-form",children:[!s.ghAuthenticated&&!s.ghInstalled&&u.jsxs("p",{className:"sync-hint",children:["Create a ",u.jsx("a",{href:"https://github.com/settings/tokens/new?scopes=repo&description=OpenWriter",target:"_blank",rel:"noreferrer",children:"Personal Access Token"})," with ",u.jsx("code",{children:"repo"})," scope."]}),u.jsxs("label",{children:["Personal Access Token",u.jsx("input",{type:"password",value:g,onChange:T=>y(T.target.value),placeholder:"ghp_..."})]}),u.jsxs("label",{children:["Repository name",u.jsx("input",{type:"text",value:d,onChange:T=>f(T.target.value),placeholder:"openwriter-docs"})]}),u.jsxs("label",{className:"sync-checkbox",children:[u.jsx("input",{type:"checkbox",checked:h,onChange:T=>m(T.target.checked)}),"Private repository"]})]}),o==="connect"&&u.jsxs("div",{className:"sync-form",children:[u.jsxs("label",{children:["Remote URL",u.jsx("input",{type:"text",value:b,onChange:T=>x(T.target.value),placeholder:"https://github.com/user/repo.git"})]}),u.jsxs("label",{children:["PAT (optional, for private repos)",u.jsx("input",{type:"password",value:g,onChange:T=>y(T.target.value),placeholder:"ghp_..."})]})]}),u.jsxs("div",{className:"sync-modal-actions",children:[u.jsx("button",{className:"sync-btn secondary",onClick:t,children:"Cancel"}),u.jsx("button",{className:"sync-btn primary",onClick:_,disabled:o==="pat"&&!g||o==="connect"&&!b||o!=="connect"&&!d,children:o==="connect"?"Connect & Sync":"Create & Sync"})]})]})]}),n==="progress"&&u.jsxs("div",{className:"sync-modal-body",children:[u.jsx("div",{className:"sync-spinner"}),u.jsx("p",{children:C})]}),n==="done"&&u.jsxs("div",{className:"sync-modal-body",children:[u.jsx("div",{className:"sync-success-icon",children:"✓"}),u.jsx("p",{children:"Successfully synced to GitHub!"}),u.jsx("div",{className:"sync-modal-actions",children:u.jsx("button",{className:"sync-btn primary",onClick:t,children:"Done"})})]}),n==="error"&&u.jsxs("div",{className:"sync-modal-body",children:[u.jsx("div",{className:"sync-error-msg",children:k}),u.jsxs("div",{className:"sync-modal-actions",children:[u.jsx("button",{className:"sync-btn secondary",onClick:()=>r("setup"),children:"Back"}),u.jsx("button",{className:"sync-btn secondary",onClick:t,children:"Close"})]})]})]})})}function E8({onNodeChanges:t,onAgentStatus:e,onDocumentSwitched:n,onDocumentsChanged:r,onWorkspacesChanged:s,onTitleChanged:i,onPendingDocsChanged:o,onMetadataChanged:l,onSyncStatus:d,onWritingStarted:f,onWritingFinished:h,onPendingFilenamesChanged:m,getEditorState:g}){const y=S.useRef(null),[b,x]=S.useState(!1),k=S.useRef(0),E=S.useRef(new Set),C=()=>{var re;return(re=G.current)==null?void 0:re.call(G,new Set(E.current))},O=S.useRef(t),_=S.useRef(e),T=S.useRef(n),R=S.useRef(r),I=S.useRef(s),B=S.useRef(i),P=S.useRef(o),D=S.useRef(d),V=S.useRef(l),$=S.useRef(f),Q=S.useRef(h),G=S.useRef(m),K=S.useRef(g);O.current=t,_.current=e,T.current=n,R.current=r,I.current=s,B.current=i,P.current=o,V.current=l,D.current=d,$.current=f,Q.current=h,G.current=m,K.current=g,S.useEffect(()=>{const J=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;let oe,U=!1,A=1e3;function L(){const se=new WebSocket(J);y.current=se,se.onopen=()=>{x(!0),A=1e3,U&&se.send(JSON.stringify({type:"request-document"})),U=!0},se.onmessage=be=>{var ee,ge,fe,Te,Xe,tt,st,nt,Le,yt,Ke,Et;try{const je=JSON.parse(be.data);if(je.type==="node-changes"&&je.changes&&(typeof je.version=="number"&&(k.current=je.version),(ee=O.current)==null||ee.call(O,je.changes)),je.type==="agent-status"&&((ge=_.current)==null||ge.call(_,!!je.agentConnected)),je.type==="document-switched"&&(k.current=0,(fe=T.current)==null||fe.call(T,{document:je.document,title:je.title,filename:je.filename,docId:je.docId,metadata:je.metadata})),je.type==="metadata-changed"&&je.metadata&&((Te=V.current)==null||Te.call(V,je.metadata)),je.type==="documents-changed"&&((Xe=R.current)==null||Xe.call(R)),je.type==="workspaces-changed"&&((tt=I.current)==null||tt.call(I)),je.type==="title-changed"&&je.title&&((st=B.current)==null||st.call(B,je.title)),je.type==="pending-docs-changed"&&je.pendingDocs&&((nt=P.current)==null||nt.call(P,je.pendingDocs)),je.type==="sync-status"&&((Le=D.current)==null||Le.call(D,{state:je.state,lastSyncTime:je.lastSyncTime,pendingFiles:je.pendingFiles,error:je.error})),je.type==="writing-started"&&je.title&&(typeof je.key=="string"&&(E.current.add(je.key),C()),(yt=$.current)==null||yt.call($,je.title,je.target||null)),je.type==="writing-finished"&&(typeof je.key=="string"&&je.key?E.current.delete(je.key):E.current.clear(),C(),(Ke=Q.current)==null||Ke.call(Q)),je.type==="pending-writes-sync"&&Array.isArray(je.writes)&&(E.current=new Set(je.writes.map(Je=>Je.key).filter(Boolean)),C(),je.writes.length>0)){const Je=je.writes.reduce((Fe,Nt)=>Fe.startedAt>Nt.startedAt?Fe:Nt);Je!=null&&Je.title&&((Et=$.current)==null||Et.call($,Je.title,Je.target||null))}je.type==="plugins-changed"&&window.dispatchEvent(new CustomEvent("ow-plugins-changed")),je.type==="marks-changed"&&je.filename&&window.dispatchEvent(new CustomEvent("ow-marks-changed",{detail:{filename:je.filename}}))}catch{}},se.onclose=()=>{x(!1),oe=setTimeout(L,A),A=Math.min(A*1.5,8e3)},se.onerror=()=>{se.close()}}L();function te(){var se;document.visibilityState==="visible"&&((se=y.current)==null?void 0:se.readyState)!==WebSocket.OPEN&&(clearTimeout(oe),A=1e3,L())}return document.addEventListener("visibilitychange",te),()=>{clearTimeout(oe),document.removeEventListener("visibilitychange",te),y.current&&(y.current.onclose=null,y.current.close())}},[]);const X=S.useCallback(re=>{var J;((J=y.current)==null?void 0:J.readyState)===WebSocket.OPEN&&y.current.send(JSON.stringify(re))},[]);return{connected:b,sendMessage:X,docVersionRef:k}}function N8(t){const[e,n]=S.useState(null),[r,s]=S.useState(!1),[i,o]=S.useState(null),l=S.useRef(void 0);return S.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 C8(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(`
207
+ `)})();return ie?u.jsx("div",{className:"context-menu-mark-quote",children:ie}):null})(),u.jsx("textarea",{autoFocus:!0,className:"context-menu-mark-textarea",value:Q,onChange:ie=>G(ie.target.value),onKeyDown:ie=>{ie.key==="Enter"&&(ie.metaKey||ie.ctrlKey)&&(ie.preventDefault(),Et()),ie.key==="Escape"&&(s(!1),$(!1),G(""),X(null))},placeholder:"Note for agent (optional)...",rows:4}),u.jsxs("div",{className:"context-menu-mark-actions",children:[u.jsx("span",{className:"context-menu-mark-hint",children:"⌘↵ to save · Esc to cancel"}),u.jsx("button",{onClick:Et,children:K?"Save":"Mark"})]})]}):re?u.jsxs(u.Fragment,{children:[u.jsx("button",{className:"context-menu-item",onClick:je,children:u.jsx("span",{children:"Edit mark"})}),u.jsx("button",{className:"context-menu-item",onClick:Je,children:u.jsx("span",{children:"Resolve mark"})})]}):m?u.jsxs("div",{className:"context-menu-custom",children:[u.jsx("input",{autoFocus:!0,value:f,onChange:ie=>h(ie.target.value),onKeyDown:ie=>{ie.key==="Enter"&&Ke(),ie.key==="Escape"&&s(!1)},placeholder:"Custom instruction..."}),u.jsx("button",{onClick:Ke,children:"Apply"})]}):te?u.jsxs("div",{className:"context-menu-link-picker",children:[u.jsxs("div",{className:"context-menu-link-header",children:[u.jsx("button",{className:"context-menu-link-back",onClick:()=>se(null),title:"Back to doc list",children:"←"}),u.jsxs("span",{children:['Pick paragraph in "',te.title,'"']})]}),u.jsx("button",{className:"context-menu-item context-menu-new-link",onClick:()=>Fe({filename:te.filename,docId:te.docId}),children:u.jsx("span",{children:"Link whole doc"})}),u.jsx("div",{className:"context-menu-link-list",children:te.loading?u.jsx("div",{className:"context-menu-loading",children:"Loading…"}):te.paragraphs.length===0?u.jsx("div",{className:"context-menu-loading",children:"No paragraphs"}):te.paragraphs.map(ie=>{const H=ie.preview.replace(/…$/,"").slice(0,50),q=ie.type==="heading"?Math.max(0,(ie.level||1)-1)*12:12;return u.jsx("button",{className:`context-menu-item context-menu-paragraph-row context-menu-paragraph-row--${ie.type}`,style:{paddingLeft:8+q},onClick:()=>Fe({filename:te.filename,docId:te.docId},{nodeId:ie.nodeId,quote:H}),children:u.jsx("span",{children:ie.preview})},ie.nodeId)})})]}):A&&oe?u.jsxs("div",{className:"context-menu-link-picker",children:[u.jsxs("div",{className:"context-menu-link-header",children:["Linked from ",oe.entries.length," ",oe.entries.length===1?"place":"places"]}),u.jsx("div",{className:"context-menu-link-list",children:oe.entries.map((ie,H)=>{const q=E.find(me=>me.docId===ie.from_doc),de=(q==null?void 0:q.title)||ie.from_doc;return u.jsxs("button",{className:"context-menu-item",onClick:()=>{window.dispatchEvent(new CustomEvent("ow-navigate-to-link",{detail:{docId:ie.from_doc,nodeId:ie.from_node,filename:null,quote:null}})),s(!1),L(!1)},children:[u.jsx("span",{children:de}),u.jsxs("span",{className:"context-menu-shortcut",children:['"',ie.text,'"']})]},`${ie.from_doc}-${ie.from_node}-${H}`)})})]}):x?u.jsxs("div",{className:"context-menu-link-picker",children:[u.jsx("div",{className:"context-menu-link-header",children:"Link to document"}),T?u.jsxs("div",{className:"context-menu-custom",children:[u.jsx("input",{autoFocus:!0,value:I,onChange:ie=>B(ie.target.value),onKeyDown:ie=>{ie.key==="Enter"&&qt(),ie.key==="Escape"&&R(!1)},placeholder:"New document title..."}),u.jsx("button",{onClick:qt,children:"Create"})]}):u.jsx("button",{className:"context-menu-item context-menu-new-link",onClick:()=>R(!0),children:u.jsx("span",{children:"+ New link doc"})}),u.jsxs("div",{className:"context-menu-link-list",children:[O.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-section-header",children:"Linked in this doc"}),E.filter(ie=>ew(ie,O)).map(ie=>u.jsxs("div",{className:"context-menu-link-row",children:[u.jsx("button",{className:"context-menu-item context-menu-link-row__main",onClick:()=>Fe(ie),children:u.jsx("span",{children:ie.title})}),ie.docId&&u.jsx("button",{className:"context-menu-link-row__drill",title:"Pick a paragraph in this doc",onClick:()=>Nt(ie),children:"▸"})]},`linked-${ie.filename}`))]}),u.jsx("div",{className:"context-menu-section-header",children:"All documents"}),E.filter(ie=>!ew(ie,O)).map(ie=>u.jsxs("div",{className:"context-menu-link-row",children:[u.jsx("button",{className:"context-menu-item context-menu-link-row__main",onClick:()=>Fe(ie),children:u.jsx("span",{children:ie.title})}),ie.docId&&u.jsx("button",{className:"context-menu-link-row__drill",title:"Pick a paragraph in this doc",onClick:()=>Nt(ie),children:"▸"})]},ie.filename)),E.length===0&&u.jsx("div",{className:"context-menu-loading",children:"No documents"})]})]}):(()=>{const ie=st();let H;return ie.map((q,de)=>{const me=q.isPlugin&&q.pluginDisplayName&&q.pluginDisplayName!==H,Ee=H!==void 0;q.isPlugin?H=q.pluginDisplayName:H=void 0;const De=!q.isPlugin&&Ee;return u.jsxs("span",{children:[me&&u.jsx("div",{className:"context-menu-section-header",children:q.pluginDisplayName}),De&&u.jsx("div",{className:"context-menu-divider"}),u.jsxs("button",{className:"context-menu-item",onClick:()=>yt(q),children:[u.jsx("span",{children:q.label}),q.shortcut&&u.jsx("span",{className:"context-menu-shortcut",children:q.shortcut})]})]},q.action)})})()}):null}function qv(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 x5(t,e){const n=Cn(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 w5(t,e){const n=Cn(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 k5(t,e){var o;const n=Cn(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=qv(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function S5(t,e){var o;const n=Cn(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=qv(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function E5(t,e){var o,l;const n=Cn(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=qv(t.state.doc,s,s+r.nodeSize);t.chain().deleteRange(d).run()}return!0}function N5(t,e){var i;const n=Cn(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 C5(t,e){const n=zd(t,e);if(n.length===0)return!1;for(const r of[...n].reverse()){const s=Cn(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 _5(t,e){var l;const n=zd(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 J_(t,e){var i,o;const n=Cn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return C5(t,r);switch((o=n.node.attrs)==null?void 0:o.pendingStatus){case"insert":return x5(t,e);case"rewrite":return w5(t,e);case"delete":return k5(t,e);default:return!1}}function Y_(t,e){var i,o;const n=Cn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return _5(t,r);switch((o=n.node.attrs)==null?void 0:o.pendingStatus){case"insert":return S5(t,e);case"rewrite":return E5(t,e);case"delete":return N5(t,e);default:return!1}}function T5(t){const e=X_(t).reverse();for(const n of e)J_(t,n);t.view&&Uv(t.view)}function M5(t){const e=X_(t).reverse();for(const n of e)Y_(t,n);t.view&&Uv(t.view)}function Vv(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 bp(t){const e=[];for(const n of t)n&&!n.isDestroyed&&e.push(...Vv(n));return e}function X_(t){return Vv(t).map(e=>e.nodeId)}function A5(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 Ha(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 j5(t){const[e,n]=S.useState([]),[r,s]=S.useState(0),i=S.useRef(),o=S.useRef(new Set),l=S.useCallback(()=>{const E=t.filter(R=>R&&!R.isDestroyed);if(E.length===0){n([]),o.current=new Set;return}const C=bp(E);n(C);const O=o.current,_=new Set(C.map(R=>R.nodeId));let T=-1;if(O.size>0){for(let R=0;R<C.length;R++)if(!O.has(C[R].nodeId)){T=R;break}}o.current=_,T>=0?(s(T),Ha(C[T].editor,C[T].nodeId)):C.length===0?s(0):s(R=>Math.min(R,C.length-1))},[t]);S.useEffect(()=>{const E=t.filter(_=>_&&!_.isDestroyed);if(E.length===0)return;const C=()=>{clearTimeout(i.current),i.current=setTimeout(l,50)};for(const _ of E)_.on("transaction",C);l();const O=setTimeout(()=>{const _=bp(E.filter(T=>!T.isDestroyed));_.length>0&&Ha(_[0].editor,_[0].nodeId)},150);return()=>{for(const _ of E)_.isDestroyed||_.off("transaction",C);clearTimeout(i.current),clearTimeout(O)}},[t,l]),S.useEffect(()=>{const E=e[r]??null;return U1((E==null?void 0:E.nodeId)??null,(E==null?void 0:E.groupId)??null),E!=null&&E.editor&&!E.editor.isDestroyed&&E.editor.view&&Uv(E.editor.view),()=>{U1(null)}},[r,e]);const d=A5(e),f=e[r]??null,h=S.useCallback(()=>{if(e.length===0)return;const E=(r+1)%e.length;s(E),e[E]&&Ha(e[E].editor,e[E].nodeId)},[e,r]),m=S.useCallback(()=>{if(e.length===0)return;const E=(r-1+e.length)%e.length;s(E),e[E]&&Ha(e[E].editor,e[E].nodeId)},[e,r]),g=S.useCallback(()=>{const E=t.filter(_=>_&&!_.isDestroyed),C=bp(E);if(C.length===0)return;const O=Math.min(r,C.length-1);Ha(C[O].editor,C[O].nodeId)},[t,r]),y=S.useCallback(()=>{f&&(J_(f.editor,f.nodeId),l(),g())},[f,l,g]),b=S.useCallback(()=>{f&&(Y_(f.editor,f.nodeId),l(),g())},[f,l,g]),x=S.useCallback(()=>{const E=t.filter(C=>C&&!C.isDestroyed);for(const C of E)T5(C);l()},[t,l]),k=S.useCallback(()=>{const E=t.filter(C=>C&&!C.isDestroyed);for(const C of E)M5(C);l()},[t,l]);return{pendingNodes:e,counts:d,currentNode:f,currentIndex:r,hasPending:d.total>0,goToNext:h,goToPrevious:m,acceptCurrent:y,rejectCurrent:b,acceptAll:x,rejectAll:k,refresh:l}}const na={strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},O5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M10 3L5 8l5 5",stroke:"currentColor",...na})}),R5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M6 3l5 5-5 5",stroke:"currentColor",...na})}),I5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M3 10l5-5 5 5",stroke:"currentColor",...na})}),L5=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M3 6l5 5 5-5",stroke:"currentColor",...na})}),tw=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M3 8.5l3.5 3.5L13 5",stroke:"currentColor",...na})}),nw=()=>u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M4 4l8 8M12 4l-8 8",stroke:"currentColor",...na})});function Q_(t,e,n){const r=Cn(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 Z_(t,e,n){const r=zd(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 du(t,e){if(!Fv()||!e)return!1;const n=_B(),r=CB();return r&&n&&Array.isArray(n)?Z_(t,r,n):n&&Q_(t,e,n),Dg(!1),!0}function D5({editors:t,pendingDocs:e,currentFilename:n,onSwitchDocument:r,sendMessage:s,getDocument:i,docVersionRef:o}){const{counts:l,currentNode:d,currentIndex:f,hasPending:h,goToNext:m,goToPrevious:g,acceptCurrent:y,rejectCurrent:b,acceptAll:x,rejectAll:k}=j5(t),[E,C]=S.useState(!1),O=S.useRef(null),_=S.useRef(null),T=e.filenames.length,R=P5(e.filenames,n),I=(d==null?void 0:d.pendingStatus)==="rewrite",B=!!(d!=null&&d.groupId),P=I,D=S.useCallback(()=>{var A,L;const U=d==null?void 0:d.editor;if(!(!U||!d||d.pendingStatus!=="rewrite"))if(E)_.current&&du(_.current,O.current),O.current=null,_.current=null,C(!1);else if(B&&d.groupId){const te=zd(U,d.groupId);if(te.length===0)return;const se=(A=te[0].node.attrs)==null?void 0:A.pendingOriginalContent;if(!se||!Array.isArray(se))return;const be=te.map(fe=>fe.node.toJSON()),ee=se.map((fe,Te)=>({...fe,attrs:{...fe.attrs||{},pendingStatus:"rewrite",pendingGroupId:d.groupId,...Te===0?{pendingOriginalContent:se}:{}}}));if(!Z_(U,d.groupId,ee))return;Dg(!0,d.nodeId,be,d.groupId),O.current=d.nodeId,_.current=U,C(!0)}else{const te=Cn(U,d.nodeId);if(!te)return;const{node:se}=te,be=(L=se.attrs)==null?void 0:L.pendingOriginalContent;if(!be)return;const ee=se.toJSON();if(!Q_(U,d.nodeId,be))return;Dg(!0,d.nodeId,ee),O.current=d.nodeId,_.current=U,C(!0)}},[d,E,B]);S.useEffect(()=>{if(!E)return;const U=O.current,A=_.current;U&&A&&(d==null?void 0:d.nodeId)!==U&&(du(A,U),O.current=null,_.current=null,C(!1))},[d==null?void 0:d.nodeId,E]),S.useEffect(()=>{if(t.length!==0)return()=>{Fv()&&O.current&&_.current&&(du(_.current,O.current),O.current=null,_.current=null)}},[t]);const V=S.useCallback(U=>{if(!n)return;if(!t.some(L=>!L||L.isDestroyed?!1:Vv(L).length>0)){const L=i==null?void 0:i();L&&s({type:"doc-update",document:L,filename:n,version:(o==null?void 0:o.current)??0}),s({type:"pending-resolved",filename:n,action:U})}},[t,n,s,i,o]),$=S.useCallback(()=>{_.current&&E&&O.current&&(du(_.current,O.current),O.current=null,_.current=null,C(!1))},[E]),Q=S.useCallback(()=>{$(),y(),V("accept")},[$,y,V]),G=S.useCallback(()=>{$(),b(),V("reject")},[$,b,V]),K=S.useCallback(()=>{$(),x(),V("accept")},[$,x,V]);S.useEffect(()=>{const U=()=>K();return window.addEventListener("ow-accept-all",U),()=>window.removeEventListener("ow-accept-all",U)},[K]);const X=S.useCallback(()=>{$(),k(),V("reject")},[$,k,V]),re=S.useCallback(()=>{if(T===0||T===1&&R===0)return;const U=R<=0?T-1:R-1;r(e.filenames[U])},[T,R,e.filenames,r]),J=S.useCallback(()=>{if(T===0||T===1&&R===0)return;const U=R>=T-1?0:R+1;r(e.filenames[U])},[T,R,e.filenames,r]);if(S.useEffect(()=>{if(!h)return;const U=A=>{if(!(A.target instanceof HTMLInputElement||A.target instanceof HTMLTextAreaElement)&&!(A.target instanceof HTMLElement&&A.target.closest("[contenteditable]")))switch(A.key){case"j":case"ArrowDown":!A.metaKey&&!A.ctrlKey&&(A.preventDefault(),m());break;case"k":case"ArrowUp":!A.metaKey&&!A.ctrlKey&&(A.preventDefault(),g());break;case"h":case"ArrowLeft":!A.metaKey&&!A.ctrlKey&&!A.altKey&&(A.preventDefault(),re());break;case"l":case"ArrowRight":!A.metaKey&&!A.ctrlKey&&!A.altKey&&(A.preventDefault(),J());break;case"a":!A.metaKey&&!A.ctrlKey&&!A.shiftKey&&(A.preventDefault(),Q());break;case"r":!A.metaKey&&!A.ctrlKey&&(A.preventDefault(),G());break;case"A":A.shiftKey&&!A.metaKey&&!A.ctrlKey&&(A.preventDefault(),K());break;case"R":A.shiftKey&&!A.metaKey&&!A.ctrlKey&&(A.preventDefault(),X());break;case"o":!A.metaKey&&!A.ctrlKey&&!A.shiftKey&&(A.preventDefault(),D());break}};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[h,m,g,re,J,Q,G,K,X,D]),!h)return null;const oe=R>=0?R+1:"?";return u.jsxs("div",{className:"review-panel",children:[T>1&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"review-panel__nav",children:[u.jsx("button",{className:"review-panel__btn",onClick:re,title:"Previous doc (h)",children:u.jsx(O5,{})}),u.jsx("button",{className:"review-panel__btn",onClick:J,title:"Next doc (l)",children:u.jsx(R5,{})}),u.jsxs("span",{className:"review-panel__counter",children:[oe,"/",T]})]}),u.jsx("div",{className:"review-panel__divider"})]}),u.jsxs("div",{className:"review-panel__nav",children:[u.jsx("button",{className:"review-panel__btn",onClick:g,disabled:l.total===0,title:"Previous (k)",children:u.jsx(I5,{})}),u.jsx("button",{className:"review-panel__btn",onClick:m,disabled:l.total===0,title:"Next (j)",children:u.jsx(L5,{})}),u.jsxs("span",{className:"review-panel__counter",children:[f+1,"/",l.total]})]}),u.jsx("div",{className:"review-panel__divider"}),u.jsxs("div",{className:"review-panel__toggle",children:[u.jsx("button",{className:`review-panel__toggle-btn${P&&!E?" review-panel__toggle-btn--active":""}`,onClick:()=>P&&E&&D(),disabled:!P,title:"Show modified (o)",children:"Modified"}),u.jsx("button",{className:`review-panel__toggle-btn${P&&E?" review-panel__toggle-btn--active":""}`,onClick:()=>P&&!E&&D(),disabled:!P,title:"Show original (o)",children:"Original"})]}),u.jsx("div",{className:"review-panel__divider"}),u.jsxs("div",{className:"review-panel__actions",children:[u.jsx("button",{className:"review-panel__accept",onClick:Q,title:"Accept (a)",children:u.jsx(tw,{})}),u.jsx("button",{className:"review-panel__reject",onClick:G,title:"Reject (r)",children:u.jsx(nw,{})}),u.jsxs("button",{className:"review-panel__accept-all",onClick:K,title:"Accept all (Shift+A)",children:[u.jsx(tw,{}),u.jsx("span",{children:"All"})]}),u.jsxs("button",{className:"review-panel__reject-all",onClick:X,title:"Reject all (Shift+R)",children:[u.jsx(nw,{}),u.jsx("span",{children:"All"})]})]})]})}function P5(t,e){return t.indexOf(e)}function fu(t){return t.type==="doc"?t.file:t.id}function yl(t,e){for(const n of t)n.type==="doc"?e.add(n.file):n.type==="container"&&yl(n.items,e)}function ea(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 ks(t){return/^[A-Z]:[/\\]|^\//.test(t)}function e2(t){const e=t.replace(/\\/g,"/").split("/");return e.length>=2?e[e.length-2]:""}function B5(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 z5(t,e){const[n,r]=S.useState([]),[s,i]=S.useState([]),o=S.useRef(null),l=S.useRef(new Set),d=S.useCallback(g=>{l.current.add(g)},[]),f=S.useMemo(()=>{const g=new Set;for(const y of s)y.workspace&&yl(y.workspace.root,g);return g},[s]),h=S.useCallback(()=>{fetch("/api/documents").then(g=>g.json()).then(g=>{if(!Array.isArray(g))return;const y=l.current;if(y.size>0){const x=new Set(g.map(k=>k.filename));for(const k of[...y])x.has(k)||y.delete(k)}const b=y.size>0?g.filter(x=>!y.has(x.filename)):g;r(b)}).catch(()=>{})},[]),m=S.useCallback(()=>{fetch("/api/workspaces").then(g=>g.json()).then(async g=>{if(!Array.isArray(g))return;const y=await Promise.all(g.map(async b=>{try{const k=await(await fetch(`/api/workspaces/${encodeURIComponent(b.filename)}`)).json();return{...b,workspace:k}}catch{return b}}));i(y)}).catch(()=>{})},[]);return S.useEffect(()=>{h()},[h,t]),S.useEffect(()=>{m()},[m,e]),S.useEffect(()=>{const g=requestAnimationFrame(()=>{var b;const y=(b=o.current)==null?void 0:b.querySelector(".sidebar-item.active");y==null||y.scrollIntoView({block:"nearest",behavior:"instant"})});return()=>cancelAnimationFrame(g)},[n]),{docs:n,setDocs:r,workspaces:s,setWorkspaces:i,assignedFiles:f,fetchDocs:h,fetchWorkspaces:m,scrollRef:o,markPendingDelete:d}}function Bg(t,e){return t.filter(n=>!e(n)).map(n=>n.type==="container"?{...n,items:Bg(n.items,e)}:n)}function t2(t,e,n){return t.map(r=>r.type==="container"&&r.id===e?{...r,name:n}:r.type==="container"?{...r,items:t2(r.items,e,n)}:r)}function $5(t,e,n,r,s,i){const o=S.useCallback(B=>{n(P=>P.filter(D=>D.filename!==B)),i==null||i(B),fetch(`/api/documents/${encodeURIComponent(B)}`,{method:"DELETE"}).catch(()=>t())},[n,t]),l=S.useCallback(B=>{n(P=>P.filter(D=>D.filename!==B)),fetch(`/api/documents/${encodeURIComponent(B)}/archive`,{method:"POST"}).catch(()=>t())},[n,t]),d=S.useCallback(B=>{n(P=>P.filter(D=>D.filename!==B)),fetch(`/api/documents/${encodeURIComponent(B)}/unarchive`,{method:"POST"}).catch(()=>t())},[n,t]),f=S.useCallback((B,P,D)=>{!D.trim()||D.trim()===P||(n(V=>V.map($=>$.filename===B?{...$,title:D.trim()}:$)),fetch(`/api/documents/${encodeURIComponent(B)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:D.trim()})}).catch(()=>t()))},[n,t]),h=S.useCallback(B=>{r(P=>P.filter(D=>D.filename!==B)),fetch(`/api/workspaces/${encodeURIComponent(B)}`,{method:"DELETE"}).catch(()=>e())},[r,e]),m=S.useCallback((B,P)=>{P.trim()&&(r(D=>D.map(V=>V.filename===B?{...V,title:P.trim()}:V)),fetch(`/api/workspaces/${encodeURIComponent(B)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:P.trim()})}).catch(()=>e()))},[r,e]),g=S.useCallback((B,P)=>{r(D=>D.map(V=>V.filename!==B||!V.workspace?V:{...V,docCount:Math.max(0,V.docCount-1),workspace:{...V.workspace,root:Bg(V.workspace.root,$=>$.type==="doc"&&$.file===P)}})),fetch(`/api/workspaces/${encodeURIComponent(B)}/docs/${encodeURIComponent(P)}`,{method:"DELETE"}).catch(()=>e())},[r,e]),y=S.useCallback((B,P,D=!1)=>{r($=>$.map(Q=>Q.filename!==B||!Q.workspace?Q:{...Q,workspace:{...Q.workspace,root:Bg(Q.workspace.root,G=>G.type==="container"&&G.id===P)}}));const V=`/api/workspaces/${encodeURIComponent(B)}/containers/${encodeURIComponent(P)}${D?"?cascade=true":""}`;fetch(V,{method:"DELETE"}).then(()=>{D&&t()}).catch(()=>e())},[r,e,t]),b=S.useCallback((B,P,D)=>{D.trim()&&(r(V=>V.map($=>$.filename!==B||!$.workspace?$:{...$,workspace:{...$.workspace,root:t2($.workspace.root,P,D.trim())}})),fetch(`/api/workspaces/${encodeURIComponent(B)}/containers/${encodeURIComponent(P)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:D.trim()})}).catch(()=>e()))},[r,e]),x=S.useCallback(()=>{fetch("/api/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:"Untitled Workspace"})}).catch(()=>{})},[]),k=S.useCallback((B,P,D)=>{fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D?{metadata:D}:{})}).then(V=>V.json()).then(V=>{if(V.filename)return fetch(`/api/workspaces/${encodeURIComponent(B)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:V.filename,title:V.title||"Untitled",containerId:P})})}).catch(()=>{})},[]),E=S.useCallback((B,P)=>{fetch(`/api/workspaces/${encodeURIComponent(B)}/containers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:"Untitled",parentContainerId:P})}).catch(()=>{})},[]),[C,O]=S.useState({}),_=S.useRef(-1);S.useEffect(()=>{s!==_.current&&(_.current=s??0,fetch("/api/documents").then(B=>B.json()).then(B=>{const P={};return Promise.all(B.map(D=>fetch(`/api/doc-tags/${encodeURIComponent(D.filename)}`).then(V=>V.json()).then(V=>{var $;($=V.tags)!=null&&$.length&&(P[D.filename]=V.tags)}).catch(()=>{}))).then(()=>O(P))}).catch(()=>{}))},[s]);const T=S.useCallback(B=>C[B]||[],[C]),R=S.useCallback((B,P)=>{P.trim()&&(O(D=>{const V=D[B]||[];return V.includes(P.trim())?D:{...D,[B]:[...V,P.trim()]}}),fetch(`/api/doc-tags/${encodeURIComponent(B)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag:P.trim()})}).catch(()=>{}))},[]),I=S.useCallback((B,P)=>{O(D=>{const $=(D[B]||[]).filter(Q=>Q!==P);if($.length===0){const Q={...D};return delete Q[B],Q}return{...D,[B]:$}}),fetch(`/api/doc-tags/${encodeURIComponent(B)}/${encodeURIComponent(P)}`,{method:"DELETE"}).catch(()=>{})},[]);return{fetchDocs:t,handleDelete:o,handleArchive:l,handleUnarchive:d,handleRename:f,handleCreateWorkspace:x,handleDeleteWorkspace:h,handleCreateInWorkspace:k,handleRemoveFromWorkspace:g,handleCreateContainer:E,handleDeleteContainer:y,handleRenameContainer:b,handleRenameWorkspace:m,getDocTags:T,handleAddTag:R,handleRemoveTag:I}}function n2({docs:t,workspaces:e,assignedFiles:n,scrollRef:r,setCollapsedSections:s}){const[i,o]=S.useState(null),[l,d]=S.useState(null),f=S.useRef(null),h=S.useRef(null),m=S.useRef(null),g=S.useRef(null),y=S.useRef(null),b=5,x=(D,V,$)=>$==="before"?V>0?fu(D[V-1]):null:fu(D[V]),k=S.useCallback((D,V)=>{if(V===null){const G=t.filter(X=>!n.has(X.filename)).map(X=>({type:"doc",file:X.filename,title:X.title})),K=G.findIndex(X=>fu(X)===D);return K>=0?{siblings:G,index:K,containerId:null}:null}const $=e.find(G=>G.filename===V);if(!($!=null&&$.workspace))return null;const Q=(G,K)=>{for(let X=0;X<G.length;X++){if(fu(G[X])===D)return{siblings:G,index:X,containerId:K};if(G[X].type==="container"){const re=Q(G[X].items,G[X].id);if(re)return re}}return null};return Q($.workspace.root,null)},[t,n,e]),E=S.useCallback(()=>{o(null),d(null),y.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=""},[]),C=S.useCallback((D,V)=>{if(!D||!V)return;if(D.type==="workspace"){const J=V.itemId;if(J===D.filename)return;const oe=e.map(L=>L.filename),U=oe.indexOf(D.filename);if(U<0)return;oe.splice(U,1);let A=oe.indexOf(J);if(A<0)return;V.position==="after"&&(A+=1),oe.splice(A,0,D.filename),fetch("/api/workspaces/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:oe})}).catch(()=>{});return}const{wsFilename:$,containerId:Q,afterId:G}=V,K=D.type==="doc"?D.file:D.id,X=D.sourceWs;if(V.itemId===K)return;if(D.type==="container"){if($===null&&Q===null&&V.itemId!=="__section__"){const J=V.itemId,oe=V.position==="after"?J:(()=>{const U=e.findIndex(A=>A.filename===J);return U>0?e[U-1].filename:null})();fetch("/api/workspaces/promote-container",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:X,containerId:K,afterWorkspaceFilename:oe})}).catch(()=>{});return}if(X!==$&&$){fetch(`/api/workspaces/${encodeURIComponent($)}/containers/${encodeURIComponent(K)}/cross-move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:X,targetContainerId:Q??null,afterIdentifier:G})}).catch(()=>{});return}if(!$)return;fetch(`/api/workspaces/${encodeURIComponent($)}/docs/${encodeURIComponent(K)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:Q??null,afterFile:G})}).catch(()=>{});return}const re=D.file;if(X===null&&$===null){const J=t.filter(te=>!n.has(te.filename)).map(te=>te.filename),oe=J.indexOf(re);if(oe<0)return;J.splice(oe,1);let U=G?J.indexOf(G):-1;U>=0?U+=1:U=0,J.splice(U,0,re);const A=[];let L=0;for(const te of t)n.has(te.filename)?A.push(te.filename):A.push(J[L++]);fetch("/api/documents/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:A})}).catch(()=>{});return}if(X===null&&$!==null){fetch(`/api/workspaces/${encodeURIComponent($)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:re,title:re.replace(/\.md$/,""),containerId:Q??null,afterFile:G})}).catch(()=>{});return}if(X!==null&&$===null){fetch(`/api/workspaces/${encodeURIComponent(X)}/docs/${encodeURIComponent(re)}`,{method:"DELETE"}).catch(()=>{});return}if(X===$&&$!==null){fetch(`/api/workspaces/${encodeURIComponent($)}/docs/${encodeURIComponent(re)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:Q??null,afterFile:G})}).catch(()=>{});return}X!==null&&$!==null&&fetch(`/api/workspaces/${encodeURIComponent($)}/docs/${encodeURIComponent(re)}/cross-move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:X,containerId:Q??null,afterFile:G,title:re.replace(/\.md$/,"")})}).catch(()=>{})},[e,t,n]),O=S.useCallback((D,V)=>{const $=m.current;$&&($.style.display="none");const Q=document.elementFromPoint(D,V);if($&&($.style.display=""),!Q)return null;if((i==null?void 0:i.type)==="workspace"||(i==null?void 0:i.type)==="container"){const te=Q.closest("[data-ws-drag]");if(te){const se=te.dataset.wsDrag,be=te.getBoundingClientRect(),ee=(V-be.top)/be.height;return{itemId:se,position:ee<.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 te=Q.closest("[data-ws-drag]");if(te)return{itemId:"__section__",position:"inside",wsFilename:te.dataset.wsDrag,containerId:null,afterId:null}}const G=Q.closest("[data-drag-id]");if(!G){const te=Q.closest("[data-drop-ws]");return te?{itemId:"__section__",position:"inside",wsFilename:te.dataset.dropWs==="__docs__"?null:te.dataset.dropWs,containerId:te.dataset.dropContainer||null,afterId:null}:null}const K=G.dataset.dragId,X=G.dataset.dragType,re=G.dataset.dragWs==="__docs__"?null:G.dataset.dragWs,J=G.getBoundingClientRect(),oe=(V-J.top)/J.height;if(X==="container-header"){const te=K,se=G.dataset.dragParent||null,be=k(te,re);if(!be)return null;const ee=(i==null?void 0:i.type)==="container"?.33:.25;return oe<ee?{itemId:te,position:"before",wsFilename:re,containerId:se,afterId:x(be.siblings,be.index,"before")}:oe>1-ee?{itemId:te,position:"after",wsFilename:re,containerId:se,afterId:x(be.siblings,be.index,"after")}:{itemId:te,position:"inside",wsFilename:re,containerId:te,afterId:null}}const U=G.dataset.dragContainer||null,A=k(K,re);if(!A)return null;const L=oe<.5?"before":"after";return{itemId:K,position:L,wsFilename:re,containerId:U,afterId:x(A.siblings,A.index,L)}},[k,i]),_=S.useCallback(D=>{const V=r.current;if(!V)return;const $=V.getBoundingClientRect(),Q=80,G=18;let K=0;if(D<$.top+Q?K=-G*Math.max(0,1-(D-$.top)/Q):D>$.bottom-Q&&(K=G*Math.max(0,1-($.bottom-D)/Q)),h.current&&(cancelAnimationFrame(h.current),h.current=null),K!==0){const X=()=>{V.scrollTop+=K,h.current=requestAnimationFrame(X)};h.current=requestAnimationFrame(X)}},[r]),T=S.useCallback((D,V)=>{const $=m.current;$&&($.style.display="none");const Q=document.elementFromPoint(D,V);$&&($.style.display="");const G=Q==null?void 0:Q.closest("[data-section-key]");if(!G){f.current&&(clearTimeout(f.current),f.current=null);return}const K=G.dataset.sectionKey;f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{s(X=>{if(!X.has(K))return X;const re=new Set(X);return re.delete(K),re})},500)},[s]);S.useEffect(()=>{if(!i)return;const D=$=>{m.current&&(m.current.style.left=`${$.clientX+12}px`,m.current.style.top=`${$.clientY-8}px`),d(O($.clientX,$.clientY)),_($.clientY),T($.clientX,$.clientY)},V=$=>{C(i,O($.clientX,$.clientY)),E()};return window.addEventListener("pointermove",D),window.addEventListener("pointerup",V),()=>{window.removeEventListener("pointermove",D),window.removeEventListener("pointerup",V)}},[i,O,C,E,_,T]);const R=S.useCallback((D,V,$)=>{if(D.button!==0||D.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:D.clientX,y:D.clientY},y.current=V;const G=X=>{if(!g.current||!y.current)return;const re=X.clientX-g.current.x,J=X.clientY-g.current.y;if(Math.abs(re)+Math.abs(J)>=b){document.body.style.userSelect="none",window.removeEventListener("pointermove",G),window.removeEventListener("pointerup",K),o(y.current),y.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=$,document.body.appendChild(oe),m.current=oe,oe.style.left=`${X.clientX+12}px`,oe.style.top=`${X.clientY-8}px`}},K=()=>{window.removeEventListener("pointermove",G),window.removeEventListener("pointerup",K),g.current=null,y.current=null,document.body.style.userSelect=""};window.addEventListener("pointermove",G),window.addEventListener("pointerup",K)},[]);return{draggedItem:i,dropIndicator:l,handlePointerDown:R,dropClass:D=>!l||l.itemId!==D?"":l.position==="before"?"drop-before":l.position==="after"?"drop-after":l.position==="inside"?"drop-inside":"",isDragging:D=>i?i.type==="doc"?i.file===D:i.type==="workspace"?i.filename===D:i.id===D:!1,isContainerDropTarget:D=>!l||!i?!1:l.containerId===D}}function F5({items:t,onAction:e,menuRef:n}){const[r,s]=S.useState(null),i=S.useRef(null),o=S.useMemo(()=>{const h=new Map;for(const m of t){const g=m.pluginDisplayName||"_ungrouped",y=h.get(g)||[];y.push(m),h.set(g,y)}return h},[t]),[l,d]=S.useState({});S.useLayoutEffect(()=>{if(!r||!i.current||!n.current)return;const h=n.current.getBoundingClientRect(),m=i.current.getBoundingClientRect(),g=8;let y=h.right-4,b=i.current.offsetTop+h.top-4;y+m.width+g>window.innerWidth&&(y=h.left-m.width+4),b+m.height+g>window.innerHeight&&(b=window.innerHeight-m.height-g),b<g&&(b=g),d({position:"fixed",left:y,top:b})},[r,n]);const f=[];for(const[h,m]of o)if(h!=="_ungrouped"&&m.length>=3)f.push(u.jsxs("span",{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsxs("button",{className:"context-menu-item context-menu-submenu-trigger",onMouseEnter:()=>s(h),onClick:()=>s(r===h?null:h),children:[u.jsx("span",{children:"Transform"}),u.jsx("span",{className:"context-menu-submenu-arrow",children:"▸"})]}),r===h&&u.jsx("div",{ref:i,className:"context-menu context-menu-submenu",style:l,onMouseLeave:()=>s(null),children:m.map(g=>u.jsx("button",{className:"context-menu-item",onClick:()=>e(g),children:u.jsx("span",{children:g.label})},g.action))})]},`sub-${h}`));else{let g=!0;for(const y of m){const b=g&&h!=="_ungrouped";g=!1,f.push(u.jsxs("span",{children:[b&&u.jsx("div",{className:"context-menu-divider"}),b&&u.jsx("div",{className:"context-menu-section-header",children:h}),u.jsx("button",{className:"context-menu-item",onClick:()=>e(y),children:u.jsx("span",{children:y.label})})]},y.action))}}return u.jsx(u.Fragment,{children:f})}function wd({x:t,y:e,filename:n,title:r,onClose:s,onDuplicate:i,onRename:o,onArchive:l,onDelete:d,onPluginAction:f,pluginItems:h,onSchedulePost:m,onViewAnalytics:g,viewAnalyticsLabel:y,onMarkSent:b,isAlreadySent:x,isApproved:k,onToggleApprove:E,isAutoAccept:C,onToggleAutoAccept:O,folderMode:_,onNewDoc:T,onNewContainer:R,onAcceptAll:I,onRejectAll:B,folderAutoAccept:P,onToggleFolderAutoAccept:D,folderAutoAcceptLabel:V,folderDocCount:$,onDeleteWithDocs:Q,bulkCount:G,onBulkDelete:K}){const X=S.useRef(null),[re,J]=S.useState(!1),[oe,U]=S.useState(!1),[A,L]=S.useState({left:t,top:e});S.useLayoutEffect(()=>{const se=X.current;if(!se)return;const be=se.getBoundingClientRect(),ee=8;let ge=t,fe=e;e+be.height+ee>window.innerHeight&&(fe=e-be.height),t+be.width+ee>window.innerWidth&&(ge=t-be.width),fe<ee&&(fe=ee),ge<ee&&(ge=ee),L({left:ge,top:fe})},[t,e]),S.useEffect(()=>{const se=be=>{X.current&&!X.current.contains(be.target)&&s()};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[s]),S.useEffect(()=>{const se=be=>{be.key==="Escape"&&s()};return document.addEventListener("keydown",se),()=>document.removeEventListener("keydown",se)},[s]);const te=S.useCallback(se=>{f(se.action,se),s()},[f,s]);return G&&G>1&&K?u.jsxs("div",{ref:X,className:"context-menu",style:{left:A.left,top:A.top},children:[u.jsxs("div",{className:"context-menu-section-header",children:[G," selected"]}),re?u.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:se=>se.stopPropagation(),children:[u.jsxs("span",{children:["Delete ",G,"?"]}),u.jsx("button",{onClick:()=>{K(),s()},children:"Yes"}),u.jsx("button",{onClick:()=>J(!1),children:"No"})]}):u.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>J(!0),children:u.jsxs("span",{children:["Delete (",G,")"]})})]}):_?u.jsxs("div",{ref:X,className:"context-menu",style:{left:A.left,top:A.top},children:[u.jsx("button",{className:"context-menu-item",onClick:()=>{o(),s()},children:u.jsx("span",{children:"Rename"})}),T&&u.jsx("button",{className:"context-menu-item",onClick:se=>{T(se),s()},children:u.jsx("span",{children:"New Document"})}),R&&u.jsx("button",{className:"context-menu-item",onClick:()=>{R(),s()},children:u.jsx("span",{children:"New Container"})}),(I||B)&&u.jsx("div",{className:"context-menu-divider"}),I&&u.jsx("button",{className:"context-menu-item",onClick:()=>{I(),s()},children:u.jsx("span",{children:"Accept All Changes"})}),B&&u.jsx("button",{className:"context-menu-item",onClick:()=>{B(),s()},children:u.jsx("span",{children:"Reject All Changes"})}),D&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{D(),s()},children:u.jsx("span",{children:P?`Turn off auto-accept${V?" "+V:""}`:`Turn on auto-accept${V?" "+V:""}`})})]}),u.jsx("div",{className:"context-menu-divider"}),re?$&&$>0&&Q?u.jsxs("div",{className:"sidebar-ctx-folder-delete",onClick:se=>se.stopPropagation(),children:[u.jsx("div",{className:"sidebar-ctx-folder-delete-prompt",children:"Delete this folder?"}),u.jsxs("button",{className:"context-menu-item sidebar-ctx-delete-option",onClick:()=>{d(),s()},children:[u.jsx("span",{children:"Folder only"}),u.jsxs("span",{className:"sidebar-ctx-delete-hint",children:[$," doc",$===1?"":"s"," → Documents"]})]}),u.jsxs("button",{className:"context-menu-item sidebar-ctx-delete-option sidebar-ctx-delete",onClick:()=>{Q(),s()},children:[u.jsxs("span",{children:["Folder + ",$," doc",$===1?"":"s"]}),u.jsx("span",{className:"sidebar-ctx-delete-hint",children:"permanently deletes files"})]}),u.jsx("button",{className:"context-menu-item sidebar-ctx-delete-cancel",onClick:()=>J(!1),children:u.jsx("span",{children:"Cancel"})})]}):u.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:se=>se.stopPropagation(),children:[u.jsx("span",{children:"Delete?"}),u.jsx("button",{onClick:()=>{d(),s()},children:"Yes"}),u.jsx("button",{onClick:()=>J(!1),children:"No"})]}):u.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>J(!0),children:u.jsx("span",{children:"Delete"})})]}):u.jsxs("div",{ref:X,className:"context-menu",style:{left:A.left,top:A.top},children:[u.jsx("button",{className:"context-menu-item",onClick:()=>{i(),s()},children:u.jsx("span",{children:"Duplicate"})}),u.jsx("button",{className:"context-menu-item",onClick:()=>{o(),s()},children:u.jsx("span",{children:"Rename"})}),oe?u.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:se=>se.stopPropagation(),children:[u.jsx("span",{children:"Archive?"}),u.jsx("button",{onClick:()=>{l(),s()},children:"Yes"}),u.jsx("button",{onClick:()=>U(!1),children:"No"})]}):u.jsx("button",{className:"context-menu-item",onClick:()=>U(!0),children:u.jsx("span",{children:"Archive"})}),re?u.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:se=>se.stopPropagation(),children:[u.jsx("span",{children:ks(n)?"Remove?":"Delete?"}),u.jsx("button",{onClick:()=>{d(),s()},children:"Yes"}),u.jsx("button",{onClick:()=>J(!1),children:"No"})]}):u.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>J(!0),children:u.jsx("span",{children:ks(n)?"Remove":"Delete"})}),E&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{E(),s()},children:u.jsx("span",{children:k?"Remove Approval":"Approve"})})]}),O&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{O(),s()},children:u.jsx("span",{children:C?"Turn off auto-accept":"Turn on auto-accept"})})]}),m&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{m(),s()},children:u.jsx("span",{children:"Schedule Post"})})]}),b&&!x&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{b(),s()},children:u.jsx("span",{children:"Mark as Sent"})})]}),g&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{g(),s()},children:u.jsx("span",{children:y||"View Analytics"})})]}),h.length>0&&u.jsx(F5,{items:h,onAction:te,menuRef:X})]})}function r2({actionLabel:t,docTitle:e,onConfirm:n,onClose:r}){const[s,i]=S.useState(""),o=S.useRef(null);S.useEffect(()=>{var d;(d=o.current)==null||d.focus()},[]),S.useEffect(()=>{const d=f=>{f.key==="Escape"&&r()};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const l=S.useCallback(()=>{n(s.trim())},[s,n]);return u.jsx("div",{className:"focus-modal-overlay",onClick:r,children:u.jsxs("div",{className:"focus-modal",onClick:d=>d.stopPropagation(),children:[u.jsxs("div",{className:"focus-modal-header",children:[u.jsx("h2",{children:t}),u.jsx("button",{className:"focus-modal-close",onClick:r,children:"×"})]}),u.jsxs("div",{className:"focus-modal-body",children:[u.jsxs("label",{children:['Focus instructions for "',e,'"',u.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()}})]}),u.jsxs("div",{className:"focus-modal-hint",children:[s.length,"/500"]}),u.jsxs("div",{className:"focus-modal-actions",children:[u.jsx("button",{className:"focus-modal-btn secondary",onClick:r,children:"Cancel"}),u.jsx("button",{className:"focus-modal-btn primary",onClick:l,children:"Go"})]})]})]})})}function xp(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(u.jsx("mark",{children:t.slice(o,o+e.length)},o)),i=o+e.length}return n}function rw({r:t,query:e,onClick:n}){return u.jsxs("div",{className:`sidebar-item search-result-item ${t.isActive?"active":""} ${t.isArchived?"search-result-archived":""}`,onClick:n,children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-item-title-text",children:t.matchType==="title"?xp(t.title,e):t.title}),t.isArchived&&u.jsx("span",{className:"search-archived-badge",children:"archived"})]}),t.matchType==="tag"&&t.matchedTag&&u.jsxs("div",{className:"search-result-tag",children:["Tag: ",xp(t.matchedTag,e)]}),t.matchType==="content"&&t.snippet&&u.jsx("div",{className:"search-result-snippet",children:xp(t.snippet,e)}),u.jsxs("div",{className:"sidebar-item-meta",children:[t.wordCount.toLocaleString()," words · ",ea(t.lastModified)]})]})}function $d({results:t,query:e,onSwitchDocument:n,actions:r}){if(t.length===0)return u.jsx("div",{className:"sidebar-scroll",children:u.jsxs("div",{className:"search-empty",children:['No results for "',e,'"']})});const s=t.filter(o=>!o.isArchived),i=t.filter(o=>o.isArchived);return u.jsx("div",{className:"sidebar-scroll",children:u.jsxs("div",{className:"search-results",children:[s.map(o=>u.jsx(rw,{r:o,query:e,onClick:()=>n(o.filename)},o.filename)),i.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"search-archived-divider",children:u.jsx("span",{children:"Archived"})}),i.map(o=>u.jsx(rw,{r:o,query:e,onClick:()=>r.handleUnarchive(o.filename)},o.filename))]})]})})}async function wp(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 kp(t,e){return e?(t/e*100).toFixed(1)+"%":"0%"}function sw(t){return new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function iw(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 s2({docId:t,title:e,onClose:n}){const[r,s]=S.useState("loading"),[i,o]=S.useState([]),[l,d]=S.useState(""),[f,h]=S.useState(null),[m,g]=S.useState(null),[y,b]=S.useState("links"),[x,k]=S.useState("all"),[E,C]=S.useState(!1),[O,_]=S.useState(!1),[T,R]=S.useState(""),[I,B]=S.useState(!1),[P,D]=S.useState(null),V=S.useRef(null);S.useEffect(()=>{let ee=!1;return(async()=>{try{const ge=await wp("list_newsletter_issues",{limit:20});if(ee)return;if(!ge.issues||ge.issues.length===0){s("no-data");return}o(ge.issues);const fe=ge.issues[0].id;d(fe)}catch(ge){ee||(g(ge.message),s("error"))}})(),()=>{ee=!0}},[]),S.useEffect(()=>{if(!l)return;let ee=!1;return C(!0),_(!1),D(null),R(""),(async()=>{try{const ge=await wp("get_newsletter_analytics",{issue_id:l});if(ee)return;if(ge.error){g(ge.error),s("error");return}h(ge),s("loaded")}catch(ge){ee||(g(ge.message),s("error"))}finally{ee||C(!1)}})(),()=>{ee=!0}},[l]),S.useEffect(()=>{const ee=ge=>{V.current&&!V.current.contains(ge.target)&&n()};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[n]),S.useEffect(()=>{const ee=ge=>{ge.key==="Escape"&&n()};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[n]);const $=f?H5(f.subscriber_events):[],Q=(f==null?void 0:f.issue.recipient_count)??0,G=f?f.stats.delivered||Q-f.stats.bounces:0,K=f?new Set(f.subscriber_events.filter(ee=>{var ge;return ee.event_type==="click"&&((ge=ee.url)==null?void 0:ge.includes("/newsletter/unsubscribe/"))}).map(ee=>ee.email)).size:0,X=f?f.stats.unsubscribes||K:0,re=f?f.subscriber_events.filter(ee=>ee.event_type==="dropped").length:0,J=f?Math.max(0,Q-f.stats.unique_opens):0,oe=f!=null&&f.issue.sent_at?Date.now()-new Date(f.issue.sent_at).getTime():0,U=Math.floor(oe/36e5),A=!!(f!=null&&f.issue.resent_at||P),L=ee=>{const ge=Math.floor(ee/36e5);return ge<1?"just now":ge<24?`${ge}h ago`:`${Math.floor(ge/24)}d ${ge%24}h ago`},te=async()=>{if(!(!T.trim()||I)){B(!0);try{const ee=await wp("resend_to_unopened",{issue_id:l,subject:T});ee.error?(g(ee.error),s("error")):(D({sent:ee.sent,failed:ee.failed}),_(!1))}catch(ee){g(ee.message),s("error")}finally{B(!1)}}},se=ee=>{var ge;return ee.event_type==="unsubscribe"||ee.event_type==="click"&&!!((ge=ee.url)!=null&&ge.includes("/newsletter/unsubscribe/"))},be=f?U5(f.subscriber_events.filter(ee=>x==="all"?!0:x==="unsubscribe"?se(ee):ee.event_type===x)):[];return u.jsx("div",{className:"newsletter-modal-overlay",children:u.jsxs("div",{className:"na-modal",ref:V,children:[u.jsxs("div",{className:"na-header",children:[u.jsx("h3",{children:"Newsletter Analytics"}),u.jsx("button",{className:"newsletter-modal__close",onClick:n,children:"×"})]}),r==="loading"&&!f&&u.jsx("div",{className:"na-body",children:u.jsxs("div",{className:"newsletter-modal__status",children:[u.jsx("div",{className:"newsletter-modal__spinner"}),u.jsx("span",{children:"Loading analytics..."})]})}),r==="no-data"&&u.jsxs("div",{className:"na-body",children:[u.jsx("div",{className:"newsletter-modal__status",children:u.jsx("span",{children:"No newsletter sends found yet."})}),u.jsx("div",{className:"newsletter-modal__actions",children:u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:n,children:"Done"})})]}),r==="error"&&u.jsxs("div",{className:"na-body",children:[u.jsx("div",{className:"newsletter-modal__error",children:m}),u.jsx("div",{className:"newsletter-modal__actions",children:u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:n,children:"Done"})})]}),r==="loaded"&&f&&u.jsxs("div",{className:"na-body",children:[i.length>1&&u.jsx("select",{className:"newsletter-modal__select na-issue-select",value:l,onChange:ee=>d(ee.target.value),children:i.map(ee=>u.jsxs("option",{value:ee.id,children:[ee.subject," — ",sw(ee.sent_at)]},ee.id))}),E?u.jsxs("div",{className:"newsletter-modal__status",children:[u.jsx("div",{className:"newsletter-modal__spinner"}),u.jsx("span",{children:"Loading..."})]}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"na-kpi-row",children:[u.jsxs("div",{className:"na-kpi",children:[u.jsx("div",{className:"na-kpi__value",children:G.toLocaleString()}),u.jsx("div",{className:"na-kpi__label",children:"Delivered"}),u.jsxs("div",{className:"na-kpi__sub",children:[Q.toLocaleString()," sent"]})]}),u.jsxs("div",{className:"na-kpi",children:[u.jsx("div",{className:"na-kpi__value",children:kp(f.stats.unique_opens,G)}),u.jsx("div",{className:"na-kpi__label",children:"Open rate"}),u.jsxs("div",{className:"na-kpi__sub",children:[f.stats.unique_opens.toLocaleString()," opens"]})]}),u.jsxs("div",{className:"na-kpi",children:[u.jsx("div",{className:"na-kpi__value",children:kp(f.stats.unique_clicks,G)}),u.jsx("div",{className:"na-kpi__label",children:"Click rate"}),u.jsxs("div",{className:"na-kpi__sub",children:[f.stats.unique_clicks.toLocaleString()," clicks"]})]})]}),u.jsxs("div",{className:"na-kpi-row na-kpi-row--secondary",children:[u.jsxs("div",{className:"na-kpi na-kpi--sm",children:[u.jsx("span",{className:"na-kpi__value--sm",children:f.stats.bounces}),u.jsx("span",{className:"na-kpi__label--sm",children:"Bounces"})]}),u.jsxs("div",{className:"na-kpi na-kpi--sm",children:[u.jsx("span",{className:"na-kpi__value--sm",children:X}),u.jsx("span",{className:"na-kpi__label--sm",children:"Unsubs"})]}),u.jsxs("div",{className:"na-kpi na-kpi--sm",children:[u.jsx("span",{className:"na-kpi__value--sm",children:re}),u.jsx("span",{className:"na-kpi__label--sm",children:"Dropped"})]}),f.stats.complaints>0&&u.jsxs("div",{className:"na-kpi na-kpi--sm",children:[u.jsx("span",{className:"na-kpi__value--sm",children:f.stats.complaints}),u.jsx("span",{className:"na-kpi__label--sm",children:"Spam"})]})]}),J>0&&!A&&u.jsx("div",{className:"na-resend",children:O?u.jsxs("div",{className:"na-resend-panel",children:[u.jsxs("div",{className:"na-resend-label-row",children:[u.jsx("span",{className:"na-resend-label",children:"New subject line"}),u.jsxs("span",{className:"na-resend-meta",children:["sent ",L(oe),U<48?" · consider waiting 48h":""]})]}),u.jsx("input",{className:"na-resend-input",type:"text",value:T,onChange:ee=>R(ee.target.value),placeholder:"Try a different angle"}),u.jsxs("div",{className:"na-resend-actions",children:[u.jsx("button",{className:"na-resend-cancel",onClick:()=>_(!1),children:"Cancel"}),u.jsx("button",{className:"na-resend-send",onClick:te,disabled:I||!T.trim(),children:I?"Sending...":`Send to ${J.toLocaleString()}`})]})]}):u.jsxs("button",{className:"na-resend-toggle",onClick:()=>{_(!0),R(f.issue.subject)},children:["Resend to ",J.toLocaleString()," non-openers ",u.jsx("span",{style:{float:"right"},children:"›"})]})}),A&&u.jsxs("div",{className:"na-resend-done",children:["Resent ",f.issue.resent_at?L(Date.now()-new Date(f.issue.resent_at).getTime()):"just now",P?` — ${P.sent} sent`:"",f.issue.resend_subject?` — "${f.issue.resend_subject}"`:""]}),u.jsxs("div",{className:"na-tabs",children:[u.jsxs("button",{className:`na-tab${y==="links"?" active":""}`,onClick:()=>b("links"),children:["Links (",$.length,")"]}),u.jsxs("button",{className:`na-tab${y==="activity"?" active":""}`,onClick:()=>b("activity"),children:["Activity (",f.subscriber_events.length,")"]})]}),y==="links"&&u.jsx("div",{className:"na-table-wrap",children:$.length===0?u.jsx("div",{className:"na-empty",children:"No link clicks recorded yet."}):u.jsxs("table",{className:"na-table",children:[u.jsx("thead",{children:u.jsxs("tr",{children:[u.jsx("th",{children:"Link"}),u.jsx("th",{children:"Unique"}),u.jsx("th",{children:"Total"}),u.jsx("th",{children:"CTR"})]})}),u.jsx("tbody",{children:$.map(ee=>u.jsxs("tr",{children:[u.jsx("td",{className:"na-table__url",title:ee.url,children:u.jsx("a",{href:ee.url,target:"_blank",rel:"noopener noreferrer",children:iw(ee.url)})}),u.jsx("td",{children:ee.uniqueClicks}),u.jsx("td",{children:ee.totalClicks}),u.jsx("td",{children:kp(ee.uniqueClicks,G)})]},ee.url))})]})}),y==="activity"&&u.jsxs("div",{className:"na-activity",children:[u.jsx("div",{className:"na-filter-row",children:["all","open","click","bounce","dropped","unsubscribe"].map(ee=>u.jsx("button",{className:`na-filter-btn${x===ee?" active":""}`,onClick:()=>k(ee),children:ee==="all"?"All":ee.charAt(0).toUpperCase()+ee.slice(1)+"s"},ee))}),u.jsxs("div",{className:"na-table-wrap",children:[be.length===0?u.jsxs("div",{className:"na-empty",children:["No ",x==="all"?"":x+" ","events recorded."]}):u.jsxs("table",{className:"na-table",children:[u.jsx("thead",{children:u.jsxs("tr",{children:[u.jsx("th",{children:"Email"}),u.jsx("th",{children:"Event"}),u.jsx("th",{children:"Detail"}),u.jsx("th",{children:"Time"})]})}),u.jsx("tbody",{children:be.slice(0,100).map(ee=>u.jsxs("tr",{children:[u.jsx("td",{className:"na-table__email",children:ee.email}),u.jsxs("td",{children:[u.jsx("span",{className:`na-badge na-badge--${ee.event_type}`,children:ee.event_type}),ee.count>1&&u.jsxs("span",{className:"na-count",children:[ee.count,"x"]})]}),u.jsx("td",{className:"na-table__url",children:ee.url?u.jsx("a",{href:ee.url,target:"_blank",rel:"noopener noreferrer",children:iw(ee.url,35)}):"—"}),u.jsx("td",{className:"na-table__time",children:sw(ee.latestTimestamp)})]},ee.key))})]}),be.length>100&&u.jsxs("div",{className:"na-truncated",children:["Showing 100 of ",be.length," events"]})]})]})]})]})]})})}function U5(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 H5(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 W5(t){return t.tweetContext?"tweet":t.articleContext?"article":t.linkedinContext?"linkedin":t.newsletterContext?"newsletter":t.blogContext?"blog":"tweet"}function Cl({filename:t,title:e,onClose:n}){const[r,s]=S.useState("queue"),[i,o]=S.useState(null),[l,d]=S.useState(null),[f,h]=S.useState(""),[m,g]=S.useState(!1),[y,b]=S.useState(null),[x,k]=S.useState(null);S.useEffect(()=>{fetch(`/api/documents/${encodeURIComponent(t)}/text`).then(O=>{if(!O.ok)throw new Error("Failed to load document");return O.json()}).then(O=>{d(O.text||""),o(W5(O.meta||{}))}).catch(O=>k(O.message))},[t]);const E=async()=>{var O;if(!(!l||!i)){g(!0);try{const _={content:l,content_type:i,mode:r};r==="custom"&&f&&(_.scheduled_at=new Date(f).toISOString());const T=await fetch("/api/scheduler/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)}),R=await T.json();if(T.ok){const I=(O=R.item)!=null&&O.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(_){b({success:!1,message:_.message})}finally{g(!1)}}},C=i===null&&!x;return u.jsx("div",{className:"schedule-post-overlay",onClick:n,children:u.jsxs("div",{className:"schedule-post-modal",onClick:O=>O.stopPropagation(),children:[u.jsxs("div",{className:"schedule-post-modal-header",children:[u.jsx("h3",{children:"Schedule Post"}),u.jsx("button",{className:"schedule-post-modal-close",onClick:n,children:"×"})]}),u.jsx("div",{className:"schedule-post-modal-doc",children:e}),x?u.jsxs("div",{className:"schedule-post-modal-result error",children:[x,u.jsx("button",{className:"schedule-post-modal-done",onClick:n,children:"Done"})]}):y?u.jsxs("div",{className:`schedule-post-modal-result ${y.success?"success":"error"}`,children:[y.message,u.jsx("button",{className:"schedule-post-modal-done",onClick:n,children:"Done"})]}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"schedule-post-modal-field",children:[u.jsx("label",{children:"Content Type"}),u.jsx("div",{className:"schedule-post-modal-type",children:C?"...":i})]}),u.jsxs("div",{className:"schedule-post-modal-field",children:[u.jsx("label",{children:"Mode"}),u.jsxs("div",{className:"schedule-post-modal-modes",children:[u.jsx("button",{className:`schedule-post-mode ${r==="queue"?"active":""}`,onClick:()=>s("queue"),children:"Queue Next"}),u.jsx("button",{className:`schedule-post-mode ${r==="now"?"active":""}`,onClick:()=>s("now"),children:"Post Now"}),u.jsx("button",{className:`schedule-post-mode ${r==="custom"?"active":""}`,onClick:()=>s("custom"),children:"Custom Time"})]})]}),r==="custom"&&u.jsxs("div",{className:"schedule-post-modal-field",children:[u.jsx("label",{children:"Date & Time"}),u.jsx("input",{type:"datetime-local",value:f,onChange:O=>h(O.target.value)})]}),u.jsxs("div",{className:"schedule-post-modal-actions",children:[u.jsx("button",{className:"schedule-post-modal-cancel",onClick:n,children:"Cancel"}),u.jsx("button",{className:"schedule-post-modal-submit",onClick:E,disabled:m||C||r==="custom"&&!f,children:m?"Scheduling...":r==="now"?"Post Now":"Schedule"})]})]})]})})}const ow=[{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 i2({anchorRect:t,onSelect:e,onClose:n}){const r=S.useRef(null),[s,i]=S.useState(null),[o,l]=S.useState(""),d=S.useRef(null),[f,h]=S.useState({left:t.left,top:t.bottom+4});S.useLayoutEffect(()=>{const b=r.current;if(!b)return;const x=b.getBoundingClientRect(),k=8;let E=t.left,C=t.bottom+4;C+x.height+k>window.innerHeight&&(C=t.top-x.height-4),E+x.width+k>window.innerWidth&&(E=t.right-x.width),C<k&&(C=k),E<k&&(E=k),h({left:E,top:C})},[t]),S.useEffect(()=>{const b=x=>{r.current&&!r.current.contains(x.target)&&n()};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[n]),S.useEffect(()=>{const b=x=>{x.key==="Escape"&&n()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[n]),S.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 x=ow.find(E=>E.key===s);if(!(x!=null&&x.metadata))return;const k=JSON.parse(JSON.stringify(x.metadata));k.tweetContext&&(k.tweetContext.url=b),e(k)},y=o.trim().includes("x.com")||o.trim().includes("twitter.com");return u.jsx("div",{ref:r,className:"create-doc-dropdown",style:{left:f.left,top:f.top},children:ow.map(b=>u.jsxs("div",{children:[u.jsx("button",{className:`create-doc-dropdown-item${s===b.key?" active":""}`,onClick:()=>m(b),children:b.label}),s===b.key&&u.jsxs("div",{className:"create-doc-dropdown-url",children:[u.jsx("input",{ref:d,type:"text",placeholder:b.urlPlaceholder,value:o,onChange:x=>l(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),g()),x.key==="Escape"&&(i(null),l(""))}}),u.jsx("button",{onClick:g,disabled:!y,children:u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"9 18 15 12 9 6"})})})]})]},b.key))})}const q5=[{id:"full",label:"Full"},{id:"compact",label:"Compact"},{id:"minimal",label:"Minimal"}];function o2(t,e){if(!e)return!0;for(const n of t)if(n.type==="container"&&(n.id===e||o2(n.items,e)))return!0;return!1}function a2(t,e){for(const n of t){if(n.type==="doc"&&n.file===e)return[];if(n.type==="container"){const r=a2(n.items,e);if(r)return[n.id,...r]}}return null}function V5({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:y,onSearchChange:b}){var Jt;const x=M=>!!m&&m.has(M),[k,E]=S.useState(null),[C,O]=S.useState(""),[_,T]=S.useState(null),[R,I]=S.useState(()=>{try{const M=localStorage.getItem("ow-collapsed-sections");return M?new Set(JSON.parse(M)):new Set}catch{return new Set}}),[B,P]=S.useState(null),[D,V]=S.useState(null),[$,Q]=S.useState(""),[G,K]=S.useState(null),[X,re]=S.useState(""),[J,oe]=S.useState(null),[U,A]=S.useState(""),[L,te]=S.useState(null),[se,be]=S.useState(null),[ee,ge]=S.useState([]),[fe,Te]=S.useState(null),[Xe,tt]=S.useState(null),[st,nt]=S.useState(null),[Le,yt]=S.useState(null),[Ke,Et]=S.useState(null),[je,Je]=S.useState(oE),Fe=S.useRef(null);S.useEffect(()=>{if(!Ke)return;const M=ne=>{Fe.current&&!Fe.current.contains(ne.target)&&Et(null)};return document.addEventListener("mousedown",M),()=>document.removeEventListener("mousedown",M)},[Ke]);const Nt=M=>{Je(M),zM(M),Et(null)},qt=M=>{M.preventDefault(),Et({x:M.clientX,y:M.clientY})},ie=S.useCallback((M,ne)=>{fetch("/api/documents/batch-resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filenames:M,action:ne})}).catch(()=>{})},[]),{draggedItem:H,dropIndicator:q,handlePointerDown:de,dropClass:me,isDragging:Ee,isContainerDropTarget:De}=n2({docs:t,workspaces:n,assignedFiles:r,scrollRef:d,setCollapsedSections:I}),$e=S.useCallback(()=>{fetch("/api/plugins").then(M=>M.json()).then(M=>{const ne=[];for(const ue of M.plugins||[]){const Me=ue.displayName||void 0;for(const ct of ue.sidebarMenuItems||[])ne.push({...ct,pluginDisplayName:Me})}ge(ne)}).catch(()=>{})},[]);S.useEffect(()=>{$e()},[$e]),S.useEffect(()=>{const M=()=>$e();return window.addEventListener("ow-plugins-changed",M),()=>window.removeEventListener("ow-plugins-changed",M)},[$e]);const{variantsByMaster:qe,variantFilenames:W}=S.useMemo(()=>{const M=new Map,ne=new Set;for(const ue of t)if(ue.masterDocId){const Me=M.get(ue.masterDocId)||[];Me.push(ue),M.set(ue.masterDocId,Me),ne.add(ue.filename)}return{variantsByMaster:M,variantFilenames:ne}},[t]),pe=S.useCallback((M,ne)=>{M.preventDefault(),M.stopPropagation(),te({x:M.clientX,y:M.clientY,filename:ne.filename,title:ne.title,docId:ne.docId,lastSent:ne.lastSent,postedUrl:ne.postedUrl,isNewsletter:ne.isNewsletter})},[]),xe=S.useCallback(M=>{fetch("/api/documents/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:M})}).catch(()=>{})},[]),Ye=S.useCallback((M,ne,ue,Me,ct)=>{if(ne.promptForFocus&&ct===void 0){Te({action:M,label:ne.label,filename:ue,title:Me});return}fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:M,filename:ue,title:Me,instructions:ct||"",label:ne.label})}).catch(()=>{})},[]),it=M=>{I(ne=>{const ue=new Set(ne);return ue.has(M)?ue.delete(M):ue.add(M),localStorage.setItem("ow-collapsed-sections",JSON.stringify([...ue])),ue})},ot=t.find(M=>M.isActive),Re=S.useRef(n);if(Re.current=n,S.useEffect(()=>{var M;if(ot)for(const ne of Re.current){const ue=a2(((M=ne.workspace)==null?void 0:M.root)||[],ot.filename);if(ue){I(Me=>{const ct=[ne.filename,...ue.map(ve=>`container-${ve}`)];if(ct.every(ve=>!Me.has(ve)))return Me;const gt=new Set(Me);for(const ve of ct)gt.delete(ve);return localStorage.setItem("ow-collapsed-sections",JSON.stringify([...gt])),gt});break}}},[ot==null?void 0:ot.filename]),y!==null)return u.jsx($d,{results:y,query:g,onSwitchDocument:i,actions:l});const vt=t.filter(M=>!r.has(M.filename)&&!W.has(M.filename)),ht=(M,ne,ue,Me,ct,gt=!1)=>u.jsxs("div",{className:`sidebar-item ${M.isActive?"active":""} ${Ee(M.filename)?"dragging":""} ${me(M.filename)}`,"data-drag-id":M.filename,"data-drag-type":"doc","data-drag-ws":ne||"__docs__","data-drag-container":ue||"",onPointerDown:ve=>de(ve,{type:"doc",file:M.filename,sourceWs:ne||null},M.title),onClick:()=>!M.isActive&&!H&&i(M.filename),onDoubleClick:()=>{E(M.filename),O(M.title)},onContextMenu:ve=>pe(ve,M),children:[k===M.filename?u.jsx("input",{className:"sidebar-rename-input",value:C,onChange:ve=>O(ve.target.value),onBlur:()=>{l.handleRename(M.filename,M.title,C),E(null)},onKeyDown:ve=>{ve.key==="Enter"&&(l.handleRename(M.filename,M.title,C),E(null)),ve.key==="Escape"&&E(null)},autoFocus:!0,onClick:ve=>ve.stopPropagation()}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-item-title-text",children:M.title}),M.variantType&&u.jsx("span",{className:"files-badge-variant",children:M.variantType}),l.getDocTags(M.filename).includes("✓")&&u.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:u.jsx("polyline",{points:"20 6 9 17 4 12"})}),M.lastSent&&u.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:u.jsx("polyline",{points:"20 6 9 17 4 12"})}),(M.autoAccept===!0||M.autoAccept!==!1&&gt)&&u.jsx("span",{className:"sidebar-auto-accept-dot",title:M.autoAccept===!0?"Auto-accept on":"Auto-accept inherited"}),s.filenames.includes(M.filename)&&u.jsx("span",{className:"sidebar-pending-dot"})]}),ks(M.filename)&&u.jsx("div",{className:"sidebar-item-context",children:e2(M.filename)}),u.jsxs("div",{className:"sidebar-item-meta",children:[M.wordCount.toLocaleString()," words · ",ea(M.lastModified)]}),u.jsxs("div",{className:"sidebar-tags",children:[l.getDocTags(M.filename).filter(ve=>ve!=="✓").map(ve=>u.jsxs("span",{className:"sidebar-tag",onClick:z=>z.stopPropagation(),children:[ve,u.jsx("span",{className:"sidebar-tag-remove",onClick:z=>{z.stopPropagation(),l.handleRemoveTag(M.filename,ve)},children:"×"})]},ve)),J===M.filename?u.jsx("input",{className:"sidebar-tag-input",value:U,onChange:ve=>A(ve.target.value),onBlur:()=>{U.trim()&&l.handleAddTag(M.filename,U),oe(null)},onKeyDown:ve=>{ve.key==="Enter"&&(l.handleAddTag(M.filename,U),oe(null),A("")),ve.key==="Escape"&&(oe(null),A(""))},autoFocus:!0,onClick:ve=>ve.stopPropagation(),placeholder:"tag..."}):u.jsx("button",{className:"sidebar-tag-add",onClick:ve=>{ve.stopPropagation(),oe(M.filename),A("")},children:"+"})]})]}),_===M.filename?u.jsxs("div",{className:"sidebar-confirm-delete",onClick:ve=>ve.stopPropagation(),children:[u.jsx("span",{children:ks(M.filename)?"Remove?":"Delete?"}),u.jsx("button",{onClick:()=>{l.handleDelete(M.filename),T(null)},children:"Yes"}),u.jsx("button",{onClick:()=>T(null),children:"No"})]}):u.jsx("button",{className:"sidebar-delete-btn",onClick:ve=>{ve.stopPropagation(),T(M.filename)},title:ks(M.filename)?"Remove document":"Delete document",children:"×"})]},M.filename),zt=(M,ne,ue,Me,ct,gt=!1)=>{const ve=M.docId?qe.get(M.docId):void 0,z=f&&(h==null?void 0:h.parentDocId)&&h.parentDocId===M.docId;if(!(ve&&ve.length>0||z))return ht(M,ne,ue,Me,ct,gt);const Ie=`variants-${M.docId}`,He=!R.has(Ie);return u.jsxs("div",{className:"sidebar-variant-group",children:[u.jsxs("div",{className:"sidebar-variant-master",onClick:We=>{We.target.closest(".sidebar-variant-chevron")&&(We.stopPropagation(),it(Ie))},children:[ht(M,ne,ue,Me,ct,gt),u.jsx("span",{className:`sidebar-variant-chevron${He?"":" collapsed"}`,children:u.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"6 9 12 15 18 9"})})})]}),He&&u.jsxs("div",{className:"sidebar-variant-children",children:[ve==null?void 0:ve.map((We,Mt)=>ht(We,ne,ue,Me,Mt,gt)),z&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:f})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]})]})]},`vg-${M.filename}`)},Ut=(M,ne,ue,Me,ct,gt,ve=!1)=>{if(M.type==="doc"){const ut=t.find(yn=>yn.filename===M.file);return ut?W.has(ut.filename)?u.jsx(u.Fragment,{}):zt(ut,ue,Me,ct,gt,ve):ks(M.file)?u.jsx("div",{className:"sidebar-item sidebar-unavailable",children:u.jsxs("div",{className:"sidebar-item-title",children:[M.title||M.file," (unavailable)"]})},M.file):u.jsxs("div",{className:"sidebar-item sidebar-missing",children:[u.jsxs("div",{className:"sidebar-item-title",children:[M.title||M.file," (missing)"]}),u.jsx("button",{className:"sidebar-delete-btn",onClick:()=>l.handleRemoveFromWorkspace(ue,M.file),title:"Remove",children:"×"})]},M.file)}const z=M,he=`container-${z.id}`,Ie=R.has(he),He=ne<=2?`depth-${ne}`:"depth-2",We=z.autoAccept===!0,Mt=We||ve;return u.jsxs("div",{className:`sidebar-container ${He} ${Ie?"collapsed":""} ${me(z.id)} ${De(z.id)?"drop-inside":""}`,children:[u.jsxs("div",{className:`sidebar-container-header ${(q==null?void 0:q.itemId)===z.id&&q.position==="inside"?"drop-inside":""}`,"data-drag-id":z.id,"data-drag-type":"container-header","data-drag-ws":ue,"data-drag-parent":Me||"","data-section-key":he,onPointerDown:ut=>de(ut,{type:"container",id:z.id,sourceWs:ue},z.name),onClick:()=>!H&&it(he),onContextMenu:ut=>{ut.preventDefault(),ut.stopPropagation(),yt({x:ut.clientX,y:ut.clientY,type:"container",wsFilename:ue,containerId:z.id,title:z.name,nodes:z.items,autoAccept:We})},children:[u.jsx("span",{className:`sidebar-chevron ${Ie?"collapsed":""}`,children:"▾"}),D===z.id?u.jsx("input",{className:"sidebar-rename-input",value:$,onChange:ut=>Q(ut.target.value),onBlur:()=>{l.handleRenameContainer(ue,z.id,$),V(null)},onKeyDown:ut=>{ut.key==="Enter"&&(l.handleRenameContainer(ue,z.id,$),V(null)),ut.key==="Escape"&&V(null)},autoFocus:!0,onClick:ut=>ut.stopPropagation()}):u.jsx("span",{className:"sidebar-container-name",onDoubleClick:ut=>{ut.stopPropagation(),V(z.id),Q(z.name)},children:z.name}),Mt&&u.jsx("span",{className:"sidebar-auto-accept-dot",title:We?"Auto-accept on for this container":"Auto-accept inherited from workspace"}),u.jsxs("div",{className:"sidebar-container-actions",children:[u.jsx("button",{className:"sidebar-new-btn",onClick:ut=>{ut.stopPropagation(),nt({anchor:ut.target.getBoundingClientRect(),wsFilename:ue,containerId:z.id})},title:"New doc",children:"+"}),ne<2&&u.jsx("button",{className:"sidebar-new-btn",onClick:ut=>{ut.stopPropagation(),l.handleCreateContainer(ue,z.id)},title:"New sub-container",children:"☐"}),u.jsx("button",{className:"sidebar-new-btn sidebar-container-delete",onClick:ut=>{ut.stopPropagation(),l.handleDeleteContainer(ue,z.id)},title:"Delete container",children:"×"})]})]}),!Ie&&u.jsxs("div",{className:"sidebar-container-list","data-drop-ws":ue,"data-drop-container":z.id,children:[f&&!(h!=null&&h.parentDocId)&&(h==null?void 0:h.wsFilename)===ue&&h.containerId===z.id&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:f})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),z.items.filter(ut=>ut.type!=="doc"?!0:!(x(ut.file)||f&&(h==null?void 0:h.wsFilename)===ue&&h.containerId===z.id&&ut.title===f)).map((ut,yn)=>Ut(ut,ne+1,ue,z.id,z.items,yn,Mt)),z.items.length===0&&!f&&u.jsx("div",{className:"sidebar-empty",children:H?"Drop here":"Empty"})]})]},z.id)};return u.jsxs("div",{className:"sidebar-scroll",ref:d,children:[u.jsxs("div",{className:`sidebar-section sidebar-docs-section ${R.has("docs")?"docs-collapsed":""}`,children:[u.jsxs("div",{className:"sidebar-section-header","data-section-key":"docs",onClick:()=>it("docs"),onContextMenu:qt,children:[u.jsx("span",{className:`sidebar-chevron ${R.has("docs")?"collapsed":""}`,children:"▾"}),u.jsx("span",{className:"sidebar-label",children:"Documents"}),u.jsx("button",{className:"sidebar-new-btn",onClick:M=>{M.stopPropagation(),nt({anchor:M.target.getBoundingClientRect()})},title:"New document",children:"+"})]}),!R.has("docs")&&u.jsxs("div",{className:"sidebar-section-list","data-drop-ws":"__docs__",children:[f&&!(h!=null&&h.parentDocId)&&(!h||!n.some(M=>M.filename===(h==null?void 0:h.wsFilename)))&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:f})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),vt.filter(M=>!x(M.filename)&&(!f||M.title!==f)).map((M,ne)=>{const ue=vt.map(Me=>({type:"doc",file:Me.filename,title:Me.title}));return zt(M,void 0,null,ue,ne)}),vt.length===0&&u.jsx("div",{className:"sidebar-empty",children:H?"Drop here to unassign":"No unassigned documents"})]})]}),n.map(M=>{var ct,gt,ve;const ne=((ct=M.workspace)==null?void 0:ct.root)||[],ue=R.has(M.filename),Me=((gt=M.workspace)==null?void 0:gt.autoAccept)===!0||M.autoAccept===!0;return u.jsxs("div",{className:`sidebar-section sidebar-workspace-section ${ue?"ws-collapsed":""} ${Ee(M.filename)?"dragging":""} ${(q==null?void 0:q.itemId)===M.filename?q.position==="before"?"drop-before":"drop-after":""}`,children:[u.jsxs("div",{className:"sidebar-section-header","data-section-key":M.filename,"data-ws-drag":M.filename,onPointerDown:z=>de(z,{type:"workspace",filename:M.filename},M.title),onClick:()=>!H&&it(M.filename),onContextMenu:z=>{var he;z.preventDefault(),z.stopPropagation(),yt({x:z.clientX,y:z.clientY,type:"workspace",wsFilename:M.filename,title:M.title,nodes:ne,autoAccept:((he=M.workspace)==null?void 0:he.autoAccept)===!0||M.autoAccept===!0})},children:[u.jsx("span",{className:`sidebar-chevron ${ue?"collapsed":""}`,children:"▾"}),G===M.filename?u.jsx("input",{className:"sidebar-rename-input",value:X,onChange:z=>re(z.target.value),onBlur:()=>{l.handleRenameWorkspace(M.filename,X),K(null)},onKeyDown:z=>{z.key==="Enter"&&(l.handleRenameWorkspace(M.filename,X),K(null)),z.key==="Escape"&&K(null)},autoFocus:!0,onClick:z=>z.stopPropagation()}):u.jsx("span",{className:"sidebar-label sidebar-workspace-label",onDoubleClick:z=>{z.stopPropagation(),K(M.filename),re(M.title)},children:M.title}),(((ve=M.workspace)==null?void 0:ve.autoAccept)===!0||M.autoAccept===!0)&&u.jsx("span",{className:"sidebar-auto-accept-dot",title:"Auto-accept on for this workspace"}),u.jsxs("div",{className:"sidebar-workspace-actions",children:[u.jsx("button",{className:"sidebar-new-btn",onClick:z=>{z.stopPropagation(),nt({anchor:z.target.getBoundingClientRect(),wsFilename:M.filename,containerId:null})},title:"New document",children:"+"}),u.jsx("button",{className:"sidebar-new-btn",onClick:z=>{z.stopPropagation(),l.handleCreateContainer(M.filename,null)},title:"New container",children:"☐"}),B===M.filename?u.jsxs("span",{className:"sidebar-inline-confirm",onClick:z=>z.stopPropagation(),children:[u.jsx("button",{onClick:()=>{l.handleDeleteWorkspace(M.filename),P(null)},children:"Yes"}),u.jsx("button",{onClick:()=>P(null),children:"No"})]}):u.jsx("button",{className:"sidebar-new-btn sidebar-workspace-delete",onClick:z=>{z.stopPropagation(),P(M.filename)},title:"Delete workspace",children:"×"})]})]}),!ue&&u.jsxs("div",{className:"sidebar-section-list","data-drop-ws":M.filename,children:[f&&!(h!=null&&h.parentDocId)&&(h==null?void 0:h.wsFilename)===M.filename&&(h.containerId===null||!o2(ne,h.containerId))&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:f})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),ne.filter(z=>z.type!=="doc"?!0:!(x(z.file)||f&&(h==null?void 0:h.wsFilename)===M.filename&&h.containerId===null&&z.title===f)).map((z,he)=>Ut(z,0,M.filename,null,ne,he,Me)),ne.length===0&&!f&&u.jsx("div",{className:"sidebar-empty",children:H?"Drop here to add":"Empty workspace"})]})]},M.filename)}),u.jsx("div",{className:"sidebar-new-workspace",children:u.jsx("button",{onClick:l.handleCreateWorkspace,children:"+ New Workspace"})}),Le&&u.jsx(wd,{x:Le.x,y:Le.y,filename:Le.wsFilename,title:Le.title,onClose:()=>yt(null),onDuplicate:()=>{},onRename:()=>{Le.type==="workspace"?(K(Le.wsFilename),re(Le.title)):Le.containerId&&(V(Le.containerId),Q(Le.title)),yt(null)},onArchive:()=>{},onDelete:()=>{Le.type==="workspace"?l.handleDeleteWorkspace(Le.wsFilename):Le.containerId&&l.handleDeleteContainer(Le.wsFilename,Le.containerId)},onPluginAction:()=>{},pluginItems:[],folderMode:!0,onNewDoc:M=>{nt({anchor:M.target.getBoundingClientRect(),wsFilename:Le.wsFilename,containerId:Le.type==="container"?Le.containerId:null}),yt(null)},onNewContainer:()=>{l.handleCreateContainer(Le.wsFilename,Le.type==="container"?Le.containerId:null),yt(null)},onAcceptAll:()=>{const M=new Set;yl(Le.nodes,M),M.size&&ie([...M],"accept"),yt(null)},onRejectAll:()=>{const M=new Set;yl(Le.nodes,M),M.size&&ie([...M],"reject"),yt(null)},folderAutoAccept:Le.autoAccept,folderAutoAcceptLabel:Le.type==="workspace"?"for workspace":"for container",onToggleFolderAutoAccept:()=>{fetch("/api/auto-accept/inherit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wsFile:Le.wsFilename,...Le.type==="container"?{containerId:Le.containerId}:{},enabled:!Le.autoAccept})}).catch(()=>{})}}),L&&u.jsx(wd,{x:L.x,y:L.y,filename:L.filename,title:L.title,onClose:()=>te(null),onDuplicate:()=>xe(L.filename),onRename:()=>{E(L.filename),O(L.title)},onArchive:()=>l.handleArchive(L.filename),onDelete:()=>l.handleDelete(L.filename),onPluginAction:(M,ne)=>Ye(M,ne,L.filename,L.title),pluginItems:ee,onSchedulePost:()=>{tt({filename:L.filename,title:L.title}),te(null)},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"),te(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:((Jt=t.find(M=>M.filename===L.filename))==null?void 0:Jt.autoAccept)===!0,onToggleAutoAccept:()=>{var ne;const M=((ne=t.find(ue=>ue.filename===L.filename))==null?void 0:ne.autoAccept)===!0;fetch("/api/auto-accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:L.filename,enabled:!M})}).then(()=>l.fetchDocs()).catch(()=>{})},isAlreadySent:!!L.lastSent,onMarkSent:()=>{const M=L.filename;l.getDocTags(M).includes("✓")&&l.handleRemoveTag(M,"✓"),i(M),setTimeout(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualPost:{postedAt:new Date().toISOString()}})}).then(()=>l.fetchDocs()).catch(()=>{})},100),te(null)}}),fe&&u.jsx(r2,{actionLabel:fe.label,docTitle:fe.title,onClose:()=>Te(null),onConfirm:M=>{const ne=ee.find(ue=>ue.action===fe.action);ne&&Ye(fe.action,ne,fe.filename,fe.title,M),Te(null)}}),se&&u.jsx(s2,{docId:se.docId,title:se.title,onClose:()=>be(null)}),Xe&&u.jsx(Cl,{filename:Xe.filename,title:Xe.title,onClose:()=>tt(null)}),st&&u.jsx(i2,{anchorRect:st.anchor,onClose:()=>nt(null),onSelect:M=>{nt(null),st.wsFilename?l.handleCreateInWorkspace(st.wsFilename,st.containerId??null,M):M?fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:M})}).catch(()=>{}):o()}}),Ke&&u.jsx("div",{ref:Fe,className:"sidebar-density-dropdown",style:{position:"fixed",left:Ke.x,top:Ke.y,zIndex:200},children:q5.map(M=>u.jsx("button",{className:`sidebar-density-option ${je===M.id?"active":""}`,onClick:()=>Nt(M.id),children:M.label},M.id))})]})}function K5({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,onCreateDocument:i,actions:o,scrollRef:l,searchQuery:d,searchResults:f}){const[h,m]=S.useState(null);if(f!==null)return u.jsx($d,{results:f,query:d,onSwitchDocument:s});const g=[...t].sort((k,E)=>new Date(E.lastModified).getTime()-new Date(k.lastModified).getTime()),y=[];let b="";for(const k of g){const E=B5(k.lastModified);E!==b&&(y.push({label:E,docs:[]}),b=E),y[y.length-1].docs.push(k)}const x=k=>{for(const E of e){if(!E.workspace)continue;const C=O=>{for(const _ of O)if(_.type==="doc"&&_.file===k||_.type==="container"&&C(_.items))return!0;return!1};if(C(E.workspace.root))return E.title}return null};return u.jsxs("div",{className:"sidebar-scroll tl-scroll",ref:l,children:[u.jsxs("div",{className:"tl-header",children:[u.jsx("span",{className:"tl-title",children:"Timeline"}),u.jsx("button",{className:"sidebar-new-btn",onClick:i,title:"New document",children:"+"})]}),y.map(k=>u.jsxs("div",{className:"tl-group",children:[u.jsx("div",{className:"tl-date",children:k.label}),k.docs.map(E=>{const C=x(E.filename);return u.jsxs("div",{className:`tl-item ${E.isActive?"active":""}`,onClick:()=>!E.isActive&&s(E.filename),children:[u.jsx("div",{className:"tl-dot"}),u.jsxs("div",{className:"tl-content",children:[u.jsxs("div",{className:"tl-item-title",children:[u.jsx("span",{children:E.title}),r.filenames.includes(E.filename)&&u.jsx("span",{className:"sidebar-pending-dot"})]}),ks(E.filename)&&u.jsx("div",{className:"tl-item-context",children:e2(E.filename)}),u.jsxs("div",{className:"tl-item-meta",children:[E.wordCount.toLocaleString()," words · ",ea(E.lastModified)]}),C&&u.jsx("div",{className:"tl-badge",children:C})]}),h===E.filename?u.jsxs("div",{className:"sidebar-confirm-delete",onClick:O=>O.stopPropagation(),children:[u.jsx("span",{children:ks(E.filename)?"Remove?":"Delete?"}),u.jsx("button",{onClick:()=>{o.handleDelete(E.filename),m(null)},children:"Yes"}),u.jsx("button",{onClick:()=>m(null),children:"No"})]}):u.jsx("button",{className:"sidebar-delete-btn",onClick:O=>{O.stopPropagation(),m(E.filename)},title:ks(E.filename)?"Remove":"Delete",children:"×"})]},E.filename)})]},k.label)),t.length===0&&u.jsx("div",{className:"sidebar-empty",children:"No documents yet"})]})}function G5({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:o,searchQuery:l,searchResults:d,onSearchChange:f}){const[h,m]=S.useState([]),[g,y]=S.useState(null),[b,x]=S.useState(null),k=S.useRef(null);S.useEffect(()=>{if(!g)return;const A=L=>{k.current&&!k.current.contains(L.target)&&y(null)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[g]);const E=(A,L)=>{for(const te of A)if(te.type==="container"){if(te.id===L)return te;const se=E(te.items,L);if(se)return se}return null},C=A=>{let L=0;for(const te of A)te.type==="doc"?L++:te.type==="container"&&(L+=C(te.items));return L},O=A=>{const L=[];for(const te of A)te.type==="doc"?L.push(te.file):te.type==="container"&&L.push(...O(te.items));return L},_=S.useMemo(()=>{if(h.length===0)return[];const A=h[h.length-1],L=e.find(se=>se.filename===A.wsFilename);if(!(L!=null&&L.workspace))return[];if(A.type==="workspace")return L.workspace.root;const te=E(L.workspace.root,A.key);return te?te.items:[]},[h,e]),T=_.filter(A=>A.type==="container"),R=S.useMemo(()=>{const A=_.filter(L=>L.type==="doc").map(L=>L.file);return t.filter(L=>A.includes(L.filename))},[_,t]),I=A=>{const L=O(A.items);return t.filter(te=>L.includes(te.filename))},B=A=>{const L=e.find(se=>se.filename===A);if(!(L!=null&&L.workspace))return[];const te=O(L.workspace.root);return t.filter(se=>te.includes(se.filename))},P=S.useMemo(()=>t.filter(A=>!n.has(A.filename)),[t,n]),D=A=>{m(L=>[...L,A]),y(null)},V=()=>{m(A=>A.slice(0,-1)),y(null)},$=(A,L)=>{if(g===A){y(null);return}const se=L.currentTarget.getBoundingClientRect();x({top:se.bottom+4,left:se.left}),y(A)},Q=A=>{s(A),y(null)},G=h.length>1?h[h.length-2].title:"All",K=S.useRef(null),X=S.useRef(null),[re,J]=S.useState(null),oe=S.useCallback(A=>{const te=A.currentTarget.getBoundingClientRect();J({top:te.bottom+4,left:te.left})},[]);S.useEffect(()=>{if(!d)return;const A=L=>{X.current&&!X.current.contains(L.target)&&K.current&&!K.current.contains(L.target)&&f("")};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[d,f]);const U=()=>{if(!g)return[];if(g==="__unassigned__")return P;if(g==="__level-docs__")return R;const A=e.find(L=>L.filename===g);if(A)return B(A.filename);for(const L of e){if(!L.workspace)continue;const te=E(L.workspace.root,g);if(te)return I(te)}return[]};return u.jsxs("div",{className:"board-scroll",ref:o,children:[u.jsxs("div",{className:"board-search-pill",children:[u.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:[u.jsx("circle",{cx:"11",cy:"11",r:"8"}),u.jsx("path",{d:"m21 21-4.3-4.3"})]}),u.jsx("input",{ref:K,className:"board-search-input",type:"text",placeholder:"Search...",value:l,onChange:A=>f(A.target.value),onFocus:oe}),l&&u.jsx("button",{className:"board-search-clear",onClick:()=>f(""),children:"×"})]}),h.length===0?u.jsx("button",{className:"board-back board-back--static",tabIndex:-1,children:"All"}):u.jsxs("button",{className:"board-back",onClick:V,title:`Back to ${G}`,children:["← ",G]}),h.length===0&&u.jsxs(u.Fragment,{children:[P.length>0&&u.jsxs("button",{className:`board-chip ${g==="__unassigned__"?"open":""}`,onClick:A=>$("__unassigned__",A),children:["Documents ",u.jsx("span",{className:"board-chip-count",children:P.length})]}),e.map(A=>{var te;const L=(te=A.workspace)==null?void 0:te.root.some(se=>se.type==="container");return u.jsxs("button",{className:`board-chip ${g===A.filename?"open":""}`,onClick:se=>L?D({type:"workspace",key:A.filename,title:A.title,wsFilename:A.filename}):$(A.filename,se),children:[A.title," ",u.jsx("span",{className:"board-chip-count",children:A.docCount}),L&&u.jsx("span",{className:"board-chip-arrow",children:"›"})]},A.filename)}),u.jsx("button",{className:"board-chip board-chip-add",onClick:i.handleCreateWorkspace,title:"New workspace",children:"+"})]}),h.length>0&&u.jsxs(u.Fragment,{children:[R.length>0&&u.jsxs("button",{className:`board-chip board-chip-docs ${g==="__level-docs__"?"open":""}`,onClick:A=>$("__level-docs__",A),children:["Docs ",u.jsx("span",{className:"board-chip-count",children:R.length})]}),T.map(A=>{const L=A.items.some(te=>te.type==="container");return u.jsxs("button",{className:`board-chip ${g===A.id?"open":""}`,onClick:te=>L?D({type:"container",key:A.id,title:A.name,wsFilename:h[h.length-1].wsFilename}):$(A.id,te),children:[A.name," ",u.jsx("span",{className:"board-chip-count",children:C(A.items)}),L&&u.jsx("span",{className:"board-chip-arrow",children:"›"})]},A.id)})]}),g&&b&&(()=>{const A=U();return u.jsxs("div",{className:"board-dropdown",ref:k,style:{position:"fixed",top:b.top,left:b.left},children:[A.map(L=>u.jsxs("div",{className:`board-dropdown-item ${L.isActive?"active":""}`,onClick:()=>Q(L.filename),children:[u.jsxs("span",{className:"board-dropdown-title",children:[L.title,r.filenames.includes(L.filename)&&u.jsx("span",{className:"board-pending-dot"})]}),u.jsxs("span",{className:"board-dropdown-meta",children:[L.wordCount.toLocaleString()," words · ",ea(L.lastModified)]})]},L.filename)),A.length===0&&u.jsx("div",{className:"board-dropdown-empty",children:"No documents"})]})})(),d&&re&&u.jsxs("div",{className:"board-dropdown board-search-dropdown",ref:X,style:{position:"fixed",top:re.top,left:re.left},children:[d.map(A=>u.jsxs("div",{className:`board-dropdown-item ${A.isActive?"active":""}`,onClick:()=>{s(A.filename),f("")},children:[u.jsx("span",{className:"board-dropdown-title",children:A.title}),A.matchType==="tag"&&A.matchedTag&&u.jsxs("span",{className:"board-dropdown-meta",children:["Tag: ",A.matchedTag]}),A.matchType==="content"&&A.snippet&&u.jsx("span",{className:"board-dropdown-meta board-search-snippet",children:A.snippet}),u.jsxs("span",{className:"board-dropdown-meta",children:[A.wordCount.toLocaleString()," words · ",ea(A.lastModified)]})]},A.filename)),d.length===0&&u.jsx("div",{className:"board-dropdown-empty",children:"No results"})]})]})}function J5({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:o,searchQuery:l,searchResults:d}){const[f,h]=S.useState([]);if(d!==null)return u.jsx($d,{results:d,query:l,onSwitchDocument:s});const m=(_,T)=>{for(const R of _)if(R.type==="container"){if(R.id===T)return R;const I=m(R.items,T);if(I)return I}return null},g=_=>{let T=0;for(const R of _)R.type==="doc"?T++:R.type==="container"&&(T+=g(R.items));return T},y=S.useMemo(()=>{if(f.length===0)return[];const _=f[f.length-1],T=e.find(I=>I.filename===_.wsFilename);if(!(T!=null&&T.workspace))return[];if(_.type==="workspace")return T.workspace.root;const R=m(T.workspace.root,_.key);return R?R.items:[]},[f,e]),b=y.filter(_=>_.type==="container"),x=S.useMemo(()=>{if(f.length===0)return t.filter(T=>!n.has(T.filename));const _=y.filter(T=>T.type==="doc").map(T=>T.file);return t.filter(T=>_.includes(T.filename))},[f,y,t,n]),k=_=>h(T=>[...T,_]),E=()=>h(_=>_.slice(0,-1)),C=f.length>1?f[f.length-2].title:"Shelf",O=f.length>0?f[f.length-1].title:"Documents";return u.jsxs("div",{className:"shelf-wrapper",children:[u.jsxs("div",{className:"shelf-spines",ref:o,children:[f.length>0&&u.jsxs("button",{className:"shelf-back",onClick:E,title:`Back to ${C}`,children:[u.jsx("span",{className:"shelf-back-arrow",children:"←"}),u.jsx("span",{className:"shelf-back-label",children:C})]}),f.length===0&&u.jsxs(u.Fragment,{children:[e.map(_=>u.jsxs("div",{className:"shelf-section-spine",onClick:()=>k({type:"workspace",key:_.filename,title:_.title,wsFilename:_.filename}),title:_.title,children:[u.jsx("span",{className:"shelf-section-title",children:_.title}),u.jsx("span",{className:"shelf-section-count",children:_.docCount})]},_.filename)),u.jsx("button",{className:"shelf-add",onClick:i.handleCreateWorkspace,title:"New workspace",children:"+"})]}),f.length>0&&b.map(_=>u.jsxs("div",{className:"shelf-section-spine shelf-section-container",onClick:()=>k({type:"container",key:_.id,title:_.name,wsFilename:f[f.length-1].wsFilename}),title:_.name,children:[u.jsx("span",{className:"shelf-section-title",children:_.name}),u.jsx("span",{className:"shelf-section-count",children:g(_.items)})]},_.id))]}),u.jsxs("div",{className:"shelf-docs",children:[u.jsx("div",{className:"shelf-docs-header",children:O}),u.jsxs("div",{className:"shelf-docs-list",children:[x.map(_=>u.jsxs("div",{className:`shelf-doc-item ${_.isActive?"active":""}`,onClick:()=>s(_.filename),children:[u.jsxs("div",{className:"shelf-doc-title",children:[u.jsx("span",{children:_.title}),r.filenames.includes(_.filename)&&u.jsx("span",{className:"shelf-pending-dot"})]}),u.jsxs("div",{className:"shelf-doc-meta",children:[_.wordCount.toLocaleString()," words · ",ea(_.lastModified)]})]},_.filename)),x.length===0&&u.jsx("div",{className:"shelf-docs-empty",children:"No documents"})]})]})]})}const Y5=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.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"}),u.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14",opacity:"0.5"})]}),X5=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),u.jsx("polyline",{points:"14 2 14 8 20 8"}),u.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),u.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]}),Q5=()=>u.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:u.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"})}),Z5=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[u.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"}),u.jsx("path",{d:"M7 15l-4-3.5L7 8",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),e8=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[u.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"}),u.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"})]}),t8=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:[u.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"}),u.jsx("rect",{x:"2",y:"16",width:"8",height:"7",rx:"1.5",fill:"none",stroke:"currentColor",strokeWidth:"1.5"}),u.jsx("line",{x1:"4",y1:"18.5",x2:"8",y2:"18.5",stroke:"currentColor",strokeWidth:"1",opacity:"0.7"}),u.jsx("line",{x1:"4",y1:"20.5",x2:"7",y2:"20.5",stroke:"currentColor",strokeWidth:"1",opacity:"0.7"})]}),n8=()=>u.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",children:u.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"})}),r8=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{width:"20",height:"16",x:"2",y:"4",rx:"2"}),u.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]}),s8=()=>u.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("path",{d:"M2 12h20"}),u.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"})]}),aw=()=>u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"20 6 9 17 4 12"})});function i8({type:t}){switch(t){case"tweet":return u.jsx(Q5,{});case"reply":return u.jsx(Z5,{});case"quote":return u.jsx(e8,{});case"article":return u.jsx(t8,{});case"linkedin":return u.jsx(n8,{});case"newsletter":return u.jsx(r8,{});case"blog":return u.jsx(s8,{});default:return u.jsx(X5,{})}}function Eu(t){let e=0;for(const n of t)n.type==="doc"?e++:n.type==="container"&&(e+=Eu(n.items));return e}function l2(t,e){for(const n of t){if(n.type==="doc"&&n.file===e)return[];if(n.type==="container"){const r=l2(n.items,e);if(r)return[n.id,...r]}}return null}function lw(t){const e=new Set;return yl(t,e),[...e]}function c2(t,e,n=0){for(const r of t)if(r.type==="container"){if(r.id===e)return n;const s=c2(r.items,e,n+1);if(s>=0)return s}return-1}function o8(t,e){if(!e)return 12;for(const n of t){if(!n.workspace)continue;const r=c2(n.workspace.root,e);if(r>=0)return 12+(r+1)*16}return 12}function a8({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:y}){var qe;const b=W=>!!h&&h.has(W),[x,k]=S.useState(()=>{try{const W=localStorage.getItem("ow-files-collapsed");return W?new Set(JSON.parse(W)):new Set}catch{return new Set}}),{draggedItem:E,dropIndicator:C,handlePointerDown:O,dropClass:_,isDragging:T,isContainerDropTarget:R}=n2({docs:t,workspaces:e,assignedFiles:n,scrollRef:l,setCollapsedSections:k}),I=W=>!C||C.itemId!==W||C.position==="inside"?void 0:{"--drop-indent":`${o8(e,C.containerId)}px`},{variantsByMaster:B,variantFilenames:P}=S.useMemo(()=>{const W=new Map,pe=new Set;for(const xe of t)if(xe.masterDocId){const Ye=W.get(xe.masterDocId)||[];Ye.push(xe),W.set(xe.masterDocId,Ye),pe.add(xe.filename)}return{variantsByMaster:W,variantFilenames:pe}},[t]),[D,V]=S.useState(null),[$,Q]=S.useState(null),[G,K]=S.useState(new Set),[X,re]=S.useState(null),[J,oe]=S.useState([]),[U,A]=S.useState(null),[L,te]=S.useState(null),[se,be]=S.useState(null),[ee,ge]=S.useState(null),[fe,Te]=S.useState(null),[Xe,tt]=S.useState(new Set);S.useEffect(()=>{tt(new Set)},[r]);const st=S.useCallback(()=>{fetch("/api/plugins").then(W=>W.json()).then(W=>{const pe=[];for(const xe of W.plugins||[]){const Ye=xe.displayName||void 0;for(const it of xe.sidebarMenuItems||[])pe.push({...it,pluginDisplayName:Ye})}oe(pe)}).catch(()=>{})},[]);S.useEffect(()=>{st()},[st]),S.useEffect(()=>{const W=()=>st();return window.addEventListener("ow-plugins-changed",W),()=>window.removeEventListener("ow-plugins-changed",W)},[st]);const nt=S.useCallback((W,pe)=>{if(W.preventDefault(),W.stopPropagation(),G.has(pe.filename)&&G.size>1){Q({x:W.clientX,y:W.clientY,filename:pe.filename,title:pe.title,bulkCount:G.size});return}G.size>0&&!G.has(pe.filename)&&K(new Set),Q({x:W.clientX,y:W.clientY,filename:pe.filename,title:pe.title,docId:pe.docId,lastSent:pe.lastSent,postedUrl:pe.postedUrl,isNewsletter:pe.isNewsletter})},[G]),Le=S.useCallback(W=>{fetch("/api/documents/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:W})}).catch(()=>{})},[]),yt=S.useCallback((W,pe,xe,Ye,it)=>{if(pe.promptForFocus&&it===void 0){A({action:W,label:pe.label,filename:xe,title:Ye});return}fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:W,filename:xe,title:Ye,instructions:it||"",label:pe.label})}).catch(()=>{})},[]),Ke=S.useCallback((W,pe)=>{tt(xe=>{const Ye=new Set(xe);for(const it of W)Ye.add(it);return Ye}),fetch("/api/documents/batch-resolve",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filenames:W,action:pe})}).catch(()=>{})},[]),Et=W=>{k(pe=>{const xe=new Set(pe);return xe.has(W)?xe.delete(W):xe.add(W),localStorage.setItem("ow-files-collapsed",JSON.stringify([...xe])),xe})},je=(W,pe,xe,Ye)=>{V({type:W,key:pe,value:xe,wsFilename:Ye})},Je=()=>{if(!D)return;const{type:W,key:pe,value:xe,wsFilename:Ye}=D;W==="doc"?o.handleRename(pe,"",xe):W==="workspace"?o.handleRenameWorkspace(pe,xe):W==="container"&&Ye&&o.handleRenameContainer(Ye,pe,xe),V(null)},Fe=t.find(W=>W.isActive),Nt=S.useRef(e);Nt.current=e,S.useEffect(()=>{var W;if(Fe)for(const pe of Nt.current){const xe=l2(((W=pe.workspace)==null?void 0:W.root)||[],Fe.filename);if(xe){k(Ye=>{const it=[pe.filename,...xe.map(Re=>`container-${Re}`)];if(it.every(Re=>!Ye.has(Re)))return Ye;const ot=new Set(Ye);for(const Re of it)ot.delete(Re);return localStorage.setItem("ow-files-collapsed",JSON.stringify([...ot])),ot});break}}},[Fe==null?void 0:Fe.filename]);const qt=S.useMemo(()=>t.filter(W=>!n.has(W.filename)&&!P.has(W.filename)&&!b(W.filename)),[t,n,P,h]),ie=S.useMemo(()=>{var Ye;const W=[],pe=it=>{W.push(it.filename);const ot=it.docId?B.get(it.docId):void 0,Re=it.docId&&!x.has(`variants-${it.docId}`);if(ot&&Re)for(const vt of ot)W.push(vt.filename)},xe=it=>{for(const ot of it)if(ot.type==="doc"){const Re=t.find(vt=>vt.filename===ot.file);Re&&!P.has(Re.filename)&&pe(Re)}else x.has(`container-${ot.id}`)||xe(ot.items)};x.has("docs")||qt.forEach(pe);for(const it of e)x.has(it.filename)||xe(((Ye=it.workspace)==null?void 0:Ye.root)||[]);return W},[t,e,qt,P,B,x]),H=S.useCallback(()=>{K(new Set)},[]),q=S.useCallback((W,pe)=>{if(E)return;const xe=W.shiftKey,Ye=W.ctrlKey||W.metaKey;if(xe){const ot=X||(Fe==null?void 0:Fe.filename)||pe,Re=ie.indexOf(ot),vt=ie.indexOf(pe);if(Re<0||vt<0){K(new Set([pe])),re(pe);return}const[ht,zt]=Re<vt?[Re,vt]:[vt,Re];K(new Set(ie.slice(ht,zt+1)));return}if(Ye){K(ot=>{const Re=new Set(ot);return Re.has(pe)?Re.delete(pe):Re.add(pe),Re}),re(pe);return}K(new Set),re(pe);const it=t.find(ot=>ot.filename===pe);it&&!it.isActive&&s(pe)},[E,X,Fe==null?void 0:Fe.filename,ie,s,t]);S.useEffect(()=>{if(G.size===0)return;const W=pe=>{pe.key==="Escape"&&H()};return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[G.size,H]);const de=S.useCallback(()=>{for(const W of G)o.handleDelete(W);K(new Set),re(null)},[G,o]);if(g!==null)return u.jsx($d,{results:g,query:m,onSwitchDocument:s,actions:o});const me=W=>u.jsx("input",{className:"sidebar-rename-input",value:D.value,onChange:pe=>V(xe=>xe?{...xe,value:pe.target.value}:null),onBlur:W,onKeyDown:pe=>{pe.key==="Enter"&&W(),pe.key==="Escape"&&V(null)},autoFocus:!0,onClick:pe=>pe.stopPropagation()}),Ee=(W,pe,xe,Ye,it,ot=!1)=>u.jsxs("div",{className:`files-row${W.isActive?" active":""}${G.has(W.filename)?" selected":""} ${T(W.filename)?"dragging":""} ${_(W.filename)}${W.masterDocId?" is-variant":""}`,style:{paddingLeft:pe,...I(W.filename)},"data-drag-id":W.filename,"data-drag-type":"doc","data-drag-ws":xe||"__docs__","data-drag-container":Ye||"",onPointerDown:Re=>O(Re,{type:"doc",file:W.filename,sourceWs:xe||null},W.title),onClick:Re=>q(Re,W.filename),onDoubleClick:()=>je("doc",W.filename,W.title),onContextMenu:Re=>nt(Re,W),children:[u.jsx("span",{className:"files-row-icon",children:u.jsx(i8,{type:W.contentType})}),(D==null?void 0:D.type)==="doc"&&D.key===W.filename?me(Je):u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"files-row-label",children:W.title}),W.variantType&&u.jsx("span",{className:"files-badge-variant",children:W.variantType}),(W.autoAccept===!0||W.autoAccept!==!1&&ot)&&u.jsx("span",{className:"sidebar-auto-accept-dot",title:W.autoAccept===!0?"Auto-accept on":"Auto-accept inherited"}),r.filenames.includes(W.filename)&&!Xe.has(W.filename)&&u.jsx("span",{className:"files-badge-pending"}),o.getDocTags(W.filename).includes("✓")&&u.jsx("span",{className:"files-badge-approved",children:u.jsx(aw,{})}),W.lastSent&&u.jsx("span",{className:"files-badge-sent",children:u.jsx(aw,{})}),it&&u.jsx("span",{className:`files-row-chevron${x.has(`variants-${W.docId}`)?" collapsed":""}`,onClick:Re=>{Re.stopPropagation(),Et(`variants-${W.docId}`)},children:u.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"6 9 12 15 18 9"})})})]})]},W.filename),De=(W,pe,xe,Ye,it=!1)=>{const ot=W.docId?B.get(W.docId):void 0,Re=!!(ot&&ot.length>0),vt=d&&(f==null?void 0:f.parentDocId)&&f.parentDocId===W.docId,ht=Re||vt,zt=!x.has(`variants-${W.docId}`);return ht?u.jsxs("div",{className:"files-variant-group",children:[Ee(W,pe,xe,Ye,Re,it),zt&&(ot==null?void 0:ot.map(Ut=>Ee(Ut,pe+16,xe,Ye,!1,it))),vt&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",style:{paddingLeft:pe+16},children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:d})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]})]},`vg-${W.filename}`):Ee(W,pe,xe,Ye,!1,it)},$e=(W,pe,xe,Ye,it=!1)=>{const ot=12+pe*16;if(W.type==="doc"){const M=t.find(ne=>ne.filename===W.file);return!M||P.has(M.filename)?null:De(M,ot,xe,Ye,it)}const Re=W,vt=`container-${Re.id}`,ht=x.has(vt),zt=Eu(Re.items),Ut=Re.autoAccept===!0,Jt=Ut||it;return u.jsxs("div",{className:`${_(Re.id)} ${R(Re.id)?"files-drop-inside":""}`,children:[u.jsxs("div",{className:`files-row is-container ${T(Re.id)?"dragging":""} ${_(Re.id)}`,style:{paddingLeft:ot,...I(Re.id)},"data-drag-id":Re.id,"data-drag-type":"container-header","data-drag-ws":xe,"data-drag-parent":Ye||"","data-section-key":vt,onPointerDown:M=>O(M,{type:"container",id:Re.id,sourceWs:xe},Re.name),onClick:()=>!E&&Et(vt),onDoubleClick:M=>{M.stopPropagation(),je("container",Re.id,Re.name,xe)},onContextMenu:M=>{M.preventDefault(),M.stopPropagation(),Te({x:M.clientX,y:M.clientY,type:"container",wsFilename:xe,containerId:Re.id,title:Re.name,nodes:Re.items,autoAccept:Ut})},children:[u.jsx("span",{className:"files-row-icon",children:u.jsx(Y5,{})}),(D==null?void 0:D.type)==="container"&&D.key===Re.id?me(Je):u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"files-row-label",children:Re.name}),Jt&&u.jsx("span",{className:"sidebar-auto-accept-dot",title:Ut?"Auto-accept on for this container":"Auto-accept inherited from workspace"}),u.jsx("span",{className:"files-row-count",children:zt})]})]}),u.jsxs("div",{className:`files-children${ht?" collapsed":""}`,"data-drop-ws":xe,"data-drop-container":Re.id,children:[d&&!(f!=null&&f.parentDocId)&&(f==null?void 0:f.wsFilename)===xe&&f.containerId===Re.id&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:d})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),Re.items.filter(M=>M.type!=="doc"||!b(M.file)).map(M=>$e(M,pe+1,xe,Re.id,Jt))]})]},Re.id)};return u.jsxs("div",{className:"files-scroll",ref:l,children:[u.jsxs("div",{className:"files-section",children:[u.jsxs("div",{className:"files-row is-section","data-section-key":"docs",onClick:()=>Et("docs"),children:[u.jsx("span",{className:`files-row-chevron leading${x.has("docs")?" collapsed":""}`,children:u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"6 9 12 15 18 9"})})}),u.jsx("span",{className:"files-row-label",children:"Documents"}),u.jsx("button",{className:"files-section-btn",onClick:W=>{W.stopPropagation(),ge({anchor:W.target.getBoundingClientRect()})},title:"New document",children:"+"})]}),u.jsxs("div",{className:`files-section-list files-children${x.has("docs")?" collapsed":""}`,"data-drop-ws":"__docs__",children:[d&&!(f!=null&&f.parentDocId)&&(!f||!e.some(W=>W.filename===(f==null?void 0:f.wsFilename)))&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:d})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),qt.map(W=>De(W,28))]})]}),e.map(W=>{var ot,Re,vt;const pe=((ot=W.workspace)==null?void 0:ot.root)||[],xe=x.has(W.filename),Ye=Eu(pe),it=((Re=W.workspace)==null?void 0:Re.autoAccept)===!0||W.autoAccept===!0;return u.jsxs("div",{className:`files-section ${T(W.filename)?"dragging":""} ${(C==null?void 0:C.itemId)===W.filename?C.position==="before"?"files-ws-drop-before":"files-ws-drop-after":""}`,children:[u.jsx("div",{className:`files-row is-section${(C==null?void 0:C.itemId)==="__section__"&&C.wsFilename===W.filename&&C.position==="inside"?" files-ws-drop-target":""}`,"data-section-key":W.filename,"data-ws-drag":W.filename,onPointerDown:ht=>O(ht,{type:"workspace",filename:W.filename},W.title),onClick:()=>!E&&Et(W.filename),onDoubleClick:ht=>{ht.stopPropagation(),je("workspace",W.filename,W.title)},onContextMenu:ht=>{var zt;ht.preventDefault(),ht.stopPropagation(),Te({x:ht.clientX,y:ht.clientY,type:"workspace",wsFilename:W.filename,title:W.title,nodes:pe,autoAccept:((zt=W.workspace)==null?void 0:zt.autoAccept)===!0||W.autoAccept===!0})},children:(D==null?void 0:D.type)==="workspace"&&D.key===W.filename?u.jsxs(u.Fragment,{children:[u.jsx("span",{className:`files-row-chevron leading${xe?" collapsed":""}`,children:u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"6 9 12 15 18 9"})})}),me(Je)]}):u.jsxs(u.Fragment,{children:[u.jsx("span",{className:`files-row-chevron leading${xe?" collapsed":""}`,children:u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"6 9 12 15 18 9"})})}),u.jsx("span",{className:"files-row-label",children:W.title}),(((vt=W.workspace)==null?void 0:vt.autoAccept)===!0||W.autoAccept===!0)&&u.jsx("span",{className:"sidebar-auto-accept-dot",title:"Auto-accept on for this workspace"}),u.jsx("span",{className:"files-row-count",children:Ye}),u.jsxs("div",{className:"files-section-actions",children:[u.jsx("button",{className:"files-section-btn",onClick:ht=>{ht.stopPropagation(),ge({anchor:ht.target.getBoundingClientRect(),wsFilename:W.filename,containerId:null})},title:"New document",children:"+"}),u.jsx("button",{className:"files-section-btn",onClick:ht=>{ht.stopPropagation(),o.handleCreateContainer(W.filename,null)},title:"New container",children:"☐"})]})]})}),u.jsxs("div",{className:`files-section-list files-children${xe?" collapsed":""}`,"data-drop-ws":W.filename,children:[d&&!(f!=null&&f.parentDocId)&&(f==null?void 0:f.wsFilename)===W.filename&&(f.containerId===null||!pe.some(ht=>ht.type==="container"&&ht.id===f.containerId))&&u.jsxs("div",{className:"sidebar-item sidebar-writing-placeholder",children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-writing-spinner"}),u.jsx("span",{className:"sidebar-item-title-text",children:d})]}),u.jsx("div",{className:"sidebar-item-meta",children:"Writing..."})]}),pe.filter(ht=>ht.type!=="doc"||!b(ht.file)).map(ht=>$e(ht,1,W.filename,null,it))]})]},W.filename)}),u.jsx("div",{className:"files-new-ws",children:u.jsx("button",{onClick:o.handleCreateWorkspace,children:"+ New Workspace"})}),fe&&u.jsx(wd,{x:fe.x,y:fe.y,filename:fe.wsFilename,title:fe.title,onClose:()=>Te(null),onDuplicate:()=>{},onRename:()=>{fe.type==="workspace"?je("workspace",fe.wsFilename,fe.title):fe.containerId&&je("container",fe.containerId,fe.title,fe.wsFilename),Te(null)},onArchive:()=>{},onDelete:()=>{fe.type==="workspace"?o.handleDeleteWorkspace(fe.wsFilename):fe.containerId&&o.handleDeleteContainer(fe.wsFilename,fe.containerId,!1)},folderDocCount:fe.type==="container"?Eu(fe.nodes):0,onDeleteWithDocs:fe.type==="container"&&fe.containerId?()=>{o.handleDeleteContainer(fe.wsFilename,fe.containerId,!0)}:void 0,onPluginAction:()=>{},pluginItems:[],folderMode:!0,onNewDoc:W=>{ge({anchor:W.target.getBoundingClientRect(),wsFilename:fe.wsFilename,containerId:fe.type==="container"?fe.containerId:null}),Te(null)},onNewContainer:()=>{o.handleCreateContainer(fe.wsFilename,fe.type==="container"?fe.containerId:null),Te(null)},onAcceptAll:()=>{const W=lw(fe.nodes);W.length&&Ke(W,"accept"),Te(null)},onRejectAll:()=>{const W=lw(fe.nodes);W.length&&Ke(W,"reject"),Te(null)},folderAutoAccept:fe.autoAccept,folderAutoAcceptLabel:fe.type==="workspace"?"for workspace":"for container",onToggleFolderAutoAccept:()=>{fetch("/api/auto-accept/inherit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({wsFile:fe.wsFilename,...fe.type==="container"?{containerId:fe.containerId}:{},enabled:!fe.autoAccept})}).catch(()=>{})}}),$&&u.jsx(wd,{x:$.x,y:$.y,filename:$.filename,title:$.title,bulkCount:$.bulkCount,onBulkDelete:de,onClose:()=>Q(null),onDuplicate:()=>Le($.filename),onRename:()=>{je("doc",$.filename,$.title),Q(null)},onArchive:()=>o.handleArchive($.filename),onDelete:()=>o.handleDelete($.filename),onPluginAction:(W,pe)=>yt(W,pe,$.filename,$.title),pluginItems:J,onSchedulePost:()=>{te({filename:$.filename,title:$.title}),Q(null)},onViewAnalytics:$.docId&&$.lastSent&&($.postedUrl||$.isNewsletter)?()=>{$.isNewsletter?be({docId:$.docId,title:$.title}):$.postedUrl&&window.open($.postedUrl,"_blank"),Q(null)}:void 0,viewAnalyticsLabel:$.isNewsletter?"View Analytics":$.postedUrl?"View on X":"View Analytics",isApproved:o.getDocTags($.filename).includes("✓"),onToggleApprove:()=>{o.getDocTags($.filename).includes("✓")?o.handleRemoveTag($.filename,"✓"):(o.handleAddTag($.filename,"✓"),setTimeout(()=>window.dispatchEvent(new CustomEvent("ow-accept-all")),50))},isAutoAccept:((qe=t.find(W=>W.filename===$.filename))==null?void 0:qe.autoAccept)===!0,onToggleAutoAccept:()=>{var pe;const W=((pe=t.find(xe=>xe.filename===$.filename))==null?void 0:pe.autoAccept)===!0;fetch("/api/auto-accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:$.filename,enabled:!W})}).then(()=>o.fetchDocs()).catch(()=>{})},isAlreadySent:!!$.lastSent,onMarkSent:()=>{const W=$.filename;o.getDocTags(W).includes("✓")&&o.handleRemoveTag(W,"✓"),s(W),setTimeout(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualPost:{postedAt:new Date().toISOString()}})}).then(()=>o.fetchDocs()).catch(()=>{})},100),Q(null)}}),U&&u.jsx(r2,{actionLabel:U.label,docTitle:U.title,onClose:()=>A(null),onConfirm:W=>{const pe=J.find(xe=>xe.action===U.action);pe&&yt(U.action,pe,U.filename,U.title,W),A(null)}}),se&&u.jsx(s2,{docId:se.docId,title:se.title,onClose:()=>be(null)}),L&&u.jsx(Cl,{filename:L.filename,title:L.title,onClose:()=>te(null)}),ee&&u.jsx(i2,{anchorRect:ee.anchor,onClose:()=>ge(null),onSelect:W=>{ge(null),ee.wsFilename?o.handleCreateInWorkspace(ee.wsFilename,ee.containerId??null,W):W?fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:W})}).catch(()=>{}):i()}})]})}const l8=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],c8=[{value:"any",label:"Any"},{value:"content_type",label:"Content Type"},{value:"connection",label:"Connection"}],u2=["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 cw(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 u8(t){if(t.length>0)return t[0].timezone;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;if(u2.includes(e))return e}catch{}return"America/New_York"}function d8({slots:t,onBack:e}){const[n,r]=S.useState(t),[s,i]=S.useState(()=>u8(t)),[o,l]=S.useState(!1),[d,f]=S.useState("09:00"),[h,m]=S.useState(["default"]),[g,y]=S.useState("any"),[b,x]=S.useState(!1),k=S.useRef(null);S.useEffect(()=>{if(!o)return;function T(R){k.current&&!k.current.contains(R.target)&&l(!1)}return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[o]);async function E(T){i(T);const R=[];for(const I of n){const B=await fetch(`/api/scheduler/slots/${I.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({timezone:T})});if(B.ok){const P=await B.json();R.push(P.slot)}else R.push(I)}R.length>0&&r(R)}async function C(){const T=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(T.ok){const R=await T.json();r(I=>[...I,R.slot]),x(!1),f("09:00"),m(["default"]),y("any")}}async function O(T){(await fetch(`/api/scheduler/slots/${T}`,{method:"DELETE"})).ok&&r(I=>I.filter(B=>B.id!==T))}function _(T){m(R=>{if(T==="default")return["default"];const I=R.filter(B=>B!=="default");if(I.includes(T)){const B=I.filter(P=>P!==T);return B.length===0?["default"]:B}return[...I,T]})}return u.jsxs("div",{className:"sidebar-schedule",children:[u.jsxs("div",{className:"sidebar-schedule-header",children:[u.jsx("button",{className:"sidebar-schedule-btn",onClick:e,title:"Back",children:u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"m15 18-6-6 6-6"})})}),u.jsx("h3",{children:"Slot Settings"}),u.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>x(!b),children:b?"Cancel":"+ Add"})]}),u.jsxs("div",{className:"slot-tz",ref:k,children:[u.jsx("label",{className:"slot-tz-label",children:"Timezone"}),u.jsxs("button",{className:"slot-tz-trigger",onClick:()=>l(!o),children:[u.jsx("span",{children:cw(s)}),u.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:u.jsx("path",{d:"m6 9 6 6 6-6"})})]}),o&&u.jsx("div",{className:"slot-tz-dropdown",children:u2.map(T=>u.jsx("div",{className:`slot-tz-option ${T===s?"active":""}`,onClick:()=>{E(T),l(!1)},children:cw(T)},T))})]}),b&&u.jsxs("div",{className:"slot-add-form",children:[u.jsxs("div",{className:"slot-add-row",children:[u.jsx("input",{type:"time",className:"slot-input",value:d,onChange:T=>f(T.target.value)}),u.jsx("select",{className:"slot-input",value:g,onChange:T=>y(T.target.value),children:c8.map(T=>u.jsx("option",{value:T.value,children:T.label},T.value))})]}),u.jsxs("div",{className:"slot-add-days",children:[u.jsx("button",{className:`sidebar-schedule-btn slot-day-btn ${h.includes("default")?"sidebar-schedule-btn--active":""}`,onClick:()=>_("default"),children:"Every day"}),l8.map(T=>u.jsx("button",{className:`sidebar-schedule-btn slot-day-btn ${h.includes(T.toLowerCase())?"sidebar-schedule-btn--active":""}`,onClick:()=>_(T.toLowerCase()),children:T},T))]}),u.jsx("button",{className:"sidebar-schedule-btn sidebar-schedule-btn--active slot-create-btn",onClick:C,children:"Create Slot"})]}),u.jsx("div",{className:"slot-list",children:n.length===0?u.jsxs("div",{className:"schedule-empty",children:[u.jsx("div",{className:"schedule-empty-title",children:"No slots"}),u.jsx("div",{className:"schedule-empty-desc",children:"Create time slots to define your posting schedule."})]}):n.map(T=>u.jsxs("div",{className:"schedule-item slot-item",children:[u.jsx("div",{className:"schedule-item-time slot-item-time",children:f8(T.time)}),u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:T.days.includes("default")?"Every day":T.days.join(", ")}),u.jsxs("div",{className:"schedule-item-meta",children:[u.jsxs("span",{children:["Filter: ",T.filter_type]}),T.filter_value&&u.jsxs("span",{children:["(",T.filter_value,")"]})]})]}),u.jsx("button",{className:"schedule-item-action schedule-item-action--danger slot-delete-btn",onClick:()=>O(T.id),title:"Delete slot",children:"×"})]},T.id))})]})}function f8(t){const[e,n]=t.split(":").map(Number),r=e>=12?"PM":"AM";return`${e%12||12}:${String(n).padStart(2,"0")} ${r}`}function h8({onBack:t}){const[e,n]=S.useState([]),[r,s]=S.useState([]),[i,o]=S.useState(null),[l,d]=S.useState(!1),[f,h]=S.useState(!0),m=S.useCallback(async()=>{try{const[E,C]=await Promise.all([fetch("/api/scheduler/autoplugs/goals"),fetch("/api/scheduler/autoplugs/tracking")]);if(E.ok){const O=await E.json();n(O.goals||[])}if(C.ok){const O=await C.json();s(O.tracking||[])}}catch{}h(!1)},[]);S.useEffect(()=>{m()},[m]);const g=async E=>{(await fetch(`/api/scheduler/autoplugs/goals/${E.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!E.enabled})})).ok&&n(O=>O.map(_=>_.id===E.id?{..._,enabled:!_.enabled}:_))},y=async E=>{(await fetch(`/api/scheduler/autoplugs/goals/${E}`,{method:"DELETE"})).ok&&(n(O=>O.filter(_=>_.id!==E)),o(null))},b=async E=>{(await fetch(`/api/scheduler/autoplugs/tracking/${E}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({skipped:!0})})).ok&&s(O=>O.map(_=>_.id===E?{..._,skipped:!0}:_))},x=e.reduce((E,C)=>C.rule&&C.enabled?Math.min(E,C.rule.threshold):E,1/0),k=x===1/0?50:x;return u.jsxs("div",{className:"sidebar-schedule",children:[u.jsxs("div",{className:"sidebar-schedule-header",children:[u.jsx("button",{className:"sidebar-schedule-back",onClick:t,title:"Back",children:u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"m15 18-6-6 6-6"})})}),u.jsx("h3",{children:"Autoplugs"}),u.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>d(!l),children:l?"Cancel":"+ Add"})]}),l&&u.jsx(m8,{onCreated:E=>{n(C=>[...C,E]),d(!1)}}),f?null:u.jsxs(u.Fragment,{children:[e.length===0?u.jsxs("div",{className:"schedule-empty",children:[u.jsx("div",{className:"schedule-empty-title",children:"No goals"}),u.jsx("div",{className:"schedule-empty-desc",children:"Create a goal to start autoplugging your tweets."})]}):e.map(E=>u.jsxs("div",{children:[u.jsxs("div",{className:"schedule-item",onClick:()=>o(i===E.id?null:E.id),children:[u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:E.name}),u.jsx("div",{className:"schedule-item-meta",children:p8(E).map((C,O)=>u.jsx("span",{children:C},O))})]}),u.jsx("button",{className:`autoplug-toggle ${E.enabled?"autoplug-toggle--on":"autoplug-toggle--off"}`,onClick:C=>{C.stopPropagation(),g(E)},title:E.enabled?"Disable":"Enable"})]}),i===E.id&&u.jsx(g8,{goal:E,onSaved:C=>{n(O=>O.map(_=>_.id===C.id?C:_))},onDeleted:()=>y(E.id),onRefresh:m})]},E.id)),u.jsx("div",{className:"schedule-day-header",children:"Tracking"}),r.length===0?u.jsxs("div",{className:"schedule-empty",children:[u.jsx("div",{className:"schedule-empty-title",children:"No tracked tweets"}),u.jsx("div",{className:"schedule-empty-desc",children:"Tweets will appear here after posting."})]}):r.map(E=>u.jsxs("div",{className:"schedule-item",children:[u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:E.original_text||`Tweet ${E.tweet_id}`}),u.jsxs("div",{className:"schedule-item-meta",children:[u.jsx("span",{children:v8(E.posted_at)}),u.jsxs("span",{children:[E.likes," likes"]}),u.jsxs("span",{children:[E.retweets," RTs"]}),E.views>0&&u.jsxs("span",{children:[y8(E.views)," views"]})]}),E.triggered?u.jsxs("div",{className:"autoplug-tracking-triggered",children:[u.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Autoplugged ",E.goal_name?`→ ${E.goal_name}`:""]}):E.skipped?u.jsx("div",{className:"autoplug-tracking-skipped",children:"Skipped"}):u.jsx("div",{className:"autoplug-tracking-bar",children:u.jsx("div",{className:"autoplug-tracking-bar-fill",style:{width:`${Math.min(100,E.likes/k*100)}%`}})})]}),!E.triggered&&!E.skipped&&u.jsx("button",{className:"autoplug-tracking-skip",onClick:()=>b(E.id),title:"Skip autoplug for this tweet",children:"×"})]},E.id))]})]})}function p8(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 m8({onCreated:t}){const[e,n]=S.useState(""),[r,s]=S.useState(""),[i,o]=S.useState(""),[l,d]=S.useState("likes"),[f,h]=S.useState(50),[m,g]=S.useState(30),[y,b]=S.useState("static"),[x,k]=S.useState(!1),E=async()=>{if(e.trim()){k(!0);try{const C=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(!C.ok){k(!1);return}const{goal:O}=await C.json();await fetch("/api/scheduler/autoplugs/rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({goal_id:O.id,metric:l,threshold:f,delay_minutes:m,mode:y})});const _=await fetch("/api/scheduler/autoplugs/goals");if(_.ok){const R=((await _.json()).goals||[]).find(I=>I.id===O.id);if(R){t(R);return}}t({...O,rule_count:1,pool_count:0,rule:{metric:l,threshold:f,delay_minutes:m,mode:y,id:""}})}finally{k(!1)}}};return u.jsxs("div",{className:"autoplug-editor",children:[u.jsxs("label",{children:["Name",u.jsx("input",{value:e,onChange:C=>n(C.target.value),placeholder:"Newsletter, Course..."})]}),u.jsxs("label",{children:["Link",u.jsx("input",{value:r,onChange:C=>s(C.target.value),placeholder:"https://..."})]}),u.jsxs("label",{children:["Description (context for LLM)",u.jsx("textarea",{value:i,onChange:C=>o(C.target.value),placeholder:"Weekly engineering insights...",rows:2})]}),u.jsxs("div",{className:"autoplug-editor-row",children:[u.jsx("input",{type:"number",value:f,onChange:C=>h(Number(C.target.value)),min:1}),u.jsxs("select",{value:l,onChange:C=>d(C.target.value),children:[u.jsx("option",{value:"likes",children:"likes"}),u.jsx("option",{value:"retweets",children:"retweets"}),u.jsx("option",{value:"views",children:"views"})]}),u.jsx("span",{className:"autoplug-editor-row-label",children:"wait"}),u.jsx("input",{type:"number",value:m,onChange:C=>g(Number(C.target.value)),min:0,className:"autoplug-delay-input"}),u.jsx("span",{className:"autoplug-editor-row-label",children:"min"})]}),u.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map(C=>u.jsx("button",{className:y===C?"active":"",onClick:()=>b(C),children:C==="llm"?"LLM":C.charAt(0).toUpperCase()+C.slice(1)},C))}),u.jsx("button",{className:"sidebar-schedule-btn sidebar-schedule-btn--active autoplug-create-btn",onClick:E,disabled:x||!e.trim(),children:x?"Creating...":"Create Goal"})]})}function g8({goal:t,onSaved:e,onDeleted:n,onRefresh:r}){var V,$,Q,G;const[s,i]=S.useState(t.name),[o,l]=S.useState(t.link||""),[d,f]=S.useState(t.description||""),[h,m]=S.useState(((V=t.rule)==null?void 0:V.metric)||"likes"),[g,y]=S.useState((($=t.rule)==null?void 0:$.threshold)||50),[b,x]=S.useState(((Q=t.rule)==null?void 0:Q.delay_minutes)||30),[k,E]=S.useState(((G=t.rule)==null?void 0:G.mode)||"static"),[C,O]=S.useState([]),[_,T]=S.useState(""),[R,I]=S.useState(!1);S.useEffect(()=>{fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`).then(K=>K.json()).then(K=>O(K.pool||[])).catch(()=>{})},[t.id]);const B=async()=>{var K;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})}),(K=t.rule)!=null&&K.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:k})}):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:k})}),r()}finally{I(!1)}},P=async()=>{if(!_.trim())return;const K=await fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:_.trim()})});if(K.ok){const X=await K.json();O(re=>[...re,X.message]),T("")}},D=async K=>{(await fetch(`/api/scheduler/autoplugs/pool/${K}`,{method:"DELETE"})).ok&&O(re=>re.filter(J=>J.id!==K))};return u.jsxs("div",{className:"autoplug-editor",children:[u.jsxs("label",{children:["Name",u.jsx("input",{value:s,onChange:K=>i(K.target.value)})]}),u.jsxs("label",{children:["Link",u.jsx("input",{value:o,onChange:K=>l(K.target.value),placeholder:"https://..."})]}),u.jsxs("label",{children:["Description",u.jsx("textarea",{value:d,onChange:K=>f(K.target.value),rows:2})]}),u.jsx("div",{className:"autoplug-editor-section-label",children:"Trigger"}),u.jsxs("div",{className:"autoplug-editor-row",children:[u.jsx("input",{type:"number",value:g,onChange:K=>y(Number(K.target.value)),min:1}),u.jsxs("select",{value:h,onChange:K=>m(K.target.value),children:[u.jsx("option",{value:"likes",children:"likes"}),u.jsx("option",{value:"retweets",children:"retweets"}),u.jsx("option",{value:"views",children:"views"})]}),u.jsx("span",{className:"autoplug-editor-row-label",children:"wait"}),u.jsx("input",{type:"number",value:b,onChange:K=>x(Number(K.target.value)),min:0,className:"autoplug-delay-input"}),u.jsx("span",{className:"autoplug-editor-row-label",children:"min"})]}),u.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map(K=>u.jsx("button",{className:k===K?"active":"",onClick:()=>E(K),children:K==="llm"?"LLM":K.charAt(0).toUpperCase()+K.slice(1)},K))}),u.jsxs("div",{className:"autoplug-pool-section",children:[u.jsx("div",{className:"autoplug-editor-section-label",children:"Static Pool"}),C.map(K=>u.jsxs("div",{className:"autoplug-pool-item",children:[u.jsx("span",{children:K.content}),u.jsx("button",{onClick:()=>D(K.id),title:"Remove",children:"×"})]},K.id)),u.jsxs("div",{className:"autoplug-pool-add",children:[u.jsx("input",{value:_,onChange:K=>T(K.target.value),placeholder:"Add message... (use {{link}} for link)",onKeyDown:K=>K.key==="Enter"&&P()}),u.jsx("button",{onClick:P,children:"+"})]})]}),(k==="llm"||k==="hybrid")&&u.jsx("div",{className:"autoplug-llm-hint",children:"LLM mode uses Author's Voice to generate contextual replies referencing the original tweet."}),u.jsxs("div",{className:"autoplug-editor-actions",children:[u.jsx("button",{className:"schedule-item-action",onClick:B,disabled:R,children:R?"Saving...":"Save"}),u.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:n,children:"Delete"})]})]})}function v8(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 y8(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function b8({onBack:t}){const[e,n]=S.useState([]),[r,s]=S.useState([]),[i,o]=S.useState(!1),[l,d]=S.useState(!1),[f,h]=S.useState(null),[m,g]=S.useState(!0),y=S.useCallback(async()=>{try{const[k,E]=await Promise.all([fetch("/api/scheduler/queue"),fetch("/api/scheduler/slots"),fetch("/api/scheduler/sync",{method:"POST"})]);if(k.ok){const C=await k.json();n(C.items||[])}if(E.ok){const C=await E.json();s(C.slots||[])}}catch{}g(!1)},[]);S.useEffect(()=>{y()},[y]);const b=async k=>{(await fetch(`/api/scheduler/queue/${k}`,{method:"DELETE"})).ok&&(n(C=>C.filter(O=>O.id!==k)),h(null))};if(l)return u.jsx(h8,{onBack:()=>{d(!1),y()}});if(i)return u.jsx(d8,{slots:r,onBack:()=>{o(!1),y()}});const x=x8(r,e);return u.jsxs("div",{className:"sidebar-schedule",children:[u.jsxs("div",{className:"sidebar-schedule-header",children:[u.jsx("button",{className:"sidebar-schedule-back",onClick:t,title:"Back to documents",children:u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"m15 18-6-6 6-6"})})}),u.jsx("h3",{children:"Schedule"}),u.jsxs("div",{className:"sidebar-schedule-actions",children:[u.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>d(!0),title:"Autoplugs",children:u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}),u.jsx("button",{className:"sidebar-schedule-btn",onClick:()=>o(!0),title:"Manage slots",children:u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.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"}),u.jsx("circle",{cx:"12",cy:"12",r:"3"})]})})]})]}),m?null:r.length===0?u.jsxs("div",{className:"schedule-empty",children:[u.jsx("div",{className:"schedule-empty-title",children:"No time slots"}),u.jsx("div",{className:"schedule-empty-desc",children:"Create time slots to define your posting schedule."})]}):x.map(({label:k,entries:E})=>u.jsxs("div",{className:"schedule-day",children:[u.jsx("div",{className:"schedule-day-header",children:k}),E.map((C,O)=>{var _,T,R,I,B;return C.type==="empty"?u.jsxs("div",{className:"schedule-slot-empty",children:[u.jsx("div",{className:"schedule-item-time",children:dw(C.time)}),u.jsx("div",{className:"schedule-slot-empty-label",children:((_=C.slot)==null?void 0:_.filter_type)==="any"?"Open slot":`${(T=C.slot)==null?void 0:T.filter_type}: ${((R=C.slot)==null?void 0:R.filter_value)||"any"}`})]},`empty-${O}`):u.jsxs("div",{children:[u.jsxs("div",{className:"schedule-item",onClick:()=>h(f===C.item.id?null:C.item.id),children:[u.jsx("div",{className:"schedule-item-time",children:dw(C.time)}),u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:((I=C.item.content)==null?void 0:I.text)||JSON.stringify(C.item.content)}),u.jsxs("div",{className:"schedule-item-meta",children:[u.jsx("span",{className:`schedule-item-status schedule-item-status--${C.item.status}`}),u.jsx("span",{children:C.item.status}),C.item.connection_name&&u.jsx("span",{children:C.item.connection_name}),C.item.provider&&u.jsx("span",{children:C.item.provider})]})]})]}),f===C.item.id&&u.jsxs("div",{className:"schedule-item-expanded",children:[u.jsx("div",{className:"schedule-item-full-text",children:((B=C.item.content)==null?void 0:B.text)||JSON.stringify(C.item.content,null,2)}),u.jsx("div",{className:"schedule-item-actions",children:u.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:()=>b(C.item.id),children:"Cancel"})})]})]},C.item.id)})]},k))]})}function x8(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 y of t){if(!(y.days.includes("default")||y.days.includes(g)))continue;const[x,k]=y.time.split(":").map(Number),E=new Date(d);if(E.setHours(x,k,0,0),uw(d,n)&&E<n)continue;const C=`${E.getFullYear()}-${E.getMonth()}-${E.getDate()}-${x}-${k}`,O=s.get(C);O?(f.push({type:"filled",time:E,item:O,slot:y}),i.add(O.id)):f.push({type:"empty",time:E,slot:y})}for(const y of e){if(i.has(y.id))continue;const b=new Date(y.scheduled_at);uw(b,d)&&(f.push({type:"filled",time:b,item:y}),i.add(y.id))}f.sort((y,b)=>y.time.getTime()-b.time.getTime()),f.length>0&&o.push({label:l,entries:f})}return o}function uw(t,e){return t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate()}function dw(t){return t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function w8({onBack:t}){const[e,n]=S.useState([]),[r,s]=S.useState(""),[i,o]=S.useState(null),[l,d]=S.useState(!1),f=S.useRef(null),h=S.useCallback(async()=>{try{const k=await fetch("/api/tasks");if(k.ok){const E=await k.json();n(E.tasks||[])}}catch{}},[]);S.useEffect(()=>{h()},[h]);const m=async()=>{const k=r.trim();if(k){s("");try{const E=await fetch("/api/tasks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:k})});if(E.ok){const C=await E.json();n(O=>[...O,C.task])}}catch{}}},g=k=>{o(k),fetch(`/api/tasks/${k}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({completed:!0})}).catch(()=>{}),setTimeout(()=>{n(E=>E.filter(C=>C.id!==k)),o(null)},400)},y=async k=>{try{(await fetch(`/api/tasks/${k}`,{method:"DELETE"})).ok&&n(C=>C.filter(O=>O.id!==k))}catch{}},b=()=>{d(!0),setTimeout(()=>{var k;return(k=f.current)==null?void 0:k.focus()},0)},x=e.filter(k=>!k.completed);return u.jsxs("div",{className:"sidebar-tasks",children:[u.jsxs("div",{className:"sidebar-tasks-header",children:[u.jsx("button",{className:"sidebar-tasks-back",onClick:t,title:"Back to documents",children:u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("path",{d:"m15 18-6-6 6-6"})})}),u.jsx("h3",{children:"Tasks"}),u.jsx("button",{className:"sidebar-tasks-add-btn",onClick:b,title:"Add task",children:"+"})]}),x.length===0&&!l?u.jsxs("div",{className:"sidebar-tasks-empty",children:[u.jsx("div",{className:"sidebar-tasks-empty-title",children:"No tasks"}),u.jsx("div",{className:"sidebar-tasks-empty-desc",children:"Add tasks to track your checklist."})]}):u.jsx("div",{className:"sidebar-tasks-list",children:x.map(k=>u.jsxs("div",{className:`sidebar-tasks-item${i===k.id?" completing":""}`,children:[u.jsx("input",{type:"checkbox",className:"sidebar-tasks-checkbox",checked:i===k.id,onChange:()=>g(k.id)}),u.jsx("span",{className:`sidebar-tasks-text${i===k.id?" completed":""}`,children:k.text}),u.jsx("button",{className:"sidebar-tasks-delete",onClick:()=>y(k.id),title:"Remove",children:"×"})]},k.id))}),l&&u.jsx("div",{className:"sidebar-tasks-add",children:u.jsx("input",{ref:f,type:"text",placeholder:"New task...",value:r,onChange:k=>s(k.target.value),onKeyDown:k=>{k.key==="Enter"&&m(),k.key==="Escape"&&(d(!1),s(""))},onBlur:()=>{r.trim()||d(!1)}})})]})}function k8({profiles:t,activeProfile:e,trashedProfiles:n,onSwitch:r,onCreate:s,onDelete:i,onRestore:o}){const[l,d]=S.useState(!1),[f,h]=S.useState(!1),[m,g]=S.useState(""),[y,b]=S.useState(null),x=S.useRef(null),k=S.useRef(null);S.useEffect(()=>{if(!l)return;const C=O=>{x.current&&!x.current.contains(O.target)&&(d(!1),h(!1),g(""),b(null))};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[l]),S.useEffect(()=>{f&&k.current&&k.current.focus()},[f]);const E=()=>{const C=m.trim();C&&(s(C),g(""),h(!1))};return u.jsxs("div",{className:"sidebar-profile-wrapper",ref:x,children:[u.jsx("button",{className:"sidebar-collapse-btn",onClick:()=>d(!l),title:`Profile: ${e}`,children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"8",r:"4"}),u.jsx("path",{d:"M5.5 21a8.38 8.38 0 0 1 13 0"})]})}),l&&u.jsxs("div",{className:"sidebar-profile-dropdown",children:[t.map(C=>u.jsxs("div",{className:"sidebar-profile-row",children:[y===C?u.jsxs("div",{className:"sidebar-profile-confirm",children:[u.jsx("span",{children:"Delete?"}),u.jsxs("div",{className:"sidebar-inline-confirm",children:[u.jsx("button",{onClick:()=>{i(C),b(null)},children:"Yes"}),u.jsx("button",{onClick:()=>b(null),children:"No"})]})]}):u.jsx(u.Fragment,{children:u.jsxs("button",{className:`sidebar-profile-option ${C===e?"active":""}`,onClick:()=>{C!==e&&r(C),d(!1)},children:[u.jsx("span",{className:"sidebar-profile-check",children:C===e?"✓":""}),u.jsx("span",{children:C})]})}),C!=="Default"&&C!==e&&y!==C&&u.jsx("button",{className:"sidebar-profile-delete-btn",onClick:O=>{O.stopPropagation(),b(C)},title:"Delete profile",children:"×"})]},C)),n.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"sidebar-profile-divider"}),u.jsx("div",{className:"sidebar-profile-trash-label",children:"Trash"}),n.map(C=>u.jsxs("div",{className:"sidebar-profile-row sidebar-profile-trashed",children:[u.jsx("span",{className:"sidebar-profile-trash-name",children:C}),u.jsx("button",{className:"sidebar-profile-restore-btn",onClick:()=>o(C),children:"Restore"})]},C))]}),u.jsx("div",{className:"sidebar-profile-divider"}),f?u.jsx("div",{className:"sidebar-profile-add-input",children:u.jsx("input",{ref:k,type:"text",value:m,onChange:C=>g(C.target.value),onKeyDown:C=>{C.key==="Enter"&&E(),C.key==="Escape"&&(h(!1),g(""))},placeholder:"Profile name..."})}):u.jsxs("button",{className:"sidebar-profile-option sidebar-profile-add",onClick:()=>h(!0),children:[u.jsx("span",{className:"sidebar-profile-check",children:"+"}),u.jsx("span",{children:"New Profile"})]})]})]})}const fw=200,hw=600,Sp=260;function pw({open:t,onSwitchDocument:e,onCreateDocument:n,refreshKey:r,workspacesRefreshKey:s,pendingDocs:i,writingTitle:o,writingTarget:l,pendingWriteFilenames:d,onClose:f}){const{docs:h,setDocs:m,workspaces:g,setWorkspaces:y,assignedFiles:b,fetchDocs:x,fetchWorkspaces:k,scrollRef:E,markPendingDelete:C}=z5(r,s),O=$5(x,k,m,y,r,C),_=kd(),[T,R]=S.useState(()=>{try{const Je=localStorage.getItem("ow-sidebar-width");if(Je){const Fe=parseInt(Je,10);if(!isNaN(Fe)&&Fe>=fw&&Fe<=hw)return Fe}}catch{}return Sp}),I=S.useRef(!1),B=S.useCallback(Je=>{Je.preventDefault(),I.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none";const Fe=qt=>{if(!I.current)return;const ie=Math.min(hw,Math.max(fw,qt.clientX));R(ie)},Nt=()=>{I.current=!1,document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("pointermove",Fe),window.removeEventListener("pointerup",Nt);try{localStorage.setItem("ow-sidebar-width",String(P.current))}catch{}};window.addEventListener("pointermove",Fe),window.addEventListener("pointerup",Nt)},[]),P=S.useRef(T);P.current=T;const D=S.useCallback(Je=>{m(Fe=>Fe.map(Nt=>({...Nt,isActive:Nt.filename===Je}))),e(Je)},[m,e]),[V,$]=S.useState(!1),[Q,G]=S.useState(!1),[K,X]=S.useState([]),[re,J]=S.useState("Default"),oe=S.useCallback(async()=>{try{const Je=await fetch("/api/profiles");if(Je.ok){const Fe=await Je.json();X(Fe.profiles),J(Fe.active)}}catch{}},[]);S.useEffect(()=>{oe()},[oe]);const U=S.useCallback(async Je=>{try{(await fetch("/api/profiles/switch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Je})})).ok&&(J(Je),oe())}catch{}},[oe]),A=S.useCallback(async Je=>{try{(await fetch("/api/profiles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Je})})).ok&&oe()}catch{}},[oe]),[L,te]=S.useState([]),se=S.useCallback(async()=>{try{const Je=await fetch("/api/profiles/trash");if(Je.ok){const Fe=await Je.json();te(Fe.profiles)}}catch{}},[]);S.useEffect(()=>{se()},[se]);const be=S.useCallback(async Je=>{try{(await fetch(`/api/profiles/${encodeURIComponent(Je)}`,{method:"DELETE"})).ok&&(oe(),se())}catch{}},[oe,se]),ee=S.useCallback(async Je=>{try{(await fetch("/api/profiles/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Je})})).ok&&(oe(),se())}catch{}},[oe,se]),[ge,fe]=S.useState(""),[Te,Xe]=S.useState(null),tt=S.useRef(),st=S.useRef(null),nt=S.useCallback(Je=>{if(fe(Je),tt.current&&clearTimeout(tt.current),!Je.trim()){Xe(null);return}tt.current=setTimeout(async()=>{try{const Fe=await fetch(`/api/documents/search?q=${encodeURIComponent(Je.trim())}&archived=true`);Fe.ok&&Xe(await Fe.json())}catch{}},250)},[]);S.useEffect(()=>()=>{tt.current&&clearTimeout(tt.current)},[]);const Le={docs:h,archivedDocs:[],workspaces:g,assignedFiles:b,pendingDocs:i,writingTitle:o,writingTarget:l,pendingWriteFilenames:d,onSwitchDocument:D,onCreateDocument:n,actions:O,scrollRef:E,searchQuery:ge,searchResults:Te,onSearchChange:nt},yt=()=>{switch(_){case"files":return u.jsx(a8,{...Le});case"timeline":return u.jsx(K5,{...Le});case"board":return u.jsx(G5,{...Le});case"shelf":return u.jsx(J5,{...Le});default:return u.jsx(V5,{...Le})}},Ke=u.jsxs("div",{className:"sidebar-search",children:[u.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:[u.jsx("circle",{cx:"10.5",cy:"10.5",r:"7"}),u.jsx("path",{d:"m20 20-4.5-4.5"})]}),u.jsx("input",{ref:st,className:"sidebar-search-input",type:"text",placeholder:"Search...",value:ge,onChange:Je=>nt(Je.target.value)}),ge&&u.jsx("button",{className:"sidebar-search-clear",onClick:()=>nt(""),title:"Clear search",children:"×"})]}),Et=t?{width:`${T}px`,minWidth:`${T}px`}:void 0,je=t?u.jsx("div",{className:"sidebar-resize-handle",onPointerDown:B,onDoubleClick:()=>{R(Sp);try{localStorage.setItem("ow-sidebar-width",String(Sp))}catch{}},title:"Drag to resize · double-click to reset"}):null;return _==="board"?u.jsxs("div",{className:`sidebar sidebar-board-mode ${t?"open":""}`,style:Et,children:[yt(),je]}):u.jsxs("div",{className:`sidebar ${t?"open":""}`,style:Et,children:[u.jsxs("div",{className:"sidebar-topbar",children:[u.jsxs("div",{className:"sidebar-logo",children:[u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[u.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"}),u.jsx("path",{d:"M15 5l4 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),u.jsx("span",{className:"sidebar-logo-text",children:"OpenWriter"})]}),u.jsxs("div",{className:"sidebar-topbar-actions",children:[u.jsx(k8,{profiles:K,activeProfile:re,trashedProfiles:L,onSwitch:U,onCreate:A,onDelete:be,onRestore:ee}),u.jsx("button",{className:`sidebar-collapse-btn${V?" sidebar-collapse-btn--active":""}`,onClick:()=>{$(!V),G(!1)},title:"Schedule",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),u.jsx("line",{x1:"16",x2:"16",y1:"1",y2:"5"}),u.jsx("line",{x1:"8",x2:"8",y1:"1",y2:"5"}),u.jsx("line",{x1:"3",x2:"21",y1:"9",y2:"9"})]})}),u.jsx("button",{className:`sidebar-collapse-btn${Q?" sidebar-collapse-btn--active":""}`,onClick:()=>{G(!Q),$(!1)},title:"Tasks",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),u.jsx("path",{d:"m9 12 2 2 4-4"})]})}),f&&u.jsx("button",{className:"sidebar-collapse-btn",onClick:f,title:"Close sidebar",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",children:[u.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",stroke:"currentColor",strokeWidth:"2"}),u.jsx("path",{d:"M9 3v18",stroke:"currentColor",strokeWidth:"2"}),u.jsx("path",{d:"M15 10l-2 2 2 2",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})]}),Q?u.jsx(w8,{onBack:()=>G(!1)}):V?u.jsx(b8,{onBack:()=>$(!1)}):u.jsxs(u.Fragment,{children:[Ke,yt()]}),je]})}function S8({onClose:t,onSetupComplete:e}){const[n,r]=S.useState("detecting"),[s,i]=S.useState(null),[o,l]=S.useState("gh"),[d,f]=S.useState("openwriter-docs"),[h,m]=S.useState(!0),[g,y]=S.useState(""),[b,x]=S.useState(""),[k,E]=S.useState(""),[C,O]=S.useState("");S.useEffect(()=>{fetch("/api/sync/capabilities").then(T=>T.json()).then(T=>{i(T),T.ghAuthenticated?l("gh"):(T.gitInstalled,l("pat")),r("setup")}).catch(()=>{E("Failed to detect git capabilities"),r("error")})},[]);const _=S.useCallback(async()=>{r("progress"),O(o==="connect"?"Connecting to repository...":"Creating repository and syncing...");try{const T={method:o,repoName:d,isPrivate:h};o==="pat"&&(T.pat=g),o==="connect"&&(T.remoteUrl=b,T.pat=g||void 0);const R=await fetch("/api/sync/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(T)});if(!R.ok){const I=await R.json().catch(()=>({}));throw new Error(I.error||`Setup failed (${R.status})`)}r("done"),e()}catch(T){E(T.message),r("error")}},[o,d,h,g,b,e]);return u.jsx("div",{className:"sync-modal-overlay",onClick:t,children:u.jsxs("div",{className:"sync-modal",onClick:T=>T.stopPropagation(),children:[u.jsxs("div",{className:"sync-modal-header",children:[u.jsx("h2",{children:"Sync to GitHub"}),u.jsx("button",{className:"sync-modal-close",onClick:t,children:"×"})]}),n==="detecting"&&u.jsxs("div",{className:"sync-modal-body",children:[u.jsx("div",{className:"sync-spinner"}),u.jsx("p",{children:"Detecting git configuration..."})]}),n==="setup"&&s&&u.jsxs("div",{className:"sync-modal-body",children:[!s.gitInstalled&&u.jsxs("div",{className:"sync-warning",children:["Git is not installed. Please ",u.jsx("a",{href:"https://git-scm.com/downloads",target:"_blank",rel:"noreferrer",children:"install git"})," first."]}),s.gitInstalled&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"sync-tabs",children:[s.ghAuthenticated&&u.jsx("button",{className:`sync-tab${o==="gh"?" active":""}`,onClick:()=>l("gh"),children:"GitHub CLI"}),u.jsx("button",{className:`sync-tab${o==="pat"?" active":""}`,onClick:()=>l("pat"),children:"Personal Access Token"}),u.jsx("button",{className:`sync-tab${o==="connect"?" active":""}`,onClick:()=>l("connect"),children:"Connect Existing"})]}),o==="gh"&&u.jsxs("div",{className:"sync-form",children:[u.jsxs("label",{children:["Repository name",u.jsx("input",{type:"text",value:d,onChange:T=>f(T.target.value),placeholder:"openwriter-docs"})]}),u.jsxs("label",{className:"sync-checkbox",children:[u.jsx("input",{type:"checkbox",checked:h,onChange:T=>m(T.target.checked)}),"Private repository"]})]}),o==="pat"&&u.jsxs("div",{className:"sync-form",children:[!s.ghAuthenticated&&!s.ghInstalled&&u.jsxs("p",{className:"sync-hint",children:["Create a ",u.jsx("a",{href:"https://github.com/settings/tokens/new?scopes=repo&description=OpenWriter",target:"_blank",rel:"noreferrer",children:"Personal Access Token"})," with ",u.jsx("code",{children:"repo"})," scope."]}),u.jsxs("label",{children:["Personal Access Token",u.jsx("input",{type:"password",value:g,onChange:T=>y(T.target.value),placeholder:"ghp_..."})]}),u.jsxs("label",{children:["Repository name",u.jsx("input",{type:"text",value:d,onChange:T=>f(T.target.value),placeholder:"openwriter-docs"})]}),u.jsxs("label",{className:"sync-checkbox",children:[u.jsx("input",{type:"checkbox",checked:h,onChange:T=>m(T.target.checked)}),"Private repository"]})]}),o==="connect"&&u.jsxs("div",{className:"sync-form",children:[u.jsxs("label",{children:["Remote URL",u.jsx("input",{type:"text",value:b,onChange:T=>x(T.target.value),placeholder:"https://github.com/user/repo.git"})]}),u.jsxs("label",{children:["PAT (optional, for private repos)",u.jsx("input",{type:"password",value:g,onChange:T=>y(T.target.value),placeholder:"ghp_..."})]})]}),u.jsxs("div",{className:"sync-modal-actions",children:[u.jsx("button",{className:"sync-btn secondary",onClick:t,children:"Cancel"}),u.jsx("button",{className:"sync-btn primary",onClick:_,disabled:o==="pat"&&!g||o==="connect"&&!b||o!=="connect"&&!d,children:o==="connect"?"Connect & Sync":"Create & Sync"})]})]})]}),n==="progress"&&u.jsxs("div",{className:"sync-modal-body",children:[u.jsx("div",{className:"sync-spinner"}),u.jsx("p",{children:C})]}),n==="done"&&u.jsxs("div",{className:"sync-modal-body",children:[u.jsx("div",{className:"sync-success-icon",children:"✓"}),u.jsx("p",{children:"Successfully synced to GitHub!"}),u.jsx("div",{className:"sync-modal-actions",children:u.jsx("button",{className:"sync-btn primary",onClick:t,children:"Done"})})]}),n==="error"&&u.jsxs("div",{className:"sync-modal-body",children:[u.jsx("div",{className:"sync-error-msg",children:k}),u.jsxs("div",{className:"sync-modal-actions",children:[u.jsx("button",{className:"sync-btn secondary",onClick:()=>r("setup"),children:"Back"}),u.jsx("button",{className:"sync-btn secondary",onClick:t,children:"Close"})]})]})]})})}function E8({onNodeChanges:t,onAgentStatus:e,onDocumentSwitched:n,onDocumentsChanged:r,onWorkspacesChanged:s,onTitleChanged:i,onPendingDocsChanged:o,onMetadataChanged:l,onSyncStatus:d,onWritingStarted:f,onWritingFinished:h,onPendingFilenamesChanged:m,getEditorState:g}){const y=S.useRef(null),[b,x]=S.useState(!1),k=S.useRef(0),E=S.useRef(new Set),C=()=>{var re;return(re=G.current)==null?void 0:re.call(G,new Set(E.current))},O=S.useRef(t),_=S.useRef(e),T=S.useRef(n),R=S.useRef(r),I=S.useRef(s),B=S.useRef(i),P=S.useRef(o),D=S.useRef(d),V=S.useRef(l),$=S.useRef(f),Q=S.useRef(h),G=S.useRef(m),K=S.useRef(g);O.current=t,_.current=e,T.current=n,R.current=r,I.current=s,B.current=i,P.current=o,V.current=l,D.current=d,$.current=f,Q.current=h,G.current=m,K.current=g,S.useEffect(()=>{const J=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;let oe,U=!1,A=1e3;function L(){const se=new WebSocket(J);y.current=se,se.onopen=()=>{x(!0),A=1e3,U&&se.send(JSON.stringify({type:"request-document"})),U=!0},se.onmessage=be=>{var ee,ge,fe,Te,Xe,tt,st,nt,Le,yt,Ke,Et;try{const je=JSON.parse(be.data);if(je.type==="node-changes"&&je.changes&&(typeof je.version=="number"&&(k.current=je.version),(ee=O.current)==null||ee.call(O,je.changes)),je.type==="agent-status"&&((ge=_.current)==null||ge.call(_,!!je.agentConnected)),je.type==="document-switched"&&(k.current=0,(fe=T.current)==null||fe.call(T,{document:je.document,title:je.title,filename:je.filename,docId:je.docId,metadata:je.metadata})),je.type==="metadata-changed"&&je.metadata&&((Te=V.current)==null||Te.call(V,je.metadata)),je.type==="documents-changed"&&((Xe=R.current)==null||Xe.call(R)),je.type==="workspaces-changed"&&((tt=I.current)==null||tt.call(I)),je.type==="title-changed"&&je.title&&((st=B.current)==null||st.call(B,je.title)),je.type==="pending-docs-changed"&&je.pendingDocs&&((nt=P.current)==null||nt.call(P,je.pendingDocs)),je.type==="sync-status"&&((Le=D.current)==null||Le.call(D,{state:je.state,lastSyncTime:je.lastSyncTime,pendingFiles:je.pendingFiles,error:je.error})),je.type==="writing-started"&&je.title&&(typeof je.key=="string"&&(E.current.add(je.key),C()),(yt=$.current)==null||yt.call($,je.title,je.target||null)),je.type==="writing-finished"&&(typeof je.key=="string"&&je.key?E.current.delete(je.key):E.current.clear(),C(),(Ke=Q.current)==null||Ke.call(Q)),je.type==="pending-writes-sync"&&Array.isArray(je.writes)&&(E.current=new Set(je.writes.map(Je=>Je.key).filter(Boolean)),C(),je.writes.length>0)){const Je=je.writes.reduce((Fe,Nt)=>Fe.startedAt>Nt.startedAt?Fe:Nt);Je!=null&&Je.title&&((Et=$.current)==null||Et.call($,Je.title,Je.target||null))}je.type==="plugins-changed"&&window.dispatchEvent(new CustomEvent("ow-plugins-changed")),je.type==="marks-changed"&&je.filename&&window.dispatchEvent(new CustomEvent("ow-marks-changed",{detail:{filename:je.filename}}))}catch{}},se.onclose=()=>{x(!1),oe=setTimeout(L,A),A=Math.min(A*1.5,8e3)},se.onerror=()=>{se.close()}}L();function te(){var se;document.visibilityState==="visible"&&((se=y.current)==null?void 0:se.readyState)!==WebSocket.OPEN&&(clearTimeout(oe),A=1e3,L())}return document.addEventListener("visibilitychange",te),()=>{clearTimeout(oe),document.removeEventListener("visibilitychange",te),y.current&&(y.current.onclose=null,y.current.close())}},[]);const X=S.useCallback(re=>{var J;((J=y.current)==null?void 0:J.readyState)===WebSocket.OPEN&&y.current.send(JSON.stringify(re))},[]);return{connected:b,sendMessage:X,docVersionRef:k}}function N8(t){const[e,n]=S.useState(null),[r,s]=S.useState(!1),[i,o]=S.useState(null),l=S.useRef(void 0);return S.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 C8(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(`
208
208
 
209
209
  `)}function _8(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 T8(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 M8(t,e){const[n,r]=S.useState("idle"),s=S.useRef();return{copyText:S.useCallback(async()=>{const o=t.current[e];if(!o)return;const l=C8(o),d=_8(o);if(!(!l&&!d)){try{const f={};if(l&&(f["text/plain"]=new Blob([l],{type:"text/plain"})),d){const h=await T8(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 Ep(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 A8(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 j8=()=>u.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:u.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"})}),O8=()=>u.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:u.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"})}),R8=()=>u.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:u.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"})}),I8=()=>u.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:u.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"})}),L8=()=>u.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:u.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 d2({tweet:t,nested:e,url:n}){const r=A8(t.createdAt);return u.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:[u.jsxs("div",{className:"tweet-author-row",children:[t.author.avatarUrl?u.jsx("img",{className:"tweet-avatar",src:t.author.avatarUrl,alt:""}):u.jsx("div",{className:"tweet-avatar tweet-avatar-placeholder"}),u.jsxs("div",{className:"tweet-author-info",children:[u.jsx("span",{className:"tweet-author-name",children:t.author.name}),u.jsxs("span",{className:"tweet-author-handle",children:["@",t.author.username]}),r&&u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"tweet-author-separator",children:"·"}),u.jsx("span",{className:"tweet-author-timestamp",children:r})]})]})]}),u.jsx("div",{className:"tweet-text",children:t.text}),t.media&&t.media.length>0&&u.jsx("div",{className:"tweet-media","data-count":t.media.length,children:t.media.map((s,i)=>s.type==="photo"?u.jsx("img",{className:"tweet-media-img",src:s.url,alt:"",loading:"lazy"},i):s.type==="video"||s.type==="gif"?u.jsx("div",{className:"tweet-media-video-placeholder",children:u.jsx("span",{children:"Video"})},i):null)}),t.quoteTweet&&u.jsx(d2,{tweet:t.quoteTweet,nested:!0}),!e&&u.jsxs("div",{className:"tweet-actions-row",children:[u.jsxs("span",{className:"tweet-action tweet-action-reply",children:[u.jsx(j8,{}),t.metrics.replies>0&&Ep(t.metrics.replies)]}),u.jsxs("span",{className:"tweet-action tweet-action-retweet",children:[u.jsx(O8,{}),t.metrics.retweets>0&&Ep(t.metrics.retweets)]}),u.jsxs("span",{className:"tweet-action tweet-action-like",children:[u.jsx(R8,{}),t.metrics.likes>0&&Ep(t.metrics.likes)]}),u.jsx("span",{className:"tweet-action tweet-action-bookmark",children:u.jsx(I8,{})}),u.jsx("span",{className:"tweet-action tweet-action-share",children:u.jsx(L8,{})})]})]})}function mw({tweet:t,url:e}){return u.jsx(d2,{tweet:t,url:e})}function D8({initialContent:t,initialPreviewImages:e,placeholder:n="What is happening?!",onUpdate:r,onReady:s,onFocus:i,onPreviewImagesChange:o}){const[l,d]=S.useState(e||[]),f=S.useRef(e||[]),h=S.useRef(!1),m=S.useRef(s);m.current=s;const g=S.useRef(o);g.current=o;const y=S.useCallback(E=>{var O;const C=E.slice(0,4);f.current=C,d(C),(O=g.current)==null||O.call(g,C)},[]),b=S.useCallback(E=>{if(h.current)return;const C=[],O=[];if(E.state.doc.descendants((I,B)=>{var P;I.type.name==="image"&&((P=I.attrs)!=null&&P.src)&&(C.push(I.attrs.src),O.push({from:B,to:B+I.nodeSize}))}),C.length===0)return;h.current=!0;const{tr:_}=E.state;for(let I=O.length-1;I>=0;I--)_.delete(O[I].from,O[I].to);E.view.dispatch(_);const T=f.current,R=4-T.length;R>0&&y([...T,...C.slice(0,R)]),h.current=!1},[y]),x=kC({extensions:[...D_,Pd.configure({placeholder:n})],content:t||"<p></p>",onCreate:({editor:E})=>{b(E)},onUpdate:({editor:E})=>{b(E),r==null||r(E)},onFocus:()=>{i==null||i()},editorProps:{handlePaste:q_,handleDrop:V_}},[t]);S.useEffect(()=>{x&&BB(x.view,{addToPreview:E=>{const C=f.current;C.length>=4||y([...C,E])},getPreviewImages:()=>f.current})},[x,y]),S.useEffect(()=>{if(!x)return;const{state:E}=x.view;if(E.plugins.some(_=>_.key==="pendingDecoration$"))return;const C=F_(),O=E.reconfigure({plugins:[...E.plugins,C]});x.view.updateState(O)},[x]),S.useEffect(()=>{if(!x)return;const{state:E}=x.view;if(E.plugins.some(_=>_.key==="markDecoration$"))return;const C=H_(),O=E.reconfigure({plugins:[...E.plugins,C]});x.view.updateState(O)},[x]),S.useEffect(()=>{var E;x&&((E=m.current)==null||E.call(m,x))},[x]);const k=S.useCallback(E=>{y(f.current.filter((C,O)=>O!==E))},[y]);return x?u.jsxs(u.Fragment,{children:[u.jsx(vv,{editor:x}),l.length>0&&u.jsx("div",{className:"tweet-preview-grid","data-count":l.length,children:l.map((E,C)=>u.jsxs("div",{className:"tweet-image-card",children:[u.jsx("img",{className:"tweet-image-card-img",src:E,alt:"",draggable:!1}),u.jsx("button",{className:"tweet-image-card-remove",onClick:()=>k(C),title:"Remove image",children:"×"})]},E))})]}):null}function P8({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:u.jsxs("div",{className:"tweet-char-counter",title:`${t} / ${e}`,style:{width:i,height:i},children:[u.jsxs("svg",{width:i,height:i,viewBox:`0 0 ${i} ${i}`,children:[u.jsx("circle",{cx:i/2,cy:i/2,r:l,fill:"none",stroke:"var(--x-border, #eff3f4)",strokeWidth:o}),u.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&&u.jsx("span",{className:"tweet-char-number",style:{color:h,fontSize:n<-9||n>9?10:11},children:n})]})}const gw="@openwriter/plugin-x-api",vw=[{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 B8({onConnected:t,onCancel:e}){const[n,r]=S.useState({"api-key":"","api-secret":"","access-token":"","access-token-secret":""}),[s,i]=S.useState(!1),[o,l]=S.useState(""),d=vw.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:gw,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:gw})})).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 u.jsxs("div",{className:"x-connect-prompt",children:[u.jsxs("div",{className:"x-connect-header",children:[u.jsx("span",{className:"x-connect-title",children:"Connect your X account to post"}),u.jsx("button",{className:"x-connect-cancel",onClick:e,title:"Cancel",children:u.jsx("svg",{viewBox:"0 0 24 24",width:"18",height:"18",children:u.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"})})})]}),u.jsx("div",{className:"x-connect-fields",children:vw.map(h=>u.jsxs("div",{className:"x-connect-field",children:[u.jsx("label",{className:"x-connect-label",children:h.label}),u.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&&u.jsx("div",{className:"x-connect-error",children:o}),u.jsxs("div",{className:"x-connect-actions",children:[u.jsx("a",{className:"x-connect-dev-link",href:"https://developer.x.com/en/portal/dashboard",target:"_blank",rel:"noopener noreferrer",children:"Get credentials"}),u.jsx("button",{className:"x-connect-btn",onClick:f,disabled:!d||s,children:s?"Connecting...":"Connect"})]})]})}var yw={},Np,bw;function Cs(){return bw||(bw=1,Np=function(t){return typeof t=="object"?t!==null:typeof t=="function"}),Np}var Cp,xw;function hr(){if(xw)return Cp;xw=1;var t=Cs();return Cp=function(e){if(!t(e))throw TypeError(e+" is not an object!");return e},Cp}var _p,ww;function Fd(){return ww||(ww=1,_p=function(t){if(t==null)throw TypeError("Can't call method on "+t);return t}),_p}var Tp,kw;function gi(){if(kw)return Tp;kw=1;var t=Fd();return Tp=function(e){return Object(t(e))},Tp}var Mp,Sw;function Ud(){if(Sw)return Mp;Sw=1;var t=Math.ceil,e=Math.floor;return Mp=function(n){return isNaN(n=+n)?0:(n>0?e:t)(n)},Mp}var Ap,Ew;function so(){if(Ew)return Ap;Ew=1;var t=Ud(),e=Math.min;return Ap=function(n){return n>0?e(t(n),9007199254740991):0},Ap}var jp,Nw;function f2(){if(Nw)return jp;Nw=1;var t=Ud(),e=Fd();return jp=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)}},jp}var Op,Cw;function Kv(){if(Cw)return Op;Cw=1;var t=f2()(!0);return Op=function(e,n,r){return n+(r?t(e,n).length:1)},Op}var Rp,_w;function Hd(){if(_w)return Rp;_w=1;var t={}.toString;return Rp=function(e){return t.call(e).slice(8,-1)},Rp}var Ip={exports:{}},Lp={exports:{}},Dp={exports:{}},Tw;function ra(){if(Tw)return Dp.exports;Tw=1;var t=Dp.exports={version:"2.6.12"};return typeof __e=="number"&&(__e=t),Dp.exports}var Pp={exports:{}},Mw;function _r(){if(Mw)return Pp.exports;Mw=1;var t=Pp.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();return typeof __g=="number"&&(__g=t),Pp.exports}var Bp,Aw;function Wd(){return Aw||(Aw=1,Bp=!1),Bp}var jw;function qd(){if(jw)return Lp.exports;jw=1;var t=ra(),e=_r(),n="__core-js_shared__",r=e[n]||(e[n]={});return(Lp.exports=function(s,i){return r[s]||(r[s]=i!==void 0?i:{})})("versions",[]).push({version:t.version,mode:Wd()?"pure":"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"}),Lp.exports}var zp,Ow;function _l(){if(Ow)return zp;Ow=1;var t=0,e=Math.random();return zp=function(n){return"Symbol(".concat(n===void 0?"":n,")_",(++t+e).toString(36))},zp}var Rw;function _n(){if(Rw)return Ip.exports;Rw=1;var t=qd()("wks"),e=_l(),n=_r().Symbol,r=typeof n=="function",s=Ip.exports=function(i){return t[i]||(t[i]=r&&n[i]||(r?n:e)("Symbol."+i))};return s.store=t,Ip.exports}var $p,Iw;function Gv(){if(Iw)return $p;Iw=1;var t=Hd(),e=_n()("toStringTag"),n=t((function(){return arguments})())=="Arguments",r=function(s,i){try{return s[i]}catch{}};return $p=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},$p}var Fp,Lw;function Jv(){if(Lw)return Fp;Lw=1;var t=Gv(),e=RegExp.prototype.exec;return Fp=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)},Fp}var Dw={},Up,Pw;function Vd(){if(Pw)return Up;Pw=1;var t=hr();return Up=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},Up}var Hp,Bw;function Yv(){if(Bw)return Hp;Bw=1;var t=Vd(),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,y,b;return o&&(g=new RegExp("^"+h.source+"$(?!\\s)",t.call(h))),i&&(m=h[s]),y=e.call(h,f),i&&y&&(h[s]=h.global?y.index+y[0].length:m),o&&y&&y.length>1&&n.call(y[0],g,function(){for(b=1;b<arguments.length-2;b++)arguments[b]===void 0&&(y[b]=void 0)}),y}),Hp=r,Hp}var Wp={},qp,zw;function Hr(){return zw||(zw=1,qp=function(t){try{return!!t()}catch{return!0}}),qp}var Vp,$w;function Tr(){return $w||($w=1,Vp=!Hr()(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})),Vp}var Kp,Fw;function h2(){if(Fw)return Kp;Fw=1;var t=Cs(),e=_r().document,n=t(e)&&t(e.createElement);return Kp=function(r){return n?e.createElement(r):{}},Kp}var Gp,Uw;function p2(){return Uw||(Uw=1,Gp=!Tr()&&!Hr()(function(){return Object.defineProperty(h2()("div"),"a",{get:function(){return 7}}).a!=7})),Gp}var Jp,Hw;function Xv(){if(Hw)return Jp;Hw=1;var t=Cs();return Jp=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")},Jp}var Ww;function Wr(){if(Ww)return Wp;Ww=1;var t=hr(),e=p2(),n=Xv(),r=Object.defineProperty;return Wp.f=Tr()?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},Wp}var Yp,qw;function Tl(){return qw||(qw=1,Yp=function(t,e){return{enumerable:!(t&1),configurable:!(t&2),writable:!(t&4),value:e}}),Yp}var Xp,Vw;function vi(){if(Vw)return Xp;Vw=1;var t=Wr(),e=Tl();return Xp=Tr()?function(n,r,s){return t.f(n,r,e(1,s))}:function(n,r,s){return n[r]=s,n},Xp}var Qp={exports:{}},Zp,Kw;function io(){if(Kw)return Zp;Kw=1;var t={}.hasOwnProperty;return Zp=function(e,n){return t.call(e,n)},Zp}var em,Gw;function z8(){return Gw||(Gw=1,em=qd()("native-function-to-string",Function.toString)),em}var Jw;function _s(){if(Jw)return Qp.exports;Jw=1;var t=_r(),e=vi(),n=io(),r=_l()("src"),s=z8(),i="toString",o=(""+s).split(i);return ra().inspectSource=function(l){return s.call(l)},(Qp.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)}),Qp.exports}var tm,Yw;function Kd(){return Yw||(Yw=1,tm=function(t){if(typeof t!="function")throw TypeError(t+" is not a function!");return t}),tm}var nm,Xw;function Gd(){if(Xw)return nm;Xw=1;var t=Kd();return nm=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)}},nm}var rm,Qw;function ir(){if(Qw)return rm;Qw=1;var t=_r(),e=ra(),n=vi(),r=_s(),s=Gd(),i="prototype",o=function(l,d,f){var h=l&o.F,m=l&o.G,g=l&o.S,y=l&o.P,b=l&o.B,x=m?t:g?t[d]||(t[d]={}):(t[d]||{})[i],k=m?e:e[d]||(e[d]={}),E=k[i]||(k[i]={}),C,O,_,T;m&&(f=d);for(C in f)O=!h&&x&&x[C]!==void 0,_=(O?x:f)[C],T=b&&O?s(_,t):y&&typeof _=="function"?s(Function.call,_):_,x&&r(x,C,_,l&o.U),k[C]!=_&&n(k,C,T),y&&E[C]!=_&&(E[C]=_)};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,rm=o,rm}var Zw;function $8(){if(Zw)return Dw;Zw=1;var t=Yv();return ir()({target:"RegExp",proto:!0,forced:t!==/./.exec},{exec:t}),Dw}var sm,ek;function Qv(){if(ek)return sm;ek=1,$8();var t=_s(),e=vi(),n=Hr(),r=Fd(),s=_n(),i=Yv(),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 sm=function(f,h,m){var g=s(f),y=!n(function(){var O={};return O[g]=function(){return 7},""[f](O)!=7}),b=y?!n(function(){var O=!1,_=/a/;return _.exec=function(){return O=!0,null},f==="split"&&(_.constructor={},_.constructor[o]=function(){return _}),_[g](""),!O}):void 0;if(!y||!b||f==="replace"&&!l||f==="split"&&!d){var x=/./[g],k=m(r,g,""[f],function(_,T,R,I,B){return T.exec===i?y&&!B?{done:!0,value:x.call(T,R,I)}:{done:!0,value:_.call(R,T,I)}:{done:!1}}),E=k[0],C=k[1];t(String.prototype,f,E),e(RegExp.prototype,g,h==2?function(O,_){return C.call(O,this,_)}:function(O){return C.call(O,this)})}},sm}var tk;function F8(){if(tk)return yw;tk=1;var t=hr(),e=gi(),n=so(),r=Ud(),s=Kv(),i=Jv(),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 Qv()("replace",2,function(g,y,b,x){return[function(C,O){var _=g(this),T=C==null?void 0:C[y];return T!==void 0?T.call(C,_,O):b.call(String(_),C,O)},function(E,C){var O=x(b,E,this,C);if(O.done)return O.value;var _=t(E),T=String(this),R=typeof C=="function";R||(C=String(C));var I=_.global;if(I){var B=_.unicode;_.lastIndex=0}for(var P=[];;){var D=i(_,T);if(D===null||(P.push(D),!I))break;var V=String(D[0]);V===""&&(_.lastIndex=s(T,n(_.lastIndex),B))}for(var $="",Q=0,G=0;G<P.length;G++){D=P[G];for(var K=String(D[0]),X=o(l(r(D.index),T.length),0),re=[],J=1;J<D.length;J++)re.push(m(D[J]));var oe=D.groups;if(R){var U=[K].concat(re,X,T);oe!==void 0&&U.push(oe);var A=String(C.apply(void 0,U))}else A=k(K,T,X,re,oe,C);X>=Q&&($+=T.slice(Q,X)+A,Q=X+K.length)}return $+T.slice(Q)}];function k(E,C,O,_,T,R){var I=O+E.length,B=_.length,P=h;return T!==void 0&&(T=e(T),P=f),b.call(R,P,function(D,V){var $;switch(V.charAt(0)){case"$":return"$";case"&":return E;case"`":return C.slice(0,O);case"'":return C.slice(I);case"<":$=T[V.slice(1,-1)];break;default:var Q=+V;if(Q===0)return D;if(Q>B){var G=d(Q/10);return G===0?D:G<=B?_[G-1]===void 0?V.charAt(1):_[G-1]+V.charAt(1):D}$=_[Q-1]}return $===void 0?"":$})}}),yw}F8();var nk={},im,rk;function Zv(){if(rk)return im;rk=1;var t=Hd();return im=Object("z").propertyIsEnumerable(0)?Object:function(e){return t(e)=="String"?e.split(""):Object(e)},im}var om,sk;function oo(){if(sk)return om;sk=1;var t=Zv(),e=Fd();return om=function(n){return t(e(n))},om}var am,ik;function U8(){if(ik)return am;ik=1;var t=Ud(),e=Math.max,n=Math.min;return am=function(r,s){return r=t(r),r<0?e(r+s,0):n(r,s)},am}var lm,ok;function m2(){if(ok)return lm;ok=1;var t=oo(),e=so(),n=U8();return lm=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}},lm}var cm,ak;function Ml(){if(ak)return cm;ak=1;var t=Hr();return cm=function(e,n){return!!e&&t(function(){n?e.call(null,function(){},1):e.call(null)})},cm}var lk;function H8(){if(lk)return nk;lk=1;var t=ir(),e=m2()(!1),n=[].indexOf,r=!!n&&1/[1].indexOf(1,-0)<0;return t(t.P+t.F*(r||!Ml()(n)),"Array",{indexOf:function(i){return r?n.apply(this,arguments)||0:e(this,i,arguments[1])}}),nk}H8();var W8=/[a-z]{1,6}(?:[._][a-z]{1,2})?/i,g2=/\!'#%&'\(\)*\+,\\\-\.\/:;<=>\?@\[\]\^_{|}~\$/,ck={},um={},dm={},uk;function e0(){return uk||(uk=1,dm.f={}.propertyIsEnumerable),dm}var dk;function t0(){if(dk)return um;dk=1;var t=e0(),e=Tl(),n=oo(),r=Xv(),s=io(),i=p2(),o=Object.getOwnPropertyDescriptor;return um.f=Tr()?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])},um}var fm,fk;function q8(){if(fk)return fm;fk=1;var t=Cs(),e=hr(),n=function(r,s){if(e(r),!t(s)&&s!==null)throw TypeError(s+": can't set as prototype!")};return fm={set:Object.setPrototypeOf||("__proto__"in{}?(function(r,s,i){try{i=Gd()(Function.call,t0().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},fm}var hm,hk;function V8(){if(hk)return hm;hk=1;var t=Cs(),e=q8().set;return hm=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},hm}var pm={},mm,pk;function n0(){if(pk)return mm;pk=1;var t=qd()("keys"),e=_l();return mm=function(n){return t[n]||(t[n]=e(n))},mm}var gm,mk;function v2(){if(mk)return gm;mk=1;var t=io(),e=oo(),n=m2()(!1),r=n0()("IE_PROTO");return gm=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},gm}var vm,gk;function r0(){return gk||(gk=1,vm="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")),vm}var vk;function Jd(){if(vk)return pm;vk=1;var t=v2(),e=r0().concat("length","prototype");return pm.f=Object.getOwnPropertyNames||function(r){return t(r,e)},pm}var ym,yk;function y2(){if(yk)return ym;yk=1;var t=Cs(),e=Hd(),n=_n()("match");return ym=function(r){var s;return t(r)&&((s=r[n])!==void 0?!!s:e(r)=="RegExp")},ym}var bm,bk;function K8(){if(bk)return bm;bk=1;var t=_r(),e=Wr(),n=Tr(),r=_n()("species");return bm=function(s){var i=t[s];n&&i&&!i[r]&&e.f(i,r,{configurable:!0,get:function(){return this}})},bm}var xk;function G8(){if(xk)return ck;xk=1;var t=_r(),e=V8(),n=Wr().f,r=Jd().f,s=y2(),i=Vd(),o=t.RegExp,l=o,d=o.prototype,f=/a/g,h=/a/g,m=new o(f)!==f;if(Tr()&&(!m||Hr()(function(){return h[_n()("match")]=!1,o(f)!=f||o(h)==h||o(f,"i")!="/a/i"}))){o=function(k,E){var C=this instanceof o,O=s(k),_=E===void 0;return!C&&O&&k.constructor===o&&_?k:e(m?new l(O&&!_?k.source:k,E):l((O=k instanceof o)?k.source:k,O&&_?i.call(k):E),C?this:d,o)};for(var g=function(x){x in o||n(o,x,{configurable:!0,get:function(){return l[x]},set:function(k){l[x]=k}})},y=r(l),b=0;y.length>b;)g(y[b++]);d.constructor=o,o.prototype=d,_s()(t,"RegExp",o)}return K8()("RegExp"),ck}G8();function wt(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 b2=/\x09-\x0D\x20\x85\xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000/;const x2=wt(/[#{spacesGroup}]/,{spacesGroup:b2});wt("(^|#{spaces})(\\$)(#{cashtag})(?=$|\\s|[#{punct}])",{cashtag:W8,spaces:x2,punct:g2},"gi");var wk={},kk;function J8(){if(kk)return wk;kk=1;var t=hr(),e=so(),n=Kv(),r=Jv();return Qv()("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 y=[],b=0,x;(x=r(h,m))!==null;){var k=String(x[0]);y[b]=k,k===""&&(h.lastIndex=n(m,e(h.lastIndex),g)),b++}return b===0?null:y}]}),wk}J8();var w2=/[##]/;wt(/^(?:#{hashSigns}|:\/\/)/,{hashSigns:w2});var k2=wt(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@+-]|$))")),S2=/\u202A-\u202E\u061C\u200E\u200F\u2066\u2067\u2068\u2069/,s0=/\uFFFE\uFEFF\uFFFF/;function Y8(t,e){return t.replace(/#\{(\w+)\}/g,function(n,r){return e[r]||""})}var X8=Y8("#{punct}#{spacesGroup}#{invalidCharsGroup}#{directionalMarkersGroup}",{punct:g2,spacesGroup:b2,invalidCharsGroup:s0,directionalMarkersGroup:S2}),E2=wt(/[^#{invalidDomainChars}]/,{invalidDomainChars:X8}),Q8=wt(/(?:(?:#{validDomainChars}(?:-|#{validDomainChars})*)?#{validDomainChars}\.)/,{validDomainChars:E2}),N2=wt(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@+-]|$))")),C2=/(?:xn--[\-0-9a-z]+)/,Z8=wt(/(?:(?:#{validDomainChars}(?:[_-]|#{validDomainChars})*)?#{validDomainChars}\.)/,{validDomainChars:E2}),ez=wt(/(?:#{validSubdomain}*#{validDomainName}(?:#{validGTLD}|#{validCCTLD}|#{validPunycode}))/,{validDomainName:Q8,validSubdomain:Z8,validGTLD:N2,validCCTLD:k2,validPunycode:C2}),tz=/[0-9]+/,_2=/\u0400-\u04FF/,Yd=/\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/,T2=wt(/[a-z#{cyrillicLettersAndMarks}0-9!\*';:=\+,\.\$\/%#\[\]\-\u2013_~@\|&#{latinAccentChars}]/i,{cyrillicLettersAndMarks:_2,latinAccentChars:Yd}),M2=wt("\\((?:#{validGeneralUrlPathChars}+|(?:#{validGeneralUrlPathChars}*\\(#{validGeneralUrlPathChars}+\\)#{validGeneralUrlPathChars}*))\\)",{validGeneralUrlPathChars:T2},"i"),nz=wt(/[\+\-a-z#{cyrillicLettersAndMarks}0-9=_#\/#{latinAccentChars}]|(?:#{validUrlBalancedParens})/i,{cyrillicLettersAndMarks:_2,latinAccentChars:Yd,validUrlBalancedParens:M2}),rz=wt("(?:(?:#{validGeneralUrlPathChars}*(?:#{validUrlBalancedParens}#{validGeneralUrlPathChars}*)*#{validUrlPathEndingChars})|(?:@#{validGeneralUrlPathChars}+/))",{validGeneralUrlPathChars:T2,validUrlBalancedParens:M2,validUrlPathEndingChars:nz},"i"),sz=wt(/(?:[^A-Za-z0-9@@$###{invalidCharsGroup}]|[#{directionalMarkersGroup}]|^)/,{invalidCharsGroup:s0,directionalMarkersGroup:S2}),A2=/[a-z0-9!?\*'@\(\);:&=\+\$\/%#\[\]\-_\.,~|]/i,j2=/[a-z0-9\-_&=#\/]/i,Sk=wt("((#{validUrlPrecedingChars})((https?:\\/\\/)?(#{validDomain})(?::(#{validPortNumber}))?(\\/#{validUrlPath}*)?(\\?#{validUrlQueryChars}*#{validUrlQueryEndingChars})?))",{validUrlPrecedingChars:sz,validDomain:ez,validPortNumber:tz,validUrlPath:rz,validUrlQueryChars:A2,validUrlQueryEndingChars:j2},"gi"),iz=/[-_.\/]$/,Ek={},xm,Nk;function oz(){if(Nk)return xm;Nk=1;var t=hr(),e=Kd(),n=_n()("species");return xm=function(r,s){var i=t(r).constructor,o;return i===void 0||(o=t(i)[n])==null?s:e(o)},xm}var Ck;function az(){if(Ck)return Ek;Ck=1;var t=y2(),e=hr(),n=oz(),r=Kv(),s=so(),i=Jv(),o=Yv(),l=Hr(),d=Math.min,f=[].push,h="split",m="length",g="lastIndex",y=4294967295,b=!l(function(){});return Qv()("split",2,function(x,k,E,C){var O;return"abbc"[h](/(b)*/)[1]=="c"||"test"[h](/(?:)/,-1)[m]!=4||"ab"[h](/(?:ab)*/)[m]!=2||"."[h](/(.?)(.?)/)[m]!=4||"."[h](/()()/)[m]>1||""[h](/.?/)[m]?O=function(_,T){var R=String(this);if(_===void 0&&T===0)return[];if(!t(_))return E.call(R,_,T);for(var I=[],B=(_.ignoreCase?"i":"")+(_.multiline?"m":"")+(_.unicode?"u":"")+(_.sticky?"y":""),P=0,D=T===void 0?y:T>>>0,V=new RegExp(_.source,B+"g"),$,Q,G;($=o.call(V,R))&&(Q=V[g],!(Q>P&&(I.push(R.slice(P,$.index)),$[m]>1&&$.index<R[m]&&f.apply(I,$.slice(1)),G=$[0][m],P=Q,I[m]>=D)));)V[g]===$.index&&V[g]++;return P===R[m]?(G||!V.test(""))&&I.push(""):I.push(R.slice(P)),I[m]>D?I.slice(0,D):I}:"0"[h](void 0,0)[m]?O=function(_,T){return _===void 0&&T===0?[]:E.call(this,_,T)}:O=E,[function(T,R){var I=x(this),B=T==null?void 0:T[k];return B!==void 0?B.call(T,I,R):O.call(String(I),T,R)},function(_,T){var R=C(O,_,this,T,O!==E);if(R.done)return R.value;var I=e(_),B=String(this),P=n(I,RegExp),D=I.unicode,V=(I.ignoreCase?"i":"")+(I.multiline?"m":"")+(I.unicode?"u":"")+(b?"y":"g"),$=new P(b?I:"^(?:"+I.source+")",V),Q=T===void 0?y:T>>>0;if(Q===0)return[];if(B.length===0)return i($,B)===null?[B]:[];for(var G=0,K=0,X=[];K<B.length;){$.lastIndex=b?K:0;var re=i($,b?B:B.slice(K)),J;if(re===null||(J=d(s($.lastIndex+(b?0:K)),B.length))===G)K=r(B,K,D);else{if(X.push(B.slice(G,K)),X.length===Q)return X;for(var oe=1;oe<=re.length-1;oe++)if(X.push(re[oe]),X.length===Q)return X;K=G=J}}return X.push(B.slice(G)),X}]}),Ek}az();var Ja={exports:{}};/*! https://mths.be/punycode v1.4.1 by @mathias */var lz=Ja.exports,_k;function cz(){return _k||(_k=1,(function(t,e){(function(n){var r=e&&!e.nodeType&&e,s=t&&!t.nodeType&&t,i=typeof Cb=="object"&&Cb;(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,y=72,b=128,x="-",k=/^xn--/,E=/[^\x20-\x7E]/,C=/[\x2E\u3002\uFF0E\uFF61]/g,O={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},_=d-f,T=Math.floor,R=String.fromCharCode,I;function B(U){throw new RangeError(O[U])}function P(U,A){for(var L=U.length,te=[];L--;)te[L]=A(U[L]);return te}function D(U,A){var L=U.split("@"),te="";L.length>1&&(te=L[0]+"@",U=L[1]),U=U.replace(C,".");var se=U.split("."),be=P(se,A).join(".");return te+be}function V(U){for(var A=[],L=0,te=U.length,se,be;L<te;)se=U.charCodeAt(L++),se>=55296&&se<=56319&&L<te?(be=U.charCodeAt(L++),(be&64512)==56320?A.push(((se&1023)<<10)+(be&1023)+65536):(A.push(se),L--)):A.push(se);return A}function $(U){return P(U,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 Q(U){return U-48<10?U-22:U-65<26?U-65:U-97<26?U-97:d}function G(U,A){return U+22+75*(U<26)-((A!=0)<<5)}function K(U,A,L){var te=0;for(U=L?T(U/g):U>>1,U+=T(U/A);U>_*h>>1;te+=d)U=T(U/_);return T(te+(_+1)*U/(U+m))}function X(U){var A=[],L=U.length,te,se=0,be=b,ee=y,ge,fe,Te,Xe,tt,st,nt,Le,yt;for(ge=U.lastIndexOf(x),ge<0&&(ge=0),fe=0;fe<ge;++fe)U.charCodeAt(fe)>=128&&B("not-basic"),A.push(U.charCodeAt(fe));for(Te=ge>0?ge+1:0;Te<L;){for(Xe=se,tt=1,st=d;Te>=L&&B("invalid-input"),nt=Q(U.charCodeAt(Te++)),(nt>=d||nt>T((l-se)/tt))&&B("overflow"),se+=nt*tt,Le=st<=ee?f:st>=ee+h?h:st-ee,!(nt<Le);st+=d)yt=d-Le,tt>T(l/yt)&&B("overflow"),tt*=yt;te=A.length+1,ee=K(se-Xe,te,Xe==0),T(se/te)>l-be&&B("overflow"),be+=T(se/te),se%=te,A.splice(se++,0,be)}return $(A)}function re(U){var A,L,te,se,be,ee,ge,fe,Te,Xe,tt,st=[],nt,Le,yt,Ke;for(U=V(U),nt=U.length,A=b,L=0,be=y,ee=0;ee<nt;++ee)tt=U[ee],tt<128&&st.push(R(tt));for(te=se=st.length,se&&st.push(x);te<nt;){for(ge=l,ee=0;ee<nt;++ee)tt=U[ee],tt>=A&&tt<ge&&(ge=tt);for(Le=te+1,ge-A>T((l-L)/Le)&&B("overflow"),L+=(ge-A)*Le,A=ge,ee=0;ee<nt;++ee)if(tt=U[ee],tt<A&&++L>l&&B("overflow"),tt==A){for(fe=L,Te=d;Xe=Te<=be?f:Te>=be+h?h:Te-be,!(fe<Xe);Te+=d)Ke=fe-Xe,yt=d-Xe,st.push(R(G(Xe+Ke%yt,0))),fe=T(Ke/yt);st.push(R(G(fe,0))),be=K(L,Le,te==se),L=0,++te}++L,++A}return st.join("")}function J(U){return D(U,function(A){return k.test(A)?X(A.slice(4).toLowerCase()):A})}function oe(U){return D(U,function(A){return E.test(A)?"xn--"+re(A):A})}if(o={version:"1.4.1",ucs2:{decode:V,encode:$},decode:X,encode:re,toASCII:oe,toUnicode:J},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})(lz)})(Ja,Ja.exports)),Ja.exports}var uz=cz();const dz=bl(uz);var O2=wt(/(?:(?:[\-a-z0-9#{latinAccentChars}]+)\.)+(?:#{validGTLD}|#{validCCTLD}|#{validPunycode})/gi,{latinAccentChars:Yd,validGTLD:N2,validCCTLD:k2,validPunycode:C2}),fz=63,hz="xn--",pz={toAscii:function(e){if(!(e.substring(0,4)===hz&&!e.match(O2))){for(var n=e.split("."),r=0;r<n.length;r++){var s=n[r],i=dz.toASCII(s);if(i.length<1||i.length>fz)return}return n.join(".")}}},mz=wt(/^https?:\/\/t\.co\/([a-z0-9]+)(?:\?#{validUrlQueryChars}*#{validUrlQueryEndingChars})?/,{validUrlQueryChars:A2,validUrlQueryEndingChars:j2},"i"),gz="https://",vz={extractUrlsWithoutProtocol:!0},yz=4096,bz=40,xz=function(e){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:vz;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=Sk.lastIndex,y=g-d.length;if(!wz(d,f||gz,h))return"continue";if(f){if(d.match(mz)){var k=RegExp.$1;if(k&&k.length>bz)return"continue";d=RegExp.lastMatch,g=y+d.length}r.push({url:d,indices:[y,g]})}else{if(!n.extractUrlsWithoutProtocol||l.match(iz))return"continue";var b=null,x=0;if(h.replace(O2,function(E){var C=h.indexOf(E,x);x=C+E.length,b={url:E,indices:[y+C,y+x]},r.push(b)}),b==null)return"continue";m&&(b.url=d.replace(h,b.url),b.indices[1]=g)}};Sk.exec(e);)var i=s();return r},wz=function(e,n,r){var s=e.length,i=pz.toAscii(r);return!i||!i.length?!1:(s=s+i.length-r.length,n.length+s<=yz)},Tk={},Mk;function kz(){if(Mk)return Tk;Mk=1;var t=ir(),e=Kd(),n=gi(),r=Hr(),s=[].sort,i=[1,2,3];return t(t.P+t.F*(r(function(){i.sort(void 0)})||!r(function(){i.sort(null)})||!Ml()(s)),"Array",{sort:function(l){return l===void 0?s.call(n(this)):s.call(n(this),e(l))}}),Tk}kz();var R2=/\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]/,I2=/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/,L2=/[\uD800-\uDBFF][\uDC00-\uDFFF]/gm,Sz=wt(/(?:[#{bmpLetterAndMarks}]|(?=#{nonBmpCodePairs})(?:#{astralLetterAndMarks}))/,{bmpLetterAndMarks:I2,nonBmpCodePairs:L2,astralLetterAndMarks:R2}),Ez=/\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]/,Nz=/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/,Cz=/_\u200c\u200d\ua67e\u05be\u05f3\u05f4\uff5e\u301c\u309b\u309c\u30a0\u30fb\u3003\u0f0b\u0f0c\xb7/,D2=wt(/(?:[#{bmpLetterAndMarks}#{bmpNumerals}#{hashtagSpecialChars}]|(?=#{nonBmpCodePairs})(?:#{astralLetterAndMarks}|#{astralNumerals}))/,{bmpLetterAndMarks:I2,bmpNumerals:Nz,hashtagSpecialChars:Cz,nonBmpCodePairs:L2,astralLetterAndMarks:R2,astralNumerals:Ez}),_z=/(?:[^\uD800-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF])/,Tz=wt(/(?:^|\uFE0E|\uFE0F|$|(?!#{hashtagAlphaNumeric}|&)#{codePoint})/,{codePoint:_z,hashtagAlphaNumeric:D2});wt(/(#{hashtagBoundary})(#{hashSigns})(?!\uFE0F|\u20E3)(#{hashtagAlphaNumeric}*#{hashtagAlpha}#{hashtagAlphaNumeric}*)/gi,{hashtagBoundary:Tz,hashSigns:w2,hashtagAlphaNumeric:D2,hashtagAlpha:Sz});var i0=/[@@]/;wt(/^(?:#{atSigns}|[#{latinAccentChars}]|:\/\/)/,{atSigns:i0,latinAccentChars:Yd});var Mz=/(?:^|[^a-zA-Z0-9_!#$%&*@@]|(?:^|[^a-zA-Z0-9_+~.-])(?:rt|RT|rT|Rt):?)/,Az=wt("(#{validMentionPrecedingChars})(#{atSigns})([a-zA-Z0-9_]{1,20})(/[a-zA-Z][a-zA-Z0-9_-]{0,24})?",{validMentionPrecedingChars:Mz,atSigns:i0},"g"),Ak={},jk={},Ok;function jz(){return Ok||(Ok=1,Tr()&&/./g.flags!="g"&&Wr().f(RegExp.prototype,"flags",{configurable:!0,get:Vd()})),jk}var Rk;function Oz(){if(Rk)return Ak;Rk=1,jz();var t=hr(),e=Vd(),n=Tr(),r="toString",s=/./[r],i=function(o){_s()(RegExp.prototype,r,o,!0)};return Hr()(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)}),Ak}Oz();var Ik={},Lk;function Rz(){if(Lk)return Ik;Lk=1;var t=Date.prototype,e="Invalid Date",n="toString",r=t[n],s=t.getTime;return new Date(NaN)+""!=e&&_s()(t,n,function(){var o=s.call(this);return o===o?r.call(this):e}),Ik}Rz();var Dk={},Pk;function Iz(){if(Pk)return Dk;Pk=1;var t=Gv(),e={};return e[_n()("toStringTag")]="z",e+""!="[object z]"&&_s()(Object.prototype,"toString",function(){return"[object "+t(this)+"]"},!0),Dk}Iz();const Bk={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}]}};wt(/^(?:#{spaces})*#{atSigns}([a-zA-Z0-9_]{1,20})/,{atSigns:i0,spaces:x2});var zk={},wm,$k;function o0(){if($k)return wm;$k=1;var t=Hd();return wm=Array.isArray||function(n){return t(n)=="Array"},wm}var Fk;function Lz(){if(Fk)return zk;Fk=1;var t=ir();return t(t.S,"Array",{isArray:o0()}),zk}Lz();var Dz=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},Uk={},km,Hk;function Pz(){if(Hk)return km;Hk=1;var t=Kd(),e=gi(),n=Zv(),r=so();return km=function(s,i,o,l,d){t(i);var f=e(s),h=n(f),m=r(f.length),g=d?m-1:0,y=d?-1:1;if(o<2)for(;;){if(g in h){l=h[g],g+=y;break}if(g+=y,d?g<0:m<=g)throw TypeError("Reduce of empty array with no initial value")}for(;d?g>=0:m>g;g+=y)g in h&&(l=i(l,h[g],g,f));return l},km}var Wk;function Bz(){if(Wk)return Uk;Wk=1;var t=ir(),e=Pz();return t(t.P+t.F*!Ml()([].reduce,!0),"Array",{reduce:function(r){return e(this,r,arguments.length,arguments[1],!1)}}),Uk}Bz();var qk={},Sm,Vk;function zz(){if(Vk)return Sm;Vk=1;var t=_n()("unscopables"),e=Array.prototype;return e[t]==null&&vi()(e,t,{}),Sm=function(n){e[t][n]=!0},Sm}var Em,Kk;function $z(){return Kk||(Kk=1,Em=function(t,e){return{value:e,done:!!t}}),Em}var Nm,Gk;function Al(){return Gk||(Gk=1,Nm={}),Nm}var Cm,Jk;function jl(){if(Jk)return Cm;Jk=1;var t=v2(),e=r0();return Cm=Object.keys||function(r){return t(r,e)},Cm}var _m,Yk;function P2(){if(Yk)return _m;Yk=1;var t=Wr(),e=hr(),n=jl();return _m=Tr()?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},_m}var Tm,Xk;function Fz(){if(Xk)return Tm;Xk=1;var t=_r().document;return Tm=t&&t.documentElement,Tm}var Mm,Qk;function B2(){if(Qk)return Mm;Qk=1;var t=hr(),e=P2(),n=r0(),r=n0()("IE_PROTO"),s=function(){},i="prototype",o=function(){var l=h2()("iframe"),d=n.length,f="<",h=">",m;for(l.style.display="none",Fz().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 Mm=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)},Mm}var Am,Zk;function a0(){if(Zk)return Am;Zk=1;var t=Wr().f,e=io(),n=_n()("toStringTag");return Am=function(r,s,i){r&&!e(r=i?r:r.prototype,n)&&t(r,n,{configurable:!0,value:s})},Am}var jm,eS;function Uz(){if(eS)return jm;eS=1;var t=B2(),e=Tl(),n=a0(),r={};return vi()(r,_n()("iterator"),function(){return this}),jm=function(s,i,o){s.prototype=t(r,{next:e(1,o)}),n(s,i+" Iterator")},jm}var Om,tS;function Hz(){if(tS)return Om;tS=1;var t=io(),e=gi(),n=n0()("IE_PROTO"),r=Object.prototype;return Om=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},Om}var Rm,nS;function z2(){if(nS)return Rm;nS=1;var t=Wd(),e=ir(),n=_s(),r=vi(),s=Al(),i=Uz(),o=a0(),l=Hz(),d=_n()("iterator"),f=!([].keys&&"next"in[].keys()),h="@@iterator",m="keys",g="values",y=function(){return this};return Rm=function(b,x,k,E,C,O,_){i(k,x,E);var T=function(re){if(!f&&re in P)return P[re];switch(re){case m:return function(){return new k(this,re)};case g:return function(){return new k(this,re)}}return function(){return new k(this,re)}},R=x+" Iterator",I=C==g,B=!1,P=b.prototype,D=P[d]||P[h]||C&&P[C],V=D||T(C),$=C?I?T("entries"):V:void 0,Q=x=="Array"&&P.entries||D,G,K,X;if(Q&&(X=l(Q.call(new b)),X!==Object.prototype&&X.next&&(o(X,R,!0),!t&&typeof X[d]!="function"&&r(X,d,y))),I&&D&&D.name!==g&&(B=!0,V=function(){return D.call(this)}),(!t||_)&&(f||B||!P[d])&&r(P,d,V),s[x]=V,s[R]=y,C)if(G={values:I?V:T(g),keys:O?V:T(m),entries:$},_)for(K in G)K in P||n(P,K,G[K]);else e(e.P+e.F*(f||B),x,G);return G},Rm}var Im,rS;function $2(){if(rS)return Im;rS=1;var t=zz(),e=$z(),n=Al(),r=oo();return Im=z2()(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"),Im}var sS;function Wz(){if(sS)return qk;sS=1;for(var t=$2(),e=jl(),n=_s(),r=_r(),s=vi(),i=Al(),o=_n(),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 y=m[g],b=h[y],x=r[y],k=x&&x.prototype,E;if(k&&(k[l]||s(k,l,f),k[d]||s(k,d,y),i[y]=f,b))for(E in t)k[E]||n(k,E,t[E],!0)}return qk}Wz();$2();var iS={},Lm,oS;function qz(){if(oS)return Lm;oS=1;var t=ir(),e=ra(),n=Hr();return Lm=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)},Lm}var aS;function Vz(){if(aS)return iS;aS=1;var t=gi(),e=jl();return qz()("keys",function(){return function(r){return e(t(r))}}),iS}Vz();var Kz=wt(/[#{invalidCharsGroup}]/,{invalidCharsGroup:s0});function Gz(t){return Kz.test(t)}var Bi={},hu={},lS;function Jz(){return lS||(lS=1,Object.defineProperty(hu,"__esModule",{value:!0}),hu.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),hu}var cS;function Yz(){if(cS)return Bi;cS=1,Object.defineProperty(Bi,"__esModule",{value:!0}),Bi.TypeName=void 0,Bi.parse=s,Bi.toCodePoints=d;var t=Jz(),e=n(t);function n(f){return f&&f.__esModule?f:{default:f}}var r=Bi.TypeName="emoji";function s(f,h){var m=h&&h.assetType?h.assetType:"svg",g=h&&h.buildUrl?h.buildUrl:function(E,C){return C==="png"?"https://twemoji.maxcdn.com/2/72x72/"+E+".png":"https://twemoji.maxcdn.com/2/svg/"+E+".svg"},y=[];for(e.default.lastIndex=0;;){var b=e.default.exec(f);if(!b)break;var x=b[0],k=d(l(x)).join("-");y.push({url:k?g(k,m):"",indices:[b.index,e.default.lastIndex],text:x,type:r})}return y}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,y=0;y<f.length;)m=f.charCodeAt(y++),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 Bi}var Xz=Yz(),Qz=function(){for(var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Bk.defaults,r=Object.keys(n).length?n:Bk.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=uS(xz(f)),m=i?uS(Xz.parse(f)):[],g=f.length,y=0,b=0,x=!0,k=0;k<g;k++){if(h[k]){var E=h[k],C=E.url;E.indices,y+=d*o,k+=C.length-1}else if(i&&m[k]){var O=m[k],_=O.text;O.indices,y+=s,k+=_.length-1}else k+=Zz(f,k)?1:0,y+=Dz(f.charAt(k),r);x&&(x=!Gz(f.substring(k,k+1))),x&&y<=l*o&&(b=k)}y=y/o,x=x&&y>0&&y<=l;var T=Math.floor(y/l*1e3),R=e.length-f.length;return b+=R,{weightedLength:y,valid:x,permillage:T,validRangeStart:0,validRangeEnd:b,displayRangeStart:0,displayRangeEnd:e.length>0?e.length-1:0}},uS=function(e){return e.reduce(function(n,r){return n[r.indices[0]]=r,n},{})},Zz=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},dS={},fS;function e$(){if(fS)return dS;fS=1;var t=ir();return t(t.S+t.F*!Tr(),"Object",{defineProperty:Wr().f}),dS}e$();var hS={},pS;function t$(){if(pS)return hS;pS=1;var t=ir();return t(t.S+t.F*!Tr(),"Object",{defineProperties:P2()}),hS}t$();var mS={},Dm={},gS;function l0(){return gS||(gS=1,Dm.f=Object.getOwnPropertySymbols),Dm}var Pm,vS;function n$(){if(vS)return Pm;vS=1;var t=Jd(),e=l0(),n=hr(),r=_r().Reflect;return Pm=r&&r.ownKeys||function(i){var o=t.f(n(i)),l=e.f;return l?o.concat(l(i)):o},Pm}var Bm,yS;function F2(){if(yS)return Bm;yS=1;var t=Wr(),e=Tl();return Bm=function(n,r,s){r in n?t.f(n,r,e(0,s)):n[r]=s},Bm}var bS;function r$(){if(bS)return mS;bS=1;var t=ir(),e=n$(),n=oo(),r=t0(),s=F2();return t(t.S,"Object",{getOwnPropertyDescriptors:function(o){for(var l=n(o),d=r.f,f=e(l),h={},m=0,g,y;f.length>m;)y=d(l,g=f[m++]),y!==void 0&&s(h,g,y);return h}}),mS}r$();var xS={},zm,wS;function s$(){if(wS)return zm;wS=1;var t=Cs(),e=o0(),n=_n()("species");return zm=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},zm}var $m,kS;function i$(){if(kS)return $m;kS=1;var t=s$();return $m=function(e,n){return new(t(e))(n)},$m}var Fm,SS;function U2(){if(SS)return Fm;SS=1;var t=Gd(),e=Zv(),n=gi(),r=so(),s=i$();return Fm=function(i,o){var l=i==1,d=i==2,f=i==3,h=i==4,m=i==6,g=i==5||m,y=o||s;return function(b,x,k){for(var E=n(b),C=e(E),O=t(x,k,3),_=r(C.length),T=0,R=l?y(b,_):d?y(b,0):void 0,I,B;_>T;T++)if((g||T in C)&&(I=C[T],B=O(I,T,E),i)){if(l)R[T]=B;else if(B)switch(i){case 3:return!0;case 5:return I;case 6:return T;case 2:R.push(I)}else if(h)return!1}return m?-1:f||h?h:R}},Fm}var ES;function o$(){if(ES)return xS;ES=1;var t=ir(),e=U2()(0),n=Ml()([].forEach,!0);return t(t.P+t.F*!n,"Array",{forEach:function(s){return e(this,s,arguments[1])}}),xS}o$();var NS={},CS;function a$(){if(CS)return NS;CS=1;var t=ir(),e=U2()(2);return t(t.P+t.F*!Ml()([].filter,!0),"Array",{filter:function(r){return e(this,r,arguments[1])}}),NS}a$();var _S={},Um={exports:{}},TS;function l$(){if(TS)return Um.exports;TS=1;var t=_l()("meta"),e=Cs(),n=io(),r=Wr().f,s=0,i=Object.isExtensible||function(){return!0},o=!Hr()(function(){return i(Object.preventExtensions({}))}),l=function(g){r(g,t,{value:{i:"O"+ ++s,w:{}}})},d=function(g,y){if(!e(g))return typeof g=="symbol"?g:(typeof g=="string"?"S":"P")+g;if(!n(g,t)){if(!i(g))return"F";if(!y)return"E";l(g)}return g[t].i},f=function(g,y){if(!n(g,t)){if(!i(g))return!0;if(!y)return!1;l(g)}return g[t].w},h=function(g){return o&&m.NEED&&i(g)&&!n(g,t)&&l(g),g},m=Um.exports={KEY:t,NEED:!1,fastKey:d,getWeak:f,onFreeze:h};return Um.exports}var Hm={},MS;function H2(){return MS||(MS=1,Hm.f=_n()),Hm}var Wm,AS;function c$(){if(AS)return Wm;AS=1;var t=_r(),e=ra(),n=Wd(),r=H2(),s=Wr().f;return Wm=function(i){var o=e.Symbol||(e.Symbol=n?{}:t.Symbol||{});i.charAt(0)!="_"&&!(i in o)&&s(o,i,{value:r.f(i)})},Wm}var qm,jS;function u$(){if(jS)return qm;jS=1;var t=jl(),e=l0(),n=e0();return qm=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},qm}var Vm={},OS;function d$(){if(OS)return Vm;OS=1;var t=oo(),e=Jd().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 Vm.f=function(o){return r&&n.call(o)=="[object Window]"?s(o):e(t(o))},Vm}var RS;function f$(){if(RS)return _S;RS=1;var t=_r(),e=io(),n=Tr(),r=ir(),s=_s(),i=l$().KEY,o=Hr(),l=qd(),d=a0(),f=_l(),h=_n(),m=H2(),g=c$(),y=u$(),b=o0(),x=hr(),k=Cs(),E=gi(),C=oo(),O=Xv(),_=Tl(),T=B2(),R=d$(),I=t0(),B=l0(),P=Wr(),D=jl(),V=I.f,$=P.f,Q=R.f,G=t.Symbol,K=t.JSON,X=K&&K.stringify,re="prototype",J=h("_hidden"),oe=h("toPrimitive"),U={}.propertyIsEnumerable,A=l("symbol-registry"),L=l("symbols"),te=l("op-symbols"),se=Object[re],be=typeof G=="function"&&!!B.f,ee=t.QObject,ge=!ee||!ee[re]||!ee[re].findChild,fe=n&&o(function(){return T($({},"a",{get:function(){return $(this,"a",{value:7}).a}})).a!=7})?function(ie,H,q){var de=V(se,H);de&&delete se[H],$(ie,H,q),de&&ie!==se&&$(se,H,de)}:$,Te=function(ie){var H=L[ie]=T(G[re]);return H._k=ie,H},Xe=be&&typeof G.iterator=="symbol"?function(ie){return typeof ie=="symbol"}:function(ie){return ie instanceof G},tt=function(H,q,de){return H===se&&tt(te,q,de),x(H),q=O(q,!0),x(de),e(L,q)?(de.enumerable?(e(H,J)&&H[J][q]&&(H[J][q]=!1),de=T(de,{enumerable:_(0,!1)})):(e(H,J)||$(H,J,_(1,{})),H[J][q]=!0),fe(H,q,de)):$(H,q,de)},st=function(H,q){x(H);for(var de=y(q=C(q)),me=0,Ee=de.length,De;Ee>me;)tt(H,De=de[me++],q[De]);return H},nt=function(H,q){return q===void 0?T(H):st(T(H),q)},Le=function(H){var q=U.call(this,H=O(H,!0));return this===se&&e(L,H)&&!e(te,H)?!1:q||!e(this,H)||!e(L,H)||e(this,J)&&this[J][H]?q:!0},yt=function(H,q){if(H=C(H),q=O(q,!0),!(H===se&&e(L,q)&&!e(te,q))){var de=V(H,q);return de&&e(L,q)&&!(e(H,J)&&H[J][q])&&(de.enumerable=!0),de}},Ke=function(H){for(var q=Q(C(H)),de=[],me=0,Ee;q.length>me;)!e(L,Ee=q[me++])&&Ee!=J&&Ee!=i&&de.push(Ee);return de},Et=function(H){for(var q=H===se,de=Q(q?te:C(H)),me=[],Ee=0,De;de.length>Ee;)e(L,De=de[Ee++])&&(!q||e(se,De))&&me.push(L[De]);return me};be||(G=function(){if(this instanceof G)throw TypeError("Symbol is not a constructor!");var H=f(arguments.length>0?arguments[0]:void 0),q=function(de){this===se&&q.call(te,de),e(this,J)&&e(this[J],H)&&(this[J][H]=!1),fe(this,H,_(1,de))};return n&&ge&&fe(se,H,{configurable:!0,set:q}),Te(H)},s(G[re],"toString",function(){return this._k}),I.f=yt,P.f=tt,Jd().f=R.f=Ke,e0().f=Le,B.f=Et,n&&!Wd()&&s(se,"propertyIsEnumerable",Le,!0),m.f=function(ie){return Te(h(ie))}),r(r.G+r.W+r.F*!be,{Symbol:G});for(var je="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),Je=0;je.length>Je;)h(je[Je++]);for(var Fe=D(h.store),Nt=0;Fe.length>Nt;)g(Fe[Nt++]);r(r.S+r.F*!be,"Symbol",{for:function(ie){return e(A,ie+="")?A[ie]:A[ie]=G(ie)},keyFor:function(H){if(!Xe(H))throw TypeError(H+" is not a symbol!");for(var q in A)if(A[q]===H)return q},useSetter:function(){ge=!0},useSimple:function(){ge=!1}}),r(r.S+r.F*!be,"Object",{create:nt,defineProperty:tt,defineProperties:st,getOwnPropertyDescriptor:yt,getOwnPropertyNames:Ke,getOwnPropertySymbols:Et});var qt=o(function(){B.f(1)});return r(r.S+r.F*qt,"Object",{getOwnPropertySymbols:function(H){return B.f(E(H))}}),K&&r(r.S+r.F*(!be||o(function(){var ie=G();return X([ie])!="[null]"||X({a:ie})!="{}"||X(Object(ie))!="{}"})),"JSON",{stringify:function(H){for(var q=[H],de=1,me,Ee;arguments.length>de;)q.push(arguments[de++]);if(Ee=me=q[1],!(!k(me)&&H===void 0||Xe(H)))return b(me)||(me=function(De,$e){if(typeof Ee=="function"&&($e=Ee.call(this,De,$e)),!Xe($e))return $e}),q[1]=me,X.apply(K,q)}}),G[re][oe]||vi()(G[re],oe,G[re].valueOf),d(G,"Symbol"),d(Math,"Math",!0),d(t.JSON,"JSON",!0),_S}f$();wt(/^#{validMentionOrList}$/,{validMentionOrList:Az});var W2=/[a-z\u0400-\u04FF0-9\-._~]/i,q2=/(?:%[0-9a-f]{2})/i,V2=/[!$&'()*+,;=]/i,K2=wt("(?:#{validateUrlUnreserved}|#{validateUrlPctEncoded}|#{validateUrlSubDelims}|:)*",{validateUrlUnreserved:W2,validateUrlPctEncoded:q2,validateUrlSubDelims:V2},"i"),h$=/(?:[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?)/i,p$=/(?:[a-z](?:[a-z0-9\-]*[a-z0-9])?)/i,m$=/(?:[a-z0-9](?:[a-z0-9_\-]*[a-z0-9])?)/i,g$=wt(/(?:(?:#{validateUrlSubDomainSegment}\.)*(?:#{validateUrlDomainSegment}\.)#{validateUrlDomainTld})/i,{validateUrlSubDomainSegment:m$,validateUrlDomainSegment:h$,validateUrlDomainTld:p$}),v$=/(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9]{2})|(?:2[0-4][0-9])|(?:25[0-5]))/i,y$=wt(/(?:#{validateUrlDecOctet}(?:\.#{validateUrlDecOctet}){3})/i,{validateUrlDecOctet:v$}),b$=/(?:\[[a-f0-9:\.]+\])/i,G2=wt("(?:#{validateUrlIpv4}|#{validateUrlIpv6})",{validateUrlIpv4:y$,validateUrlIpv6:b$},"i"),x$=wt("(?:#{validateUrlIp}|#{validateUrlDomain})",{validateUrlIp:G2,validateUrlDomain:g$},"i"),J2=/[0-9]{1,5}/;wt("(?:(#{validateUrlUserinfo})@)?(#{validateUrlHost})(?::(#{validateUrlPort}))?",{validateUrlUserinfo:K2,validateUrlHost:x$,validateUrlPort:J2},"i");var c0=wt("(?:#{validateUrlUnreserved}|#{validateUrlPctEncoded}|#{validateUrlSubDelims}|[:|@])",{validateUrlUnreserved:W2,validateUrlPctEncoded:q2,validateUrlSubDelims:V2},"i");wt(/(#{validateUrlPchar}|\/|\?)*/i,{validateUrlPchar:c0});wt(/(\/#{validateUrlPchar}*)*/i,{validateUrlPchar:c0});wt(/(#{validateUrlPchar}|\/|\?)*/i,{validateUrlPchar:c0});wt("^(?:([^:/?#]+):\\/\\/)?([^/?#]*)([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$","i");var w$=/(?:(?:[a-z0-9]|[^\u0000-\u007f])(?:(?:[a-z0-9_\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i,k$=/(?:(?:[a-z0-9]|[^\u0000-\u007f])(?:(?:[a-z0-9\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i,S$=/(?:(?:[a-z]|[^\u0000-\u007f])(?:(?:[a-z0-9\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i,E$=wt(/(?:(?:#{validateUrlUnicodeSubDomainSegment}\.)*(?:#{validateUrlUnicodeDomainSegment}\.)#{validateUrlUnicodeDomainTld})/i,{validateUrlUnicodeSubDomainSegment:w$,validateUrlUnicodeDomainSegment:k$,validateUrlUnicodeDomainTld:S$}),N$=wt("(?:#{validateUrlIp}|#{validateUrlUnicodeDomain})",{validateUrlIp:G2,validateUrlUnicodeDomain:E$},"i");wt("(?:(#{validateUrlUserinfo})@)?(#{validateUrlUnicodeHost})(?::(#{validateUrlPort}))?",{validateUrlUserinfo:K2,validateUrlUnicodeHost:N$,validateUrlPort:J2},"i");var IS={},LS;function C$(){if(LS)return IS;LS=1;var t=f2()(!0);return z2()(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})}),IS}C$();var DS={},Km,PS;function _$(){if(PS)return Km;PS=1;var t=hr();return Km=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}},Km}var Gm,BS;function T$(){if(BS)return Gm;BS=1;var t=Al(),e=_n()("iterator"),n=Array.prototype;return Gm=function(r){return r!==void 0&&(t.Array===r||n[e]===r)},Gm}var Jm,zS;function M$(){if(zS)return Jm;zS=1;var t=Gv(),e=_n()("iterator"),n=Al();return Jm=ra().getIteratorMethod=function(r){if(r!=null)return r[e]||r["@@iterator"]||n[t(r)]},Jm}var Ym,$S;function A$(){if($S)return Ym;$S=1;var t=_n()("iterator"),e=!1;try{var n=[7][t]();n.return=function(){e=!0},Array.from(n,function(){throw 2})}catch{}return Ym=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},Ym}var FS;function j$(){if(FS)return DS;FS=1;var t=Gd(),e=ir(),n=gi(),r=_$(),s=T$(),i=so(),o=F2(),l=M$();return e(e.S+e.F*!A$()(function(d){Array.from(d)}),"Array",{from:function(f){var h=n(f),m=typeof this=="function"?this:Array,g=arguments.length,y=g>1?arguments[1]:void 0,b=y!==void 0,x=0,k=l(h),E,C,O,_;if(b&&(y=t(y,g>2?arguments[2]:void 0,2)),k!=null&&!(m==Array&&s(k)))for(_=k.call(h),C=new m;!(O=_.next()).done;x++)o(C,x,b?r(_,y,[O.value,x],!0):O.value);else for(E=i(h.length),C=new m(E);E>x;x++)o(C,x,b?y(h[x],x):h[x]);return C.length=x,C}}),DS}j$();const O$={parseTweet:Qz},{parseTweet:R$}=O$;function US(t){return R$(t).weightedLength}const HS="ow-x-handle";function I$(){const[t,e]=S.useState(()=>localStorage.getItem(HS)||""),[n,r]=S.useState(!1),[s,i]=S.useState(""),o=S.useRef(null),l=S.useRef(null),d=()=>{const m=s.replace(/^@/,"").trim();m&&(localStorage.setItem(HS,m),e(m)),r(!1)},f=()=>{i(t),r(!0),setTimeout(()=>{var m;return(m=o.current)==null?void 0:m.focus()},0)};S.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 u.jsxs("div",{className:"tweet-compose-avatar-wrapper",ref:l,children:[t?u.jsx("img",{className:"tweet-compose-avatar tweet-compose-avatar-img",src:h,alt:`@${t}`,onClick:f,title:`@${t} — click to change`}):u.jsx("div",{className:"tweet-compose-avatar",onClick:f,title:"Set your @handle"}),n&&u.jsx("div",{className:"tweet-handle-popover",children:u.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})})]})}function WS(){return u.jsxs("div",{className:"tweet-skeleton",children:[u.jsxs("div",{className:"tweet-author-row",children:[u.jsx("div",{className:"tweet-avatar tweet-avatar-placeholder tweet-pulse"}),u.jsxs("div",{className:"tweet-author-info",children:[u.jsx("span",{className:"tweet-skeleton-line tweet-pulse",style:{width:120}}),u.jsx("span",{className:"tweet-skeleton-line tweet-pulse",style:{width:80}})]})]}),u.jsx("div",{className:"tweet-skeleton-line tweet-pulse",style:{width:"100%",height:16,marginTop:12}}),u.jsx("div",{className:"tweet-skeleton-line tweet-pulse",style:{width:"75%",height:16,marginTop:8}})]})}function L$(t){var e;if(t)return(e=t.match(/\/status\/(\d+)/))==null?void 0:e[1]}function pu(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 mu(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 qS(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 gu(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 VS(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 Xm(t){fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tweetContext:t}),keepalive:!0}).catch(()=>{})}function D$({tweetContext:t,initialContent:e,onUpdate:n,onEditorReady:r,onEditorsChange:s,onActiveEditorChange:i,filename:o,title:l}){const{tweet:d,loading:f,error:h}=N8(t==null?void 0:t.url),[m,g]=S.useState(()=>pu(e).map(q=>{const de=mu(q);return qS(q,de.length)})),[y,b]=S.useState(0),x=S.useRef([]),k=S.useRef(null),E=S.useRef(!0),C=S.useRef(!1),O=S.useRef(m.length),[_,T]=S.useState(()=>m.map(()=>0)),[R,I]=S.useState(0),[B,P]=S.useState(0),D=S.useRef(pu(e).map(H=>mu(H))),[V,$]=S.useState(()=>pu(e).map(q=>mu(q).length)),[Q,G]=S.useState(null),[K,X]=S.useState(),[re,J]=S.useState(!1),[oe,U]=S.useState("idle"),[A,L]=S.useState(""),te=S.useRef(),{copyText:se,copyState:be}=M8(x,R),[ee,ge]=S.useState(!1);S.useEffect(()=>{let H=!1;return(async()=>{try{const q=await fetch("/api/x/status");if(H)return;if(q.ok){const de=await q.json();G(de.connected),X(de.username)}else G(!1)}catch{H||G(!1)}})(),()=>{H=!0}},[]),S.useEffect(()=>{if(E.current){E.current=!1;return}if(!e||JSON.stringify(e)===k.current)return;const q=pu(e),de=q.map(Ee=>mu(Ee)),me=q.map((Ee,De)=>qS(Ee,de[De].length));C.current=!0,O.current=me.length,x.current=[],D.current=de,g(me),T(me.map(()=>0)),$(de.map(Ee=>Ee.length)),b(Ee=>Ee+1)},[e]);const fe=S.useCallback((H,q)=>{if(x.current[H]=q,T(me=>{const Ee=[...me];return Ee[H]=US(q.getText()),Ee}),C.current)return;const de=gu(x.current,D.current);k.current=JSON.stringify(de),n==null||n(de)},[n]),Te=S.useCallback((H,q)=>{if(x.current[H]=q,T(de=>{const me=[...de];return me[H]=US(q.getText()),me}),P(de=>de+1),C.current&&x.current.filter(Boolean).length>=O.current){C.current=!1;const me=gu(x.current,D.current);k.current=JSON.stringify(me)}H===0&&(r==null||r(q)),s==null||s(x.current.filter(Boolean))},[r,s]),Xe=m.length>1;_.reduce((H,q)=>H+q,0);const tt=S.useCallback(()=>{const H=R+1;g(q=>[...q.slice(0,H),"<p></p>",...q.slice(H)]),T(q=>[...q.slice(0,H),0,...q.slice(H)]),D.current.splice(H,0,[]),$(q=>[...q.slice(0,H),0,...q.slice(H)]),I(H)},[R]),st=S.useCallback(H=>{H!==0&&(x.current.splice(H,1),D.current.splice(H,1),g(q=>q.filter((de,me)=>me!==H)),T(q=>q.filter((de,me)=>me!==H)),$(q=>q.filter((de,me)=>me!==H)),setTimeout(()=>{const q=gu(x.current,D.current);n==null||n(q),s==null||s(x.current.filter(Boolean))},0))},[n,s]),nt=!!(t!=null&&t.url),Le=(t==null?void 0:t.mode)==="reply",yt=(()=>{const q=x.current.filter(Boolean).some(me=>me.getText().trim()||VS(me).length>0),de=V.some(me=>me>0);return q||de})(),Ke=Q&&yt&&oe==="idle",Et=async()=>{if(!Q){J(!0);return}if(Ke){U("uploading"),L("");try{const H=[];for(let de=0;de<x.current.length;de++){const me=x.current[de];if(!me)continue;const Ee=me.getText().trim(),De=VS(me,D.current[de]);if(!Ee&&De.length===0)continue;const $e=[];for(const qe of De){const pe=await(await fetch("/api/x/upload-media",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({src:qe})})).json();if(!pe.success)throw new Error(pe.error||"Image upload failed");$e.push(pe.mediaId)}H.push({text:Ee,mediaIds:$e})}if(H.length===0)return;U("posting");const q=L$(t==null?void 0:t.url);if(H.length===1){const de={};H[0].text&&(de.text=H[0].text),H[0].mediaIds.length>0&&(de.mediaIds=H[0].mediaIds),(t==null?void 0:t.mode)==="reply"&&q?de.replyTo=q:(t==null?void 0:t.mode)==="quote"&&q&&(de.quoteTweetId=q);const Ee=await(await fetch("/api/x/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(de)})).json();Ee.success?(Xm({lastPost:{postedAt:new Date().toISOString(),tweetUrl:Ee.tweetUrl}}),U("success"),te.current=setTimeout(()=>U("idle"),2500)):(console.error("[TweetCompose] Post error:",Ee.error),L(Ee.error||"Post failed"),U("error"),setTimeout(()=>U("idle"),3e3))}else{const me={tweets:H.map($e=>({text:$e.text,...$e.mediaIds.length>0?{mediaIds:$e.mediaIds}:{}}))};(t==null?void 0:t.mode)==="reply"&&q&&(me.replyTo=q);const De=await(await fetch("/api/x/post-thread",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(me)})).json();De.success?(Xm({lastPost:{postedAt:new Date().toISOString(),tweetUrl:De.threadUrl}}),U("success"),te.current=setTimeout(()=>U("idle"),2500)):(L(De.error||"Thread post failed"),U("error"),setTimeout(()=>U("idle"),3e3))}}catch(H){L(H.message||"Network error"),U("error"),setTimeout(()=>U("idle"),3e3)}}};S.useEffect(()=>()=>{te.current&&clearTimeout(te.current)},[]);const je=()=>{G(!0),J(!1),fetch("/api/x/status").then(H=>H.json()).then(H=>{H.username&&X(H.username)}).catch(()=>{})},Je=oe==="uploading"?"Uploading...":oe==="posting"?"Posting...":oe==="success"?"Posted!":oe==="error"?"Failed":Xe?R===0?"Post Thread":"Post All":"Post",Fe=m.map((H,q)=>q===0?Le?"Post your reply":"What is happening?!":"Add another tweet"),Nt=H=>{var q;return u.jsxs("div",{className:`tweet-compose-footer${H?" tweet-compose-footer--inline":""}`,children:[R===0&&((q=t==null?void 0:t.lastPost)==null?void 0:q.postedAt)&&u.jsxs("a",{className:"tweet-posted-status",href:t.lastPost.tweetUrl,target:"_blank",rel:"noopener noreferrer",title:t.lastPost.tweetUrl||"Posted to X",children:[u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Posted ",new Date(t.lastPost.postedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})]}),oe==="error"&&A&&u.jsx("span",{className:"tweet-post-error",children:A}),Xe&&u.jsxs("span",{className:"tweet-thread-counter",children:[R+1,"/",m.length]}),u.jsx(P8,{count:_[R]||0}),u.jsx("button",{className:"tweet-thread-add",onClick:tt,title:"Add another tweet",children:u.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:[u.jsx("line",{x1:"10",y1:"4",x2:"10",y2:"16",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),u.jsx("line",{x1:"4",y1:"10",x2:"16",y2:"10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})}),u.jsx("button",{className:`tweet-copy-btn${be==="copied"?" tweet-copy-btn--copied":""}`,disabled:!yt,onClick:se,title:"Copy tweet text to clipboard",children:be==="copied"?u.jsxs(u.Fragment,{children:[u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:u.jsx("path",{d:"M3 8.5L6.5 12L13 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Copied!"]}):u.jsxs(u.Fragment,{children:[u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:[u.jsx("rect",{x:"5.5",y:"2",width:"8.5",height:"10.5",rx:"1.5",stroke:"currentColor",strokeWidth:"1.5"}),u.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"]})}),R===0&&(()=>{var me;const de=!!((me=t==null?void 0:t.lastPost)!=null&&me.postedAt);return u.jsx("button",{className:`tweet-mark-sent-btn${de?" tweet-mark-sent-btn--done":""}`,onClick:()=>{de||Xm({lastPost:{postedAt:new Date().toISOString()}})},title:de?"Posted":"Mark as manually posted",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:de?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("polyline",{points:"8 12 11 15 16 9",stroke:de?"#fff":"currentColor"})]})})})(),o&&u.jsx("button",{className:"tweet-schedule-btn",onClick:()=>ge(!0),title:"Schedule post",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("polyline",{points:"12 6 12 12 16 14"})]})}),u.jsx("button",{className:`tweet-post-btn${Ke||!Q&&Q!==null?" tweet-post-btn--active":""}${oe==="success"?" tweet-post-btn--success":""}${oe==="error"?" tweet-post-btn--error":""}`,disabled:Q?!Ke:!1,onClick:Et,title:Q?K?`Post as @${K}`:"Post to X":"Connect X to post",children:Je})]})},qt=nt&&!Le,ie=()=>u.jsx("div",{className:"tweet-thread-editors",children:m.map((H,q)=>u.jsxs("div",{className:`tweet-thread-item${q===R?" tweet-thread-item--active":" tweet-thread-item--inactive"}`,children:[u.jsxs("div",{className:"tweet-thread-item-left",children:[u.jsx(I$,{}),q<m.length-1&&u.jsx("div",{className:"tweet-thread-line"})]}),u.jsxs("div",{className:"tweet-thread-item-right",children:[q>0&&u.jsx("button",{className:"tweet-thread-remove",onClick:()=>st(q),title:"Remove this tweet",children:"×"}),u.jsx("div",{className:`tweet-compose-box${q===0&&!Xe?" tweet-compose-box--standalone":""}`,children:u.jsx(D8,{initialContent:H,initialPreviewImages:D.current[q],placeholder:Fe[q],onUpdate:de=>fe(q,de),onReady:de=>Te(q,de),onFocus:()=>{I(q);const de=x.current[q];de&&(i==null||i(de))},onPreviewImagesChange:de=>{if(D.current[q]=de,$(me=>{const Ee=[...me];return Ee[q]=de.length,Ee}),!C.current){const me=gu(x.current,D.current);k.current=JSON.stringify(me),n==null||n(me)}}})}),q===R&&!qt&&Nt(q<m.length-1)]})]},`${y}-${q}`))});return u.jsxs("div",{className:"tweet-compose-wrapper",children:[nt&&Le&&u.jsxs(u.Fragment,{children:[f&&u.jsx("div",{className:"tweet-context-section",children:u.jsx(WS,{})}),h&&u.jsx("div",{className:"tweet-context-section",children:u.jsxs("div",{className:"tweet-embed-error",children:[u.jsx("span",{children:"Could not load tweet"}),u.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",className:"tweet-fallback-link",children:t.url})]})}),d&&u.jsxs("div",{className:"tweet-reply-parent-section",children:[u.jsx("div",{className:"tweet-reply-parent-card",children:u.jsx(mw,{tweet:d,url:t==null?void 0:t.url})}),u.jsxs("div",{className:"tweet-replying-to",children:["Replying to ",u.jsxs("span",{className:"tweet-reply-handle",children:["@",d.author.username]})]})]}),ie()]}),qt&&u.jsxs(u.Fragment,{children:[ie(),u.jsxs("div",{className:"tweet-quote-section",style:{padding:"0 16px 12px"},children:[f&&u.jsx(WS,{}),h&&u.jsxs("div",{className:"tweet-embed-error",children:[u.jsx("span",{children:"Could not load tweet"}),u.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",className:"tweet-fallback-link",children:t.url})]}),d&&u.jsx(mw,{tweet:d,url:t==null?void 0:t.url})]}),u.jsx("div",{className:"tweet-quote-footer",children:Nt()})]}),!nt&&ie(),re&&u.jsx(B8,{onConnected:je,onCancel:()=>J(!1)}),ee&&o&&u.jsx(Cl,{filename:o,title:l||"Untitled",onClose:()=>ge(!1)})]})}function P$(){const[t,e]=S.useState("idle"),n=S.useRef();return{copyAsHtml:S.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>
210
210
  `);const d=o+i.innerHTML,f=B$(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 B$(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(`