openwriter 0.6.5 → 0.6.6

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.
@@ -201,7 +201,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),Xt=ge,dt=De),lt===void
201
201
  `,1;if(oi>1e5&&oi>Ae.index*3)throw new Error("potential infinite loop, way more iterations than matches");return St+=Qe,Qe.length}const or=vr(ge);if(!or)throw rt(Tt.replace("{}",ge)),new Error('Unknown language: "'+ge+'"');const Do=_t(or);let pt="",nt=dt||Do;const Po={},Zt=new _e.__emitter(_e);sa();let St="",ii=0,Ir=0,oi=0,ys=!1;try{if(or.__emitTokens)or.__emitTokens(De,Zt);else{for(nt.matcher.considerAll();;){oi++,ys?ys=!1:nt.matcher.considerAll(),nt.matcher.lastIndex=Ir;const xe=nt.matcher.exec(De);if(!xe)break;const Ae=De.substring(Ir,xe.index),Qe=gs(Ae,xe);Ir=xe.index+Qe}gs(De.substring(Ir))}return Zt.finalize(),pt=Zt.toHTML(),{language:ge,value:pt,relevance:ii,illegal:!1,_emitter:Zt,_top:nt}}catch(xe){if(xe.message&&xe.message.includes("Illegal"))return{language:ge,value:cn(De),illegal:!0,relevance:0,_illegalBy:{message:xe.message,index:Ir,context:De.slice(Ir-100,Ir+100),mode:xe.mode,resultSoFar:pt},_emitter:Zt};if(Et)return{language:ge,value:cn(De),illegal:!1,relevance:0,errorRaised:xe,_emitter:Zt,_top:nt};throw xe}}function hs(ge){const De={value:cn(ge),illegal:!1,relevance:0,_top:Me,_emitter:new _e.__emitter(_e)};return De._emitter.addText(ge),De}function ti(ge,De){De=De||_e.languages||Object.keys(oe);const lt=hs(ge),dt=De.filter(vr).filter(ra).map(Pn=>Rr(Pn,ge,!1));dt.unshift(lt);const Xt=dt.sort((Pn,Bn)=>{if(Pn.relevance!==Bn.relevance)return Bn.relevance-Pn.relevance;if(Pn.language&&Bn.language){if(vr(Pn.language).supersetOf===Bn.language)return 1;if(vr(Bn.language).supersetOf===Pn.language)return-1}return 0}),[Ut,jr]=Xt,Fi=Ut;return Fi.secondBest=jr,Fi}function sd(ge,De,lt){const dt=De&&ve[De]||lt;ge.classList.add("hljs"),ge.classList.add(`language-${dt}`)}function Ro(ge){let De=null;const lt=nn(ge);if(We(lt))return;if(ni("before:highlightElement",{el:ge,language:lt}),ge.dataset.highlighted){console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",ge);return}if(ge.children.length>0&&(_e.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(ge)),_e.throwUnescapedHTML))throw new Wn("One of your code blocks includes unescaped HTML.",ge.innerHTML);De=ge;const dt=De.textContent,Xt=lt?Ot(dt,{language:lt,ignoreIllegals:!0}):ti(dt);ge.innerHTML=Xt.value,ge.dataset.highlighted="yes",sd(ge,lt,Xt.language),ge.result={language:Xt.language,re:Xt.relevance,relevance:Xt.relevance},Xt.secondBest&&(ge.secondBest={language:Xt.secondBest.language,relevance:Xt.secondBest.relevance}),ni("after:highlightElement",{el:ge,result:Xt,text:dt})}function id(ge){_e=Tn(_e,ge)}const Kr=()=>{zi(),zt("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")};function Xl(){zi(),zt("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")}let jo=!1;function zi(){function ge(){zi()}if(document.readyState==="loading"){jo||window.addEventListener("DOMContentLoaded",ge,!1),jo=!0;return}document.querySelectorAll(_e.cssSelector).forEach(Ro)}function Zl(ge,De){let lt=null;try{lt=De(L)}catch(dt){if(rt("Language definition for '{}' could not be registered.".replace("{}",ge)),Et)rt(dt);else throw dt;lt=Me}lt.name||(lt.name=ge),oe[ge]=lt,lt.rawDefinition=De.bind(null,L),lt.aliases&&na(lt.aliases,{languageName:ge})}function ea(ge){delete oe[ge];for(const De of Object.keys(ve))ve[De]===ge&&delete ve[De]}function ta(){return Object.keys(oe)}function vr(ge){return ge=(ge||"").toLowerCase(),oe[ge]||oe[ve[ge]]}function na(ge,{languageName:De}){typeof ge=="string"&&(ge=[ge]),ge.forEach(lt=>{ve[lt.toLowerCase()]=De})}function ra(ge){const De=vr(ge);return De&&!De.disableAutodetect}function Ft(ge){ge["before:highlightBlock"]&&!ge["before:highlightElement"]&&(ge["before:highlightElement"]=De=>{ge["before:highlightBlock"](Object.assign({block:De.el},De))}),ge["after:highlightBlock"]&&!ge["after:highlightElement"]&&(ge["after:highlightElement"]=De=>{ge["after:highlightBlock"](Object.assign({block:De.el},De))})}function od(ge){Ft(ge),qe.push(ge)}function Io(ge){const De=qe.indexOf(ge);De!==-1&&qe.splice(De,1)}function ni(ge,De){const lt=ge;qe.forEach(function(dt){dt[lt]&&dt[lt](De)})}function $i(ge){return zt("10.7.0","highlightBlock will be removed entirely in v12.0"),zt("10.7.0","Please use highlightElement now."),Ro(ge)}Object.assign(L,{highlight:Ot,highlightAuto:ti,highlightAll:zi,highlightElement:Ro,highlightBlock:$i,configure:id,initHighlighting:Kr,initHighlightingOnLoad:Xl,registerLanguage:Zl,unregisterLanguage:ea,listLanguages:ta,getLanguage:vr,registerAliases:na,autoDetection:ra,inherit:Tn,addPlugin:od,removePlugin:Io}),L.debugMode=function(){Et=!1},L.safeMode=function(){Et=!0},L.versionString=Ge,L.regex={concat:k,lookahead:y,either:N,optional:v,anyNumberOfTimes:b};for(const ge in ce)typeof ce[ge]=="object"&&t(ce[ge]);return Object.assign(L,ce),L},Lt=ot({});return Lt.newInstance=()=>ot({}),Sh=Lt,Lt.HighlightJS=Lt,Lt.default=Lt,Sh}var kj=xj();const e1=Bu(kj);function t1(t,e=[]){return t.flatMap(n=>{const r=[...e,...n.properties?n.properties.className:[]];return n.children?t1(n.children,r):{text:n.value,classes:r}})}function Kv(t){return t.value||t.children||[]}function wj(t){return!!e1.getLanguage(t)}function Gv({doc:t,name:e,lowlight:n,defaultLanguage:r}){const s=[];return tu(t,i=>i.type.name===e).forEach(i=>{var l;let c=i.pos+1;const d=i.node.attrs.language||r,f=n.listLanguages(),p=d&&(f.includes(d)||wj(d)||(l=n.registered)!=null&&l.call(n,d))?Kv(n.highlight(d,i.node.textContent)):Kv(n.highlightAuto(i.node.textContent));t1(p).forEach(m=>{const y=c+m.text.length;if(m.classes.length){const b=jt.inline(c,y,{class:m.classes.join(" ")});s.push(b)}c=y})}),bt.create(t,s)}function Sj(t){return typeof t=="function"}function Ej({name:t,lowlight:e,defaultLanguage:n}){if(!["highlight","highlightAuto","listLanguages"].every(s=>Sj(e[s])))throw Error("You should provide an instance of lowlight to use the code-block-lowlight extension");const r=new wt({key:new At("lowlight"),state:{init:(s,{doc:i})=>Gv({doc:i,name:t,lowlight:e,defaultLanguage:n}),apply:(s,i,l,c)=>{const d=l.selection.$head.parent.type.name,f=c.selection.$head.parent.type.name,p=tu(l.doc,y=>y.type.name===t),m=tu(c.doc,y=>y.type.name===t);return s.docChanged&&([d,f].includes(t)||m.length!==p.length||s.steps.some(y=>y.from!==void 0&&y.to!==void 0&&p.some(b=>b.pos>=y.from&&b.pos+b.node.nodeSize<=y.to)))?Gv({doc:s.doc,name:t,lowlight:e,defaultLanguage:n}):i.map(s.mapping,s.doc)}},props:{decorations(s){return r.getState(s)}}});return r}var Nj=rj.extend({addOptions(){var t;return{...(t=this.parent)==null?void 0:t.call(this),lowlight:{},languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:4,HTMLAttributes:{}}},addProseMirrorPlugins(){var t;return[...((t=this.parent)==null?void 0:t.call(this))||[],Ej({name:this.name,lowlight:this.options.lowlight,defaultLanguage:this.options.defaultLanguage})]}}),Cj=Nj;function _j(t){const e=t.regex,n=t.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",s="[a-zA-Z_]\\w*::",l="(?!struct)("+r+"|"+e.optional(s)+"[a-zA-Z_]\\w*"+e.optional("<[^<>]+>")+")",c={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},f={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[t.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},t.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},p={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},m={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},t.inherit(f,{className:"string"}),{className:"string",begin:/<.*?>/},n,t.C_BLOCK_COMMENT_MODE]},y={className:"title",begin:e.optional(s)+t.IDENT_RE,relevance:0},b=e.optional(s)+t.IDENT_RE+"\\s*\\(",v=["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],k=["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],w=["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"],N=["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"],_={type:k,keyword:v,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:w},M={className:"function.dispatch",relevance:0,keywords:{_hint:N},begin:e.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,t.IDENT_RE,e.lookahead(/(<[^<>]+>|)\s*\(/))},R=[M,m,c,n,t.C_BLOCK_COMMENT_MODE,p,f],D={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:_,contains:R.concat([{begin:/\(/,end:/\)/,keywords:_,contains:R.concat(["self"]),relevance:0}]),relevance:0},F={className:"function",begin:"("+l+"[\\*&\\s]+)+"+b,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:_,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:_,relevance:0},{begin:b,returnBegin:!0,contains:[y],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[f,p]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:_,relevance:0,contains:[n,t.C_BLOCK_COMMENT_MODE,f,p,c,{begin:/\(/,end:/\)/,keywords:_,relevance:0,contains:["self",n,t.C_BLOCK_COMMENT_MODE,f,p,c]}]},c,n,t.C_BLOCK_COMMENT_MODE,m]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:_,illegal:"</",classNameAliases:{"function.dispatch":"built_in"},contains:[].concat(D,F,M,R,[m,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:_,contains:["self",c]},{begin:t.IDENT_RE+"::",keywords:_},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}function Tj(t){const e={type:["boolean","byte","word","String"],built_in:["KeyboardController","MouseController","SoftwareSerial","EthernetServer","EthernetClient","LiquidCrystal","RobotControl","GSMVoiceCall","EthernetUDP","EsploraTFT","HttpClient","RobotMotor","WiFiClient","GSMScanner","FileSystem","Scheduler","GSMServer","YunClient","YunServer","IPAddress","GSMClient","GSMModem","Keyboard","Ethernet","Console","GSMBand","Esplora","Stepper","Process","WiFiUDP","GSM_SMS","Mailbox","USBHost","Firmata","PImage","Client","Server","GSMPIN","FileIO","Bridge","Serial","EEPROM","Stream","Mouse","Audio","Servo","File","Task","GPRS","WiFi","Wire","TFT","GSM","SPI","SD"],_hints:["setup","loop","runShellCommandAsynchronously","analogWriteResolution","retrieveCallingNumber","printFirmwareVersion","analogReadResolution","sendDigitalPortPair","noListenOnLocalhost","readJoystickButton","setFirmwareVersion","readJoystickSwitch","scrollDisplayRight","getVoiceCallStatus","scrollDisplayLeft","writeMicroseconds","delayMicroseconds","beginTransmission","getSignalStrength","runAsynchronously","getAsynchronously","listenOnLocalhost","getCurrentCarrier","readAccelerometer","messageAvailable","sendDigitalPorts","lineFollowConfig","countryNameWrite","runShellCommand","readStringUntil","rewindDirectory","readTemperature","setClockDivider","readLightSensor","endTransmission","analogReference","detachInterrupt","countryNameRead","attachInterrupt","encryptionType","readBytesUntil","robotNameWrite","readMicrophone","robotNameRead","cityNameWrite","userNameWrite","readJoystickY","readJoystickX","mouseReleased","openNextFile","scanNetworks","noInterrupts","digitalWrite","beginSpeaker","mousePressed","isActionDone","mouseDragged","displayLogos","noAutoscroll","addParameter","remoteNumber","getModifiers","keyboardRead","userNameRead","waitContinue","processInput","parseCommand","printVersion","readNetworks","writeMessage","blinkVersion","cityNameRead","readMessage","setDataMode","parsePacket","isListening","setBitOrder","beginPacket","isDirectory","motorsWrite","drawCompass","digitalRead","clearScreen","serialEvent","rightToLeft","setTextSize","leftToRight","requestFrom","keyReleased","compassRead","analogWrite","interrupts","WiFiServer","disconnect","playMelody","parseFloat","autoscroll","getPINUsed","setPINUsed","setTimeout","sendAnalog","readSlider","analogRead","beginWrite","createChar","motorsStop","keyPressed","tempoWrite","readButton","subnetMask","debugPrint","macAddress","writeGreen","randomSeed","attachGPRS","readString","sendString","remotePort","releaseAll","mouseMoved","background","getXChange","getYChange","answerCall","getResult","voiceCall","endPacket","constrain","getSocket","writeJSON","getButton","available","connected","findUntil","readBytes","exitValue","readGreen","writeBlue","startLoop","IPAddress","isPressed","sendSysex","pauseMode","gatewayIP","setCursor","getOemKey","tuneWrite","noDisplay","loadImage","switchPIN","onRequest","onReceive","changePIN","playFile","noBuffer","parseInt","overflow","checkPIN","knobRead","beginTFT","bitClear","updateIR","bitWrite","position","writeRGB","highByte","writeRed","setSpeed","readBlue","noStroke","remoteIP","transfer","shutdown","hangCall","beginSMS","endWrite","attached","maintain","noCursor","checkReg","checkPUK","shiftOut","isValid","shiftIn","pulseIn","connect","println","localIP","pinMode","getIMEI","display","noBlink","process","getBand","running","beginSD","drawBMP","lowByte","setBand","release","bitRead","prepare","pointTo","readRed","setMode","noFill","remove","listen","stroke","detach","attach","noTone","exists","buffer","height","bitSet","circle","config","cursor","random","IRread","setDNS","endSMS","getKey","micros","millis","begin","print","write","ready","flush","width","isPIN","blink","clear","press","mkdir","rmdir","close","point","yield","image","BSSID","click","delay","read","text","move","peek","beep","rect","line","open","seek","fill","size","turn","stop","home","find","step","tone","sqrt","RSSI","SSID","end","bit","tan","cos","sin","pow","map","abs","max","min","get","run","put"],literal:["DIGITAL_MESSAGE","FIRMATA_STRING","ANALOG_MESSAGE","REPORT_DIGITAL","REPORT_ANALOG","INPUT_PULLUP","SET_PIN_MODE","INTERNAL2V56","SYSTEM_RESET","LED_BUILTIN","INTERNAL1V1","SYSEX_START","INTERNAL","EXTERNAL","DEFAULT","OUTPUT","INPUT","HIGH","LOW"]},n=_j(t),r=n.keywords;return r.type=[...r.type,...e.type],r.literal=[...r.literal,...e.literal],r.built_in=[...r.built_in,...e.built_in],r._hints=e._hints,n.name="Arduino",n.aliases=["ino"],n.supersetOf="cpp",n}function Mj(t){const e=t.regex,n={},r={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[n]}]};Object.assign(n,{className:"variable",variants:[{begin:e.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},r]});const s={className:"subst",begin:/\$\(/,end:/\)/,contains:[t.BACKSLASH_ESCAPE]},i=t.inherit(t.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),l={begin:/<<-?\s*(?=\w+)/,starts:{contains:[t.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},c={className:"string",begin:/"/,end:/"/,contains:[t.BACKSLASH_ESCAPE,n,s]};s.contains.push(c);const d={match:/\\"/},f={className:"string",begin:/'/,end:/'/},p={match:/\\'/},m={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},t.NUMBER_MODE,n]},y=["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"],b=t.SHEBANG({binary:`(${y.join("|")})`,relevance:10}),v={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[t.inherit(t.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0},k=["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],w=["true","false"],N={match:/(\/[a-z._-]+)+/},C=["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset"],O=["alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias"],_=["autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp"],M=["chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"];return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:k,literal:w,built_in:[...C,...O,"set","shopt",..._,...M]},contains:[b,t.SHEBANG(),v,m,i,l,N,c,d,f,p,n]}}function Aj(t){const e=t.regex,n=t.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",s="[a-zA-Z_]\\w*::",l="("+r+"|"+e.optional(s)+"[a-zA-Z_]\\w*"+e.optional("<[^<>]+>")+")",c={className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{match:/\batomic_[a-z]{3,6}\b/}]},f={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[t.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},t.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},p={className:"number",variants:[{match:/\b(0b[01']+)/},{match:/(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/},{match:/(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/},{match:/(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/}],relevance:0},m={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include"},contains:[{begin:/\\\n/,relevance:0},t.inherit(f,{className:"string"}),{className:"string",begin:/<.*?>/},n,t.C_BLOCK_COMMENT_MODE]},y={className:"title",begin:e.optional(s)+t.IDENT_RE,relevance:0},b=e.optional(s)+t.IDENT_RE+"\\s*\\(",w={keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","typeof","typeof_unqual","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"],type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_BitInt","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal96","_Decimal128","_Decimal64x","_Decimal128x","_Float16","_Float32","_Float64","_Float128","_Float32x","_Float64x","_Float128x","const","static","constexpr","complex","bool","imaginary"],literal:"true false NULL",built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"},N=[m,c,n,t.C_BLOCK_COMMENT_MODE,p,f],C={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:w,contains:N.concat([{begin:/\(/,end:/\)/,keywords:w,contains:N.concat(["self"]),relevance:0}]),relevance:0},O={begin:"("+l+"[\\*&\\s]+)+"+b,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:w,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:w,relevance:0},{begin:b,returnBegin:!0,contains:[t.inherit(y,{className:"title.function"})],relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:w,relevance:0,contains:[n,t.C_BLOCK_COMMENT_MODE,f,p,c,{begin:/\(/,end:/\)/,keywords:w,relevance:0,contains:["self",n,t.C_BLOCK_COMMENT_MODE,f,p,c]}]},c,n,t.C_BLOCK_COMMENT_MODE,m]};return{name:"C",aliases:["h"],keywords:w,disableAutodetect:!0,illegal:"</",contains:[].concat(C,O,N,[m,{begin:t.IDENT_RE+"::",keywords:w},{className:"class",beginKeywords:"enum class struct union",end:/[{;:<>=]/,contains:[{beginKeywords:"final class struct"},t.TITLE_MODE]}]),exports:{preprocessor:m,strings:f,keywords:w}}}function Oj(t){const e=t.regex,n=t.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",s="[a-zA-Z_]\\w*::",l="(?!struct)("+r+"|"+e.optional(s)+"[a-zA-Z_]\\w*"+e.optional("<[^<>]+>")+")",c={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},f={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[t.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},t.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},p={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},m={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},t.inherit(f,{className:"string"}),{className:"string",begin:/<.*?>/},n,t.C_BLOCK_COMMENT_MODE]},y={className:"title",begin:e.optional(s)+t.IDENT_RE,relevance:0},b=e.optional(s)+t.IDENT_RE+"\\s*\\(",v=["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],k=["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],w=["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"],N=["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"],_={type:k,keyword:v,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:w},M={className:"function.dispatch",relevance:0,keywords:{_hint:N},begin:e.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,t.IDENT_RE,e.lookahead(/(<[^<>]+>|)\s*\(/))},R=[M,m,c,n,t.C_BLOCK_COMMENT_MODE,p,f],D={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:_,contains:R.concat([{begin:/\(/,end:/\)/,keywords:_,contains:R.concat(["self"]),relevance:0}]),relevance:0},F={className:"function",begin:"("+l+"[\\*&\\s]+)+"+b,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:_,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:_,relevance:0},{begin:b,returnBegin:!0,contains:[y],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[f,p]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:_,relevance:0,contains:[n,t.C_BLOCK_COMMENT_MODE,f,p,c,{begin:/\(/,end:/\)/,keywords:_,relevance:0,contains:["self",n,t.C_BLOCK_COMMENT_MODE,f,p,c]}]},c,n,t.C_BLOCK_COMMENT_MODE,m]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:_,illegal:"</",classNameAliases:{"function.dispatch":"built_in"},contains:[].concat(D,F,M,R,[m,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:_,contains:["self",c]},{begin:t.IDENT_RE+"::",keywords:_},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}function Rj(t){const e=["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"],n=["public","private","protected","static","internal","protected","abstract","async","extern","override","unsafe","virtual","new","sealed","partial"],r=["default","false","null","true"],s=["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"],i=["add","alias","and","ascending","args","async","await","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value|0","var","when","where","with","yield"],l={keyword:s.concat(i),built_in:e,literal:r},c=t.inherit(t.TITLE_MODE,{begin:"[a-zA-Z](\\.?\\w)*"}),d={className:"number",variants:[{begin:"\\b(0b[01']+)"},{begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],relevance:0},f={className:"string",begin:/"""("*)(?!")(.|\n)*?"""\1/,relevance:1},p={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}]},m=t.inherit(p,{illegal:/\n/}),y={className:"subst",begin:/\{/,end:/\}/,keywords:l},b=t.inherit(y,{illegal:/\n/}),v={className:"string",begin:/\$"/,end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},t.BACKSLASH_ESCAPE,b]},k={className:"string",begin:/\$@"/,end:'"',contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},y]},w=t.inherit(k,{illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},b]});y.contains=[k,v,p,t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,d,t.C_BLOCK_COMMENT_MODE],b.contains=[w,v,m,t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,d,t.inherit(t.C_BLOCK_COMMENT_MODE,{illegal:/\n/})];const N={variants:[f,k,v,p,t.APOS_STRING_MODE,t.QUOTE_STRING_MODE]},C={begin:"<",end:">",contains:[{beginKeywords:"in out"},c]},O=t.IDENT_RE+"(<"+t.IDENT_RE+"(\\s*,\\s*"+t.IDENT_RE+")*>)?(\\[\\])?",_={begin:"@"+t.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"],keywords:l,illegal:/::/,contains:[t.COMMENT("///","$",{returnBegin:!0,contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{begin:"<!--|-->"},{begin:"</?",end:">"}]}]}),t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#",end:"$",keywords:{keyword:"if else elif endif define undef warning error line region endregion pragma checksum"}},N,d,{beginKeywords:"class interface",relevance:0,end:/[{;=]/,illegal:/[^\s:,]/,contains:[{beginKeywords:"where class"},c,C,t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[c,t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE]},{beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[c,C,t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE]},{className:"meta",begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{className:"string",begin:/"/,end:/"/}]},{beginKeywords:"new return throw await else",relevance:0},{className:"function",begin:"("+O+"\\s+)+"+t.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,end:/\s*[{;=]/,excludeEnd:!0,keywords:l,contains:[{beginKeywords:n.join(" "),relevance:0},{begin:t.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,contains:[t.TITLE_MODE,C],relevance:0},{match:/\(\)/},{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,relevance:0,contains:[N,d,t.C_BLOCK_COMMENT_MODE]},t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE]},_]}}const jj=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_-]*/}}),Ij=["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"],Lj=["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"],Dj=[...Ij,...Lj],Pj=["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(),Bj=["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(),zj=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),$j=["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 Fj(t){const e=t.regex,n=jj(t),r={begin:/-(webkit|moz|ms|o)-(?=[a-z])/},s="and or not only",i=/@-?\w[\w]*(-\w+)*/,l="[a-zA-Z-][a-zA-Z0-9_-]*",c=[t.APOS_STRING_MODE,t.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[n.BLOCK_COMMENT,r,n.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\."+l,relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+Bj.join("|")+")"},{begin:":(:)?("+zj.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+$j.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,...c,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...c,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},n.FUNCTION_DISPATCH]},{begin:e.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:i},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:s,attribute:Pj.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...c,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+Dj.join("|")+")\\b"}]}}function Uj(t){const e=t.regex;return{name:"Diff",aliases:["patch"],contains:[{className:"meta",relevance:10,match:e.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:"comment",variants:[{begin:e.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/,end:/$/}]}}function Hj(t){const i={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:i,illegal:"</",contains:[t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE,{className:"string",variants:[t.QUOTE_STRING_MODE,t.APOS_STRING_MODE,{begin:"`",end:"`"}]},{className:"number",variants:[{match:/-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,relevance:0},{match:/-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b0[oO](_?[0-7])*i?/,relevance:0},{match:/-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,relevance:0}]},{begin:/:=/},{className:"function",beginKeywords:"func",end:"\\s*(\\{|$)",excludeEnd:!0,contains:[t.TITLE_MODE,{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:i,illegal:/["']/}]}]}}function Wj(t){const e=t.regex,n=/[_A-Za-z][_0-9A-Za-z]*/;return{name:"GraphQL",aliases:["gql"],case_insensitive:!0,disableAutodetect:!1,keywords:{keyword:["query","mutation","subscription","type","input","schema","directive","interface","union","scalar","fragment","enum","on"],literal:["true","false","null"]},contains:[t.HASH_COMMENT_MODE,t.QUOTE_STRING_MODE,t.NUMBER_MODE,{scope:"punctuation",match:/[.]{3}/,relevance:0},{scope:"punctuation",begin:/[\!\(\)\:\=\[\]\{\|\}]{1}/,relevance:0},{scope:"variable",begin:/\$/,end:/\W/,excludeEnd:!0,relevance:0},{scope:"meta",match:/@\w+/,excludeEnd:!0},{scope:"symbol",begin:e.concat(n,e.lookahead(/\s*:/)),relevance:0}],illegal:[/[;<']/,/BEGIN/]}}function Vj(t){const e=t.regex,n={className:"number",relevance:0,variants:[{begin:/([+-]+)?[\d]+_[\d_]+/},{begin:t.NUMBER_RE}]},r=t.COMMENT();r.variants=[{begin:/;/,end:/$/},{begin:/#/,end:/$/}];const s={className:"variable",variants:[{begin:/\$[\w\d"][\w\d_]*/},{begin:/\$\{(.*?)\}/}]},i={className:"literal",begin:/\bon|off|true|false|yes|no\b/},l={className:"string",contains:[t.BACKSLASH_ESCAPE],variants:[{begin:"'''",end:"'''",relevance:10},{begin:'"""',end:'"""',relevance:10},{begin:'"',end:'"'},{begin:"'",end:"'"}]},c={begin:/\[/,end:/\]/,contains:[r,i,s,l,n,"self"],relevance:0},d=/[A-Za-z0-9_-]+/,f=/"(\\"|[^"])*"/,p=/'[^']*'/,m=e.either(d,f,p),y=e.concat(m,"(\\s*\\.\\s*",m,")*",e.lookahead(/\s*=\s*[^#\s]/));return{name:"TOML, also INI",aliases:["toml"],case_insensitive:!0,illegal:/\S/,contains:[r,{className:"section",begin:/\[+/,end:/\]+/},{begin:y,className:"attr",starts:{end:/$/,contains:[r,c,i,s,l,n]}}]}}var yo="[0-9](_*[0-9])*",Ec=`\\.(${yo})`,Nc="[0-9a-fA-F](_*[0-9a-fA-F])*",qv={className:"number",variants:[{begin:`(\\b(${yo})((${Ec})|\\.)?|(${Ec}))[eE][+-]?(${yo})[fFdD]?\\b`},{begin:`\\b(${yo})((${Ec})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${Ec})[fFdD]?\\b`},{begin:`\\b(${yo})[fFdD]\\b`},{begin:`\\b0[xX]((${Nc})\\.?|(${Nc})?\\.(${Nc}))[pP][+-]?(${yo})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${Nc})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function n1(t,e,n){return n===-1?"":t.replace(e,r=>n1(t,e,n-1))}function Kj(t){const e=t.regex,n="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",r=n+n1("(?:<"+n+"~~~(?:\\s*,\\s*"+n+"~~~)*>)?",/~~~/g,2),d={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},f={className:"meta",begin:"@"+n,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},p={className:"params",begin:/\(/,end:/\)/,keywords:d,relevance:0,contains:[t.C_BLOCK_COMMENT_MODE],endsParent:!0};return{name:"Java",aliases:["jsp"],keywords:d,illegal:/<\/|#/,contains:[t.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[t.BACKSLASH_ESCAPE]},t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{begin:[e.concat(/(?!else)/,n),/\s+/,n,/\s+/,/=(?!=)/],className:{1:"type",3:"variable",5:"operator"}},{begin:[/record/,/\s+/,n],className:{1:"keyword",3:"title.class"},contains:[p,t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE]},{beginKeywords:"new throw return else",relevance:0},{begin:["(?:"+r+"\\s+)",t.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{2:"title.function"},keywords:d,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:d,relevance:0,contains:[f,t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,qv,t.C_BLOCK_COMMENT_MODE]},t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE]},qv,f]}}const Jv="[A-Za-z$_][0-9A-Za-z$_]*",Gj=["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"],qj=["true","false","null","undefined","NaN","Infinity"],r1=["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"],s1=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],i1=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Jj=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],Yj=[].concat(i1,r1,s1);function Qj(t){const e=t.regex,n=(H,{after:Z})=>{const G="</"+H[0].slice(1);return H.input.indexOf(G,Z)!==-1},r=Jv,s={begin:"<>",end:"</>"},i=/<[A-Za-z0-9\\._:-]+\s*\/>/,l={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(H,Z)=>{const G=H[0].length+H.index,A=H.input[G];if(A==="<"||A===","){Z.ignoreMatch();return}A===">"&&(n(H,{after:G})||Z.ignoreMatch());let j;const Q=H.input.substring(G);if(j=Q.match(/^\s*=/)){Z.ignoreMatch();return}if((j=Q.match(/^\s+extends\s+/))&&j.index===0){Z.ignoreMatch();return}}},c={$pattern:Jv,keyword:Gj,literal:qj,built_in:Yj,"variable.language":Jj},d="[0-9](_?[0-9])*",f=`\\.(${d})`,p="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",m={className:"number",variants:[{begin:`(\\b(${p})((${f})|\\.)?|(${f}))[eE][+-]?(${d})\\b`},{begin:`\\b(${p})\\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},y={className:"subst",begin:"\\$\\{",end:"\\}",keywords:c,contains:[]},b={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,y],subLanguage:"xml"}},v={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,y],subLanguage:"css"}},k={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,y],subLanguage:"graphql"}},w={className:"string",begin:"`",end:"`",contains:[t.BACKSLASH_ESCAPE,y]},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,b,v,k,w,{match:/\$\d+/},m];y.contains=O.concat({begin:/\{/,end:/\}/,keywords:c,contains:["self"].concat(O)});const _=[].concat(C,y.contains),M=_.concat([{begin:/(\s*)\(/,end:/\)/,keywords:c,contains:["self"].concat(_)}]),R={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:c,contains:M},D={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"}}]},F={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:{_:[...r1,...s1]}},B={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},V={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[R],illegal:/%/},q={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function Y(H){return e.concat("(?!",H.join("|"),")")}const le={match:e.concat(/\b/,Y([...i1,"super","import"].map(H=>`${H}\\s*\\(`)),r,e.lookahead(/\s*\(/)),className:"title.function",relevance:0},W={begin:e.concat(/\./,e.lookahead(e.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},$={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},R]},U="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+t.UNDERSCORE_IDENT_RE+")\\s*=>",te={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,e.lookahead(U)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[R]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:c,exports:{PARAMS_CONTAINS:M,CLASS_REFERENCE:F},illegal:/#(?![$_A-z])/,contains:[t.SHEBANG({label:"shebang",binary:"node",relevance:5}),B,t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,b,v,k,w,C,{match:/\$\d+/},m,F,{scope:"attr",match:r+e.lookahead(":"),relevance:0},te,{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:U,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:c,contains:M}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:s.begin,end:s.end},{match:i},{begin:l.begin,"on:begin":l.isTrulyOpeningTag,end:l.end}],subLanguage:"xml",contains:[{begin:l.begin,end:l.end,skip:!0,contains:["self"]}]}]},V,{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},W,{match:"\\$"+r,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[R]},le,q,D,$,{match:/\$[(.]/}]}}function Xj(t){const e={className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},n={match:/[{}[\],:]/,className:"punctuation",relevance:0},r=["true","false","null"],s={scope:"literal",beginKeywords:r.join(" ")};return{name:"JSON",aliases:["jsonc"],keywords:{literal:r},contains:[e,n,t.QUOTE_STRING_MODE,s,t.C_NUMBER_MODE,t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}var bo="[0-9](_*[0-9])*",Cc=`\\.(${bo})`,_c="[0-9a-fA-F](_*[0-9a-fA-F])*",Zj={className:"number",variants:[{begin:`(\\b(${bo})((${Cc})|\\.)?|(${Cc}))[eE][+-]?(${bo})[fFdD]?\\b`},{begin:`\\b(${bo})((${Cc})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${Cc})[fFdD]?\\b`},{begin:`\\b(${bo})[fFdD]\\b`},{begin:`\\b0[xX]((${_c})\\.?|(${_c})?\\.(${_c}))[pP][+-]?(${bo})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${_c})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function eI(t){const e={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},n={className:"keyword",begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol",begin:/@\w+/}]}},r={className:"symbol",begin:t.UNDERSCORE_IDENT_RE+"@"},s={className:"subst",begin:/\$\{/,end:/\}/,contains:[t.C_NUMBER_MODE]},i={className:"variable",begin:"\\$"+t.UNDERSCORE_IDENT_RE},l={className:"string",variants:[{begin:'"""',end:'"""(?=[^"])',contains:[i,s]},{begin:"'",end:"'",illegal:/\n/,contains:[t.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/,contains:[t.BACKSLASH_ESCAPE,i,s]}]};s.contains.push(l);const c={className:"meta",begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+t.UNDERSCORE_IDENT_RE+")?"},d={className:"meta",begin:"@"+t.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:[t.inherit(l,{className:"string"}),"self"]}]},f=Zj,p=t.COMMENT("/\\*","\\*/",{contains:[t.C_BLOCK_COMMENT_MODE]}),m={variants:[{className:"type",begin:t.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/,contains:[]}]},y=m;return y.variants[1].contains=[m],m.variants[1].contains=[y],{name:"Kotlin",aliases:["kt","kts"],keywords:e,contains:[t.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"}]}),t.C_LINE_COMMENT_MODE,p,n,r,c,d,{className:"function",beginKeywords:"fun",end:"[(]|$",returnBegin:!0,excludeEnd:!0,keywords:e,relevance:5,contains:[{begin:t.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0,contains:[t.UNDERSCORE_TITLE_MODE]},{className:"type",begin:/</,end:/>/,keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:e,relevance:0,contains:[{begin:/:/,end:/[=,\/]/,endsWithParent:!0,contains:[m,t.C_LINE_COMMENT_MODE,p],relevance:0},t.C_LINE_COMMENT_MODE,p,c,d,l,t.C_NUMBER_MODE]},p]},{begin:[/class|interface|trait/,/\s+/,t.UNDERSCORE_IDENT_RE],beginScope:{3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0,illegal:"extends implements",contains:[{beginKeywords:"public protected internal private constructor"},t.UNDERSCORE_TITLE_MODE,{className:"type",begin:/</,end:/>/,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/,excludeBegin:!0,returnEnd:!0},c,d]},l,{className:"meta",begin:"^#!/usr/bin/env",end:"$",illegal:`
202
202
  `},f]}}const tI=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_-]*/}}),nI=["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"],rI=["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"],sI=[...nI,...rI],iI=["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(),o1=["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(),l1=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),oI=["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(),lI=o1.concat(l1).sort().reverse();function aI(t){const e=tI(t),n=lI,r="and or not only",s="[\\w-]+",i="("+s+"|@\\{"+s+"\\})",l=[],c=[],d=function(O){return{className:"string",begin:"~?"+O+".*?"+O}},f=function(O,_,M){return{className:O,begin:_,relevance:M}},p={$pattern:/[a-z-]+/,keyword:r,attribute:iI.join(" ")},m={begin:"\\(",end:"\\)",contains:c,keywords:p,relevance:0};c.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 y=c.concat({begin:/\{/,end:/\}/,contains:l}),b={beginKeywords:"when",endsWithParent:!0,contains:[{beginKeywords:"and not"}].concat(c)},v={begin:i+"\\s*:",returnBegin:!0,end:/[;}]/,relevance:0,contains:[{begin:/-(webkit|moz|ms|o)-/},e.CSS_VARIABLE,{className:"attribute",begin:"\\b("+oI.join("|")+")\\b",end:/(?=:)/,starts:{endsWithParent:!0,illegal:"[<=$]",relevance:0,contains:c}}]},k={className:"keyword",begin:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",starts:{end:"[;{}]",keywords:p,returnEnd:!0,contains:c,relevance:0}},w={className:"variable",variants:[{begin:"@"+s+"\\s*:",relevance:15},{begin:"@"+s}],starts:{end:"[;}]",returnEnd:!0,contains:y}},N={variants:[{begin:"[\\.#:&\\[>]",end:"[;{}]"},{begin:i,end:/\{/}],returnBegin:!0,returnEnd:!0,illegal:`[<='$"]`,relevance:0,contains:[t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE,b,f("keyword","all\\b"),f("variable","@\\{"+s+"\\}"),{begin:"\\b("+sI.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:":("+o1.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+l1.join("|")+")"},{begin:/\(/,end:/\)/,relevance:0,contains:y},{begin:"!important"},e.FUNCTION_DISPATCH]},C={begin:s+`:(:)?(${n.join("|")})`,returnBegin:!0,contains:[N]};return l.push(t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE,k,w,C,v,N,b,e.FUNCTION_DISPATCH),{name:"Less",case_insensitive:!0,illegal:`[=>'/<($"]`,contains:l}}function cI(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 uI(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"}},l={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,l]}}function dI(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},l={begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},c=/[A-Za-z][A-Za-z0-9+.-]*/,d={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:e.concat(/\[.+?\]\(/,c,/:\/\/.*?\)/),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}/}]},p={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},m=t.inherit(f,{contains:[]}),y=t.inherit(p,{contains:[]});f.contains.push(y),p.contains.push(m);let b=[n,d];return[f,p,m,y].forEach(N=>{N.contains=N.contains.concat(b)}),b=b.concat(f,p),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:b},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:b}]}]},n,i,f,p,{className:"quote",begin:"^>\\s+",contains:b,end:"$"},s,r,d,l,{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}function fI(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_]*/,c={"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:c,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 hI(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},l={begin:/->\{/,end:/\}/},c={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:[c]},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},p=[t.BACKSLASH_ESCAPE,i,d],m=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],y=(k,w,N="\\1")=>{const C=N==="\\1"?N:e.concat(N,w);return e.concat(e.concat("(?:",k,")"),w,/(?:\\.|[^\\\/])*?/,C,/(?:\\.|[^\\\/])*?/,N,r)},b=(k,w,N)=>e.concat(e.concat("(?:",k,")"),w,/(?:\\.|[^\\\/])*?/,N,r),v=[d,t.HASH_COMMENT_MODE,t.COMMENT(/^=\w/,/=cut/,{endsWithParent:!0}),l,{className:"string",contains:p,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:y("s|tr|y",e.either(...m,{capture:!0}))},{begin:y("s|tr|y","\\(","\\)")},{begin:y("s|tr|y","\\[","\\]")},{begin:y("s|tr|y","\\{","\\}")}],relevance:2},{className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{begin:b("(?:m|qr)?",/\//,/\//)},{begin:b("m|qr",e.either(...m,{capture:!0}),/\1/)},{begin:b("m|qr",/\(/,/\)/)},{begin:b("m|qr",/\[/,/\]/)},{begin:b("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub method",end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[t.TITLE_MODE,c]},{className:"class",beginKeywords:"class",end:"[;{]",excludeEnd:!0,relevance:5,contains:[t.TITLE_MODE,c,f]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}]}];return i.contains=v,l.contains=v,{name:"Perl",aliases:["pl","pm"],keywords:s,contains:v}}function pI(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),l={scope:"variable",match:"\\$+"+r},c={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}),p=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":(W,$)=>{$.data._beginMatch=W[1]||W[2]},"on:end":(W,$)=>{$.data._beginMatch!==W[1]&&$.ignoreMatch()}},y=t.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/}),b=`[
203
203
  ]`,v={scope:"string",variants:[p,f,m,y]},k={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},w=["false","null","true"],N=["__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:N,literal:(W=>{const $=[];return W.forEach(U=>{$.push(U),U.toLowerCase()===U?$.push(U.toUpperCase()):$.push(U.toLowerCase())}),$})(w),built_in:C},M=W=>W.map($=>$.replace(/\|\d+$/,"")),R={variants:[{match:[/new/,e.concat(b,"+"),e.concat("(?!",M(C).join("\\b|"),"\\b)"),s],scope:{1:"keyword",4:"title.class"}}]},D=e.concat(r,"\\b(?!\\()"),F={variants:[{match:[e.concat(/::/,e.lookahead(/(?!class\b)/)),D],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[s,e.concat(/::/,e.lookahead(/(?!class\b)/)),D],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"}}]},B={scope:"attr",match:e.concat(r,e.lookahead(":"),e.lookahead(/(?!::)/))},V={relevance:0,begin:/\(/,end:/\)/,keywords:_,contains:[B,l,F,t.C_BLOCK_COMMENT_MODE,v,k,R]},q={relevance:0,match:[/\b/,e.concat("(?!fn\\b|function\\b|",M(N).join("\\b|"),"|",M(C).join("\\b|"),"\\b)"),r,e.concat(b,"*"),e.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[V]};V.contains.push(q);const Y=[B,F,t.C_BLOCK_COMMENT_MODE,v,k,R],le={begin:e.concat(/#\[\s*\\?/,e.either(s,i)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:w,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:w,keyword:["new","array"]},contains:["self",...Y]},...Y,{scope:"meta",variants:[{match:s},{match:i}]}]};return{case_insensitive:!1,keywords:_,contains:[le,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}]}},c,{scope:"variable.language",match:/\$this\b/},l,q,F,{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",le,l,F,t.C_BLOCK_COMMENT_MODE,v,k]}]},{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]},v,k]}}function mI(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 gI(t){return{name:"Plain text",aliases:["text","txt"],disableAutodetect:!0}}function yI(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"],c={$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:c,illegal:/#/},p={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,p,f]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[t.BACKSLASH_ESCAPE,d,p,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,p,f]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[t.BACKSLASH_ESCAPE,p,f]},t.APOS_STRING_MODE,t.QUOTE_STRING_MODE]},y="[0-9](_?[0-9])*",b=`(\\b(${y}))?\\.(${y})|\\b(${y})\\.`,v=`\\b|${r.join("|")}`,k={className:"number",relevance:0,variants:[{begin:`(\\b(${y})|(${b}))[eE][+-]?(${y})[jJ]?(?=${v})`},{begin:`(${b})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${v})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${v})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${v})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${v})`},{begin:`\\b(${y})[jJ](?=${v})`}]},w={className:"comment",begin:e.lookahead(/# type:/),end:/$/,keywords:c,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},N={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:c,contains:["self",d,k,m,t.HASH_COMMENT_MODE]}]};return f.contains=[m,k,d],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:c,illegal:/(<\/|\?)|=>/,contains:[d,k,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},m,w,t.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[N]},{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:[k,N,m]}]}}function bI(t){return{aliases:["pycon"],contains:[{className:"meta.prompt",starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}}function vI(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 xI(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+)*/),l={"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"]},c={className:"doctag",begin:"@[A-Za-z]+"},d={begin:"#<",end:">"},f=[t.COMMENT("#","$",{contains:[c]}),t.COMMENT("^=begin","^=end",{contains:[c],relevance:10}),t.COMMENT("^__END__",t.MATCH_NOTHING_RE)],p={className:"subst",begin:/#\{/,end:/\}/,keywords:l},m={className:"string",contains:[t.BACKSLASH_ESCAPE,p],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,p]})]}]},y="[1-9](_?[0-9])*|0",b="[0-9](_?[0-9])*",v={className:"number",relevance:0,variants:[{begin:`\\b(${y})(\\.(${b}))?([eE][+-]?(${b})|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"}]},k={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,keywords:l}]},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:l},{match:[/(include|extend)\s+/,s],scope:{2:"title.class"},keywords:l},{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:[k]},{begin:t.IDENT_RE+"::"},{className:"symbol",begin:t.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[m,{begin:n}],relevance:0},v,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:l},{begin:"("+t.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[t.BACKSLASH_ESCAPE,p],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);p.contains=R,k.contains=R;const V=[{begin:/^\s*=>/,starts:{end:"$",contains:R}},{className:"meta.prompt",begin:"^("+"[>?]>"+"|"+"[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]"+"|"+"(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>"+")(?=[ ])",starts:{end:"$",keywords:l,contains:R}}];return f.unshift(d),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:l,illegal:/\/\*/,contains:[t.SHEBANG({binary:"ruby"})].concat(V).concat(f).concat(R)}}function kI(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*\(/))},l="([ui](8|16|32|64|128|size)|f(32|64))?",c=["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!"],p=["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:p,keyword:c,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_]+)"+l},{begin:"\\b0o([0-7_]+)"+l},{begin:"\\b0x([A-Fa-f0-9_]+)"+l},{begin:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+l}],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:p}},{className:"punctuation",begin:"->"},i]}}const wI=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_-]*/}}),SI=["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"],EI=["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"],NI=[...SI,...EI],CI=["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(),_I=["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(),TI=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),MI=["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 AI(t){const e=wI(t),n=TI,r=_I,s="@[a-z-]+",i="and or not only",c={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("+NI.join("|")+")\\b",relevance:0},{className:"selector-pseudo",begin:":("+r.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+n.join("|")+")"},c,{begin:/\(/,end:/\)/,contains:[e.CSS_NUMBER_MODE]},e.CSS_VARIABLE,{className:"attribute",begin:"\\b("+MI.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,c,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:CI.join(" ")},contains:[{begin:s,className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute"},c,t.QUOTE_STRING_MODE,t.APOS_STRING_MODE,e.HEXCOLOR,e.CSS_NUMBER_MODE]},e.FUNCTION_DISPATCH]}}function OI(t){return{name:"Shell Session",aliases:["console","shellsession"],contains:[{className:"meta.prompt",begin:/^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:"bash"}}]}}function RI(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"],l=["double precision","large object","with timezone","without timezone"],c=["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"],p=["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"],y=["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"],b=p,v=[...f,...d].filter(M=>!p.includes(M)),k={scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},w={scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0},N={match:e.concat(/\b/,e.either(...b),/\s*\(/),relevance:0,keywords:{built_in:b}};function C(M){return e.concat(/\b/,e.either(...M.map(R=>R.replace(/\s+/,"\\s+"))),/\b/)}const O={scope:"keyword",match:C(y),relevance:0};function _(M,{exceptions:R,when:D}={}){const F=D;return R=R||[],M.map(B=>B.match(/\|\d+$/)||R.includes(B)?B:F(B)?`${B}|0`:B)}return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:_(v,{when:M=>M.length<3}),literal:i,type:c,built_in:m},contains:[{scope:"type",match:C(l)},O,N,k,r,s,t.C_NUMBER_MODE,t.C_BLOCK_COMMENT_MODE,n,w]}}function a1(t){return t?typeof t=="string"?t:t.source:null}function yl(t){return Nt("(?=",t,")")}function Nt(...t){return t.map(n=>a1(n)).join("")}function jI(t){const e=t[t.length-1];return typeof e=="object"&&e.constructor===Object?(t.splice(t.length-1,1),e):{}}function Fn(...t){return"("+(jI(t).capture?"":"?:")+t.map(r=>a1(r)).join("|")+")"}const pm=t=>Nt(/\b/,t,/\w$/.test(t)?/\b/:/\B/),II=["Protocol","Type"].map(pm),Yv=["init","self"].map(pm),LI=["Any","Self"],Eh=["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"],Qv=["false","nil","true"],DI=["assignment","associativity","higherThan","left","lowerThan","none","right"],PI=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],Xv=["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"],c1=Fn(/[/=\-+!*%<>&|^~?]/,/[\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]/),u1=Fn(c1,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),Nh=Nt(c1,u1,"*"),d1=Fn(/[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]/),ju=Fn(d1,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),zr=Nt(d1,ju,"*"),Tc=Nt(/[A-Z]/,ju,"*"),BI=["attached","autoclosure",Nt(/convention\(/,Fn("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",Nt(/objc\(/,zr,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],zI=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];function $I(t){const e={match:/\s+/,relevance:0},n=t.COMMENT("/\\*","\\*/",{contains:["self"]}),r=[t.C_LINE_COMMENT_MODE,n],s={match:[/\./,Fn(...II,...Yv)],className:{2:"keyword"}},i={match:Nt(/\./,Fn(...Eh)),relevance:0},l=Eh.filter(Ee=>typeof Ee=="string").concat(["_|0"]),c=Eh.filter(Ee=>typeof Ee!="string").concat(LI).map(pm),d={variants:[{className:"keyword",match:Fn(...c,...Yv)}]},f={$pattern:Fn(/\b\w+/,/#\w+/),keyword:l.concat(PI),literal:Qv},p=[s,i,d],m={match:Nt(/\./,Fn(...Xv)),relevance:0},y={className:"built_in",match:Nt(/\b/,Fn(...Xv),/(?=\()/)},b=[m,y],v={match:/->/,relevance:0},k={className:"operator",relevance:0,variants:[{match:Nh},{match:`\\.(\\.|${u1})+`}]},w=[v,k],N="([0-9]_*)+",C="([0-9a-fA-F]_*)+",O={className:"number",relevance:0,variants:[{match:`\\b(${N})(\\.(${N}))?([eE][+-]?(${N}))?\\b`},{match:`\\b0x(${C})(\\.(${C}))?([pP][+-]?(${N}))?\\b`},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},_=(Ee="")=>({className:"subst",variants:[{match:Nt(/\\/,Ee,/[0\\tnr"']/)},{match:Nt(/\\/,Ee,/u\{[0-9a-fA-F]{1,8}\}/)}]}),M=(Ee="")=>({className:"subst",match:Nt(/\\/,Ee,/[\t ]*(?:[\r\n]|\r\n)/)}),R=(Ee="")=>({className:"subst",label:"interpol",begin:Nt(/\\/,Ee,/\(/),end:/\)/}),D=(Ee="")=>({begin:Nt(Ee,/"""/),end:Nt(/"""/,Ee),contains:[_(Ee),M(Ee),R(Ee)]}),F=(Ee="")=>({begin:Nt(Ee,/"/),end:Nt(/"/,Ee),contains:[_(Ee),R(Ee)]}),B={className:"string",variants:[D(),D("#"),D("##"),D("###"),F(),F("#"),F("##"),F("###")]},V=[t.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[t.BACKSLASH_ESCAPE]}],q={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:V},Y=Ee=>{const Ye=Nt(Ee,/\//),et=Nt(/\//,Ee);return{begin:Ye,end:et,contains:[...V,{scope:"comment",begin:`#(?!.*${et})`,end:/$/}]}},le={scope:"regexp",variants:[Y("###"),Y("##"),Y("#"),q]},W={match:Nt(/`/,zr,/`/)},$={className:"variable",match:/\$\d+/},U={className:"variable",match:`\\$${ju}+`},te=[W,$,U],H={match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:zI,contains:[...w,O,B]}]}},Z={scope:"keyword",match:Nt(/@/,Fn(...BI),yl(Fn(/\(/,/\s+/)))},G={scope:"meta",match:Nt(/@/,zr)},A=[H,Z,G],j={match:yl(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:Nt(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,ju,"+")},{className:"type",match:Tc,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:Nt(/\s+&\s+/,yl(Tc)),relevance:0}]},Q={begin:/</,end:/>/,keywords:f,contains:[...r,...p,...A,v,j]};j.contains.push(Q);const se={match:Nt(zr,/\s*:/),keywords:"_|0",relevance:0},fe={begin:/\(/,end:/\)/,relevance:0,keywords:f,contains:["self",se,...r,le,...p,...b,...w,O,B,...te,...A,j]},ee={begin:/</,end:/>/,keywords:"repeat each",contains:[...r,j]},me={begin:Fn(yl(Nt(zr,/\s*:/)),yl(Nt(zr,/\s+/,zr,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:zr}]},Le={begin:/\(/,end:/\)/,keywords:f,contains:[me,...r,...p,...w,O,B,...A,j,fe],endsParent:!0,illegal:/["']/},Xe={match:[/(func|macro)/,/\s+/,Fn(W.match,zr,Nh)],className:{1:"keyword",3:"title.function"},contains:[ee,Le,e],illegal:[/\[/,/%/]},ce={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[ee,Le,e],illegal:/\[|%/},be={match:[/operator/,/\s+/,Nh],className:{1:"keyword",3:"title"}},ie={begin:[/precedencegroup/,/\s+/,Tc],className:{1:"keyword",3:"title"},contains:[j],keywords:[...DI,...Qv],end:/}/},Be={match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},Te={match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},Fe={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,zr,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:f,contains:[ee,...p,{begin:/:/,end:/\{/,keywords:f,contains:[{scope:"title.class.inherited",match:Tc},...p],relevance:0}]};for(const Ee of B.variants){const Ye=Ee.contains.find(vt=>vt.label==="interpol");Ye.keywords=f;const et=[...p,...b,...w,O,B,...te];Ye.contains=[...et,{begin:/\(/,end:/\)/,contains:["self",...et]}]}return{name:"Swift",keywords:f,contains:[...r,Xe,ce,Be,Te,Fe,be,ie,{beginKeywords:"import",end:/$/,contains:[...r],relevance:0},le,...p,...b,...w,O,B,...te,...A,j,fe]}}const Iu="[A-Za-z$_][0-9A-Za-z$_]*",f1=["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"],h1=["true","false","null","undefined","NaN","Infinity"],p1=["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"],m1=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],g1=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],y1=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],b1=[].concat(g1,p1,m1);function FI(t){const e=t.regex,n=(H,{after:Z})=>{const G="</"+H[0].slice(1);return H.input.indexOf(G,Z)!==-1},r=Iu,s={begin:"<>",end:"</>"},i=/<[A-Za-z0-9\\._:-]+\s*\/>/,l={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(H,Z)=>{const G=H[0].length+H.index,A=H.input[G];if(A==="<"||A===","){Z.ignoreMatch();return}A===">"&&(n(H,{after:G})||Z.ignoreMatch());let j;const Q=H.input.substring(G);if(j=Q.match(/^\s*=/)){Z.ignoreMatch();return}if((j=Q.match(/^\s+extends\s+/))&&j.index===0){Z.ignoreMatch();return}}},c={$pattern:Iu,keyword:f1,literal:h1,built_in:b1,"variable.language":y1},d="[0-9](_?[0-9])*",f=`\\.(${d})`,p="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",m={className:"number",variants:[{begin:`(\\b(${p})((${f})|\\.)?|(${f}))[eE][+-]?(${d})\\b`},{begin:`\\b(${p})\\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},y={className:"subst",begin:"\\$\\{",end:"\\}",keywords:c,contains:[]},b={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,y],subLanguage:"xml"}},v={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,y],subLanguage:"css"}},k={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,y],subLanguage:"graphql"}},w={className:"string",begin:"`",end:"`",contains:[t.BACKSLASH_ESCAPE,y]},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,b,v,k,w,{match:/\$\d+/},m];y.contains=O.concat({begin:/\{/,end:/\}/,keywords:c,contains:["self"].concat(O)});const _=[].concat(C,y.contains),M=_.concat([{begin:/(\s*)\(/,end:/\)/,keywords:c,contains:["self"].concat(_)}]),R={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:c,contains:M},D={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"}}]},F={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:{_:[...p1,...m1]}},B={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},V={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[R],illegal:/%/},q={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function Y(H){return e.concat("(?!",H.join("|"),")")}const le={match:e.concat(/\b/,Y([...g1,"super","import"].map(H=>`${H}\\s*\\(`)),r,e.lookahead(/\s*\(/)),className:"title.function",relevance:0},W={begin:e.concat(/\./,e.lookahead(e.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},$={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},R]},U="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+t.UNDERSCORE_IDENT_RE+")\\s*=>",te={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,e.lookahead(U)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[R]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:c,exports:{PARAMS_CONTAINS:M,CLASS_REFERENCE:F},illegal:/#(?![$_A-z])/,contains:[t.SHEBANG({label:"shebang",binary:"node",relevance:5}),B,t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,b,v,k,w,C,{match:/\$\d+/},m,F,{scope:"attr",match:r+e.lookahead(":"),relevance:0},te,{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:U,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:c,contains:M}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:s.begin,end:s.end},{match:i},{begin:l.begin,"on:begin":l.isTrulyOpeningTag,end:l.end}],subLanguage:"xml",contains:[{begin:l.begin,end:l.end,skip:!0,contains:["self"]}]}]},V,{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},W,{match:"\\$"+r,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[R]},le,q,D,$,{match:/\$[(.]/}]}}function UI(t){const e=t.regex,n=FI(t),r=Iu,s=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],i={begin:[/namespace/,/\s+/,t.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},l={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:s},contains:[n.exports.CLASS_REFERENCE]},c={className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/},d=["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"],f={$pattern:Iu,keyword:f1.concat(d),literal:h1,built_in:b1.concat(s),"variable.language":y1},p={className:"meta",begin:"@"+r},m=(k,w,N)=>{const C=k.contains.findIndex(O=>O.label===w);if(C===-1)throw new Error("can not find mode to replace");k.contains.splice(C,1,N)};Object.assign(n.keywords,f),n.exports.PARAMS_CONTAINS.push(p);const y=n.contains.find(k=>k.scope==="attr"),b=Object.assign({},y,{match:e.concat(r,e.lookahead(/\s*\?:/))});n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,y,b]),n.contains=n.contains.concat([p,i,l,b]),m(n,"shebang",t.SHEBANG()),m(n,"use_strict",c);const v=n.contains.find(k=>k.label==="func.def");return v.relevance=0,Object.assign(n,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),n}function HI(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}/,l=/(\d|1[012])(:\d+){0,2} *(AM|PM)/,c=/\d{1,2}(:\d{1,2}){1,2}/,d={className:"literal",variants:[{begin:e.concat(/# */,e.either(i,s),/ *#/)},{begin:e.concat(/# */,c,/ *#/)},{begin:e.concat(/# */,l,/ *#/)},{begin:e.concat(/# */,e.either(i,s),/ +/,e.either(l,c),/ *#/)}]},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])|[%&])?/}]},p={className:"label",begin:/^\w+:/},m=t.COMMENT(/'''/,/$/,{contains:[{className:"doctag",begin:/<\/?/,end:/>/}]}),y=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,p,m,y,{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:[y]}]}}function WI(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_]+/},l={match:/(\((?!;)|\))+/,className:"punctuation",relevance:0},c={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,l,s,t.QUOTE_STRING_MODE,d,f,c]}}function VI(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/}]},l=t.inherit(i,{begin:/\(/,end:/\)/}),c=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,c,l,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,contains:[i,l,d,c]}]}]},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 KI(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}]},l={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[t.BACKSLASH_ESCAPE,s]},c=t.inherit(l,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),y={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"},b={end:",",endsWithParent:!0,excludeEnd:!0,keywords:e,relevance:0},v={begin:/\{/,end:/\}/,contains:[b],illegal:"\\n",relevance:0},k={begin:"\\[",end:"\\]",contains:[b],illegal:"\\n",relevance:0},w=[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}},y,{className:"number",begin:t.C_NUMBER_RE+"\\b",relevance:0},v,k,i,l],N=[...w];return N.pop(),N.push(c),b.contains=N,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:w}}const GI={arduino:Tj,bash:Mj,c:Aj,cpp:Oj,csharp:Rj,css:Fj,diff:Uj,go:Hj,graphql:Wj,ini:Vj,java:Kj,javascript:Qj,json:Xj,kotlin:eI,less:aI,lua:cI,makefile:uI,markdown:dI,objectivec:fI,perl:hI,php:pI,"php-template":mI,plaintext:gI,python:yI,"python-repl":bI,r:vI,ruby:xI,rust:kI,scss:AI,shell:OI,sql:RI,swift:$I,typescript:UI,vbnet:HI,wasm:WI,xml:VI,yaml:KI},Zv={},qI="hljs-";function JI(t){const e=e1.newInstance();return t&&i(t),{highlight:n,highlightAuto:r,listLanguages:s,register:i,registerAlias:l,registered:c};function n(d,f,p){const m=p||Zv,y=typeof m.prefix=="string"?m.prefix:qI;if(!e.getLanguage(d))throw new Error("Unknown language: `"+d+"` is not registered");e.configure({__emitter:YI,classPrefix:y});const b=e.highlight(f,{ignoreIllegals:!0,language:d});if(b.errorRaised)throw new Error("Could not highlight with `Highlight.js`",{cause:b.errorRaised});const v=b._emitter.root,k=v.data;return k.language=b.language,k.relevance=b.relevance,v}function r(d,f){const m=(f||Zv).subset||s();let y=-1,b=0,v;for(;++y<m.length;){const k=m[y];if(!e.getLanguage(k))continue;const w=n(k,d,f);w.data&&w.data.relevance!==void 0&&w.data.relevance>b&&(b=w.data.relevance,v=w)}return v||{type:"root",children:[],data:{language:void 0,relevance:b}}}function s(){return e.listLanguages()}function i(d,f){if(typeof d=="string")e.registerLanguage(d,f);else{let p;for(p in d)Object.hasOwn(d,p)&&e.registerLanguage(p,d[p])}}function l(d,f){if(typeof d=="string")e.registerAliases(typeof f=="string"?f:[...f],{languageName:d});else{let p;for(p in d)if(Object.hasOwn(d,p)){const m=d[p];e.registerAliases(typeof m=="string"?m:[...m],{languageName:p})}}}function c(d){return!!e.getLanguage(d)}}class YI{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(l,c){return c?l+"_".repeat(c):n.options.classPrefix+l}),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 QI=new At("blurredLoadingNode"),mm=gt.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 wt({key:QI,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:l,type:c}=s;c==="selection"?n.push(jt.inline(i,l,{class:"node-blur-selection"})):t.doc.nodesBetween(i,l,(d,f)=>["paragraph","heading","blockquote","listItem","codeBlock"].includes(d.type.name)?(n.push(jt.node(f,f+d.nodeSize,{class:"node-blur-effect"})),!1):!0)}),bt.create(t.doc,n)}}})]}}),XI=["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","horizontalRule","table","taskList","taskItem","image"],gm=gt.create({name:"pendingAttributes",addGlobalAttributes(){return[{types:XI,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}}}]}}),ZI=JI(GI),ym=h2.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",kt(this.options.HTMLAttributes,n),0]}}),eL=[hm.configure({codeBlock:!1,link:!1,underline:!1}),Cj.configure({lowlight:ZI}),ym.configure({openOnClick:!1,HTMLAttributes:{rel:"noopener noreferrer nofollow"}}),Qw,PR,$A,z2,F2,iR,sR.configure({nested:!0}),Zp,DR,Pw.configure({resizable:!1}),Dw,Lw,Iw,mm,gm,ed.configure({placeholder:"Start writing..."}),fm.configure({types:["paragraph","heading","bulletList","orderedList","listItem","blockquote","codeBlock","horizontalRule","table","tableRow","tableHeader","tableCell","taskList","taskItem","image"],attributeName:"id",generateID:()=>crypto.randomUUID().replace(/-/g,"").slice(0,8)})],tL=[hm.configure({codeBlock:!1,horizontalRule:!0,heading:{levels:[1,2,3]},link:!1,underline:!1}),ym.configure({openOnClick:!1,HTMLAttributes:{rel:"noopener noreferrer nofollow"}}),Zp,mm,gm,ed.configure({placeholder:"Start writing..."}),fm.configure({types:["paragraph","heading","bulletList","orderedList","listItem","blockquote","image","horizontalRule"],attributeName:"id",generateID:()=>crypto.randomUUID().replace(/-/g,"").slice(0,8)})],nL=gt.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()}}}}),v1=[hm.configure({codeBlock:!1,horizontalRule:!1,heading:!1,blockquote:!1,bulletList:!1,orderedList:!1,listItem:!1,link:!1,underline:!1}),ym.configure({openOnClick:!1,HTMLAttributes:{rel:"noopener noreferrer nofollow"}}),Zp,mm,gm,nL,fm.configure({types:["paragraph","image"],attributeName:"id",generateID:()=>crypto.randomUUID().replace(/-/g,"").slice(0,8)})];[...v1,ed.configure({placeholder:"What is happening?!"})];function Cr({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 e0(){return u.jsx("div",{className:"floating-toolbar__divider"})}function rL({editor:t}){const[e,n]=E.useState(!1),[r,s]=E.useState({top:0,left:0}),[,i]=E.useState(0),l=E.useRef(-1),c=E.useRef(-1),d=E.useRef(!1);return E.useEffect(()=>{const f=t.view.dom,p=()=>{d.current=!0},m=()=>{if(!d.current)return;d.current=!1;const{from:y,to:b}=t.state.selection;if(y!==b){const v=t.isActive("codeBlock"),k=!!document.querySelector(".context-menu");if(!v&&!k){l.current=y,c.current=b;const w=t.view.coordsAtPos(y),N=t.view.coordsAtPos(b,1),C=(w.left+N.right)/2;s({top:w.top,left:C}),n(!0)}}};return f.addEventListener("mousedown",p),document.addEventListener("mouseup",m),()=>{f.removeEventListener("mousedown",p),document.removeEventListener("mouseup",m)}},[t]),E.useEffect(()=>{const f=()=>{d.current=!1,n(!1),l.current=-1,c.current=-1};return t.on("blur",f),()=>{t.off("blur",f)}},[t]),E.useEffect(()=>{const f=()=>{const{from:p,to:m}=t.state.selection,y=p===m,b=t.isActive("codeBlock"),v=!!document.querySelector(".context-menu"),k=t.view.hasFocus();if(y||b||v||!k)n(!1),l.current=-1,c.current=-1;else if(!d.current&&(n(!0),p!==l.current||m!==c.current)){l.current=p,c.current=m;const w=t.view.coordsAtPos(p),N=t.view.coordsAtPos(m,1),C=(w.left+N.right)/2;s({top:w.top,left:C})}i(w=>w+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(Cr,{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(Cr,{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(Cr,{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(Cr,{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(Cr,{onClick:()=>{const f=t.getAttributes("link").href||"",p=window.prompt("Link URL:",f);p!==null&&(p===""?t.chain().focus().unsetLink().run():t.chain().focus().setLink({href:p}).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(e0,{}),u.jsx(Cr,{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(Cr,{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(Cr,{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(e0,{}),u.jsx(Cr,{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(Cr,{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(Cr,{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 sL=new At("pendingDecoration");let x1=null,k1=null;function t0(t,e){x1=t,k1=e??null}let Lu=!1,w1=null,bm=null,S1=null;function vm(){return Lu}function iL(){return bm}function oL(){return S1}function gp(t,e,n,r){Lu=t,w1=t?e??null:null,bm=t?r??null:null,S1=t?n??null:null}function lL(t){switch(t){case"insert":return"pending-insert";case"rewrite":return"pending-rewrite";case"delete":return"pending-delete";default:return""}}function n0(t,e,n){let r=0,s=e+1;for(let i=0;i<t.childCount;i++){const l=t.child(i);if(l.isText){if(r+l.text.length>=n)return s+(n-r);r+=l.text.length,s+=l.nodeSize}else{const c=l.type.spec.leafText?l.type.spec.leafText(l).length:0;if(c>0&&r+c>=n)return s;r+=c,s+=l.nodeSize}}return n===r?s:null}function r0(t){const e=[];return t.descendants((n,r)=>{var v,k,w,N,C,O,_;const s=(v=n.attrs)==null?void 0:v.pendingStatus;if(!s)return!0;const i=(k=n.attrs)==null?void 0:k.id,l=(w=n.attrs)==null?void 0:w.pendingGroupId,c=l&&l===k1,f=Lu&&i===w1||l&&Lu&&l===bm,p=f?(N=n.attrs)==null?void 0:N.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,y=p!=null&&m!=null,b=f?"pending-original":lL(s);if(y&&n.isTextblock&&b){const M=n0(n,r,p),R=n0(n,r,m);M!==null&&R!==null&&M<R&&e.push(jt.inline(M,R,{class:b}))}else b&&(n.isTextblock&&r+1<r+n.nodeSize-1?e.push(jt.inline(r+1,r+n.nodeSize-1,{class:b})):e.push(jt.node(r,r+n.nodeSize,{class:b})));if(i&&(i===x1||c)){const M=f?"original":s;e.push(jt.node(r,r+n.nodeSize,{class:`pending-active pending-active--${M}`}))}return!0}),bt.create(t,e)}function E1(){return new wt({key:sL,state:{init(t,e){return r0(e.doc)},apply(t,e,n,r){return t.docChanged||t.getMeta("forceDecorationUpdate")?r0(r.doc):e.map(t.mapping,t.doc)}},props:{decorations(t){return this.getState(t)}}})}function xm(t){const{state:e,dispatch:n}=t,r=e.tr.setMeta("forceDecorationUpdate",!0);n(r)}const aL=new At("markDecoration");let Fc=[];function s0(t){Fc=t}function i0(t,e,n){const s=e.textContent.indexOf(t.text);if(s===-1)return null;const i=l0(e,n,s),l=l0(e,n,s+t.text.length);return i===null||l===null||i>=l?null:jt.inline(i,l,{class:"agent-mark",title:t.note?`Agent Mark: ${t.note}`:"Agent Mark","data-mark-id":t.id})}function o0(t){if(Fc.length===0)return bt.empty;const e=[],n=new Set,r=new Map;t.descendants((i,l)=>{var c;return i.isTextblock&&((c=i.attrs)!=null&&c.id)&&r.set(i.attrs.id,{node:i,pos:l}),!0});for(const i of Fc){const l=r.get(i.nodeId);if(!l)continue;const c=i0(i,l.node,l.pos);c&&(n.add(i.id),e.push(c))}const s=Fc.filter(i=>!n.has(i.id));return s.length>0&&t.descendants((i,l)=>{if(!i.isTextblock)return!0;for(const c of s){if(n.has(c.id))continue;const d=i0(c,i,l);d&&(n.add(c.id),e.push(d))}return!0}),bt.create(t,e)}function l0(t,e,n){let r=0,s=e+1;for(let i=0;i<t.childCount;i++){const l=t.child(i);if(l.isText){if(r+l.text.length>=n)return s+(n-r);r+=l.text.length,s+=l.nodeSize}else{const c=l.type.spec.leafText?l.type.spec.leafText(l).length:0;if(c>0&&r+c>=n)return s;r+=c,s+=l.nodeSize}}return n===r?s:null}function N1(){return new wt({key:aL,state:{init(t,e){return o0(e.doc)},apply(t,e,n,r){return t.docChanged||t.getMeta("forceMarkUpdate")?o0(r.doc):e.map(t.mapping,t.doc)}},props:{decorations(t){return this.getState(t)}}})}function a0(t){const{state:e,dispatch:n}=t,r=e.tr.setMeta("forceMarkUpdate",!0);n(r)}async function c0(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(),{state:i}=e,l=i.schema.nodes.image.create({src:s,alt:t.name}),c=i.tr.replaceSelectionWith(l);e.dispatch(c)}catch{}}function Mc({initialContent:t,extensions:e,onUpdate:n,onReady:r,onLinkClick:s}){const i=E.useRef(s);i.current=s;const l=ow({extensions:e||eL,content:t||"<p></p>",onUpdate:({editor:c})=>{vm()||n==null||n(c.getJSON())},editorProps:{attributes:{class:"tiptap"},handlePaste:(c,d)=>{var p;const f=(p=d.clipboardData)==null?void 0:p.items;if(!f)return!1;for(const m of f)if(m.type.startsWith("image/")){d.preventDefault();const y=m.getAsFile();return y&&c0(y,c),!0}return!1},handleDrop:(c,d)=>{var p;const f=(p=d.dataTransfer)==null?void 0:p.files;if(!(f!=null&&f.length))return!1;for(const m of f)if(m.type.startsWith("image/"))return d.preventDefault(),c0(m,c),!0;return!1}}},[t]);return E.useEffect(()=>{if(!l)return;const c=l.view.dom,d=f=>{var b;const m=f.target.closest("span.doc-link[data-doc]");if(!m)return;const y=m.getAttribute("data-doc");(b=i.current)==null||b.call(i,y)};return c.addEventListener("click",d,!0),()=>c.removeEventListener("click",d,!0)},[l]),E.useEffect(()=>{if(!l)return;const{state:c}=l.view;if(c.plugins.some(p=>p.key==="pendingDecoration$"))return;const d=E1(),f=c.reconfigure({plugins:[...c.plugins,d]});l.view.updateState(f)},[l]),E.useEffect(()=>{if(!l)return;const{state:c}=l.view;if(c.plugins.some(p=>p.key==="markDecoration$"))return;const d=N1(),f=c.reconfigure({plugins:[...c.plugins,d]});l.view.updateState(f)},[l]),E.useEffect(()=>{l&&(r==null||r(l))},[l,r]),l?u.jsxs(u.Fragment,{children:[u.jsx(Qp,{editor:l}),u.jsx(rL,{editor:l})]}):null}function tn({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 ho(){return u.jsx("div",{className:"format-toolbar__divider"})}async function cL(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 uL({editor:t}){const[,e]=E.useState(0),n=E.useRef(null);E.useEffect(()=>{const s=()=>e(i=>i+1);return t.on("transaction",s),()=>{t.off("transaction",s)}},[t]);const r=s=>{var l;const i=(l=s.target.files)==null?void 0:l[0];i&&cL(i,t),s.target.value=""};return u.jsxs("div",{className:"format-toolbar",children:[u.jsxs("div",{className:"format-toolbar__group",children:[u.jsx(tn,{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(tn,{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(tn,{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(tn,{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(tn,{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(ho,{}),u.jsxs("div",{className:"format-toolbar__group",children:[u.jsx(tn,{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(tn,{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(tn,{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(ho,{}),u.jsxs("div",{className:"format-toolbar__group",children:[u.jsx(tn,{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(tn,{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(tn,{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(tn,{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(ho,{}),u.jsxs("div",{className:"format-toolbar__group",children:[u.jsx(tn,{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(tn,{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(tn,{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(ho,{}),u.jsx("div",{className:"format-toolbar__group",children:u.jsx(tn,{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(ho,{}),u.jsxs("div",{className:"format-toolbar__group",children:[u.jsx(tn,{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(tn,{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(tn,{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(ho,{}),u.jsxs("div",{className:"format-toolbar__group",children:[u.jsx(tn,{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(tn,{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 dL={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"})}),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 fL(){const[t,e]=E.useState(!1),[n,r]=E.useState(U0),[s,i]=E.useState(H0),[l,c]=E.useState(zu),d=W0(),[f,p]=E.useState(K0),[m,y]=E.useState(G0),b=E.useRef(null),v=(_=n,M=s,R=l,D=d,F=f,B=m)=>{q0(_,M,R,D,F,B)},k=_=>{r(_),v(_)},w=()=>{const _=s==="light"?"dark":"light";i(_),v(void 0,_)},N=_=>{c(_),v(void 0,void 0,_),window.dispatchEvent(new CustomEvent("ow-sidebar-mode-change",{detail:_}))},C=_=>{p(_),v(void 0,void 0,void 0,void 0,_)},O=_=>{y(_),v(void 0,void 0,void 0,void 0,void 0,_)};return E.useEffect(()=>{if(!t)return;const _=M=>{b.current&&!b.current.contains(M.target)&&e(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[t]),u.jsxs("div",{className:"appearance-wrapper",ref:b,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:w,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:B0.map(_=>u.jsx("button",{className:`appearance-style-option ${n===_.id?"active":""}`,onClick:()=>k(_.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:F0.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:$0.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:z0.map(_=>u.jsxs("button",{className:`appearance-mode-option ${l===_.id?"active":""}`,onClick:()=>N(_.id),children:[dL[_.icon],u.jsx("span",{children:_.label})]},_.id))})]})]})]})}function u0(t){return t.replace(/^@openwriter\/plugin-/,"").replace(/-/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function hL(){const[t,e]=E.useState(!1),[n,r]=E.useState([]),[s,i]=E.useState(null),[l,c]=E.useState(new Set),d=E.useRef(null),f=E.useCallback(()=>{fetch("/api/available-plugins").then(y=>y.json()).then(y=>r(y.plugins||[])).catch(()=>{})},[]);E.useEffect(()=>{t&&f()},[t,f]),E.useEffect(()=>{const y=()=>f();return window.addEventListener("ow-plugins-changed",y),()=>window.removeEventListener("ow-plugins-changed",y)},[f]),E.useEffect(()=>{if(!t)return;const y=b=>{d.current&&!d.current.contains(b.target)&&e(!1)};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[t]);const p=E.useCallback(async(y,b)=>{i(y);try{(await fetch(b?"/api/plugins/disable":"/api/plugins/enable",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:y})})).ok&&f()}catch{}finally{i(null)}},[f]),m=E.useCallback((y,b,v)=>{fetch("/api/plugins/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:y,config:{[b]:v}})}).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(y=>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:[u0(y.name),u.jsxs("span",{className:"plugin-item-version",children:["v",y.version]})]}),y.description&&u.jsx("div",{className:"plugin-item-desc",children:y.description})]}),u.jsxs("label",{className:`plugin-toggle${s===y.name?" loading":""}`,children:[u.jsx("input",{type:"checkbox",checked:y.enabled,disabled:s===y.name,onChange:()=>p(y.name,y.enabled)}),u.jsx("span",{className:"plugin-toggle-track"}),u.jsx("span",{className:"plugin-toggle-thumb"})]})]}),y.enabled&&Object.keys(y.configSchema).length>0&&(()=>{const b=Object.entries(y.configSchema).some(([v,k])=>k.required&&!y.config[v]);return u.jsxs("div",{className:"plugin-config-section",children:[b&&u.jsxs("div",{className:"plugin-setup-hint",children:["Ask your agent: “set up ",u0(y.name),"”"]}),u.jsxs("button",{className:"plugin-config-toggle",onClick:()=>c(v=>{const k=new Set(v);return k.has(y.name)?k.delete(y.name):k.add(y.name),k}),children:[u.jsx("svg",{className:`plugin-config-chevron${l.has(y.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"]}),l.has(y.name)&&u.jsx("div",{className:"plugin-config",children:Object.entries(y.configSchema).map(([v,k])=>u.jsxs("div",{className:"plugin-config-field",children:[u.jsx("label",{className:"plugin-config-label",children:k.description||v}),u.jsx("input",{className:"plugin-config-input",type:v.toLowerCase().includes("key")||v.toLowerCase().includes("secret")||v.toLowerCase().includes("token")?"password":"text",defaultValue:y.config[v]||"",placeholder:k.env?`$${k.env}`:"",onBlur:w=>m(y.name,v,w.target.value)})]},v))})]})})()]},y.name))]})]})}function pL(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 mL(t){return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function gL(){const[t,e]=E.useState(!1),[n,r]=E.useState([]),[s,i]=E.useState(null),[l,c]=E.useState(!1),d=E.useRef(null),f=E.useCallback(()=>{fetch("/api/versions").then(m=>m.json()).then(m=>{r(Array.isArray(m)?m:[]),i(null)}).catch(()=>r([]))},[]);E.useEffect(()=>{t&&f()},[t,f]),E.useEffect(()=>{if(!t)return;const m=y=>{d.current&&!d.current.contains(y.target)&&e(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[t]);const p=E.useCallback(async m=>{if(s!==null){c(!0);try{(await fetch(`/api/versions/${s}/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:m})})).ok&&f()}catch{}c(!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:pL(m.timestamp)}),u.jsxs("span",{className:"version-dropdown__item-meta",children:[m.wordCount.toLocaleString()," words · ",mL(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||l,onClick:()=>p("review"),children:"Review"}),u.jsx("button",{className:"version-dropdown__restore-btn",disabled:s===null||l,onClick:()=>p("full"),children:"Restore"})]})]})]})}const yL=[{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 bL(){const[t,e]=E.useState(!1),n=E.useRef(null);E.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:yL.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 vL({existingConnection:t,onClose:e,onSaved:n}){const[r,s]=E.useState("form"),[i,l]=E.useState(null),[c,d]=E.useState((t==null?void 0:t.domain)||""),[f,p]=E.useState(""),[m,y]=E.useState((t==null?void 0:t.from_name)||""),[b,v]=E.useState(""),[k,w]=E.useState((t==null?void 0:t.id)||""),[N,C]=E.useState({dns_verified:!1,sender_verified:!1}),O=E.useRef(null),_=E.useRef(null);E.useEffect(()=>{const q=Y=>{r!=="submitting"&&r!=="verifying"&&_.current&&!_.current.contains(Y.target)&&e()};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[e,r]),E.useEffect(()=>{const q=Y=>{Y.key==="Escape"&&r!=="submitting"&&r!=="verifying"&&e()};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[e,r]),E.useEffect(()=>()=>{O.current&&clearInterval(O.current)},[]);async function M(){var q,Y;s("submitting"),l(null);try{const W=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"setup_custom_domain",arguments:{domain:c,from_email:f,from_name:m||void 0,physical_address:b}})})).json(),$=(Y=(q=W.content)==null?void 0:q[0])!=null&&Y.text?JSON.parse(W.content[0].text):W;if($.error){l($.error),s("error");return}const U=$.connectionId||$.connection_id||k;U&&w(U),D(U)}catch(le){l(le.message),s("error")}}async function R(){var q,Y;s("submitting"),l(null);try{const W=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"setup_custom_domain",arguments:{domain:c,from_email:f||void 0,from_name:m||void 0,physical_address:b||void 0}})})).json(),$=(Y=(q=W.content)==null?void 0:q[0])!=null&&Y.text?JSON.parse(W.content[0].text):W;if($.error){l($.error),s("error");return}s("done")}catch(le){l(le.message),s("error")}}function D(q){s("verifying"),O.current=setInterval(async()=>{var Y,le;try{const $=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"check_domain_status",arguments:{connectionId:q}})})).json(),U=(le=(Y=$.content)==null?void 0:Y[0])!=null&&le.text?JSON.parse($.content[0].text):$,te=!!U.dns_verified,H=!!U.sender_verified;C({dns_verified:te,sender_verified:H}),te&&H&&(O.current&&clearInterval(O.current),O.current=null,s("done"))}catch{}},5e3)}function F(){k&&fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"resend_domain_verification",arguments:{connectionId:k}})}).catch(()=>{})}const B=!!t,V=c.trim()&&f.trim()&&b.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:B?"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:c,onChange:q=>d(q.target.value),disabled:B,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:q=>p(q.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:q=>y(q.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:b,onChange:q=>v(q.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:B?R:M,disabled:!V,children:B?"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:B?"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${N.dns_verified?" newsletter-modal__verify-item--done":""}`,children:[N.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${N.sender_verified?" newsletter-modal__verify-item--done":""}`,children:[N.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:F,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:B?"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 xL={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 kL({connectionId:t,provider:e,displayName:n,onClose:r,onSaved:s}){const[i,l]=E.useState("loading"),[c,d]=E.useState({}),[f,p]=E.useState(null),m=E.useRef(null),y=xL[e]||[];E.useEffect(()=>{fetch(`/api/connections/${t}/config`).then(k=>k.json()).then(k=>{d(k.config||{}),l("form")}).catch(k=>{p(k.message),l("error")})},[t]),E.useEffect(()=>{const k=w=>{i!=="saving"&&m.current&&!m.current.contains(w.target)&&r()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[r,i]),E.useEffect(()=>{const k=w=>{w.key==="Escape"&&i!=="saving"&&r()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[r,i]);async function b(){l("saving"),p(null);try{const k=await fetch(`/api/connections/${t}/config`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),w=await k.json();if(!k.ok)throw new Error(w.error||"Failed to save");l("saved"),s(),setTimeout(r,800)}catch(k){p(k.message),l("error")}}function v(k){switch(k){case"x":return"X (Twitter)";case"linkedin":return"LinkedIn";case"github":return"GitHub";default:return k}}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:[v(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")&&y.length>0&&u.jsxs("div",{className:"conn-config-modal__body",children:[y.map(k=>u.jsxs("div",{className:"conn-config-field",children:[u.jsxs("label",{className:"conn-config-field__label",children:[k.label,k.readonly&&u.jsx("span",{className:"conn-config-field__badge",children:"read-only"})]}),u.jsx("input",{className:"conn-config-field__input",value:c[k.key]||"",placeholder:k.placeholder,readOnly:k.readonly,onChange:w=>d(N=>({...N,[k.key]:w.target.value}))})]},k.key)),f&&u.jsx("div",{className:"conn-config-modal__error",children:f})]}),(i==="form"||i==="error")&&y.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 ",v(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"}),y.length>0&&(i==="form"||i==="error")&&u.jsx("button",{className:"conn-config-btn conn-config-btn--primary",onClick:b,children:"Save"})]})]})})}const wL=[{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 SL(){const[t,e]=E.useState(!1),[n,r]=E.useState([]),[s,i]=E.useState(null),[l,c]=E.useState(null),[d,f]=E.useState(null),[p,m]=E.useState(null),y=E.useRef(null),b=E.useRef(null);E.useEffect(()=>{if(!t)return;const _=M=>{y.current&&!y.current.contains(M.target)&&(e(!1),i(null))};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[t]),E.useEffect(()=>{t&&v()},[t]),E.useEffect(()=>()=>{b.current&&clearInterval(b.current)},[]);function v(){fetch("/api/connections").then(_=>_.json()).then(_=>{const M=(_.connections||[]).filter(R=>R&&R.id&&R.provider);r(M)}).catch(()=>{})}async function k(_){c(_);try{const M=await fetch(`/api/connections/oauth/${_}/start`,{method:"POST"}),R=await M.json();if(!M.ok||!R.url){c(null);return}window.open(R.url,"_blank","width=600,height=700"),b.current=setInterval(async()=>{try{const F=await(await fetch(`/api/connections/oauth/${_}/status/${R.state}`)).json();F.status==="completed"?(b.current&&clearInterval(b.current),b.current=null,c(null),v()):F.status==="failed"&&(b.current&&clearInterval(b.current),b.current=null,c(null))}catch{}},2e3)}catch{c(null)}}async function w(_){await fetch(`/api/connections/${_}`,{method:"DELETE"}),i(null),v()}function N(_){return _==="active"?"connections-status--active":_==="expired"?"connections-status--expired":_==="revoked"?"connections-status--revoked":"connections-status--pending"}function C(_){switch(_){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 O=new Map;for(const _ of n)O.set(_.provider,_);return u.jsxs("div",{className:"connections-wrapper",ref:y,children:[u.jsx("button",{className:`titlebar-nav-btn${t?" titlebar-nav-btn--active":""}`,onClick:()=>e(!t),title:"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"})]})}),p&&u.jsx(kL,{connectionId:p.id,provider:p.provider,displayName:p.display_name,onClose:()=>m(null),onSaved:()=>v()}),d&&u.jsx(vL,{existingConnection:d==="edit"?O.get("newsletter"):null,onClose:()=>f(null),onSaved:()=>v()}),t&&u.jsxs("div",{className:"connections-dropdown",children:[u.jsx("div",{className:"connections-dropdown__header",children:"Connections"}),u.jsx("div",{className:"connections-dropdown__list",children:wL.map(_=>{const M=O.get(_.id);return M&&s===M.id?u.jsxs("div",{className:"connections-dropdown__confirm",children:[u.jsxs("span",{children:["Disconnect ",_.label,"?"]}),u.jsxs("div",{className:"connections-dropdown__confirm-btns",children:[u.jsx("button",{onClick:()=>w(M.id),children:"Yes"}),u.jsx("button",{onClick:()=>i(null),children:"No"})]})]},_.id):M?u.jsxs("div",{className:"connections-dropdown__item",children:[u.jsx("div",{className:"connections-dropdown__icon",children:C(_.id)}),u.jsxs("div",{className:"connections-dropdown__info",children:[u.jsx("div",{className:"connections-dropdown__name",children:M.display_name||M.domain||_.label}),u.jsxs("div",{className:"connections-dropdown__type",children:[u.jsx("span",{className:`connections-status ${N(M.status)}`}),"Connected"]})]}),u.jsxs("div",{className:"connections-dropdown__actions",children:[u.jsx("button",{className:"connections-dropdown__action-btn",onClick:()=>{_.id==="newsletter"?f("edit"):m({id:M.id,provider:_.id,display_name:M.display_name||_.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:()=>i(M.id),title:"Disconnect",children:"×"})]})]},_.id):_.oauth?u.jsxs("div",{className:"connections-dropdown__item connections-dropdown__item--disconnected",children:[u.jsx("div",{className:"connections-dropdown__icon",children:C(_.id)}),u.jsxs("div",{className:"connections-dropdown__info",children:[u.jsx("div",{className:"connections-dropdown__name",children:_.label}),u.jsx("div",{className:"connections-dropdown__type",children:"Not connected"})]}),u.jsx("button",{className:"connections-dropdown__connect-inline-btn",onClick:()=>k(_.id),disabled:l!==null,children:l===_.id?"Connecting…":"Connect"})]},_.id):u.jsxs("div",{className:"connections-dropdown__item connections-dropdown__item--disconnected",children:[u.jsx("div",{className:"connections-dropdown__icon",children:C(_.id)}),u.jsxs("div",{className:"connections-dropdown__info",children:[u.jsx("div",{className:"connections-dropdown__name",children:_.label}),u.jsx("div",{className:"connections-dropdown__type",children:"Built-in · Not configured"})]}),u.jsx("button",{className:"connections-dropdown__connect-inline-btn",onClick:()=>f("new"),children:"Configure"})]},_.id)})})]})]})}const EL=()=>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"})}),NL=()=>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"})]}),CL=()=>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"})]}),_L=()=>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 TL({title:t,onTitleChange:e,syncStatus:n,onSync:r,onToggleSidebar:s,canGoBack:i,canGoForward:l,onGoBack:c,onGoForward:d,editor:f,onToggleToolbar:p,toolbarOpen:m}){const[y,b]=E.useState(!1),[,v]=E.useState(0),k=E.useRef(null),[w,N]=E.useState(!1),[C,O]=E.useState([]),[_,M]=E.useState(!1),R=E.useRef(null),D=E.useCallback(()=>{b(!0),setTimeout(()=>{var q;return(q=k.current)==null?void 0:q.select()},0)},[]),F=E.useCallback(()=>{b(!1)},[]),B=E.useCallback(q=>{q.key==="Enter"&&b(!1),q.key==="Escape"&&b(!1)},[]),V=E.useCallback(()=>{if(w){N(!1);return}N(!0),M(!0),fetch("/api/sync/pending").then(q=>q.json()).then(q=>O(q)).catch(()=>O([])).finally(()=>M(!1))},[w]);return E.useEffect(()=>{n.state!=="pending"&&N(!1)},[n.state]),E.useEffect(()=>{if(!w)return;const q=Y=>{R.current&&!R.current.contains(Y.target)&&N(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[w]),E.useEffect(()=>{if(!f)return;const q=()=>v(Y=>Y+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"})]})}),c&&u.jsx("button",{className:"titlebar-nav-btn",onClick:c,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:!l,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.jsx("div",{className:"titlebar-center",children:y?u.jsx("input",{ref:k,className:"titlebar-input",value:t,onChange:q=>e(q.target.value),onBlur:F,onKeyDown:B,autoFocus:!0}):u.jsx("span",{className:"titlebar-title",onDoubleClick:D,children:t})}),u.jsxs("div",{className:"titlebar-right",children:[p&&u.jsx("button",{className:`titlebar-nav-btn${m?" titlebar-nav-btn--active":""}`,onClick:p,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(hL,{}),u.jsx(SL,{}),u.jsx(fL,{}),u.jsx(gL,{}),u.jsx(bL,{}),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(EL,{})," Sync"]}),n.state==="synced"&&u.jsxs(u.Fragment,{children:[u.jsx(NL,{})," Synced"]}),n.state==="pending"&&u.jsxs(u.Fragment,{children:[u.jsx(CL,{})," 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(_L,{})," Retry"]})]}),n.state==="pending"&&n.pendingFiles&&n.pendingFiles>0&&u.jsx("button",{className:"sync-details-btn",onClick:V,title:"View pending changes",children:u.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:u.jsx("path",{d:w?"M3 7.5L6 4.5L9 7.5":"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),w&&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,Y)=>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})]},Y))})]})]})]})]})}function yn(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 nd(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 wo(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,"").slice(0,8):Math.random().toString(16).slice(2,10)}function Du(t){return t?Array.isArray(t)?t.map(Du).join(""):t.text?t.text:t.content&&Array.isArray(t.content)?t.content.map(e=>Du(e)).join(""):"":""}const ML=new Set(["paragraph","heading","codeBlock","horizontalRule","table","image"]);function Pu(t,e){for(const n of t)n.type&&ML.has(n.type)?n.attrs={...n.attrs,pendingStatus:e}:n.content&&Pu(n.content,e)}function yp(t,e,n){const r=Array.isArray(n)?n:[n];if(e.nodeId&&!e.afterNodeId&&!e.beforeNodeId){const b=yn(t,e.nodeId);if(!b)return{success:!1,error:`Node ${e.nodeId} not found`};const v=r.map((k,w)=>{var N;return{...k,attrs:{...k.attrs,id:((N=k.attrs)==null?void 0:N.id)||(w===0?e.nodeId:wo())}}});Pu(v,"insert");try{return t.chain().deleteRange({from:b.pos,to:b.pos+b.node.nodeSize}).insertContentAt(b.pos,v).run(),{success:!0,nodeId:e.nodeId}}catch(k){return{success:!1,error:`Failed to replace empty node: ${k}`}}}if(!e.afterNodeId&&!e.beforeNodeId)return{success:!1,error:"Insert requires afterNodeId, beforeNodeId, or nodeId"};const s=e.afterNodeId||e.beforeNodeId,i=!!e.afterNodeId,l=yn(t,s);if(!l)return{success:!1,error:`Anchor node ${s} not found`};const c=Du(n),d=i?l.pos+l.node.nodeSize:0,f=i?l.pos+l.node.nodeSize+5e3:l.pos;let p=null;if(t.state.doc.nodesBetween(d,Math.min(f,t.state.doc.content.size),b=>{var v,k;return((v=b.attrs)==null?void 0:v.pendingStatus)==="insert"&&((k=b.attrs)!=null&&k.id)&&(b.textContent||"")===c?(p=b.attrs.id,!1):!0}),p)return{success:!0,nodeId:p};const m=r.map(b=>{var v;return{...b,attrs:{...b.attrs,id:((v=b.attrs)==null?void 0:v.id)||wo()}}});Pu(m,"insert");const y=i?l.pos+l.node.nodeSize:l.pos;try{return t.chain().insertContentAt(y,m).run(),{success:!0,nodeId:m[0].attrs.id}}catch(b){return{success:!1,error:`Failed to insert content: ${b}`}}}function km(t,e,n,r){var b;const s=yn(t,e);if(!s)return{success:!1,error:`Node ${e} not found`};const{node:i,pos:l}=s,c=Array.isArray(n)?n:[n],f=!((b=i.attrs)!=null&&b.pendingOriginalContent)?i.toJSON():i.attrs.pendingOriginalContent,p={...c[0],attrs:{...c[0].attrs,id:e,pendingStatus:"rewrite",pendingOriginalContent:f,...r?{pendingSelectionFrom:r.selectionFrom,pendingSelectionTo:r.selectionTo,pendingOriginalFrom:r.originalFrom,pendingOriginalTo:r.originalTo}:{}}},m=c.slice(1).map(v=>{var k;return{...v,attrs:{...v.attrs,id:((k=v.attrs)==null?void 0:k.id)||wo()}}});Pu(m,"insert");const y=[p,...m];try{return t.chain().deleteRange({from:l,to:l+i.nodeSize}).insertContentAt(l,y.length===1?y[0]:y).run(),{success:!0,nodeId:e}}catch(v){return{success:!1,error:`Failed to rewrite: ${v}`}}}function AL(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=>Du(m)).join("").trim().length===0)return{success:!1,error:"Range rewrite content is empty (no text) — aborting"};const s=yn(t,e[0]),i=yn(t,e[e.length-1]);if(!s||!i)return{success:!1,error:"Could not find original nodes for range rewrite"};const l=[];for(const m of e){const y=yn(t,m);y&&l.push(y.node.toJSON())}const c=s.pos,d=i.pos+i.node.nodeSize,f=wo()+wo(),p=n.map((m,y)=>{var b;return{...m,attrs:{...m.attrs,id:((b=m.attrs)==null?void 0:b.id)||wo(),pendingStatus:"rewrite",pendingGroupId:f,...y===0?{pendingOriginalContent:l}:{}}}});try{return t.chain().deleteRange({from:c,to:d}).insertContentAt(c,p).run(),{success:!0,nodeId:p[0].attrs.id}}catch(m){return{success:!1,error:`Failed to apply range rewrite: ${m}`}}}function C1(t,e){var i;const n=yn(t,e);if(!n)return{success:!1,error:`Node ${e} not found`};const{node:r,pos:s}=n;if(((i=r.attrs)==null?void 0:i.pendingStatus)==="delete")return{success:!0,nodeId:e};try{return t.chain().command(({tr:l})=>(l.setNodeMarkup(s,void 0,{...r.attrs,pendingStatus:"delete"}),!0)).run(),{success:!0,nodeId:e}}catch(l){return{success:!1,error:`Failed to mark for deletion: ${l}`}}}function OL(t,e){if(e.operation==="rewrite"&&e.nodeId&&e.content){const n=km(t,e.nodeId,e.content);return{success:n.success,error:n.error}}if(e.operation==="insert"&&e.content){let n=null;if(e.nodeId&&!e.afterNodeId?n={nodeId:e.nodeId}:e.afterNodeId&&(n={afterNodeId:e.afterNodeId}),!n)return{success:!1,error:"Insert requires afterNodeId or nodeId"};const r=yp(t,n,e.content);return{success:r.success,error:r.error}}if(e.operation==="delete"&&e.nodeId){const n=C1(t,e.nodeId);return{success:n.success,error:n.error}}return{success:!1,error:`Invalid operation: ${e.operation}`}}function d0(t,e){if(e.length===0)return;if(e.length===1){OL(t,e[0]);return}const n=t.state.schema;t.chain().command(({tr:r})=>{var s;for(const i of e)try{if(i.operation==="rewrite"&&i.nodeId&&i.content){const l=Ac(r.doc,i.nodeId);if(!l)continue;const d=(Array.isArray(i.content)?i.content:[i.content]).map(f=>n.nodeFromJSON(f));r.replaceWith(l.pos,l.pos+l.node.nodeSize,d)}else if(i.operation==="insert"&&i.content){const c=(Array.isArray(i.content)?i.content:[i.content]).map(d=>n.nodeFromJSON(d));if(i.nodeId&&!i.afterNodeId){const d=Ac(r.doc,i.nodeId);if(!d)continue;r.replaceWith(d.pos,d.pos+d.node.nodeSize,c)}else if(i.afterNodeId){const d=Ac(r.doc,i.afterNodeId);if(!d)continue;const f=d.pos+d.node.nodeSize;r.insert(f,ae.fromArray(c))}}else if(i.operation==="delete"&&i.nodeId){const l=Ac(r.doc,i.nodeId);if(!l||((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 Ac(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 f0(t,e,n,r){const s=[];if(r==="delete"){for(const l of n)s.push(C1(t,l));return s}if(r==="insert"){const l=n[n.length-1];return l&&e.length>0&&s.push(yp(t,{nodeId:l},e)),s}if(n.length>1){const l=AL(t,n,e);return s.push(l),s}const i=km(t,n[0],e[0]);if(s.push(i),e.length>1){const l=e.slice(1);s.push(yp(t,{afterNodeId:n[0]},l))}return s}const h0="[[START_SELECTION]]",p0="[[END_SELECTION]]";function RL(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 Oc(t,e,n){if(!(t!=null&&t.content)||!Array.isArray(t.content))return;const r=RL(t);let s=Math.max(0,Math.min(e,r));for(let i=0;i<t.content.length;i++){const l=t.content[i];if(l.type==="text"&&typeof l.text=="string"){if(s<=l.text.length){const c=Math.max(0,Math.min(l.text.length,s));l.text=l.text.slice(0,c)+n+l.text.slice(c);return}s-=l.text.length;continue}if(l.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 jL(t,e,n){const r=JSON.parse(JSON.stringify(t));return r.length===0?r:r.length===1?(Oc(r[0],n,p0),Oc(r[0],e,h0),r):(Oc(r[0],e,h0),Oc(r[r.length-1],n,p0),r)}function IL(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)}const LL=[{action:"agent-mark",label:"Agent Mark",shortcut:"M",condition:"has-selection"},{action:"delete",label:"Delete",shortcut:"D"}];function DL({editorRef:t,allEditors:e,documentId:n}){const[r,s]=E.useState(!1),[i,l]=E.useState({x:0,y:0}),[c,d]=E.useState(!1),[f,p]=E.useState(""),[m,y]=E.useState(!1),[b,v]=E.useState(""),[k,w]=E.useState(!1),[N,C]=E.useState([]),[O,_]=E.useState([]),[M,R]=E.useState(!1),[D,F]=E.useState(""),[B,V]=E.useState([]),[q,Y]=E.useState(!1),[le,W]=E.useState(""),$=E.useRef(null),U=E.useRef(null),te=E.useRef(null),H=E.useCallback(ce=>{if(e&&e.length>0){for(const ie of e)if(ie.view.dom.contains(ce))return ie}const be=t.current;return be&&be.view.dom.contains(ce)?be:null},[e,t]);E.useLayoutEffect(()=>{const ce=$.current;if(!ce||!r)return;const be=ce.getBoundingClientRect(),ie=8;let{x:Be,y:Te}=i;Te+be.height+ie>window.innerHeight&&(Te=i.y-be.height),Be+be.width+ie>window.innerWidth&&(Be=i.x-be.width),Te<ie&&(Te=ie),Be<ie&&(Be=ie),(Be!==i.x||Te!==i.y)&&l({x:Be,y:Te})},[r,i]);const Z=E.useCallback(()=>{fetch("/api/plugins").then(ce=>ce.json()).then(ce=>{const be=[];for(const ie of ce.plugins||[]){const Be=ie.displayName||void 0;for(const Te of ie.contextMenuItems||[])be.push({...Te,pluginDisplayName:Be})}V(be)}).catch(()=>{})},[]);E.useEffect(()=>{Z()},[Z]),E.useEffect(()=>{const ce=()=>Z();return window.addEventListener("ow-plugins-changed",ce),()=>window.removeEventListener("ow-plugins-changed",ce)},[Z]),E.useEffect(()=>{const ce=be=>{$.current&&!$.current.contains(be.target)&&(s(!1),y(!1),w(!1),Y(!1),W(""))};return document.addEventListener("mousedown",ce),()=>document.removeEventListener("mousedown",ce)},[]);const G=E.useCallback(()=>{const ce=te.current||t.current;return ce?ce.isActive("link"):!1},[t]),A=E.useCallback(()=>{const ce=te.current||t.current,be=U.current;if(!ce||!be)return!1;const{from:ie,to:Be}=be;let Te=!1;return ce.state.doc.nodesBetween(ie,Be,Fe=>{var Ee;return(Ee=Fe.attrs)!=null&&Ee.pendingStatus&&(Te=!0),!Te}),Te},[t]),j=E.useCallback(()=>{const ce=te.current||t.current,be=U.current,ie=(be==null?void 0:be.from)??0,Be=(be==null?void 0:be.to)??0,Te=ie!==Be,Fe=(()=>{if(!ce)return!1;try{return ce.state.doc.resolve(ie).parent.content.size===0}catch{return!1}})(),Ee=A(),Ye=[];for(const et of B)et.condition==="has-selection"&&!Te||et.condition==="empty-node"&&!Fe||Ye.push({action:et.action,label:et.label,shortcut:et.shortcut,isPlugin:!0,promptForInput:et.promptForInput,pluginDisplayName:et.pluginDisplayName});for(const et of LL)et.condition==="has-selection"&&(!Te||Ee)||Ye.push(et);return Te&&Ye.push({action:"link",label:"Link to doc",shortcut:"L"}),G()&&Ye.push({action:"unlink",label:"Unlink"}),Ye},[t,G,B,A]);E.useEffect(()=>{const ce=ie=>{var et;if(ie.button!==2)return;const Be=H(ie.target);if(!Be)return;te.current=Be;const{from:Te,to:Fe}=Be.state.selection,Ee=[],Ye=[];if(Te!==Fe&&Be.state.doc.nodesBetween(Te,Fe,vt=>{vt.isBlock&&vt.type.name!=="doc"&&(Ee.push(vt.toJSON()),vt.attrs.id&&Ye.push(vt.attrs.id))}),Ee.length===0){const{$from:vt}=Be.state.selection,Ce=vt.parent;Ce&&Ce.type.name!=="doc"&&(Ee.push(Ce.toJSON()),(et=Ce.attrs)!=null&&et.id&&Ye.push(Ce.attrs.id))}U.current={from:Te,to:Fe,nodes:Ee,nodeIds:Ye}},be=ie=>{H(ie.target)&&(ie.shiftKey||(ie.preventDefault(),l({x:ie.clientX,y:ie.clientY}),s(!0),y(!1),w(!1),Y(!1),W("")))};return document.addEventListener("mousedown",ce,!0),document.addEventListener("contextmenu",be),()=>{document.removeEventListener("mousedown",ce,!0),document.removeEventListener("contextmenu",be)}},[H]);const Q=E.useCallback(async(ce,be)=>{var it,ut,rt,ht,zt;const ie=te.current||t.current;if(!ie)return;const Be=U.current;if(!Be||Be.nodes.length===0){console.warn("[ContextMenu] No captured selection for action:",ce);return}let{nodes:Te,nodeIds:Fe}=Be;const{from:Ee,to:Ye}=Be;d(!0),s(!1),y(!1);const et=`ctx-${Date.now()}`,vt=ie.state.doc.resolve(Ee),Ce=ie.state.doc.resolve(Ye),we=vt.sameParent(Ce)&&Ee!==Ye;ie.commands.applyLoadingEffect(et,Ee,Ye,we?"selection":"paragraph");try{const Ct=[],Vt=[],vn=new Set(Fe);let ne=!1;const Ue=ie.state.doc;for(let ke=0;ke<Ue.childCount;ke++){const ot=Ue.child(ke),Lt=(it=ot.attrs)==null?void 0:it.id;if(Lt&&vn.has(Lt))ne=!0;else if(ne){const L=ot.textContent.trim();L&&Vt.push(L)}else{const L=ot.textContent.trim();L&&Ct.push(L)}}const He=ce.includes(":")?ce.split(":").slice(1).join(":"):ce;let _t=Te,tt=!1,st=0,Ge=0;if(we&&Te.length===1){const ke=vt.start(vt.depth);st=Ee-ke,Ge=Ye-ke;const ot=((rt=(ut=Te[0])==null?void 0:ut.content)==null?void 0:rt.reduce((Lt,L)=>{var oe;return Lt+(((oe=L.text)==null?void 0:oe.length)||(L.type==="hardBreak"?1:0))},0))??0;(st>0||Ge<ot)&&(_t=jL(Te,st,Ge),tt=!0)}const Wn=ie.state.doc.textContent,cn={nodes:_t,action:He,nodeIds:Fe,contextBefore:Ct.slice(-3),contextAfter:Vt.slice(0,3),fullDocument:Wn,documentId:n,debug:!0};tt&&(cn.hasSelectionMarkers=!0),be&&(cn.instruction=be);const Tn=await fetch(`${window.location.origin}/api/voice/apply-editor`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(cn)});if(!Tn.ok){const ke=await Tn.json().catch(()=>({}));console.error("[ContextMenu] API error:",Tn.status,ke);return}const re=await Tn.json();if(re.success&&re.nodes){let ke=re.nodes;if(ke.length===1&&Array.isArray(ke[0])&&(ke=ke[0]),IL(ke),tt&&ke.length===1&&Fe.length===1){const ot=ve=>(ve==null?void 0:ve.reduce((qe,Et)=>{var Tt;return qe+(((Tt=Et.text)==null?void 0:Tt.length)||(Et.type==="hardBreak"?1:0))},0))??0,Lt=ot((ht=Te[0])==null?void 0:ht.content),L=ot((zt=ke[0])==null?void 0:zt.content),oe={selectionFrom:st,selectionTo:L-(Lt-Ge),originalFrom:st,originalTo:Ge};km(ie,Fe[0],ke[0],oe)}else f0(ie,ke,Fe,He)}else console.warn("[ContextMenu] Unexpected response:",re)}catch(Ct){console.error("[ContextMenu] Plugin action failed:",Ct)}finally{ie.commands.removeLoadingEffect(et),d(!1)}},[t]),se=E.useCallback(async ce=>{const be=te.current||t.current;if(!be)return;const{$from:ie}=be.state.selection,Be=ie.before(ie.depth),Te=ie.after(ie.depth),Fe=ie.parent.content.size===0;d(!0),s(!1),y(!1);const Ee=`ctx-img-${Date.now()}`;be.commands.applyLoadingEffect(Ee,Be,Te,"paragraph");try{const et=await(await fetch("/api/image-gen/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:ce})})).json();et.success&&et.src?Fe?be.chain().focus().deleteRange({from:Be,to:Te}).insertContentAt(Be,{type:"image",attrs:{src:et.src,alt:ce}}).run():be.chain().focus().insertContentAt(Te,{type:"image",attrs:{src:et.src,alt:ce}}).run():console.error("[ContextMenu] Image generation failed:",et.error)}catch(Ye){console.error("[ContextMenu] Image generation failed:",Ye)}finally{be.commands.removeLoadingEffect(Ee),d(!1)}},[t]),fe=E.useCallback(ce=>{const{action:be,isPlugin:ie,promptForInput:Be}=ce;if(ie&&Be){v(be),y(!0);return}if(ie){if(be.startsWith("img:"))return;Q(be);return}if(be==="agent-mark"){Y(!0);return}if(be==="delete"){const Te=te.current||t.current;if(Te){const{from:Fe,to:Ee}=Te.state.selection;Te.state.doc.nodesBetween(Fe,Ee,Ye=>{Ye.isBlock&&Ye.type.name!=="doc"&&Ye.attrs.id&&f0(Te,[],[Ye.attrs.id],"delete")})}s(!1);return}if(be==="link"){const Te=te.current||t.current;if(Te){const Fe=[];Te.state.doc.descendants(Ee=>{var Ye;(Ye=Ee.marks)==null||Ye.forEach(et=>{var vt,Ce;if(et.type.name==="link"&&((Ce=(vt=et.attrs)==null?void 0:vt.href)!=null&&Ce.startsWith("doc:"))){const we=et.attrs.href.slice(4);Fe.includes(we)||Fe.push(we)}})}),_(Fe)}fetch("/api/documents").then(Fe=>Fe.json()).then(Fe=>{Array.isArray(Fe)&&C(Fe.map(Ee=>({filename:Ee.filename,title:Ee.title}))),R(!1),F(""),w(!0)}).catch(()=>{});return}if(be==="unlink"){const Te=te.current||t.current;Te&&Te.chain().focus().unsetLink().run(),s(!1);return}},[Q,t]),ee=E.useCallback(()=>{f.trim()&&(b.startsWith("img:")?se(f.trim()):Q(b,f.trim()),p(""),v(""))},[Q,se,b,f]),me=E.useCallback(()=>{const ce=te.current||t.current,be=U.current;if(!ce||!be||!n)return;const{from:ie,to:Be,nodeIds:Te}=be;if(ie===Be||Te.length===0)return;const Fe=ce.state.doc.textBetween(ie,Be,`
204
- `);Fe.trim()&&fetch("/api/marks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:n,text:Fe,note:le.trim(),nodeId:Te[Te.length-1]})}).then(()=>{s(!1),Y(!1),W("")}).catch(Ee=>{console.error("[ContextMenu] Agent mark failed:",Ee)})},[t,n,le]),Le=E.useCallback(ce=>{const be=te.current||t.current;be&&be.chain().focus().setLink({href:`doc:${ce}`}).run(),fetch("/api/auto-tag-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetFile:ce})}).catch(()=>{}),s(!1),w(!1)},[t]),Xe=E.useCallback(()=>{const ce=D.trim();if(!ce)return;const be=te.current||t.current;be&&(fetch("/api/create-link-doc",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:ce})}).then(ie=>ie.json()).then(ie=>{ie.filename&&be.chain().focus().setLink({href:`doc:${ie.filename}`}).run()}).catch(()=>{}),s(!1),w(!1),R(!1),F(""))},[t,D]);return r?u.jsx("div",{ref:$,className:"context-menu",style:{left:i.x,top:i.y},children:c?u.jsx("div",{className:"context-menu-loading",children:"Applying..."}):q?u.jsxs("div",{className:"context-menu-custom",children:[u.jsx("input",{autoFocus:!0,value:le,onChange:ce=>W(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"&&me(),ce.key==="Escape"&&(Y(!1),W(""))},placeholder:"Note for agent (optional)..."}),u.jsx("button",{onClick:me,children:"Mark"})]}):m?u.jsxs("div",{className:"context-menu-custom",children:[u.jsx("input",{autoFocus:!0,value:f,onChange:ce=>p(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"&&ee(),ce.key==="Escape"&&s(!1)},placeholder:"Custom instruction..."}),u.jsx("button",{onClick:ee,children:"Apply"})]}):k?u.jsxs("div",{className:"context-menu-link-picker",children:[u.jsx("div",{className:"context-menu-link-header",children:"Link to document"}),M?u.jsxs("div",{className:"context-menu-custom",children:[u.jsx("input",{autoFocus:!0,value:D,onChange:ce=>F(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"&&Xe(),ce.key==="Escape"&&R(!1)},placeholder:"New document title..."}),u.jsx("button",{onClick:Xe,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"}),N.filter(ce=>O.includes(ce.filename)).map(({filename:ce,title:be})=>u.jsx("button",{className:"context-menu-item",onClick:()=>Le(ce),children:u.jsx("span",{children:be})},`linked-${ce}`))]}),u.jsx("div",{className:"context-menu-section-header",children:"All documents"}),N.filter(ce=>!O.includes(ce.filename)).map(({filename:ce,title:be})=>u.jsx("button",{className:"context-menu-item",onClick:()=>Le(ce),children:u.jsx("span",{children:be})},ce)),N.length===0&&u.jsx("div",{className:"context-menu-loading",children:"No documents"})]})]}):(()=>{const ce=j();let be;return ce.map((ie,Be)=>{const Te=ie.isPlugin&&ie.pluginDisplayName&&ie.pluginDisplayName!==be,Fe=be!==void 0;ie.isPlugin?be=ie.pluginDisplayName:be=void 0;const Ee=!ie.isPlugin&&Fe;return u.jsxs("span",{children:[Te&&u.jsx("div",{className:"context-menu-section-header",children:ie.pluginDisplayName}),Ee&&u.jsx("div",{className:"context-menu-divider"}),u.jsxs("button",{className:"context-menu-item",onClick:()=>fe(ie),children:[u.jsx("span",{children:ie.label}),ie.shortcut&&u.jsx("span",{className:"context-menu-shortcut",children:ie.shortcut})]})]},ie.action)})})()}):null}function wm(t,e,n){let r=t.resolve(e);for(;r.depth>0;){const s=r.node(r.depth),i=r.before(r.depth),l=i+s.nodeSize;if(s.childCount===1)e=i,n=l,r=t.resolve(e);else break}return{from:e,to:n}}function PL(t,e){const n=yn(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 BL(t,e){const n=yn(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 zL(t,e){var l;const n=yn(t,e);if(!n)return!1;const{node:r,pos:s}=n;if(((l=r.attrs)==null?void 0:l.pendingStatus)!=="delete")return!0;const i=wm(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function $L(t,e){var l;const n=yn(t,e);if(!n)return!0;const{node:r,pos:s}=n;if(((l=r.attrs)==null?void 0:l.pendingStatus)!=="insert")return!0;const i=wm(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function FL(t,e){var l,c;const n=yn(t,e);if(!n)return!1;const{node:r,pos:s}=n;if(((l=r.attrs)==null?void 0:l.pendingStatus)!=="rewrite")return!0;const i=(c=r.attrs)==null?void 0:c.pendingOriginalContent;if(i)t.chain().deleteRange({from:s,to:s+r.nodeSize}).insertContentAt(s,i).run();else{const d=wm(t.state.doc,s,s+r.nodeSize);t.chain().deleteRange(d).run()}return!0}function UL(t,e){var i;const n=yn(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:l})=>(l.setNodeMarkup(s,void 0,{...r.attrs,pendingStatus:null}),!0)).run(),!0}function HL(t,e){const n=nd(t,e);if(n.length===0)return!1;for(const r of[...n].reverse()){const s=yn(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 WL(t,e){var c;const n=nd(t,e);if(n.length===0)return!1;const r=(c=n[0].node.attrs)==null?void 0:c.pendingOriginalContent,s=n[0].pos,i=n[n.length-1],l=i.pos+i.node.nodeSize;try{return r&&Array.isArray(r)&&r.length>0?t.chain().deleteRange({from:s,to:l}).insertContentAt(s,r).run():t.chain().deleteRange({from:s,to:l}).run(),!0}catch{return!1}}function _1(t,e){var i,l;const n=yn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return HL(t,r);switch((l=n.node.attrs)==null?void 0:l.pendingStatus){case"insert":return PL(t,e);case"rewrite":return BL(t,e);case"delete":return zL(t,e);default:return!1}}function T1(t,e){var i,l;const n=yn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return WL(t,r);switch((l=n.node.attrs)==null?void 0:l.pendingStatus){case"insert":return $L(t,e);case"rewrite":return FL(t,e);case"delete":return UL(t,e);default:return!1}}function VL(t){const e=M1(t).reverse();for(const n of e)_1(t,n);t.view&&xm(t.view)}function KL(t){const e=M1(t).reverse();for(const n of e)T1(t,n);t.view&&xm(t.view)}function Sm(t){const e=[],n=new Set;return t.state.doc.descendants((r,s)=>{var l,c,d;const i=(l=r.attrs)==null?void 0:l.pendingStatus;if(i&&((c=r.attrs)!=null&&c.id)){const f=(d=r.attrs)==null?void 0:d.pendingGroupId;if(f){if(n.has(f))return!0;n.add(f)}e.push({nodeId:r.attrs.id,pos:s,pendingStatus:i,groupId:f,editor:t})}return!0}),e}function Ch(t){const e=[];for(const n of t)n&&!n.isDestroyed&&e.push(...Sm(n));return e}function M1(t){return Sm(t).map(e=>e.nodeId)}function GL(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 bl(t,e){if(t.isDestroyed)return;let n=-1;if(t.state.doc.descendants((i,l)=>{var c;return((c=i.attrs)==null?void 0:c.id)===e?(n=l,!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),l=t.view.dom.closest(".editor-container");if(l){const c=l.getBoundingClientRect(),d=i.top-c.top+l.scrollTop-l.clientHeight/2;l.scrollTo({top:d,behavior:"smooth"})}}catch{}}function qL(t){const[e,n]=E.useState([]),[r,s]=E.useState(0),i=E.useRef(),l=E.useRef(new Set),c=E.useCallback(()=>{const N=t.filter(R=>R&&!R.isDestroyed);if(N.length===0){n([]),l.current=new Set;return}const C=Ch(N);n(C);const O=l.current,_=new Set(C.map(R=>R.nodeId));let M=-1;if(O.size>0){for(let R=0;R<C.length;R++)if(!O.has(C[R].nodeId)){M=R;break}}l.current=_,M>=0?(s(M),bl(C[M].editor,C[M].nodeId)):C.length===0?s(0):s(R=>Math.min(R,C.length-1))},[t]);E.useEffect(()=>{const N=t.filter(_=>_&&!_.isDestroyed);if(N.length===0)return;const C=()=>{clearTimeout(i.current),i.current=setTimeout(c,50)};for(const _ of N)_.on("transaction",C);c();const O=setTimeout(()=>{const _=Ch(N.filter(M=>!M.isDestroyed));_.length>0&&bl(_[0].editor,_[0].nodeId)},150);return()=>{for(const _ of N)_.isDestroyed||_.off("transaction",C);clearTimeout(i.current),clearTimeout(O)}},[t,c]),E.useEffect(()=>{const N=e[r]??null;return t0((N==null?void 0:N.nodeId)??null,(N==null?void 0:N.groupId)??null),N!=null&&N.editor&&!N.editor.isDestroyed&&N.editor.view&&xm(N.editor.view),()=>{t0(null)}},[r,e]);const d=GL(e),f=e[r]??null,p=E.useCallback(()=>{if(e.length===0)return;const N=(r+1)%e.length;s(N),e[N]&&bl(e[N].editor,e[N].nodeId)},[e,r]),m=E.useCallback(()=>{if(e.length===0)return;const N=(r-1+e.length)%e.length;s(N),e[N]&&bl(e[N].editor,e[N].nodeId)},[e,r]),y=E.useCallback(()=>{const N=t.filter(_=>_&&!_.isDestroyed),C=Ch(N);if(C.length===0)return;const O=Math.min(r,C.length-1);bl(C[O].editor,C[O].nodeId)},[t,r]),b=E.useCallback(()=>{f&&(_1(f.editor,f.nodeId),c(),y())},[f,c,y]),v=E.useCallback(()=>{f&&(T1(f.editor,f.nodeId),c(),y())},[f,c,y]),k=E.useCallback(()=>{const N=t.filter(C=>C&&!C.isDestroyed);for(const C of N)VL(C);c()},[t,c]),w=E.useCallback(()=>{const N=t.filter(C=>C&&!C.isDestroyed);for(const C of N)KL(C);c()},[t,c]);return{pendingNodes:e,counts:d,currentNode:f,currentIndex:r,hasPending:d.total>0,goToNext:p,goToPrevious:m,acceptCurrent:b,rejectCurrent:v,acceptAll:k,rejectAll:w,refresh:c}}const Oo={strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},JL=()=>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",...Oo})}),m0=()=>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",...Oo})}),YL=()=>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",...Oo})}),QL=()=>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",...Oo})}),g0=()=>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",...Oo})}),y0=()=>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",...Oo})});function A1(t,e,n){const r=yn(t,e);if(!r)return!1;const{pos:s,node:i}=r,l={type:n.type||i.type.name,attrs:{...n.attrs||{},id:i.attrs.id,pendingStatus:i.attrs.pendingStatus,pendingOriginalContent:i.attrs.pendingOriginalContent,pendingSelectionFrom:i.attrs.pendingSelectionFrom,pendingSelectionTo:i.attrs.pendingSelectionTo,pendingOriginalFrom:i.attrs.pendingOriginalFrom,pendingOriginalTo:i.attrs.pendingOriginalTo},content:n.content};try{return t.chain().command(({tr:c})=>(c.setMeta("addToHistory",!1),!0)).deleteRange({from:s,to:s+i.nodeSize}).insertContentAt(s,l).run(),!0}catch{return!1}}function O1(t,e,n){const r=nd(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:l})=>(l.setMeta("addToHistory",!1),!0)).deleteRange({from:s,to:i}).insertContentAt(s,n).run(),!0}catch{return!1}}function Rc(t,e){if(!vm()||!e)return!1;const n=oL(),r=iL();return r&&n&&Array.isArray(n)?O1(t,r,n):n&&A1(t,e,n),gp(!1),!0}function XL({editors:t,pendingDocs:e,currentFilename:n,onSwitchDocument:r,sendMessage:s,getDocument:i}){const{counts:l,currentNode:c,currentIndex:d,hasPending:f,goToNext:p,goToPrevious:m,acceptCurrent:y,rejectCurrent:b,acceptAll:v,rejectAll:k}=qL(t),[w,N]=E.useState(!1),C=E.useRef(null),O=E.useRef(null),_=e.filenames.length,M=b0(e.filenames,n)>=0?_-1:_,R=f||_>0,D=b0(e.filenames,n),F=(c==null?void 0:c.pendingStatus)==="rewrite",B=!!(c!=null&&c.groupId),V=F,q=E.useCallback(()=>{var j,Q;const A=c==null?void 0:c.editor;if(!(!A||!c||c.pendingStatus!=="rewrite"))if(w)O.current&&Rc(O.current,C.current),C.current=null,O.current=null,N(!1);else if(B&&c.groupId){const se=nd(A,c.groupId);if(se.length===0)return;const fe=(j=se[0].node.attrs)==null?void 0:j.pendingOriginalContent;if(!fe||!Array.isArray(fe))return;const ee=se.map(Xe=>Xe.node.toJSON()),me=fe.map((Xe,ce)=>({...Xe,attrs:{...Xe.attrs||{},pendingStatus:"rewrite",pendingGroupId:c.groupId,...ce===0?{pendingOriginalContent:fe}:{}}}));if(!O1(A,c.groupId,me))return;gp(!0,c.nodeId,ee,c.groupId),C.current=c.nodeId,O.current=A,N(!0)}else{const se=yn(A,c.nodeId);if(!se)return;const{node:fe}=se,ee=(Q=fe.attrs)==null?void 0:Q.pendingOriginalContent;if(!ee)return;const me=fe.toJSON();if(!A1(A,c.nodeId,ee))return;gp(!0,c.nodeId,me),C.current=c.nodeId,O.current=A,N(!0)}},[c,w,B]);E.useEffect(()=>{if(!w)return;const A=C.current,j=O.current;A&&j&&(c==null?void 0:c.nodeId)!==A&&(Rc(j,A),C.current=null,O.current=null,N(!1))},[c==null?void 0:c.nodeId,w]),E.useEffect(()=>{if(t.length!==0)return()=>{vm()&&C.current&&O.current&&(Rc(O.current,C.current),C.current=null,O.current=null)}},[t]);const Y=E.useCallback(A=>{if(!n)return;if(!t.some(Q=>!Q||Q.isDestroyed?!1:Sm(Q).length>0)){const Q=i==null?void 0:i();Q&&s({type:"doc-update",document:Q,filename:n}),s({type:"pending-resolved",filename:n,action:A})}},[t,n,s,i]),le=E.useCallback(()=>{O.current&&w&&C.current&&(Rc(O.current,C.current),C.current=null,O.current=null,N(!1))},[w]),W=E.useCallback(()=>{le(),y(),Y("accept")},[le,y,Y]),$=E.useCallback(()=>{le(),b(),Y("reject")},[le,b,Y]),U=E.useCallback(()=>{le(),v(),Y("accept")},[le,v,Y]),te=E.useCallback(()=>{le(),k(),Y("reject")},[le,k,Y]),H=E.useCallback(()=>{if(_===0||_===1&&D===0)return;const A=D<=0?_-1:D-1;r(e.filenames[A])},[_,D,e.filenames,r]),Z=E.useCallback(()=>{if(_===0||_===1&&D===0)return;const A=D>=_-1?0:D+1;r(e.filenames[A])},[_,D,e.filenames,r]);if(E.useEffect(()=>{if(!R)return;const A=j=>{if(!(j.target instanceof HTMLInputElement||j.target instanceof HTMLTextAreaElement)&&!(j.target instanceof HTMLElement&&j.target.closest("[contenteditable]")))switch(j.key){case"j":case"ArrowDown":!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),p());break;case"k":case"ArrowUp":!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),m());break;case"h":case"ArrowLeft":!j.metaKey&&!j.ctrlKey&&!j.altKey&&(j.preventDefault(),H());break;case"l":case"ArrowRight":!j.metaKey&&!j.ctrlKey&&!j.altKey&&(j.preventDefault(),Z());break;case"a":!j.metaKey&&!j.ctrlKey&&!j.shiftKey&&(j.preventDefault(),W());break;case"r":!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),$());break;case"A":j.shiftKey&&!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),U());break;case"R":j.shiftKey&&!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),te());break;case"o":!j.metaKey&&!j.ctrlKey&&!j.shiftKey&&(j.preventDefault(),q());break}};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[R,p,m,H,Z,W,$,U,te,q]),!R)return null;if(c!=null&&c.pendingStatus,!f&&M>0)return u.jsxs("div",{className:"review-panel",children:[u.jsxs("div",{className:"review-panel__status",children:["No changes here — ",M," other doc",M>1?"s have":" has"," changes"]}),u.jsx("div",{className:"review-panel__divider"}),u.jsx("div",{className:"review-panel__nav",children:u.jsx("button",{className:"review-panel__btn",onClick:Z,title:"Next doc (l)",children:u.jsx(m0,{})})})]});const G=D>=0?D+1:"?";return u.jsxs("div",{className:"review-panel",children:[_>1&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"review-panel__nav",children:[u.jsx("button",{className:"review-panel__btn",onClick:H,title:"Previous doc (h)",children:u.jsx(JL,{})}),u.jsx("button",{className:"review-panel__btn",onClick:Z,title:"Next doc (l)",children:u.jsx(m0,{})}),u.jsxs("span",{className:"review-panel__counter",children:[G,"/",_]})]}),u.jsx("div",{className:"review-panel__divider"})]}),u.jsxs("div",{className:"review-panel__nav",children:[u.jsx("button",{className:"review-panel__btn",onClick:m,disabled:l.total===0,title:"Previous (k)",children:u.jsx(YL,{})}),u.jsx("button",{className:"review-panel__btn",onClick:p,disabled:l.total===0,title:"Next (j)",children:u.jsx(QL,{})}),u.jsxs("span",{className:"review-panel__counter",children:[d+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${V&&!w?" review-panel__toggle-btn--active":""}`,onClick:()=>V&&w&&q(),disabled:!V,title:"Show modified (o)",children:"Modified"}),u.jsx("button",{className:`review-panel__toggle-btn${V&&w?" review-panel__toggle-btn--active":""}`,onClick:()=>V&&!w&&q(),disabled:!V,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:W,title:"Accept (a)",children:u.jsx(g0,{})}),u.jsx("button",{className:"review-panel__reject",onClick:$,title:"Reject (r)",children:u.jsx(y0,{})}),u.jsxs("button",{className:"review-panel__accept-all",onClick:U,title:"Accept all (Shift+A)",children:[u.jsx(g0,{}),u.jsx("span",{children:"All"})]}),u.jsxs("button",{className:"review-panel__reject-all",onClick:te,title:"Reject all (Shift+R)",children:[u.jsx(y0,{}),u.jsx("span",{children:"All"})]})]})]})}function b0(t,e){return t.indexOf(e)}function jc(t){return t.type==="doc"?t.file:t.id}function R1(t,e){for(const n of t)n.type==="doc"?e.add(n.file):n.type==="container"&&R1(n.items,e)}function Mo(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 bp(t){return/^[A-Z]:[/\\]|^\//.test(t)}function j1(t){const e=t.replace(/\\/g,"/").split("/");return e.length>=2?e[e.length-2]:""}function ZL(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 eD(t,e){const[n,r]=E.useState([]),[s,i]=E.useState([]),[l,c]=E.useState(new Set),d=E.useRef(null),f=E.useCallback(()=>{fetch("/api/documents").then(m=>m.json()).then(m=>{Array.isArray(m)&&r(m)}).catch(()=>{})},[]),p=E.useCallback(()=>{fetch("/api/workspaces").then(m=>m.json()).then(async m=>{if(!Array.isArray(m))return;const y=await Promise.all(m.map(async v=>{try{const w=await(await fetch(`/api/workspaces/${encodeURIComponent(v.filename)}`)).json();return{...v,workspace:w}}catch{return v}}));i(y);const b=new Set;for(const v of y)v.workspace&&R1(v.workspace.root,b);c(b)}).catch(()=>{})},[]);return E.useEffect(()=>{f()},[f,t]),E.useEffect(()=>{p()},[p,e,t]),E.useEffect(()=>{const m=requestAnimationFrame(()=>{var b;const y=(b=d.current)==null?void 0:b.querySelector(".sidebar-item.active");y==null||y.scrollIntoView({block:"nearest",behavior:"instant"})});return()=>cancelAnimationFrame(m)},[n]),{docs:n,workspaces:s,assignedFiles:l,fetchDocs:f,scrollRef:d}}function tD(t,e,n){const r=E.useCallback(M=>{fetch(`/api/documents/${encodeURIComponent(M)}`,{method:"DELETE"}).catch(()=>{})},[]),s=E.useCallback(M=>{fetch(`/api/documents/${encodeURIComponent(M)}/archive`,{method:"POST"}).then(()=>e()).catch(()=>{})},[e]),i=E.useCallback(M=>{fetch(`/api/documents/${encodeURIComponent(M)}/unarchive`,{method:"POST"}).then(()=>e()).catch(()=>{})},[e]),l=E.useCallback((M,R,D)=>{!D.trim()||D.trim()===R||fetch(`/api/documents/${encodeURIComponent(M)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:D.trim()})}).then(()=>e()).catch(()=>{})},[e]),c=E.useCallback(()=>{fetch("/api/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:"Untitled Workspace"})}).catch(()=>{})},[]),d=E.useCallback(M=>{fetch(`/api/workspaces/${encodeURIComponent(M)}`,{method:"DELETE"}).catch(()=>{})},[]),f=E.useCallback((M,R,D)=>{fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D?{metadata:D}:{})}).then(F=>F.json()).then(F=>{if(F.filename)return fetch(`/api/workspaces/${encodeURIComponent(M)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:F.filename,title:F.title||"Untitled",containerId:R})})}).catch(()=>{})},[]),p=E.useCallback((M,R)=>{fetch(`/api/workspaces/${encodeURIComponent(M)}/docs/${encodeURIComponent(R)}`,{method:"DELETE"}).catch(()=>{})},[]),m=E.useCallback((M,R)=>{fetch(`/api/workspaces/${encodeURIComponent(M)}/containers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:"Untitled",parentContainerId:R})}).catch(()=>{})},[]),y=E.useCallback((M,R)=>{fetch(`/api/workspaces/${encodeURIComponent(M)}/containers/${encodeURIComponent(R)}`,{method:"DELETE"}).catch(()=>{})},[]),b=E.useCallback((M,R,D)=>{D.trim()&&fetch(`/api/workspaces/${encodeURIComponent(M)}/containers/${encodeURIComponent(R)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:D.trim()})}).catch(()=>{})},[]),v=E.useCallback((M,R)=>{R.trim()&&fetch(`/api/workspaces/${encodeURIComponent(M)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:R.trim()})}).catch(()=>{})},[]),[k,w]=E.useState({}),N=E.useRef(-1);E.useEffect(()=>{n!==N.current&&(N.current=n??0,fetch("/api/documents").then(M=>M.json()).then(M=>{const R={};return Promise.all(M.map(D=>fetch(`/api/doc-tags/${encodeURIComponent(D.filename)}`).then(F=>F.json()).then(F=>{var B;(B=F.tags)!=null&&B.length&&(R[D.filename]=F.tags)}).catch(()=>{}))).then(()=>w(R))}).catch(()=>{}))},[n]);const C=E.useCallback(M=>k[M]||[],[k]),O=E.useCallback((M,R)=>{R.trim()&&(w(D=>{const F=D[M]||[];return F.includes(R.trim())?D:{...D,[M]:[...F,R.trim()]}}),fetch(`/api/doc-tags/${encodeURIComponent(M)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag:R.trim()})}).catch(()=>{}))},[]),_=E.useCallback((M,R)=>{w(D=>{const B=(D[M]||[]).filter(V=>V!==R);if(B.length===0){const V={...D};return delete V[M],V}return{...D,[M]:B}}),fetch(`/api/doc-tags/${encodeURIComponent(M)}/${encodeURIComponent(R)}`,{method:"DELETE"}).catch(()=>{})},[]);return{fetchDocs:e,handleDelete:r,handleArchive:s,handleUnarchive:i,handleRename:l,handleCreateWorkspace:c,handleDeleteWorkspace:d,handleCreateInWorkspace:f,handleRemoveFromWorkspace:p,handleCreateContainer:m,handleDeleteContainer:y,handleRenameContainer:b,handleRenameWorkspace:v,getDocTags:C,handleAddTag:O,handleRemoveTag:_}}function nD({docs:t,workspaces:e,assignedFiles:n,scrollRef:r,setCollapsedSections:s}){const[i,l]=E.useState(null),[c,d]=E.useState(null),f=E.useRef(null),p=E.useRef(null),m=E.useRef(null),y=E.useRef(null),b=E.useRef(null),v=5,k=(V,q,Y)=>Y==="before"?q>0?jc(V[q-1]):null:jc(V[q]),w=E.useCallback((V,q)=>{if(q===null){const W=t.filter(U=>!n.has(U.filename)).map(U=>({type:"doc",file:U.filename,title:U.title})),$=W.findIndex(U=>jc(U)===V);return $>=0?{siblings:W,index:$,containerId:null}:null}const Y=e.find(W=>W.filename===q);if(!(Y!=null&&Y.workspace))return null;const le=(W,$)=>{for(let U=0;U<W.length;U++){if(jc(W[U])===V)return{siblings:W,index:U,containerId:$};if(W[U].type==="container"){const te=le(W[U].items,W[U].id);if(te)return te}}return null};return le(Y.workspace.root,null)},[t,n,e]),N=E.useCallback(()=>{l(null),d(null),b.current=null,y.current=null,m.current&&(m.current.remove(),m.current=null),f.current&&(clearTimeout(f.current),f.current=null),p.current&&(cancelAnimationFrame(p.current),p.current=null),document.body.style.userSelect=""},[]),C=E.useCallback((V,q)=>{if(!V||!q)return;if(V.type==="workspace"){const H=q.itemId;if(H===V.filename)return;const Z=e.map(j=>j.filename),G=Z.indexOf(V.filename);if(G<0)return;Z.splice(G,1);let A=Z.indexOf(H);if(A<0)return;q.position==="after"&&(A+=1),Z.splice(A,0,V.filename),fetch("/api/workspaces/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:Z})}).catch(()=>{});return}const{wsFilename:Y,containerId:le,afterId:W}=q,$=V.type==="doc"?V.file:V.id,U=V.sourceWs;if(q.itemId===$)return;if(V.type==="container"){if(U!==Y||!Y)return;fetch(`/api/workspaces/${encodeURIComponent(Y)}/docs/${encodeURIComponent($)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:le??null,afterFile:W})}).catch(()=>{});return}const te=V.file;if(U===null&&Y===null){const H=t.filter(Q=>!n.has(Q.filename)).map(Q=>Q.filename),Z=H.indexOf(te);if(Z<0)return;H.splice(Z,1);let G=W?H.indexOf(W):-1;G>=0?G+=1:G=0,H.splice(G,0,te);const A=[];let j=0;for(const Q of t)n.has(Q.filename)?A.push(Q.filename):A.push(H[j++]);fetch("/api/documents/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:A})}).catch(()=>{});return}if(U===null&&Y!==null){fetch(`/api/workspaces/${encodeURIComponent(Y)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:te,title:te.replace(/\.md$/,""),containerId:le??null,afterFile:W})}).catch(()=>{});return}if(U!==null&&Y===null){fetch(`/api/workspaces/${encodeURIComponent(U)}/docs/${encodeURIComponent(te)}`,{method:"DELETE"}).catch(()=>{});return}if(U===Y&&Y!==null){fetch(`/api/workspaces/${encodeURIComponent(Y)}/docs/${encodeURIComponent(te)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:le??null,afterFile:W})}).catch(()=>{});return}U!==null&&Y!==null&&fetch(`/api/workspaces/${encodeURIComponent(Y)}/docs/${encodeURIComponent(te)}/cross-move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:U,containerId:le??null,afterFile:W,title:te.replace(/\.md$/,"")})}).catch(()=>{})},[e,t,n]),O=E.useCallback((V,q)=>{const Y=m.current;Y&&(Y.style.display="none");const le=document.elementFromPoint(V,q);if(Y&&(Y.style.display=""),!le)return null;if((i==null?void 0:i.type)==="workspace"){const Q=le.closest("[data-ws-drag]");if(Q){const se=Q.dataset.wsDrag,fe=Q.getBoundingClientRect(),ee=(q-fe.top)/fe.height;return{itemId:se,position:ee<.5?"before":"after",wsFilename:null,containerId:null,afterId:null}}return null}const W=le.closest("[data-drag-id]");if(!W){const Q=le.closest("[data-drop-ws]");return Q?{itemId:"__section__",position:"inside",wsFilename:Q.dataset.dropWs==="__docs__"?null:Q.dataset.dropWs,containerId:Q.dataset.dropContainer||null,afterId:null}:null}const $=W.dataset.dragId,U=W.dataset.dragType,te=W.dataset.dragWs==="__docs__"?null:W.dataset.dragWs,H=W.getBoundingClientRect(),Z=(q-H.top)/H.height;if(U==="container-header"){const Q=$,se=W.dataset.dragParent||null,fe=w(Q,te);return fe?Z<.25?{itemId:Q,position:"before",wsFilename:te,containerId:se,afterId:k(fe.siblings,fe.index,"before")}:Z>.75?{itemId:Q,position:"after",wsFilename:te,containerId:se,afterId:k(fe.siblings,fe.index,"after")}:{itemId:Q,position:"inside",wsFilename:te,containerId:Q,afterId:null}:null}const G=W.dataset.dragContainer||null,A=w($,te);if(!A)return null;const j=Z<.5?"before":"after";return{itemId:$,position:j,wsFilename:te,containerId:G,afterId:k(A.siblings,A.index,j)}},[w,i]),_=E.useCallback(V=>{const q=r.current;if(!q)return;const Y=q.getBoundingClientRect(),le=80,W=18;let $=0;if(V<Y.top+le?$=-W*Math.max(0,1-(V-Y.top)/le):V>Y.bottom-le&&($=W*Math.max(0,1-(Y.bottom-V)/le)),p.current&&(cancelAnimationFrame(p.current),p.current=null),$!==0){const U=()=>{q.scrollTop+=$,p.current=requestAnimationFrame(U)};p.current=requestAnimationFrame(U)}},[r]),M=E.useCallback((V,q)=>{const Y=m.current;Y&&(Y.style.display="none");const le=document.elementFromPoint(V,q);Y&&(Y.style.display="");const W=le==null?void 0:le.closest("[data-section-key]");if(!W){f.current&&(clearTimeout(f.current),f.current=null);return}const $=W.dataset.sectionKey;f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{s(U=>{if(!U.has($))return U;const te=new Set(U);return te.delete($),te})},500)},[s]);E.useEffect(()=>{if(!i)return;const V=Y=>{m.current&&(m.current.style.left=`${Y.clientX+12}px`,m.current.style.top=`${Y.clientY-8}px`),d(O(Y.clientX,Y.clientY)),_(Y.clientY),M(Y.clientX,Y.clientY)},q=Y=>{C(i,O(Y.clientX,Y.clientY)),N()};return window.addEventListener("pointermove",V),window.addEventListener("pointerup",q),()=>{window.removeEventListener("pointermove",V),window.removeEventListener("pointerup",q)}},[i,O,C,N,_,M]);const R=E.useCallback((V,q,Y)=>{if(V.button!==0||V.target.closest("input, button, .sidebar-tag-remove, .sidebar-tag-add, .sidebar-container-actions, .sidebar-delete-btn, .sidebar-confirm-delete, .sidebar-inline-confirm"))return;y.current={x:V.clientX,y:V.clientY},b.current=q;const W=U=>{if(!y.current||!b.current)return;const te=U.clientX-y.current.x,H=U.clientY-y.current.y;if(Math.abs(te)+Math.abs(H)>=v){document.body.style.userSelect="none",window.removeEventListener("pointermove",W),window.removeEventListener("pointerup",$),l(b.current),b.current=null;const Z=document.createElement("div");Z.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);",Z.textContent=Y,document.body.appendChild(Z),m.current=Z,Z.style.left=`${U.clientX+12}px`,Z.style.top=`${U.clientY-8}px`}},$=()=>{window.removeEventListener("pointermove",W),window.removeEventListener("pointerup",$),y.current=null,b.current=null,document.body.style.userSelect=""};window.addEventListener("pointermove",W),window.addEventListener("pointerup",$)},[]);return{draggedItem:i,dropIndicator:c,handlePointerDown:R,dropClass:V=>!c||c.itemId!==V?"":c.position==="before"?"drop-before":c.position==="after"?"drop-after":c.position==="inside"?"drop-inside":"",isDragging:V=>i?i.type==="doc"?i.file===V:i.type==="workspace"?i.filename===V:i.id===V:!1,isContainerDropTarget:V=>!c||!i?!1:c.containerId===V}}function rD({x:t,y:e,filename:n,title:r,onClose:s,onDuplicate:i,onRename:l,onArchive:c,onDelete:d,onPluginAction:f,pluginItems:p,onNewsletterSend:m,onSchedulePost:y,onViewAnalytics:b,viewAnalyticsLabel:v,onMarkSent:k,isAlreadySent:w}){const N=E.useRef(null),[C,O]=E.useState(!1),[_,M]=E.useState(!1),[R,D]=E.useState({left:t,top:e}),[F,B]=E.useState([]),[V,q]=E.useState(!1);E.useEffect(()=>{fetch("/api/connections").then(W=>W.json()).then(W=>{const $=(W.connections||[]).filter(U=>U.provider==="newsletter"&&U.status==="active");B($)}).catch(()=>{})},[]),E.useLayoutEffect(()=>{const W=N.current;if(!W)return;const $=W.getBoundingClientRect(),U=8;let te=t,H=e;e+$.height+U>window.innerHeight&&(H=e-$.height),t+$.width+U>window.innerWidth&&(te=t-$.width),H<U&&(H=U),te<U&&(te=U),D({left:te,top:H})},[t,e]),E.useEffect(()=>{const W=$=>{N.current&&!N.current.contains($.target)&&s()};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[s]),E.useEffect(()=>{const W=$=>{$.key==="Escape"&&s()};return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[s]);const Y=E.useCallback(W=>{f(W.action,W),s()},[f,s]),le=E.useCallback(()=>{m&&(F.length===1?(m(F[0].id),s()):q(!V))},[m,F,V,s]);return u.jsxs("div",{ref:N,className:"context-menu",style:{left:R.left,top:R.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:()=>{l(),s()},children:u.jsx("span",{children:"Rename"})}),_?u.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:W=>W.stopPropagation(),children:[u.jsx("span",{children:"Archive?"}),u.jsx("button",{onClick:()=>{c(),s()},children:"Yes"}),u.jsx("button",{onClick:()=>M(!1),children:"No"})]}):u.jsx("button",{className:"context-menu-item",onClick:()=>M(!0),children:u.jsx("span",{children:"Archive"})}),C?u.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:W=>W.stopPropagation(),children:[u.jsx("span",{children:"Delete?"}),u.jsx("button",{onClick:()=>{d(),s()},children:"Yes"}),u.jsx("button",{onClick:()=>O(!1),children:"No"})]}):u.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>O(!0),children:u.jsx("span",{children:"Delete"})}),y&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{y(),s()},children:u.jsx("span",{children:"Schedule Post"})})]}),F.length>0&&m&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:le,children:u.jsx("span",{children:"Send as Newsletter"})}),V&&F.length>1&&u.jsx("div",{className:"context-menu-sub",children:F.map(W=>u.jsx("button",{className:"context-menu-item context-menu-sub-item",onClick:()=>{m(W.id),s()},children:u.jsx("span",{children:W.display_name})},W.id))})]}),k&&!w&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{k(),s()},children:u.jsx("span",{children:"Mark as Sent"})})]}),b&&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:v||"View Analytics"})})]}),p.length>0&&u.jsx(u.Fragment,{children:(()=>{let W;return p.map($=>{const U=$.pluginDisplayName&&$.pluginDisplayName!==W;return W=$.pluginDisplayName,u.jsxs("span",{children:[U&&u.jsx("div",{className:"context-menu-divider"}),U&&u.jsx("div",{className:"context-menu-section-header",children:$.pluginDisplayName}),u.jsx("button",{className:"context-menu-item",onClick:()=>Y($),children:u.jsx("span",{children:$.label})})]},$.action)})})()})]})}function sD({actionLabel:t,docTitle:e,onConfirm:n,onClose:r}){const[s,i]=E.useState(""),l=E.useRef(null);E.useEffect(()=>{var d;(d=l.current)==null||d.focus()},[]),E.useEffect(()=>{const d=f=>{f.key==="Escape"&&r()};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const c=E.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:l,value:s,onChange:d=>i(d.target.value.slice(0,500)),placeholder:"Optional: guide the transformation (e.g. 'focus on the intro section', 'keep it professional')...",onKeyDown:d=>{d.key==="Enter"&&(d.ctrlKey||d.metaKey)&&c()}})]}),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:c,children:"Go"})]})]})]})})}function _h(t,e){if(!e)return[t];const n=[],r=t.toLowerCase(),s=e.toLowerCase();let i=0;for(;i<t.length;){const l=r.indexOf(s,i);if(l===-1){n.push(t.slice(i));break}l>i&&n.push(t.slice(i,l)),n.push(u.jsx("mark",{children:t.slice(l,l+e.length)},l)),i=l+e.length}return n}function v0({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"?_h(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: ",_h(t.matchedTag,e)]}),t.matchType==="content"&&t.snippet&&u.jsx("div",{className:"search-result-snippet",children:_h(t.snippet,e)}),u.jsxs("div",{className:"sidebar-item-meta",children:[t.wordCount.toLocaleString()," words · ",Mo(t.lastModified)]})]})}function Em({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(l=>!l.isArchived),i=t.filter(l=>l.isArchived);return u.jsx("div",{className:"sidebar-scroll",children:u.jsxs("div",{className:"search-results",children:[s.map(l=>u.jsx(v0,{r:l,query:e,onClick:()=>n(l.filename)},l.filename)),i.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"search-archived-divider",children:u.jsx("span",{children:"Archived"})}),i.map(l=>u.jsx(v0,{r:l,query:e,onClick:()=>r.handleUnarchive(l.filename)},l.filename))]})]})})}function I1({connectionId:t,subject:e,filename:n,onBeforeSend:r,onClose:s}){const[i,l]=E.useState("confirm"),[c,d]=E.useState("html"),[f,p]=E.useState(""),[m,y]=E.useState(null),[b,v]=E.useState(null),[k,w]=E.useState(0),[N,C]=E.useState(null),[O,_]=E.useState(null),[M,R]=E.useState("all"),[D,F]=E.useState([]),[B,V]=E.useState(""),q=E.useRef(null),Y=D.find(U=>U.id===B),le=M==="exclude_issue"&&Y&&O!=null?Math.max(0,O-Y.recipient_count):O;E.useEffect(()=>{fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"list_subscribers",arguments:{limit:1}})}).then(U=>U.json()).then(U=>{var H,Z;const te=(Z=(H=U.content)==null?void 0:H[0])!=null&&Z.text?JSON.parse(U.content[0].text):U;te.count!=null&&_(te.count)}).catch(()=>{}),fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"list_newsletter_issues",arguments:{limit:10}})}).then(U=>U.json()).then(U=>{var H,Z;const te=(Z=(H=U.content)==null?void 0:H[0])!=null&&Z.text?JSON.parse(U.content[0].text):U;te.issues&&F(te.issues)}).catch(()=>{})},[]);const W=()=>i==="sent"?{sentCount:k,issueId:N,sentAt:new Date().toISOString()}:void 0;E.useEffect(()=>{const U=te=>{i!=="sending"&&i!=="testing"&&q.current&&!q.current.contains(te.target)&&s(W())};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[s,i,k,N]),E.useEffect(()=>{const U=te=>{te.key==="Escape"&&i!=="sending"&&i!=="testing"&&s(W())};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[s,i,k,N]);async function $(U){var te,H;l(U?"testing":"sending"),v(null);try{r&&await r();const Z={subject:e,connectionId:t,format:c};U&&(Z.test_email=U),!U&&M==="exclude_issue"&&B&&(Z.exclude_issue_id=B);const A=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"send_newsletter",arguments:Z})})).json(),j=(H=(te=A.content)==null?void 0:te[0])!=null&&H.text?JSON.parse(A.content[0].text):A;if(j.error){v(j.error),l("error");return}if(j.test){y(j.sent_to),l("confirm");return}const Q=j.sent||0,se=j.issueId||null,fe=new Date().toISOString();w(Q),C(se),l("sent"),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({newsletterContext:{lastSend:{sentCount:Q,sentAt:fe,issueId:se||void 0}}})}).catch(()=>{})}catch(Z){v(Z.message),l("error")}}return u.jsx("div",{className:"newsletter-modal-overlay",children:u.jsxs("div",{className:"newsletter-modal",ref:q,children:[u.jsxs("div",{className:"newsletter-modal__header",children:[u.jsx("h3",{children:"Send Newsletter"}),u.jsx("button",{className:"newsletter-modal__close",onClick:()=>s(W()),children:"×"})]}),u.jsxs("div",{className:"newsletter-modal__body",children:[i==="confirm"&&u.jsxs(u.Fragment,{children:[u.jsxs("p",{className:"newsletter-modal__confirm-text",style:le==null?{visibility:"hidden"}:void 0,children:['Send "',u.jsx("strong",{children:e}),'" to ',le!=null?le.toLocaleString():0," subscriber",le!==1?"s":"","?"]}),u.jsxs("div",{className:"newsletter-modal__audience",children:[u.jsx("label",{className:"newsletter-modal__label",children:"Audience"}),u.jsxs("select",{className:"newsletter-modal__select",value:M,onChange:U=>{const te=U.target.value;R(te),te==="all"&&V("")},children:[u.jsx("option",{value:"all",children:"All subscribers"}),D.length>0&&u.jsx("option",{value:"exclude_issue",children:"Exclude who received..."})]}),M==="exclude_issue"&&u.jsxs("select",{className:"newsletter-modal__select",value:B,onChange:U=>V(U.target.value),children:[u.jsx("option",{value:"",children:"Select a past issue"}),D.map(U=>u.jsxs("option",{value:U.id,children:[U.subject," (",U.recipient_count," sent)"]},U.id))]})]}),u.jsxs("div",{className:"newsletter-modal__format-toggle",children:[u.jsx("button",{className:`newsletter-modal__format-btn${c==="html"?" active":""}`,onClick:()=>d("html"),children:"HTML"}),u.jsx("button",{className:`newsletter-modal__format-btn${c==="plaintext"?" active":""}`,onClick:()=>d("plaintext"),children:"Plaintext"})]}),u.jsxs("div",{className:"newsletter-modal__test-section",children:[u.jsxs("div",{className:"newsletter-modal__test-row",children:[u.jsx("input",{type:"email",className:"newsletter-modal__test-input",placeholder:"Test email address",value:f,onChange:U=>p(U.target.value),onKeyDown:U=>{U.key==="Enter"&&f.trim()&&$(f.trim())}}),u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--test",disabled:!f.trim(),onClick:()=>$(f.trim()),children:"Send Test"})]}),m&&u.jsxs("p",{className:"newsletter-modal__test-success",children:["Test sent to ",m]})]}),u.jsxs("div",{className:"newsletter-modal__actions",children:[u.jsx("button",{className:"newsletter-modal__btn",onClick:s,children:"Cancel"}),u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",disabled:M==="exclude_issue"&&!B,onClick:()=>$(),children:"Send Now"})]})]}),(i==="sending"||i==="testing")&&u.jsxs("div",{className:"newsletter-modal__status",children:[u.jsx("div",{className:"newsletter-modal__spinner"}),u.jsx("span",{children:i==="testing"?"Sending test...":"Sending..."})]}),i==="sent"&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"newsletter-modal__status newsletter-modal__status--success",children:["Sent to ",k," subscriber",k!==1?"s":"","!"]}),u.jsx("div",{className:"newsletter-modal__actions",children:u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>s({sentCount:k,issueId:N,sentAt:new Date().toISOString()}),children:"Done"})})]}),i==="error"&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"newsletter-modal__error",children:b}),u.jsxs("div",{className:"newsletter-modal__actions",children:[u.jsx("button",{className:"newsletter-modal__btn",onClick:s,children:"Cancel"}),u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>$(),children:"Retry"})]})]})]})]})})}async function Th(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 Mh(t,e){return e?(t/e*100).toFixed(1)+"%":"0%"}function x0(t){return new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function k0(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 iD({docId:t,title:e,onClose:n}){const[r,s]=E.useState("loading"),[i,l]=E.useState([]),[c,d]=E.useState(""),[f,p]=E.useState(null),[m,y]=E.useState(null),[b,v]=E.useState("links"),[k,w]=E.useState("all"),[N,C]=E.useState(!1),[O,_]=E.useState(!1),[M,R]=E.useState(""),[D,F]=E.useState(!1),[B,V]=E.useState(null),q=E.useRef(null);E.useEffect(()=>{let ee=!1;return(async()=>{try{const me=await Th("list_newsletter_issues",{limit:20});if(ee)return;if(!me.issues||me.issues.length===0){s("no-data");return}l(me.issues);const Le=me.issues[0].id;d(Le)}catch(me){ee||(y(me.message),s("error"))}})(),()=>{ee=!0}},[]),E.useEffect(()=>{if(!c)return;let ee=!1;return C(!0),_(!1),V(null),R(""),(async()=>{try{const me=await Th("get_newsletter_analytics",{issue_id:c});if(ee)return;if(me.error){y(me.error),s("error");return}p(me),s("loaded")}catch(me){ee||(y(me.message),s("error"))}finally{ee||C(!1)}})(),()=>{ee=!0}},[c]),E.useEffect(()=>{const ee=me=>{q.current&&!q.current.contains(me.target)&&n()};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[n]),E.useEffect(()=>{const ee=me=>{me.key==="Escape"&&n()};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[n]);const Y=f?lD(f.subscriber_events):[],le=(f==null?void 0:f.issue.recipient_count)??0,W=f?f.stats.delivered||le-f.stats.bounces:0,$=f?new Set(f.subscriber_events.filter(ee=>{var me;return ee.event_type==="click"&&((me=ee.url)==null?void 0:me.includes("/newsletter/unsubscribe/"))}).map(ee=>ee.email)).size:0,U=f?f.stats.unsubscribes||$:0,te=f?f.subscriber_events.filter(ee=>ee.event_type==="dropped").length:0,H=f?Math.max(0,le-f.stats.unique_opens):0,Z=f!=null&&f.issue.sent_at?Date.now()-new Date(f.issue.sent_at).getTime():0,G=Math.floor(Z/36e5),A=!!(f!=null&&f.issue.resent_at||B),j=ee=>{const me=Math.floor(ee/36e5);return me<1?"just now":me<24?`${me}h ago`:`${Math.floor(me/24)}d ${me%24}h ago`},Q=async()=>{if(!(!M.trim()||D)){F(!0);try{const ee=await Th("resend_to_unopened",{issue_id:c,subject:M});ee.error?(y(ee.error),s("error")):(V({sent:ee.sent,failed:ee.failed}),_(!1))}catch(ee){y(ee.message),s("error")}finally{F(!1)}}},se=ee=>{var me;return ee.event_type==="unsubscribe"||ee.event_type==="click"&&!!((me=ee.url)!=null&&me.includes("/newsletter/unsubscribe/"))},fe=f?oD(f.subscriber_events.filter(ee=>k==="all"?!0:k==="unsubscribe"?se(ee):ee.event_type===k)):[];return u.jsx("div",{className:"newsletter-modal-overlay",children:u.jsxs("div",{className:"na-modal",ref:q,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:c,onChange:ee=>d(ee.target.value),children:i.map(ee=>u.jsxs("option",{value:ee.id,children:[ee.subject," — ",x0(ee.sent_at)]},ee.id))}),N?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:W.toLocaleString()}),u.jsx("div",{className:"na-kpi__label",children:"Delivered"}),u.jsxs("div",{className:"na-kpi__sub",children:[le.toLocaleString()," sent"]})]}),u.jsxs("div",{className:"na-kpi",children:[u.jsx("div",{className:"na-kpi__value",children:Mh(f.stats.unique_opens,W)}),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:Mh(f.stats.unique_clicks,W)}),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:U}),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:te}),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"})]})]}),H>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 ",j(Z),G<48?" · consider waiting 48h":""]})]}),u.jsx("input",{className:"na-resend-input",type:"text",value:M,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:Q,disabled:D||!M.trim(),children:D?"Sending...":`Send to ${H.toLocaleString()}`})]})]}):u.jsxs("button",{className:"na-resend-toggle",onClick:()=>{_(!0),R(f.issue.subject)},children:["Resend to ",H.toLocaleString()," non-openers ",u.jsx("span",{style:{float:"right"},children:"›"})]})}),A&&u.jsxs("div",{className:"na-resend-done",children:["Resent ",f.issue.resent_at?j(Date.now()-new Date(f.issue.resent_at).getTime()):"just now",B?` — ${B.sent} sent`:"",f.issue.resend_subject?` — "${f.issue.resend_subject}"`:""]}),u.jsxs("div",{className:"na-tabs",children:[u.jsxs("button",{className:`na-tab${b==="links"?" active":""}`,onClick:()=>v("links"),children:["Links (",Y.length,")"]}),u.jsxs("button",{className:`na-tab${b==="activity"?" active":""}`,onClick:()=>v("activity"),children:["Activity (",f.subscriber_events.length,")"]})]}),b==="links"&&u.jsx("div",{className:"na-table-wrap",children:Y.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:Y.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:k0(ee.url)})}),u.jsx("td",{children:ee.uniqueClicks}),u.jsx("td",{children:ee.totalClicks}),u.jsx("td",{children:Mh(ee.uniqueClicks,W)})]},ee.url))})]})}),b==="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${k===ee?" active":""}`,onClick:()=>w(ee),children:ee==="all"?"All":ee.charAt(0).toUpperCase()+ee.slice(1)+"s"},ee))}),u.jsxs("div",{className:"na-table-wrap",children:[fe.length===0?u.jsxs("div",{className:"na-empty",children:["No ",k==="all"?"":k+" ","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:fe.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:k0(ee.url,35)}):"—"}),u.jsx("td",{className:"na-table__time",children:x0(ee.latestTimestamp)})]},ee.key))})]}),fe.length>100&&u.jsxs("div",{className:"na-truncated",children:["Showing 100 of ",fe.length," events"]})]})]})]})]})]})})}function oD(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 lD(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 aD(t){return t.tweetContext?"tweet":t.articleContext?"article":t.linkedinContext?"linkedin":t.newsletterContext?"newsletter":t.blogContext?"blog":"tweet"}function rd({filename:t,title:e,onClose:n}){const[r,s]=E.useState("queue"),[i,l]=E.useState(null),[c,d]=E.useState(null),[f,p]=E.useState(""),[m,y]=E.useState(!1),[b,v]=E.useState(null),[k,w]=E.useState(null);E.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||""),l(aD(O.meta||{}))}).catch(O=>w(O.message))},[t]);const N=async()=>{var O;if(!(!c||!i)){y(!0);try{const _={content:c,content_type:i,mode:r};r==="custom"&&f&&(_.scheduled_at=new Date(f).toISOString());const M=await fetch("/api/scheduler/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)}),R=await M.json();if(M.ok){const D=(O=R.item)!=null&&O.scheduled_at?new Date(R.item.scheduled_at).toLocaleString():"now";v({success:!0,message:`Scheduled for ${D}`})}else v({success:!1,message:R.error||"Failed to schedule"})}catch(_){v({success:!1,message:_.message})}finally{y(!1)}}},C=i===null&&!k;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}),k?u.jsxs("div",{className:"schedule-post-modal-result error",children:[k,u.jsx("button",{className:"schedule-post-modal-done",onClick:n,children:"Done"})]}):b?u.jsxs("div",{className:`schedule-post-modal-result ${b.success?"success":"error"}`,children:[b.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=>p(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:N,disabled:m||C||r==="custom"&&!f,children:m?"Scheduling...":r==="now"?"Post Now":"Schedule"})]})]})]})})}const w0=[{key:"document",label:"Document"},{key:"tweet",label:"Tweet",metadata:{tweetContext:{mode:"tweet"}}},{key:"reply",label:"Reply",needsUrl:!0,urlPlaceholder:"Paste tweet URL...",metadata:{tweetContext:{mode:"reply"}}},{key:"quote",label:"Quote Tweet",needsUrl:!0,urlPlaceholder:"Paste tweet URL...",metadata:{tweetContext:{mode:"quote"}}},{key:"article",label:"Article",metadata:{articleContext:{active:!0}}},{key:"linkedin",label:"LinkedIn",metadata:{linkedinContext:{active:!0}}},{key:"newsletter",label:"Newsletter",metadata:{newsletterContext:{active:!0}}},{key:"blog",label:"Blog",metadata:{blogContext:{active:!0}}}];function cD({anchorRect:t,onSelect:e,onClose:n}){const r=E.useRef(null),[s,i]=E.useState(null),[l,c]=E.useState(""),d=E.useRef(null),[f,p]=E.useState({left:t.left,top:t.bottom+4});E.useLayoutEffect(()=>{const v=r.current;if(!v)return;const k=v.getBoundingClientRect(),w=8;let N=t.left,C=t.bottom+4;C+k.height+w>window.innerHeight&&(C=t.top-k.height-4),N+k.width+w>window.innerWidth&&(N=t.right-k.width),C<w&&(C=w),N<w&&(N=w),p({left:N,top:C})},[t]),E.useEffect(()=>{const v=k=>{r.current&&!r.current.contains(k.target)&&n()};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[n]),E.useEffect(()=>{const v=k=>{k.key==="Escape"&&n()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[n]),E.useEffect(()=>{s&&setTimeout(()=>{var v;return(v=d.current)==null?void 0:v.focus()},0)},[s]);const m=v=>{if(v.needsUrl){i(v.key),c("");return}e(v.metadata)},y=()=>{if(!s||!l.trim())return;const v=l.trim();if(!v.includes("x.com")&&!v.includes("twitter.com"))return;const k=w0.find(N=>N.key===s);if(!(k!=null&&k.metadata))return;const w=JSON.parse(JSON.stringify(k.metadata));w.tweetContext&&(w.tweetContext.url=v),e(w)},b=l.trim().includes("x.com")||l.trim().includes("twitter.com");return u.jsx("div",{ref:r,className:"create-doc-dropdown",style:{left:f.left,top:f.top},children:w0.map(v=>u.jsxs("div",{children:[u.jsx("button",{className:`create-doc-dropdown-item${s===v.key?" active":""}`,onClick:()=>m(v),children:v.label}),s===v.key&&u.jsxs("div",{className:"create-doc-dropdown-url",children:[u.jsx("input",{ref:d,type:"text",placeholder:v.urlPlaceholder,value:l,onChange:k=>c(k.target.value),onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),y()),k.key==="Escape"&&(i(null),c(""))}}),u.jsx("button",{onClick:y,disabled:!b,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"})})})]})]},v.key))})}function L1(t,e){if(!e)return!0;for(const n of t)if(n.type==="container"&&(n.id===e||L1(n.items,e)))return!0;return!1}function D1(t,e){for(const n of t){if(n.type==="doc"&&n.file===e)return[];if(n.type==="container"){const r=D1(n.items,e);if(r)return[n.id,...r]}}return null}function uD({docs:t,archivedDocs:e,workspaces:n,assignedFiles:r,pendingDocs:s,onSwitchDocument:i,onCreateDocument:l,actions:c,scrollRef:d,writingTitle:f,writingTarget:p,searchQuery:m,searchResults:y,onSearchChange:b}){const[v,k]=E.useState(null),[w,N]=E.useState(""),[C,O]=E.useState(null),[_,M]=E.useState(()=>{try{const ne=localStorage.getItem("ow-collapsed-sections");return ne?new Set(JSON.parse(ne)):new Set}catch{return new Set}}),[R,D]=E.useState(null),[F,B]=E.useState(null),[V,q]=E.useState(""),[Y,le]=E.useState(null),[W,$]=E.useState(""),[U,te]=E.useState(null),[H,Z]=E.useState(""),[G,A]=E.useState(null),[j,Q]=E.useState(null),[se,fe]=E.useState([]),[ee,me]=E.useState(null),[Le,Xe]=E.useState(null),[ce,be]=E.useState(null),[ie,Be]=E.useState(null),{draggedItem:Te,dropIndicator:Fe,handlePointerDown:Ee,dropClass:Ye,isDragging:et,isContainerDropTarget:vt}=nD({docs:t,workspaces:n,assignedFiles:r,scrollRef:d,setCollapsedSections:M}),Ce=E.useCallback(()=>{fetch("/api/plugins").then(ne=>ne.json()).then(ne=>{const Ue=[];for(const He of ne.plugins||[]){const _t=He.displayName||void 0;for(const tt of He.sidebarMenuItems||[])Ue.push({...tt,pluginDisplayName:_t})}fe(Ue)}).catch(()=>{})},[]);E.useEffect(()=>{Ce()},[Ce]),E.useEffect(()=>{const ne=()=>Ce();return window.addEventListener("ow-plugins-changed",ne),()=>window.removeEventListener("ow-plugins-changed",ne)},[Ce]);const we=E.useCallback((ne,Ue)=>{ne.preventDefault(),ne.stopPropagation(),A({x:ne.clientX,y:ne.clientY,filename:Ue.filename,title:Ue.title,docId:Ue.docId,lastSent:Ue.lastSent,postedUrl:Ue.postedUrl})},[]),it=E.useCallback(ne=>{fetch("/api/documents/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:ne})}).catch(()=>{})},[]),ut=E.useCallback((ne,Ue,He,_t,tt)=>{if(Ue.promptForFocus&&tt===void 0){me({action:ne,label:Ue.label,filename:He,title:_t});return}fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:ne,filename:He,title:_t,instructions:tt||"",label:Ue.label})}).catch(()=>{})},[]),rt=ne=>{M(Ue=>{const He=new Set(Ue);return He.has(ne)?He.delete(ne):He.add(ne),localStorage.setItem("ow-collapsed-sections",JSON.stringify([...He])),He})},ht=t.find(ne=>ne.isActive),zt=E.useRef(n);if(zt.current=n,E.useEffect(()=>{var ne;if(ht)for(const Ue of zt.current){const He=D1(((ne=Ue.workspace)==null?void 0:ne.root)||[],ht.filename);if(He){M(_t=>{const tt=[Ue.filename,...He.map(Ge=>`container-${Ge}`)];if(tt.every(Ge=>!_t.has(Ge)))return _t;const st=new Set(_t);for(const Ge of tt)st.delete(Ge);return localStorage.setItem("ow-collapsed-sections",JSON.stringify([...st])),st});break}}},[ht==null?void 0:ht.filename]),y!==null)return u.jsx(Em,{results:y,query:m,onSwitchDocument:i,actions:c});const Ct=t.filter(ne=>!r.has(ne.filename)),Vt=(ne,Ue,He,_t,tt)=>u.jsxs("div",{className:`sidebar-item ${ne.isActive?"active":""} ${et(ne.filename)?"dragging":""} ${Ye(ne.filename)}`,"data-drag-id":ne.filename,"data-drag-type":"doc","data-drag-ws":Ue||"__docs__","data-drag-container":He||"",onPointerDown:st=>Ee(st,{type:"doc",file:ne.filename,sourceWs:Ue||null},ne.title),onClick:()=>!ne.isActive&&!Te&&i(ne.filename),onDoubleClick:()=>{k(ne.filename),N(ne.title)},onContextMenu:st=>we(st,ne),children:[v===ne.filename?u.jsx("input",{className:"sidebar-rename-input",value:w,onChange:st=>N(st.target.value),onBlur:()=>{c.handleRename(ne.filename,ne.title,w),k(null)},onKeyDown:st=>{st.key==="Enter"&&(c.handleRename(ne.filename,ne.title,w),k(null)),st.key==="Escape"&&k(null)},autoFocus:!0,onClick:st=>st.stopPropagation()}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-item-title-text",children:ne.title}),ne.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"})}),s.filenames.includes(ne.filename)&&u.jsx("span",{className:"sidebar-pending-dot"})]}),bp(ne.filename)&&u.jsx("div",{className:"sidebar-item-context",children:j1(ne.filename)}),u.jsxs("div",{className:"sidebar-item-meta",children:[ne.wordCount.toLocaleString()," words · ",Mo(ne.lastModified)]}),u.jsxs("div",{className:"sidebar-tags",children:[c.getDocTags(ne.filename).map(st=>u.jsxs("span",{className:"sidebar-tag",onClick:Ge=>Ge.stopPropagation(),children:[st,u.jsx("span",{className:"sidebar-tag-remove",onClick:Ge=>{Ge.stopPropagation(),c.handleRemoveTag(ne.filename,st)},children:"×"})]},st)),U===ne.filename?u.jsx("input",{className:"sidebar-tag-input",value:H,onChange:st=>Z(st.target.value),onBlur:()=>{H.trim()&&c.handleAddTag(ne.filename,H),te(null)},onKeyDown:st=>{st.key==="Enter"&&(c.handleAddTag(ne.filename,H),te(null),Z("")),st.key==="Escape"&&(te(null),Z(""))},autoFocus:!0,onClick:st=>st.stopPropagation(),placeholder:"tag..."}):u.jsx("button",{className:"sidebar-tag-add",onClick:st=>{st.stopPropagation(),te(ne.filename),Z("")},children:"+"})]})]}),C===ne.filename?u.jsxs("div",{className:"sidebar-confirm-delete",onClick:st=>st.stopPropagation(),children:[u.jsx("span",{children:"Delete?"}),u.jsx("button",{onClick:()=>{c.handleDelete(ne.filename),O(null)},children:"Yes"}),u.jsx("button",{onClick:()=>O(null),children:"No"})]}):u.jsx("button",{className:"sidebar-delete-btn",onClick:st=>{st.stopPropagation(),O(ne.filename)},title:"Delete document",children:"×"})]},ne.filename),vn=(ne,Ue,He,_t,tt,st)=>{if(ne.type==="doc"){const re=t.find(ke=>ke.filename===ne.file);return re?Vt(re,He,_t):bp(ne.file)?u.jsx("div",{className:"sidebar-item sidebar-unavailable",children:u.jsxs("div",{className:"sidebar-item-title",children:[ne.title||ne.file," (unavailable)"]})},ne.file):u.jsxs("div",{className:"sidebar-item sidebar-missing",children:[u.jsxs("div",{className:"sidebar-item-title",children:[ne.title||ne.file," (missing)"]}),u.jsx("button",{className:"sidebar-delete-btn",onClick:()=>c.handleRemoveFromWorkspace(He,ne.file),title:"Remove",children:"×"})]},ne.file)}const Ge=ne,Wn=`container-${Ge.id}`,cn=_.has(Wn),Tn=Ue<=2?`depth-${Ue}`:"depth-2";return u.jsxs("div",{className:`sidebar-container ${Tn} ${cn?"collapsed":""} ${Ye(Ge.id)} ${vt(Ge.id)?"drop-inside":""}`,children:[u.jsxs("div",{className:`sidebar-container-header ${(Fe==null?void 0:Fe.itemId)===Ge.id&&Fe.position==="inside"?"drop-inside":""}`,"data-drag-id":Ge.id,"data-drag-type":"container-header","data-drag-ws":He,"data-drag-parent":_t||"","data-section-key":Wn,onPointerDown:re=>Ee(re,{type:"container",id:Ge.id,sourceWs:He},Ge.name),onClick:()=>!Te&&rt(Wn),children:[u.jsx("span",{className:`sidebar-chevron ${cn?"collapsed":""}`,children:"▾"}),F===Ge.id?u.jsx("input",{className:"sidebar-rename-input",value:V,onChange:re=>q(re.target.value),onBlur:()=>{c.handleRenameContainer(He,Ge.id,V),B(null)},onKeyDown:re=>{re.key==="Enter"&&(c.handleRenameContainer(He,Ge.id,V),B(null)),re.key==="Escape"&&B(null)},autoFocus:!0,onClick:re=>re.stopPropagation()}):u.jsx("span",{className:"sidebar-container-name",onDoubleClick:re=>{re.stopPropagation(),B(Ge.id),q(Ge.name)},children:Ge.name}),u.jsxs("div",{className:"sidebar-container-actions",children:[u.jsx("button",{className:"sidebar-new-btn",onClick:re=>{re.stopPropagation(),Be({anchor:re.target.getBoundingClientRect(),wsFilename:He,containerId:Ge.id})},title:"New doc",children:"+"}),Ue<2&&u.jsx("button",{className:"sidebar-new-btn",onClick:re=>{re.stopPropagation(),c.handleCreateContainer(He,Ge.id)},title:"New sub-container",children:"☐"}),u.jsx("button",{className:"sidebar-new-btn sidebar-container-delete",onClick:re=>{re.stopPropagation(),c.handleDeleteContainer(He,Ge.id)},title:"Delete container",children:"×"})]})]}),!cn&&u.jsxs("div",{className:"sidebar-container-list","data-drop-ws":He,"data-drop-container":Ge.id,children:[f&&(p==null?void 0:p.wsFilename)===He&&p.containerId===Ge.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..."})]}),(f&&(p==null?void 0:p.wsFilename)===He&&p.containerId===Ge.id?Ge.items.filter(re=>re.type!=="doc"||re.title!==f):Ge.items).map((re,ke)=>vn(re,Ue+1,He,Ge.id,Ge.items)),Ge.items.length===0&&!f&&u.jsx("div",{className:"sidebar-empty",children:Te?"Drop here":"Empty"})]})]},Ge.id)};return u.jsxs("div",{className:"sidebar-scroll",ref:d,children:[u.jsxs("div",{className:`sidebar-section sidebar-docs-section ${_.has("docs")?"docs-collapsed":""}`,children:[u.jsxs("div",{className:"sidebar-section-header","data-section-key":"docs",onClick:()=>rt("docs"),children:[u.jsx("span",{className:`sidebar-chevron ${_.has("docs")?"collapsed":""}`,children:"▾"}),u.jsx("span",{className:"sidebar-label",children:"Documents"}),u.jsx("button",{className:"sidebar-new-btn",onClick:ne=>{ne.stopPropagation(),Be({anchor:ne.target.getBoundingClientRect()})},title:"New document",children:"+"})]}),!_.has("docs")&&u.jsxs("div",{className:"sidebar-section-list","data-drop-ws":"__docs__",children:[f&&(!p||!n.some(ne=>ne.filename===(p==null?void 0:p.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..."})]}),(f?Ct.filter(ne=>ne.title!==f):Ct).map((ne,Ue)=>(Ct.map(He=>({type:"doc",file:He.filename,title:He.title})),Vt(ne,void 0,null))),Ct.length===0&&u.jsx("div",{className:"sidebar-empty",children:Te?"Drop here to unassign":"No unassigned documents"})]})]}),n.map(ne=>{var _t;const Ue=((_t=ne.workspace)==null?void 0:_t.root)||[],He=_.has(ne.filename);return u.jsxs("div",{className:`sidebar-section sidebar-workspace-section ${He?"ws-collapsed":""} ${et(ne.filename)?"dragging":""} ${(Fe==null?void 0:Fe.itemId)===ne.filename?Fe.position==="before"?"drop-before":"drop-after":""}`,children:[u.jsxs("div",{className:"sidebar-section-header","data-section-key":ne.filename,"data-ws-drag":ne.filename,onPointerDown:tt=>Ee(tt,{type:"workspace",filename:ne.filename},ne.title),onClick:()=>!Te&&rt(ne.filename),children:[u.jsx("span",{className:`sidebar-chevron ${He?"collapsed":""}`,children:"▾"}),Y===ne.filename?u.jsx("input",{className:"sidebar-rename-input",value:W,onChange:tt=>$(tt.target.value),onBlur:()=>{c.handleRenameWorkspace(ne.filename,W),le(null)},onKeyDown:tt=>{tt.key==="Enter"&&(c.handleRenameWorkspace(ne.filename,W),le(null)),tt.key==="Escape"&&le(null)},autoFocus:!0,onClick:tt=>tt.stopPropagation()}):u.jsx("span",{className:"sidebar-label sidebar-workspace-label",onDoubleClick:tt=>{tt.stopPropagation(),le(ne.filename),$(ne.title)},children:ne.title}),u.jsxs("div",{className:"sidebar-workspace-actions",children:[u.jsx("button",{className:"sidebar-new-btn",onClick:tt=>{tt.stopPropagation(),Be({anchor:tt.target.getBoundingClientRect(),wsFilename:ne.filename,containerId:null})},title:"New document",children:"+"}),u.jsx("button",{className:"sidebar-new-btn",onClick:tt=>{tt.stopPropagation(),c.handleCreateContainer(ne.filename,null)},title:"New container",children:"☐"}),R===ne.filename?u.jsxs("span",{className:"sidebar-inline-confirm",onClick:tt=>tt.stopPropagation(),children:[u.jsx("button",{onClick:()=>{c.handleDeleteWorkspace(ne.filename),D(null)},children:"Yes"}),u.jsx("button",{onClick:()=>D(null),children:"No"})]}):u.jsx("button",{className:"sidebar-new-btn sidebar-workspace-delete",onClick:tt=>{tt.stopPropagation(),D(ne.filename)},title:"Delete workspace",children:"×"})]})]}),!He&&u.jsxs("div",{className:"sidebar-section-list","data-drop-ws":ne.filename,children:[f&&(p==null?void 0:p.wsFilename)===ne.filename&&(p.containerId===null||!L1(Ue,p.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..."})]}),(f&&(p==null?void 0:p.wsFilename)===ne.filename&&p.containerId===null?Ue.filter(tt=>tt.type!=="doc"||tt.title!==f):Ue).map((tt,st)=>vn(tt,0,ne.filename,null)),Ue.length===0&&!f&&u.jsx("div",{className:"sidebar-empty",children:Te?"Drop here to add":"Empty workspace"})]})]},ne.filename)}),u.jsx("div",{className:"sidebar-new-workspace",children:u.jsx("button",{onClick:c.handleCreateWorkspace,children:"+ New Workspace"})}),G&&u.jsx(rD,{x:G.x,y:G.y,filename:G.filename,title:G.title,onClose:()=>A(null),onDuplicate:()=>it(G.filename),onRename:()=>{k(G.filename),N(G.title)},onArchive:()=>c.handleArchive(G.filename),onDelete:()=>c.handleDelete(G.filename),onPluginAction:(ne,Ue)=>ut(ne,Ue,G.filename,G.title),pluginItems:se,onNewsletterSend:ne=>{Xe({connectionId:ne,filename:G.filename,title:G.title}),A(null)},onSchedulePost:()=>{be({filename:G.filename,title:G.title}),A(null)},onViewAnalytics:G.docId&&G.lastSent?()=>{G.postedUrl?window.open(G.postedUrl,"_blank"):Q({docId:G.docId,title:G.title}),A(null)}:void 0,viewAnalyticsLabel:G.postedUrl?"View on X":"View Analytics",isAlreadySent:!!G.lastSent,onMarkSent:()=>{const ne=G.filename;i(ne),setTimeout(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualPost:{postedAt:new Date().toISOString()}})}).then(()=>c.fetchDocs()).catch(()=>{})},100),A(null)}}),ee&&u.jsx(sD,{actionLabel:ee.label,docTitle:ee.title,onClose:()=>me(null),onConfirm:ne=>{const Ue=se.find(He=>He.action===ee.action);Ue&&ut(ee.action,Ue,ee.filename,ee.title,ne),me(null)}}),Le&&u.jsx(I1,{connectionId:Le.connectionId,subject:Le.title,filename:Le.filename,onClose:()=>Xe(null)}),j&&u.jsx(iD,{docId:j.docId,title:j.title,onClose:()=>Q(null)}),ce&&u.jsx(rd,{filename:ce.filename,title:ce.title,onClose:()=>be(null)}),ie&&u.jsx(cD,{anchorRect:ie.anchor,onClose:()=>Be(null),onSelect:ne=>{Be(null),ie.wsFilename?c.handleCreateInWorkspace(ie.wsFilename,ie.containerId??null,ne):ne?fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:ne})}).catch(()=>{}):l()}})]})}function dD({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,onCreateDocument:i,actions:l,scrollRef:c,searchQuery:d,searchResults:f}){const[p,m]=E.useState(null);if(f!==null)return u.jsx(Em,{results:f,query:d,onSwitchDocument:s});const y=[...t].sort((w,N)=>new Date(N.lastModified).getTime()-new Date(w.lastModified).getTime()),b=[];let v="";for(const w of y){const N=ZL(w.lastModified);N!==v&&(b.push({label:N,docs:[]}),v=N),b[b.length-1].docs.push(w)}const k=w=>{for(const N of e){if(!N.workspace)continue;const C=O=>{for(const _ of O)if(_.type==="doc"&&_.file===w||_.type==="container"&&C(_.items))return!0;return!1};if(C(N.workspace.root))return N.title}return null};return u.jsxs("div",{className:"sidebar-scroll tl-scroll",ref:c,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:"+"})]}),b.map(w=>u.jsxs("div",{className:"tl-group",children:[u.jsx("div",{className:"tl-date",children:w.label}),w.docs.map(N=>{const C=k(N.filename);return u.jsxs("div",{className:`tl-item ${N.isActive?"active":""}`,onClick:()=>!N.isActive&&s(N.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:N.title}),r.filenames.includes(N.filename)&&u.jsx("span",{className:"sidebar-pending-dot"})]}),bp(N.filename)&&u.jsx("div",{className:"tl-item-context",children:j1(N.filename)}),u.jsxs("div",{className:"tl-item-meta",children:[N.wordCount.toLocaleString()," words · ",Mo(N.lastModified)]}),C&&u.jsx("div",{className:"tl-badge",children:C})]}),p===N.filename?u.jsxs("div",{className:"sidebar-confirm-delete",onClick:O=>O.stopPropagation(),children:[u.jsx("span",{children:"Delete?"}),u.jsx("button",{onClick:()=>{l.handleDelete(N.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(N.filename)},title:"Delete",children:"×"})]},N.filename)})]},w.label)),t.length===0&&u.jsx("div",{className:"sidebar-empty",children:"No documents yet"})]})}function fD({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:l,searchQuery:c,searchResults:d,onSearchChange:f}){const[p,m]=E.useState([]),[y,b]=E.useState(null),[v,k]=E.useState(null),w=E.useRef(null);E.useEffect(()=>{if(!y)return;const A=j=>{w.current&&!w.current.contains(j.target)&&b(null)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[y]);const N=(A,j)=>{for(const Q of A)if(Q.type==="container"){if(Q.id===j)return Q;const se=N(Q.items,j);if(se)return se}return null},C=A=>{let j=0;for(const Q of A)Q.type==="doc"?j++:Q.type==="container"&&(j+=C(Q.items));return j},O=A=>{const j=[];for(const Q of A)Q.type==="doc"?j.push(Q.file):Q.type==="container"&&j.push(...O(Q.items));return j},_=E.useMemo(()=>{if(p.length===0)return[];const A=p[p.length-1],j=e.find(se=>se.filename===A.wsFilename);if(!(j!=null&&j.workspace))return[];if(A.type==="workspace")return j.workspace.root;const Q=N(j.workspace.root,A.key);return Q?Q.items:[]},[p,e]),M=_.filter(A=>A.type==="container"),R=E.useMemo(()=>{const A=_.filter(j=>j.type==="doc").map(j=>j.file);return t.filter(j=>A.includes(j.filename))},[_,t]),D=A=>{const j=O(A.items);return t.filter(Q=>j.includes(Q.filename))},F=A=>{const j=e.find(se=>se.filename===A);if(!(j!=null&&j.workspace))return[];const Q=O(j.workspace.root);return t.filter(se=>Q.includes(se.filename))},B=E.useMemo(()=>t.filter(A=>!n.has(A.filename)),[t,n]),V=A=>{m(j=>[...j,A]),b(null)},q=()=>{m(A=>A.slice(0,-1)),b(null)},Y=(A,j)=>{if(y===A){b(null);return}const se=j.currentTarget.getBoundingClientRect();k({top:se.bottom+4,left:se.left}),b(A)},le=A=>{s(A),b(null)},W=p.length>1?p[p.length-2].title:"All",$=E.useRef(null),U=E.useRef(null),[te,H]=E.useState(null),Z=E.useCallback(A=>{const Q=A.currentTarget.getBoundingClientRect();H({top:Q.bottom+4,left:Q.left})},[]);E.useEffect(()=>{if(!d)return;const A=j=>{U.current&&!U.current.contains(j.target)&&$.current&&!$.current.contains(j.target)&&f("")};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[d,f]);const G=()=>{if(!y)return[];if(y==="__unassigned__")return B;if(y==="__level-docs__")return R;const A=e.find(j=>j.filename===y);if(A)return F(A.filename);for(const j of e){if(!j.workspace)continue;const Q=N(j.workspace.root,y);if(Q)return D(Q)}return[]};return u.jsxs("div",{className:"board-scroll",ref:l,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:$,className:"board-search-input",type:"text",placeholder:"Search...",value:c,onChange:A=>f(A.target.value),onFocus:Z}),c&&u.jsx("button",{className:"board-search-clear",onClick:()=>f(""),children:"×"})]}),p.length===0?u.jsx("button",{className:"board-back board-back--static",tabIndex:-1,children:"All"}):u.jsxs("button",{className:"board-back",onClick:q,title:`Back to ${W}`,children:["← ",W]}),p.length===0&&u.jsxs(u.Fragment,{children:[B.length>0&&u.jsxs("button",{className:`board-chip ${y==="__unassigned__"?"open":""}`,onClick:A=>Y("__unassigned__",A),children:["Documents ",u.jsx("span",{className:"board-chip-count",children:B.length})]}),e.map(A=>{var Q;const j=(Q=A.workspace)==null?void 0:Q.root.some(se=>se.type==="container");return u.jsxs("button",{className:`board-chip ${y===A.filename?"open":""}`,onClick:se=>j?V({type:"workspace",key:A.filename,title:A.title,wsFilename:A.filename}):Y(A.filename,se),children:[A.title," ",u.jsx("span",{className:"board-chip-count",children:A.docCount}),j&&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:"+"})]}),p.length>0&&u.jsxs(u.Fragment,{children:[R.length>0&&u.jsxs("button",{className:`board-chip board-chip-docs ${y==="__level-docs__"?"open":""}`,onClick:A=>Y("__level-docs__",A),children:["Docs ",u.jsx("span",{className:"board-chip-count",children:R.length})]}),M.map(A=>{const j=A.items.some(Q=>Q.type==="container");return u.jsxs("button",{className:`board-chip ${y===A.id?"open":""}`,onClick:Q=>j?V({type:"container",key:A.id,title:A.name,wsFilename:p[p.length-1].wsFilename}):Y(A.id,Q),children:[A.name," ",u.jsx("span",{className:"board-chip-count",children:C(A.items)}),j&&u.jsx("span",{className:"board-chip-arrow",children:"›"})]},A.id)})]}),y&&v&&(()=>{const A=G();return u.jsxs("div",{className:"board-dropdown",ref:w,style:{position:"fixed",top:v.top,left:v.left},children:[A.map(j=>u.jsxs("div",{className:`board-dropdown-item ${j.isActive?"active":""}`,onClick:()=>le(j.filename),children:[u.jsxs("span",{className:"board-dropdown-title",children:[j.title,r.filenames.includes(j.filename)&&u.jsx("span",{className:"board-pending-dot"})]}),u.jsxs("span",{className:"board-dropdown-meta",children:[j.wordCount.toLocaleString()," words · ",Mo(j.lastModified)]})]},j.filename)),A.length===0&&u.jsx("div",{className:"board-dropdown-empty",children:"No documents"})]})})(),d&&te&&u.jsxs("div",{className:"board-dropdown board-search-dropdown",ref:U,style:{position:"fixed",top:te.top,left:te.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 · ",Mo(A.lastModified)]})]},A.filename)),d.length===0&&u.jsx("div",{className:"board-dropdown-empty",children:"No results"})]})]})}function hD({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:l,searchQuery:c,searchResults:d}){const[f,p]=E.useState([]);if(d!==null)return u.jsx(Em,{results:d,query:c,onSwitchDocument:s});const m=(_,M)=>{for(const R of _)if(R.type==="container"){if(R.id===M)return R;const D=m(R.items,M);if(D)return D}return null},y=_=>{let M=0;for(const R of _)R.type==="doc"?M++:R.type==="container"&&(M+=y(R.items));return M},b=E.useMemo(()=>{if(f.length===0)return[];const _=f[f.length-1],M=e.find(D=>D.filename===_.wsFilename);if(!(M!=null&&M.workspace))return[];if(_.type==="workspace")return M.workspace.root;const R=m(M.workspace.root,_.key);return R?R.items:[]},[f,e]),v=b.filter(_=>_.type==="container"),k=E.useMemo(()=>{if(f.length===0)return t.filter(M=>!n.has(M.filename));const _=b.filter(M=>M.type==="doc").map(M=>M.file);return t.filter(M=>_.includes(M.filename))},[f,b,t,n]),w=_=>p(M=>[...M,_]),N=()=>p(_=>_.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:l,children:[f.length>0&&u.jsxs("button",{className:"shelf-back",onClick:N,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:()=>w({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&&v.map(_=>u.jsxs("div",{className:"shelf-section-spine shelf-section-container",onClick:()=>w({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:y(_.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:[k.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 · ",Mo(_.lastModified)]})]},_.filename)),k.length===0&&u.jsx("div",{className:"shelf-docs-empty",children:"No documents"})]})]})]})}const pD=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],mD=[{value:"any",label:"Any"},{value:"content_type",label:"Content Type"},{value:"connection",label:"Connection"}];function gD({slots:t,onBack:e}){const[n,r]=E.useState(t),[s,i]=E.useState("09:00"),[l,c]=E.useState(["default"]),[d,f]=E.useState("any"),[p,m]=E.useState(!1);async function y(){const k=await fetch("/api/scheduler/slots",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({time:s,days:l.includes("default")?["default"]:l,filter_type:d})});if(k.ok){const w=await k.json();r(N=>[...N,w.slot]),m(!1),i("09:00"),c(["default"]),f("any")}}async function b(k){(await fetch(`/api/scheduler/slots/${k}`,{method:"DELETE"})).ok&&r(N=>N.filter(C=>C.id!==k))}function v(k){c(w=>{if(k==="default")return["default"];const N=w.filter(C=>C!=="default");if(N.includes(k)){const C=N.filter(O=>O!==k);return C.length===0?["default"]:C}return[...N,k]})}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:()=>m(!p),children:p?"Cancel":"+ Add"})]}),p&&u.jsxs("div",{style:{padding:"12px",borderBottom:"1px solid var(--sidebar-border)"},children:[u.jsxs("div",{style:{display:"flex",gap:"8px",marginBottom:"8px",alignItems:"center"},children:[u.jsx("input",{type:"time",value:s,onChange:k=>i(k.target.value),style:{background:"var(--sidebar-bg)",border:"1px solid var(--sidebar-border)",borderRadius:"4px",padding:"4px 8px",color:"var(--sidebar-text)",fontSize:"12px"}}),u.jsx("select",{value:d,onChange:k=>f(k.target.value),style:{background:"var(--sidebar-bg)",border:"1px solid var(--sidebar-border)",borderRadius:"4px",padding:"4px 8px",color:"var(--sidebar-text)",fontSize:"12px"},children:mD.map(k=>u.jsx("option",{value:k.value,children:k.label},k.value))})]}),u.jsxs("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginBottom:"8px"},children:[u.jsx("button",{className:`sidebar-schedule-btn ${l.includes("default")?"sidebar-schedule-btn--active":""}`,onClick:()=>v("default"),style:{fontSize:"10px",padding:"2px 6px"},children:"Every day"}),pD.map(k=>u.jsx("button",{className:`sidebar-schedule-btn ${l.includes(k.toLowerCase())?"sidebar-schedule-btn--active":""}`,onClick:()=>v(k.toLowerCase()),style:{fontSize:"10px",padding:"2px 6px"},children:k},k))]}),u.jsx("button",{className:"sidebar-schedule-btn sidebar-schedule-btn--active",onClick:y,style:{width:"100%"},children:"Create Slot"})]}),u.jsx("div",{style:{flex:1,overflow:"auto"},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(k=>u.jsxs("div",{className:"schedule-item",style:{cursor:"default"},children:[u.jsx("div",{className:"schedule-item-time",style:{width:"60px",fontWeight:600},children:yD(k.time)}),u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:k.days.includes("default")?"Every day":k.days.join(", ")}),u.jsxs("div",{className:"schedule-item-meta",children:[u.jsxs("span",{children:["Filter: ",k.filter_type]}),k.filter_value&&u.jsxs("span",{children:["(",k.filter_value,")"]}),u.jsx("span",{children:k.timezone})]})]}),u.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:()=>b(k.id),title:"Delete slot",style:{alignSelf:"center"},children:"×"})]},k.id))})]})}function yD(t){const[e,n]=t.split(":").map(Number),r=e>=12?"PM":"AM";return`${e%12||12}:${String(n).padStart(2,"0")} ${r}`}function bD({onBack:t}){const[e,n]=E.useState([]),[r,s]=E.useState([]),[i,l]=E.useState(null),[c,d]=E.useState(!1),[f,p]=E.useState(!0),m=E.useCallback(async()=>{try{const[N,C]=await Promise.all([fetch("/api/scheduler/autoplugs/goals"),fetch("/api/scheduler/autoplugs/tracking")]);if(N.ok){const O=await N.json();n(O.goals||[])}if(C.ok){const O=await C.json();s(O.tracking||[])}}catch{}p(!1)},[]);E.useEffect(()=>{m()},[m]);const y=async N=>{(await fetch(`/api/scheduler/autoplugs/goals/${N.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!N.enabled})})).ok&&n(O=>O.map(_=>_.id===N.id?{..._,enabled:!_.enabled}:_))},b=async N=>{(await fetch(`/api/scheduler/autoplugs/goals/${N}`,{method:"DELETE"})).ok&&(n(O=>O.filter(_=>_.id!==N)),l(null))},v=async N=>{(await fetch(`/api/scheduler/autoplugs/tracking/${N}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({skipped:!0})})).ok&&s(O=>O.map(_=>_.id===N?{..._,skipped:!0}:_))},k=e.reduce((N,C)=>C.rule&&C.enabled?Math.min(N,C.rule.threshold):N,1/0),w=k===1/0?50:k;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(!c),children:c?"Cancel":"+ Add"})]}),c&&u.jsx(vD,{onCreated:N=>{n(C=>[...C,N]),d(!1)}}),f?null:u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"autoplug-section-header",children:"Goals"}),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(N=>u.jsxs("div",{children:[u.jsxs("div",{className:"schedule-item",onClick:()=>l(i===N.id?null:N.id),children:[u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:N.name}),N.link&&u.jsx("div",{className:"autoplug-goal-summary",children:N.link}),u.jsxs("div",{className:"schedule-item-meta",children:[N.rule&&u.jsxs(u.Fragment,{children:[u.jsxs("span",{children:[N.rule.threshold,"+ ",N.rule.metric]}),u.jsx("span",{children:N.rule.mode.toUpperCase()}),u.jsxs("span",{children:[N.rule.delay_minutes,"m delay"]})]}),u.jsxs("span",{children:[N.pool_count," pool msg",N.pool_count!==1?"s":""]})]})]}),u.jsx("button",{className:`autoplug-toggle ${N.enabled?"autoplug-toggle--on":"autoplug-toggle--off"}`,onClick:C=>{C.stopPropagation(),y(N)},title:N.enabled?"Disable":"Enable"})]}),i===N.id&&u.jsx(xD,{goal:N,onSaved:C=>{n(O=>O.map(_=>_.id===C.id?C:_))},onDeleted:()=>b(N.id),onRefresh:m})]},N.id)),u.jsx("div",{className:"autoplug-section-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(N=>u.jsxs("div",{className:"autoplug-tracking-item",children:[u.jsxs("div",{className:"autoplug-tracking-header",children:[u.jsx("div",{className:"autoplug-tracking-text",children:N.original_text||`Tweet ${N.tweet_id}`}),!N.triggered&&!N.skipped&&u.jsx("button",{className:"autoplug-tracking-skip",onClick:()=>v(N.id),title:"Skip autoplug for this tweet",children:"×"})]}),u.jsxs("div",{className:"autoplug-tracking-meta",children:[u.jsx("span",{children:kD(N.posted_at)}),u.jsxs("span",{children:[N.likes," likes"]}),u.jsxs("span",{children:[N.retweets," RTs"]}),N.views>0&&u.jsxs("span",{children:[wD(N.views)," views"]}),u.jsx("span",{children:N.source})]}),N.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 ",N.goal_name?`→ ${N.goal_name}`:""]}):N.skipped?u.jsx("div",{style:{fontSize:"10px",color:"var(--sidebar-text-secondary)",opacity:.6},children:"Skipped"}):u.jsx("div",{className:"autoplug-tracking-bar",children:u.jsx("div",{className:"autoplug-tracking-bar-fill",style:{width:`${Math.min(100,N.likes/w*100)}%`}})})]},N.id))]})]})}function vD({onCreated:t}){const[e,n]=E.useState(""),[r,s]=E.useState(""),[i,l]=E.useState(""),[c,d]=E.useState("likes"),[f,p]=E.useState(50),[m,y]=E.useState(30),[b,v]=E.useState("static"),[k,w]=E.useState(!1),N=async()=>{if(e.trim()){w(!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){w(!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:c,threshold:f,delay_minutes:m,mode:b})});const _=await fetch("/api/scheduler/autoplugs/goals");if(_.ok){const R=((await _.json()).goals||[]).find(D=>D.id===O.id);if(R){t(R);return}}t({...O,rule_count:1,pool_count:0,rule:{metric:c,threshold:f,delay_minutes:m,mode:b,id:""}})}finally{w(!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=>l(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=>p(Number(C.target.value)),min:1}),u.jsxs("select",{value:c,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",{style:{fontSize:"11px",color:"var(--sidebar-text-secondary)"},children:"wait"}),u.jsx("input",{type:"number",value:m,onChange:C=>y(Number(C.target.value)),min:0,style:{width:"50px"}}),u.jsx("span",{style:{fontSize:"11px",color:"var(--sidebar-text-secondary)"},children:"min"})]}),u.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map(C=>u.jsx("button",{className:b===C?"active":"",onClick:()=>v(C),children:C==="llm"?"LLM":C.charAt(0).toUpperCase()+C.slice(1)},C))}),u.jsx("button",{className:"sidebar-schedule-btn sidebar-schedule-btn--active",onClick:N,disabled:k||!e.trim(),style:{width:"100%"},children:k?"Creating...":"Create Goal"})]})}function xD({goal:t,onSaved:e,onDeleted:n,onRefresh:r}){var q,Y,le,W;const[s,i]=E.useState(t.name),[l,c]=E.useState(t.link||""),[d,f]=E.useState(t.description||""),[p,m]=E.useState(((q=t.rule)==null?void 0:q.metric)||"likes"),[y,b]=E.useState(((Y=t.rule)==null?void 0:Y.threshold)||50),[v,k]=E.useState(((le=t.rule)==null?void 0:le.delay_minutes)||30),[w,N]=E.useState(((W=t.rule)==null?void 0:W.mode)||"static"),[C,O]=E.useState([]),[_,M]=E.useState(""),[R,D]=E.useState(!1);E.useEffect(()=>{fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`).then($=>$.json()).then($=>O($.pool||[])).catch(()=>{})},[t.id]);const F=async()=>{var $;D(!0);try{await fetch(`/api/scheduler/autoplugs/goals/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s,link:l||null,description:d||null})}),($=t.rule)!=null&&$.id?await fetch(`/api/scheduler/autoplugs/rules/${t.rule.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({metric:p,threshold:y,delay_minutes:v,mode:w})}):await fetch("/api/scheduler/autoplugs/rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({goal_id:t.id,metric:p,threshold:y,delay_minutes:v,mode:w})}),r()}finally{D(!1)}},B=async()=>{if(!_.trim())return;const $=await fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:_.trim()})});if($.ok){const U=await $.json();O(te=>[...te,U.message]),M("")}},V=async $=>{(await fetch(`/api/scheduler/autoplugs/pool/${$}`,{method:"DELETE"})).ok&&O(te=>te.filter(H=>H.id!==$))};return u.jsxs("div",{className:"autoplug-editor",children:[u.jsxs("label",{children:["Name",u.jsx("input",{value:s,onChange:$=>i($.target.value)})]}),u.jsxs("label",{children:["Link",u.jsx("input",{value:l,onChange:$=>c($.target.value),placeholder:"https://..."})]}),u.jsxs("label",{children:["Description",u.jsx("textarea",{value:d,onChange:$=>f($.target.value),rows:2})]}),u.jsx("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--sidebar-text-secondary)",textTransform:"uppercase",letterSpacing:"0.3px"},children:"Trigger"}),u.jsxs("div",{className:"autoplug-editor-row",children:[u.jsx("input",{type:"number",value:y,onChange:$=>b(Number($.target.value)),min:1}),u.jsxs("select",{value:p,onChange:$=>m($.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",{style:{fontSize:"11px",color:"var(--sidebar-text-secondary)"},children:"wait"}),u.jsx("input",{type:"number",value:v,onChange:$=>k(Number($.target.value)),min:0,style:{width:"50px"}}),u.jsx("span",{style:{fontSize:"11px",color:"var(--sidebar-text-secondary)"},children:"min"})]}),u.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map($=>u.jsx("button",{className:w===$?"active":"",onClick:()=>N($),children:$==="llm"?"LLM":$.charAt(0).toUpperCase()+$.slice(1)},$))}),u.jsxs("div",{className:"autoplug-pool-section",children:[u.jsx("div",{className:"autoplug-pool-label",children:"Static Pool"}),C.map($=>u.jsxs("div",{className:"autoplug-pool-item",children:[u.jsx("span",{children:$.content}),u.jsx("button",{onClick:()=>V($.id),title:"Remove",children:"×"})]},$.id)),u.jsxs("div",{className:"autoplug-pool-add",children:[u.jsx("input",{value:_,onChange:$=>M($.target.value),placeholder:"Add message... (use {{link}} for link)",onKeyDown:$=>$.key==="Enter"&&B()}),u.jsx("button",{onClick:B,children:"+"})]})]}),(w==="llm"||w==="hybrid")&&u.jsx("div",{style:{fontSize:"11px",color:"var(--sidebar-text-secondary)",padding:"4px 0"},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:"sidebar-schedule-btn sidebar-schedule-btn--active",onClick:F,disabled:R,children:R?"Saving...":"Save"}),u.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:n,children:"Delete"})]})]})}function kD(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 wD(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function SD({onBack:t}){const[e,n]=E.useState([]),[r,s]=E.useState([]),[i,l]=E.useState(!1),[c,d]=E.useState(!1),[f,p]=E.useState(null),[m,y]=E.useState(!0),b=E.useCallback(async()=>{try{const[w,N]=await Promise.all([fetch("/api/scheduler/queue"),fetch("/api/scheduler/slots")]);if(w.ok){const C=await w.json();n(C.items||[])}if(N.ok){const C=await N.json();s(C.slots||[])}}catch{}y(!1)},[]);E.useEffect(()=>{b()},[b]);const v=async w=>{(await fetch(`/api/scheduler/queue/${w}`,{method:"DELETE"})).ok&&(n(C=>C.filter(O=>O.id!==w)),p(null))};if(c)return u.jsx(bD,{onBack:()=>{d(!1),b()}});if(i)return u.jsx(gD,{slots:r,onBack:()=>{l(!1),b()}});const k=ED(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:()=>l(!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."})]}):k.map(({label:w,entries:N})=>u.jsxs("div",{className:"schedule-day",children:[u.jsx("div",{className:"schedule-day-header",children:w}),N.map((C,O)=>{var _,M,R,D,F;return C.type==="empty"?u.jsxs("div",{className:"schedule-slot-empty",children:[u.jsx("div",{className:"schedule-item-time",children:E0(C.time)}),u.jsx("div",{className:"schedule-slot-empty-label",children:((_=C.slot)==null?void 0:_.filter_type)==="any"?"Open slot":`${(M=C.slot)==null?void 0:M.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:()=>p(f===C.item.id?null:C.item.id),children:[u.jsx("div",{className:"schedule-item-time",children:E0(C.time)}),u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:((D=C.item.content)==null?void 0:D.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:((F=C.item.content)==null?void 0:F.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:()=>v(C.item.id),children:"Cancel"})})]})]},C.item.id)})]},w))]})}function ED(t,e){const n=new Date,r=[];for(let c=0;c<7;c++){const d=new Date(n);d.setDate(d.getDate()+c),d.setHours(0,0,0,0);let f;c===0?f="Today":c===1?f="Tomorrow":f=d.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}),r.push({label:f,date:d})}const s=new Map;for(const c of e){const d=new Date(c.scheduled_at),f=`${d.getFullYear()}-${d.getMonth()}-${d.getDate()}-${d.getHours()}-${d.getMinutes()}`;s.set(f,c)}const i=new Set,l=[];for(const{label:c,date:d}of r){const f=[],p=d.getDay(),y=["sun","mon","tue","wed","thu","fri","sat"][p];for(const b of t){if(!(b.days.includes("default")||b.days.includes(y)))continue;const[k,w]=b.time.split(":").map(Number),N=new Date(d);if(N.setHours(k,w,0,0),S0(d,n)&&N<n)continue;const C=`${N.getFullYear()}-${N.getMonth()}-${N.getDate()}-${k}-${w}`,O=s.get(C);O?(f.push({type:"filled",time:N,item:O,slot:b}),i.add(O.id)):f.push({type:"empty",time:N,slot:b})}for(const b of e){if(i.has(b.id))continue;const v=new Date(b.scheduled_at);S0(v,d)&&(f.push({type:"filled",time:v,item:b}),i.add(b.id))}f.sort((b,v)=>b.time.getTime()-v.time.getTime()),f.length>0&&l.push({label:c,entries:f})}return l}function S0(t,e){return t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate()}function E0(t){return t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function ND({profiles:t,activeProfile:e,trashedProfiles:n,onSwitch:r,onCreate:s,onDelete:i,onRestore:l}){const[c,d]=E.useState(!1),[f,p]=E.useState(!1),[m,y]=E.useState(""),[b,v]=E.useState(null),k=E.useRef(null),w=E.useRef(null);E.useEffect(()=>{if(!c)return;const C=O=>{k.current&&!k.current.contains(O.target)&&(d(!1),p(!1),y(""),v(null))};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[c]),E.useEffect(()=>{f&&w.current&&w.current.focus()},[f]);const N=()=>{const C=m.trim();C&&(s(C),y(""),p(!1))};return u.jsxs("div",{className:"sidebar-profile-wrapper",ref:k,children:[u.jsx("button",{className:"sidebar-collapse-btn",onClick:()=>d(!c),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"})]})}),c&&u.jsxs("div",{className:"sidebar-profile-dropdown",children:[t.map(C=>u.jsxs("div",{className:"sidebar-profile-row",children:[b===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),v(null)},children:"Yes"}),u.jsx("button",{onClick:()=>v(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&&b!==C&&u.jsx("button",{className:"sidebar-profile-delete-btn",onClick:O=>{O.stopPropagation(),v(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:()=>l(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:w,type:"text",value:m,onChange:C=>y(C.target.value),onKeyDown:C=>{C.key==="Enter"&&N(),C.key==="Escape"&&(p(!1),y(""))},placeholder:"Profile name..."})}):u.jsxs("button",{className:"sidebar-profile-option sidebar-profile-add",onClick:()=>p(!0),children:[u.jsx("span",{className:"sidebar-profile-check",children:"+"}),u.jsx("span",{children:"New Profile"})]})]})]})}const CD=[{id:"full",label:"Full",lines:3},{id:"compact",label:"Compact",lines:2},{id:"minimal",label:"Minimal",lines:1}];function _D(){const[t,e]=E.useState(!1),[n,r]=E.useState(V0),s=E.useRef(null);E.useEffect(()=>{if(!t)return;const l=c=>{s.current&&!s.current.contains(c.target)&&e(!1)};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[t]);const i=l=>{r(l),_E(l),e(!1)};return u.jsxs("div",{className:"sidebar-density-wrapper",ref:s,children:[u.jsx("button",{className:"sidebar-collapse-btn",onClick:()=>e(!t),title:"Card density",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:"M21 9H3"}),u.jsx("path",{d:"M21 15H3"})]})}),t&&u.jsx("div",{className:"sidebar-density-dropdown",children:CD.map(l=>u.jsxs("button",{className:`sidebar-density-option ${n===l.id?"active":""}`,onClick:()=>i(l.id),children:[u.jsx("span",{className:"sidebar-density-icon",children:Array.from({length:l.lines},(c,d)=>u.jsx("span",{className:"sidebar-density-line"},d))}),u.jsx("span",{children:l.label})]},l.id))})]})}function N0({open:t,onSwitchDocument:e,onCreateDocument:n,refreshKey:r,workspacesRefreshKey:s,pendingDocs:i,writingTitle:l,writingTarget:c,onClose:d}){const{docs:f,workspaces:p,assignedFiles:m,fetchDocs:y,scrollRef:b}=eD(r,s),v=tD(p,y,r),k=zu(),[w,N]=E.useState(!1),[C,O]=E.useState([]),[_,M]=E.useState("Default"),R=E.useCallback(async()=>{try{const se=await fetch("/api/profiles");if(se.ok){const fe=await se.json();O(fe.profiles),M(fe.active)}}catch{}},[]);E.useEffect(()=>{R()},[R]);const D=E.useCallback(async se=>{try{(await fetch("/api/profiles/switch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:se})})).ok&&(M(se),R())}catch{}},[R]),F=E.useCallback(async se=>{try{(await fetch("/api/profiles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:se})})).ok&&R()}catch{}},[R]),[B,V]=E.useState([]),q=E.useCallback(async()=>{try{const se=await fetch("/api/profiles/trash");if(se.ok){const fe=await se.json();V(fe.profiles)}}catch{}},[]);E.useEffect(()=>{q()},[q]);const Y=E.useCallback(async se=>{try{(await fetch(`/api/profiles/${encodeURIComponent(se)}`,{method:"DELETE"})).ok&&(R(),q())}catch{}},[R,q]),le=E.useCallback(async se=>{try{(await fetch("/api/profiles/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:se})})).ok&&(R(),q())}catch{}},[R,q]),[W,$]=E.useState(""),[U,te]=E.useState(null),H=E.useRef(),Z=E.useRef(null),G=E.useCallback(se=>{if($(se),H.current&&clearTimeout(H.current),!se.trim()){te(null);return}H.current=setTimeout(async()=>{try{const fe=await fetch(`/api/documents/search?q=${encodeURIComponent(se.trim())}&archived=true`);fe.ok&&te(await fe.json())}catch{}},250)},[]);E.useEffect(()=>()=>{H.current&&clearTimeout(H.current)},[]);const A={docs:f,archivedDocs:[],workspaces:p,assignedFiles:m,pendingDocs:i,writingTitle:l,writingTarget:c,onSwitchDocument:e,onCreateDocument:n,actions:v,scrollRef:b,searchQuery:W,searchResults:U,onSearchChange:G},j=()=>{switch(k){case"timeline":return u.jsx(dD,{...A});case"board":return u.jsx(fD,{...A});case"shelf":return u.jsx(hD,{...A});default:return u.jsx(uD,{...A})}},Q=u.jsxs("div",{className:"sidebar-search",children:[u.jsxs("svg",{className:"sidebar-search-icon",width:"14",height:"14",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:Z,className:"sidebar-search-input",type:"text",placeholder:"Search...",value:W,onChange:se=>G(se.target.value)}),W&&u.jsx("button",{className:"sidebar-search-clear",onClick:()=>G(""),title:"Clear search",children:"×"})]});return k==="board"?u.jsx("div",{className:`sidebar sidebar-board-mode ${t?"open":""}`,children:j()}):u.jsxs("div",{className:`sidebar ${t?"open":""}`,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(ND,{profiles:C,activeProfile:_,trashedProfiles:B,onSwitch:D,onCreate:F,onDelete:Y,onRestore:le}),u.jsx("button",{className:`sidebar-collapse-btn${w?" sidebar-collapse-btn--active":""}`,onClick:()=>N(!w),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(_D,{}),d&&u.jsx("button",{className:"sidebar-collapse-btn",onClick:d,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"})]})})]})]}),w?u.jsx(SD,{onBack:()=>N(!1)}):u.jsxs(u.Fragment,{children:[Q,j()]})]})}function TD({onClose:t,onSetupComplete:e}){const[n,r]=E.useState("detecting"),[s,i]=E.useState(null),[l,c]=E.useState("gh"),[d,f]=E.useState("openwriter-docs"),[p,m]=E.useState(!0),[y,b]=E.useState(""),[v,k]=E.useState(""),[w,N]=E.useState(""),[C,O]=E.useState("");E.useEffect(()=>{fetch("/api/sync/capabilities").then(M=>M.json()).then(M=>{i(M),M.ghAuthenticated?c("gh"):(M.gitInstalled,c("pat")),r("setup")}).catch(()=>{N("Failed to detect git capabilities"),r("error")})},[]);const _=E.useCallback(async()=>{r("progress"),O(l==="connect"?"Connecting to repository...":"Creating repository and syncing...");try{const M={method:l,repoName:d,isPrivate:p};l==="pat"&&(M.pat=y),l==="connect"&&(M.remoteUrl=v,M.pat=y||void 0);const R=await fetch("/api/sync/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!R.ok){const D=await R.json().catch(()=>({}));throw new Error(D.error||`Setup failed (${R.status})`)}r("done"),e()}catch(M){N(M.message),r("error")}},[l,d,p,y,v,e]);return u.jsx("div",{className:"sync-modal-overlay",onClick:t,children:u.jsxs("div",{className:"sync-modal",onClick:M=>M.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${l==="gh"?" active":""}`,onClick:()=>c("gh"),children:"GitHub CLI"}),u.jsx("button",{className:`sync-tab${l==="pat"?" active":""}`,onClick:()=>c("pat"),children:"Personal Access Token"}),u.jsx("button",{className:`sync-tab${l==="connect"?" active":""}`,onClick:()=>c("connect"),children:"Connect Existing"})]}),l==="gh"&&u.jsxs("div",{className:"sync-form",children:[u.jsxs("label",{children:["Repository name",u.jsx("input",{type:"text",value:d,onChange:M=>f(M.target.value),placeholder:"openwriter-docs"})]}),u.jsxs("label",{className:"sync-checkbox",children:[u.jsx("input",{type:"checkbox",checked:p,onChange:M=>m(M.target.checked)}),"Private repository"]})]}),l==="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:y,onChange:M=>b(M.target.value),placeholder:"ghp_..."})]}),u.jsxs("label",{children:["Repository name",u.jsx("input",{type:"text",value:d,onChange:M=>f(M.target.value),placeholder:"openwriter-docs"})]}),u.jsxs("label",{className:"sync-checkbox",children:[u.jsx("input",{type:"checkbox",checked:p,onChange:M=>m(M.target.checked)}),"Private repository"]})]}),l==="connect"&&u.jsxs("div",{className:"sync-form",children:[u.jsxs("label",{children:["Remote URL",u.jsx("input",{type:"text",value:v,onChange:M=>k(M.target.value),placeholder:"https://github.com/user/repo.git"})]}),u.jsxs("label",{children:["PAT (optional, for private repos)",u.jsx("input",{type:"password",value:y,onChange:M=>b(M.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:l==="pat"&&!y||l==="connect"&&!v||l!=="connect"&&!d,children:l==="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:w}),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 MD({onNodeChanges:t,onAgentStatus:e,onDocumentSwitched:n,onDocumentsChanged:r,onWorkspacesChanged:s,onTitleChanged:i,onPendingDocsChanged:l,onMetadataChanged:c,onSyncStatus:d,onWritingStarted:f,onWritingFinished:p,getEditorState:m}){const y=E.useRef(null),[b,v]=E.useState(!1),k=E.useRef(t),w=E.useRef(e),N=E.useRef(n),C=E.useRef(r),O=E.useRef(s),_=E.useRef(i),M=E.useRef(l),R=E.useRef(d),D=E.useRef(c),F=E.useRef(f),B=E.useRef(p),V=E.useRef(m);k.current=t,w.current=e,N.current=n,C.current=r,O.current=s,_.current=i,M.current=l,D.current=c,R.current=d,F.current=f,B.current=p,V.current=m,E.useEffect(()=>{const le=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;let W,$=!1,U=1e3;function te(){const Z=new WebSocket(le);y.current=Z,Z.onopen=()=>{v(!0),U=1e3,$&&Z.send(JSON.stringify({type:"request-document"})),$=!0},Z.onmessage=G=>{var A,j,Q,se,fe,ee,me,Le,Xe,ce,be;try{const ie=JSON.parse(G.data);ie.type==="node-changes"&&ie.changes&&((A=k.current)==null||A.call(k,ie.changes)),ie.type==="agent-status"&&((j=w.current)==null||j.call(w,!!ie.agentConnected)),ie.type==="document-switched"&&((Q=N.current)==null||Q.call(N,{document:ie.document,title:ie.title,filename:ie.filename,docId:ie.docId,metadata:ie.metadata})),ie.type==="metadata-changed"&&ie.metadata&&((se=D.current)==null||se.call(D,ie.metadata)),ie.type==="documents-changed"&&((fe=C.current)==null||fe.call(C)),ie.type==="workspaces-changed"&&((ee=O.current)==null||ee.call(O)),ie.type==="title-changed"&&ie.title&&((me=_.current)==null||me.call(_,ie.title)),ie.type==="pending-docs-changed"&&ie.pendingDocs&&((Le=M.current)==null||Le.call(M,ie.pendingDocs)),ie.type==="sync-status"&&((Xe=R.current)==null||Xe.call(R,{state:ie.state,lastSyncTime:ie.lastSyncTime,pendingFiles:ie.pendingFiles,error:ie.error})),ie.type==="writing-started"&&ie.title&&((ce=F.current)==null||ce.call(F,ie.title,ie.target||null)),ie.type==="writing-finished"&&((be=B.current)==null||be.call(B)),ie.type==="plugins-changed"&&window.dispatchEvent(new CustomEvent("ow-plugins-changed")),ie.type==="marks-changed"&&ie.filename&&window.dispatchEvent(new CustomEvent("ow-marks-changed",{detail:{filename:ie.filename}}))}catch{}},Z.onclose=()=>{v(!1),W=setTimeout(te,U),U=Math.min(U*1.5,8e3)},Z.onerror=()=>{Z.close()}}te();function H(){var Z;document.visibilityState==="visible"&&((Z=y.current)==null?void 0:Z.readyState)!==WebSocket.OPEN&&(clearTimeout(W),U=1e3,te())}return document.addEventListener("visibilitychange",H),()=>{var Z;clearTimeout(W),document.removeEventListener("visibilitychange",H),(Z=y.current)==null||Z.close()}},[]);const q=E.useCallback(Y=>{var le;((le=y.current)==null?void 0:le.readyState)===WebSocket.OPEN&&y.current.send(JSON.stringify(Y))},[]);return{connected:b,sendMessage:q}}function AD(t){const[e,n]=E.useState(null),[r,s]=E.useState(!1),[i,l]=E.useState(null),c=E.useRef(void 0);return E.useEffect(()=>{if(!t){n(null),s(!1),l(null),c.current=void 0;return}t!==c.current&&(c.current=t,s(!0),l(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=>{l(d.message),s(!1)}))},[t]),{tweet:e,loading:r,error:i}}function OD(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(`
204
+ `);Fe.trim()&&fetch("/api/marks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:n,text:Fe,note:le.trim(),nodeId:Te[Te.length-1]})}).then(()=>{s(!1),Y(!1),W("")}).catch(Ee=>{console.error("[ContextMenu] Agent mark failed:",Ee)})},[t,n,le]),Le=E.useCallback(ce=>{const be=te.current||t.current;be&&be.chain().focus().setLink({href:`doc:${ce}`}).run(),fetch("/api/auto-tag-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetFile:ce})}).catch(()=>{}),s(!1),w(!1)},[t]),Xe=E.useCallback(()=>{const ce=D.trim();if(!ce)return;const be=te.current||t.current;be&&(fetch("/api/create-link-doc",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:ce})}).then(ie=>ie.json()).then(ie=>{ie.filename&&be.chain().focus().setLink({href:`doc:${ie.filename}`}).run()}).catch(()=>{}),s(!1),w(!1),R(!1),F(""))},[t,D]);return r?u.jsx("div",{ref:$,className:"context-menu",style:{left:i.x,top:i.y},children:c?u.jsx("div",{className:"context-menu-loading",children:"Applying..."}):q?u.jsxs("div",{className:"context-menu-custom",children:[u.jsx("input",{autoFocus:!0,value:le,onChange:ce=>W(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"&&me(),ce.key==="Escape"&&(Y(!1),W(""))},placeholder:"Note for agent (optional)..."}),u.jsx("button",{onClick:me,children:"Mark"})]}):m?u.jsxs("div",{className:"context-menu-custom",children:[u.jsx("input",{autoFocus:!0,value:f,onChange:ce=>p(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"&&ee(),ce.key==="Escape"&&s(!1)},placeholder:"Custom instruction..."}),u.jsx("button",{onClick:ee,children:"Apply"})]}):k?u.jsxs("div",{className:"context-menu-link-picker",children:[u.jsx("div",{className:"context-menu-link-header",children:"Link to document"}),M?u.jsxs("div",{className:"context-menu-custom",children:[u.jsx("input",{autoFocus:!0,value:D,onChange:ce=>F(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"&&Xe(),ce.key==="Escape"&&R(!1)},placeholder:"New document title..."}),u.jsx("button",{onClick:Xe,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"}),N.filter(ce=>O.includes(ce.filename)).map(({filename:ce,title:be})=>u.jsx("button",{className:"context-menu-item",onClick:()=>Le(ce),children:u.jsx("span",{children:be})},`linked-${ce}`))]}),u.jsx("div",{className:"context-menu-section-header",children:"All documents"}),N.filter(ce=>!O.includes(ce.filename)).map(({filename:ce,title:be})=>u.jsx("button",{className:"context-menu-item",onClick:()=>Le(ce),children:u.jsx("span",{children:be})},ce)),N.length===0&&u.jsx("div",{className:"context-menu-loading",children:"No documents"})]})]}):(()=>{const ce=j();let be;return ce.map((ie,Be)=>{const Te=ie.isPlugin&&ie.pluginDisplayName&&ie.pluginDisplayName!==be,Fe=be!==void 0;ie.isPlugin?be=ie.pluginDisplayName:be=void 0;const Ee=!ie.isPlugin&&Fe;return u.jsxs("span",{children:[Te&&u.jsx("div",{className:"context-menu-section-header",children:ie.pluginDisplayName}),Ee&&u.jsx("div",{className:"context-menu-divider"}),u.jsxs("button",{className:"context-menu-item",onClick:()=>fe(ie),children:[u.jsx("span",{children:ie.label}),ie.shortcut&&u.jsx("span",{className:"context-menu-shortcut",children:ie.shortcut})]})]},ie.action)})})()}):null}function wm(t,e,n){let r=t.resolve(e);for(;r.depth>0;){const s=r.node(r.depth),i=r.before(r.depth),l=i+s.nodeSize;if(s.childCount===1)e=i,n=l,r=t.resolve(e);else break}return{from:e,to:n}}function PL(t,e){const n=yn(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 BL(t,e){const n=yn(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 zL(t,e){var l;const n=yn(t,e);if(!n)return!1;const{node:r,pos:s}=n;if(((l=r.attrs)==null?void 0:l.pendingStatus)!=="delete")return!0;const i=wm(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function $L(t,e){var l;const n=yn(t,e);if(!n)return!0;const{node:r,pos:s}=n;if(((l=r.attrs)==null?void 0:l.pendingStatus)!=="insert")return!0;const i=wm(t.state.doc,s,s+r.nodeSize);return t.chain().deleteRange(i).run(),!0}function FL(t,e){var l,c;const n=yn(t,e);if(!n)return!1;const{node:r,pos:s}=n;if(((l=r.attrs)==null?void 0:l.pendingStatus)!=="rewrite")return!0;const i=(c=r.attrs)==null?void 0:c.pendingOriginalContent;if(i)t.chain().deleteRange({from:s,to:s+r.nodeSize}).insertContentAt(s,i).run();else{const d=wm(t.state.doc,s,s+r.nodeSize);t.chain().deleteRange(d).run()}return!0}function UL(t,e){var i;const n=yn(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:l})=>(l.setNodeMarkup(s,void 0,{...r.attrs,pendingStatus:null}),!0)).run(),!0}function HL(t,e){const n=nd(t,e);if(n.length===0)return!1;for(const r of[...n].reverse()){const s=yn(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 WL(t,e){var c;const n=nd(t,e);if(n.length===0)return!1;const r=(c=n[0].node.attrs)==null?void 0:c.pendingOriginalContent,s=n[0].pos,i=n[n.length-1],l=i.pos+i.node.nodeSize;try{return r&&Array.isArray(r)&&r.length>0?t.chain().deleteRange({from:s,to:l}).insertContentAt(s,r).run():t.chain().deleteRange({from:s,to:l}).run(),!0}catch{return!1}}function _1(t,e){var i,l;const n=yn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return HL(t,r);switch((l=n.node.attrs)==null?void 0:l.pendingStatus){case"insert":return PL(t,e);case"rewrite":return BL(t,e);case"delete":return zL(t,e);default:return!1}}function T1(t,e){var i,l;const n=yn(t,e);if(!n)return!1;const r=(i=n.node.attrs)==null?void 0:i.pendingGroupId;if(r)return WL(t,r);switch((l=n.node.attrs)==null?void 0:l.pendingStatus){case"insert":return $L(t,e);case"rewrite":return FL(t,e);case"delete":return UL(t,e);default:return!1}}function VL(t){const e=M1(t).reverse();for(const n of e)_1(t,n);t.view&&xm(t.view)}function KL(t){const e=M1(t).reverse();for(const n of e)T1(t,n);t.view&&xm(t.view)}function Sm(t){const e=[],n=new Set;return t.state.doc.descendants((r,s)=>{var l,c,d;const i=(l=r.attrs)==null?void 0:l.pendingStatus;if(i&&((c=r.attrs)!=null&&c.id)){const f=(d=r.attrs)==null?void 0:d.pendingGroupId;if(f){if(n.has(f))return!0;n.add(f)}e.push({nodeId:r.attrs.id,pos:s,pendingStatus:i,groupId:f,editor:t})}return!0}),e}function Ch(t){const e=[];for(const n of t)n&&!n.isDestroyed&&e.push(...Sm(n));return e}function M1(t){return Sm(t).map(e=>e.nodeId)}function GL(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 bl(t,e){if(t.isDestroyed)return;let n=-1;if(t.state.doc.descendants((i,l)=>{var c;return((c=i.attrs)==null?void 0:c.id)===e?(n=l,!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),l=t.view.dom.closest(".editor-container");if(l){const c=l.getBoundingClientRect(),d=i.top-c.top+l.scrollTop-l.clientHeight/2;l.scrollTo({top:d,behavior:"smooth"})}}catch{}}function qL(t){const[e,n]=E.useState([]),[r,s]=E.useState(0),i=E.useRef(),l=E.useRef(new Set),c=E.useCallback(()=>{const N=t.filter(R=>R&&!R.isDestroyed);if(N.length===0){n([]),l.current=new Set;return}const C=Ch(N);n(C);const O=l.current,_=new Set(C.map(R=>R.nodeId));let M=-1;if(O.size>0){for(let R=0;R<C.length;R++)if(!O.has(C[R].nodeId)){M=R;break}}l.current=_,M>=0?(s(M),bl(C[M].editor,C[M].nodeId)):C.length===0?s(0):s(R=>Math.min(R,C.length-1))},[t]);E.useEffect(()=>{const N=t.filter(_=>_&&!_.isDestroyed);if(N.length===0)return;const C=()=>{clearTimeout(i.current),i.current=setTimeout(c,50)};for(const _ of N)_.on("transaction",C);c();const O=setTimeout(()=>{const _=Ch(N.filter(M=>!M.isDestroyed));_.length>0&&bl(_[0].editor,_[0].nodeId)},150);return()=>{for(const _ of N)_.isDestroyed||_.off("transaction",C);clearTimeout(i.current),clearTimeout(O)}},[t,c]),E.useEffect(()=>{const N=e[r]??null;return t0((N==null?void 0:N.nodeId)??null,(N==null?void 0:N.groupId)??null),N!=null&&N.editor&&!N.editor.isDestroyed&&N.editor.view&&xm(N.editor.view),()=>{t0(null)}},[r,e]);const d=GL(e),f=e[r]??null,p=E.useCallback(()=>{if(e.length===0)return;const N=(r+1)%e.length;s(N),e[N]&&bl(e[N].editor,e[N].nodeId)},[e,r]),m=E.useCallback(()=>{if(e.length===0)return;const N=(r-1+e.length)%e.length;s(N),e[N]&&bl(e[N].editor,e[N].nodeId)},[e,r]),y=E.useCallback(()=>{const N=t.filter(_=>_&&!_.isDestroyed),C=Ch(N);if(C.length===0)return;const O=Math.min(r,C.length-1);bl(C[O].editor,C[O].nodeId)},[t,r]),b=E.useCallback(()=>{f&&(_1(f.editor,f.nodeId),c(),y())},[f,c,y]),v=E.useCallback(()=>{f&&(T1(f.editor,f.nodeId),c(),y())},[f,c,y]),k=E.useCallback(()=>{const N=t.filter(C=>C&&!C.isDestroyed);for(const C of N)VL(C);c()},[t,c]),w=E.useCallback(()=>{const N=t.filter(C=>C&&!C.isDestroyed);for(const C of N)KL(C);c()},[t,c]);return{pendingNodes:e,counts:d,currentNode:f,currentIndex:r,hasPending:d.total>0,goToNext:p,goToPrevious:m,acceptCurrent:b,rejectCurrent:v,acceptAll:k,rejectAll:w,refresh:c}}const Oo={strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},JL=()=>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",...Oo})}),m0=()=>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",...Oo})}),YL=()=>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",...Oo})}),QL=()=>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",...Oo})}),g0=()=>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",...Oo})}),y0=()=>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",...Oo})});function A1(t,e,n){const r=yn(t,e);if(!r)return!1;const{pos:s,node:i}=r,l={type:n.type||i.type.name,attrs:{...n.attrs||{},id:i.attrs.id,pendingStatus:i.attrs.pendingStatus,pendingOriginalContent:i.attrs.pendingOriginalContent,pendingSelectionFrom:i.attrs.pendingSelectionFrom,pendingSelectionTo:i.attrs.pendingSelectionTo,pendingOriginalFrom:i.attrs.pendingOriginalFrom,pendingOriginalTo:i.attrs.pendingOriginalTo},content:n.content};try{return t.chain().command(({tr:c})=>(c.setMeta("addToHistory",!1),!0)).deleteRange({from:s,to:s+i.nodeSize}).insertContentAt(s,l).run(),!0}catch{return!1}}function O1(t,e,n){const r=nd(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:l})=>(l.setMeta("addToHistory",!1),!0)).deleteRange({from:s,to:i}).insertContentAt(s,n).run(),!0}catch{return!1}}function Rc(t,e){if(!vm()||!e)return!1;const n=oL(),r=iL();return r&&n&&Array.isArray(n)?O1(t,r,n):n&&A1(t,e,n),gp(!1),!0}function XL({editors:t,pendingDocs:e,currentFilename:n,onSwitchDocument:r,sendMessage:s,getDocument:i}){const{counts:l,currentNode:c,currentIndex:d,hasPending:f,goToNext:p,goToPrevious:m,acceptCurrent:y,rejectCurrent:b,acceptAll:v,rejectAll:k}=qL(t),[w,N]=E.useState(!1),C=E.useRef(null),O=E.useRef(null),_=e.filenames.length,M=b0(e.filenames,n)>=0?_-1:_,R=f||_>0,D=b0(e.filenames,n),F=(c==null?void 0:c.pendingStatus)==="rewrite",B=!!(c!=null&&c.groupId),V=F,q=E.useCallback(()=>{var j,Q;const A=c==null?void 0:c.editor;if(!(!A||!c||c.pendingStatus!=="rewrite"))if(w)O.current&&Rc(O.current,C.current),C.current=null,O.current=null,N(!1);else if(B&&c.groupId){const se=nd(A,c.groupId);if(se.length===0)return;const fe=(j=se[0].node.attrs)==null?void 0:j.pendingOriginalContent;if(!fe||!Array.isArray(fe))return;const ee=se.map(Xe=>Xe.node.toJSON()),me=fe.map((Xe,ce)=>({...Xe,attrs:{...Xe.attrs||{},pendingStatus:"rewrite",pendingGroupId:c.groupId,...ce===0?{pendingOriginalContent:fe}:{}}}));if(!O1(A,c.groupId,me))return;gp(!0,c.nodeId,ee,c.groupId),C.current=c.nodeId,O.current=A,N(!0)}else{const se=yn(A,c.nodeId);if(!se)return;const{node:fe}=se,ee=(Q=fe.attrs)==null?void 0:Q.pendingOriginalContent;if(!ee)return;const me=fe.toJSON();if(!A1(A,c.nodeId,ee))return;gp(!0,c.nodeId,me),C.current=c.nodeId,O.current=A,N(!0)}},[c,w,B]);E.useEffect(()=>{if(!w)return;const A=C.current,j=O.current;A&&j&&(c==null?void 0:c.nodeId)!==A&&(Rc(j,A),C.current=null,O.current=null,N(!1))},[c==null?void 0:c.nodeId,w]),E.useEffect(()=>{if(t.length!==0)return()=>{vm()&&C.current&&O.current&&(Rc(O.current,C.current),C.current=null,O.current=null)}},[t]);const Y=E.useCallback(A=>{if(!n)return;if(!t.some(Q=>!Q||Q.isDestroyed?!1:Sm(Q).length>0)){const Q=i==null?void 0:i();Q&&s({type:"doc-update",document:Q,filename:n}),s({type:"pending-resolved",filename:n,action:A})}},[t,n,s,i]),le=E.useCallback(()=>{O.current&&w&&C.current&&(Rc(O.current,C.current),C.current=null,O.current=null,N(!1))},[w]),W=E.useCallback(()=>{le(),y(),Y("accept")},[le,y,Y]),$=E.useCallback(()=>{le(),b(),Y("reject")},[le,b,Y]),U=E.useCallback(()=>{le(),v(),Y("accept")},[le,v,Y]),te=E.useCallback(()=>{le(),k(),Y("reject")},[le,k,Y]),H=E.useCallback(()=>{if(_===0||_===1&&D===0)return;const A=D<=0?_-1:D-1;r(e.filenames[A])},[_,D,e.filenames,r]),Z=E.useCallback(()=>{if(_===0||_===1&&D===0)return;const A=D>=_-1?0:D+1;r(e.filenames[A])},[_,D,e.filenames,r]);if(E.useEffect(()=>{if(!R)return;const A=j=>{if(!(j.target instanceof HTMLInputElement||j.target instanceof HTMLTextAreaElement)&&!(j.target instanceof HTMLElement&&j.target.closest("[contenteditable]")))switch(j.key){case"j":case"ArrowDown":!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),p());break;case"k":case"ArrowUp":!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),m());break;case"h":case"ArrowLeft":!j.metaKey&&!j.ctrlKey&&!j.altKey&&(j.preventDefault(),H());break;case"l":case"ArrowRight":!j.metaKey&&!j.ctrlKey&&!j.altKey&&(j.preventDefault(),Z());break;case"a":!j.metaKey&&!j.ctrlKey&&!j.shiftKey&&(j.preventDefault(),W());break;case"r":!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),$());break;case"A":j.shiftKey&&!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),U());break;case"R":j.shiftKey&&!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),te());break;case"o":!j.metaKey&&!j.ctrlKey&&!j.shiftKey&&(j.preventDefault(),q());break}};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[R,p,m,H,Z,W,$,U,te,q]),!R)return null;if(c!=null&&c.pendingStatus,!f&&M>0)return u.jsxs("div",{className:"review-panel",children:[u.jsxs("div",{className:"review-panel__status",children:["No changes here — ",M," other doc",M>1?"s have":" has"," changes"]}),u.jsx("div",{className:"review-panel__divider"}),u.jsx("div",{className:"review-panel__nav",children:u.jsx("button",{className:"review-panel__btn",onClick:Z,title:"Next doc (l)",children:u.jsx(m0,{})})})]});const G=D>=0?D+1:"?";return u.jsxs("div",{className:"review-panel",children:[_>1&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"review-panel__nav",children:[u.jsx("button",{className:"review-panel__btn",onClick:H,title:"Previous doc (h)",children:u.jsx(JL,{})}),u.jsx("button",{className:"review-panel__btn",onClick:Z,title:"Next doc (l)",children:u.jsx(m0,{})}),u.jsxs("span",{className:"review-panel__counter",children:[G,"/",_]})]}),u.jsx("div",{className:"review-panel__divider"})]}),u.jsxs("div",{className:"review-panel__nav",children:[u.jsx("button",{className:"review-panel__btn",onClick:m,disabled:l.total===0,title:"Previous (k)",children:u.jsx(YL,{})}),u.jsx("button",{className:"review-panel__btn",onClick:p,disabled:l.total===0,title:"Next (j)",children:u.jsx(QL,{})}),u.jsxs("span",{className:"review-panel__counter",children:[d+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${V&&!w?" review-panel__toggle-btn--active":""}`,onClick:()=>V&&w&&q(),disabled:!V,title:"Show modified (o)",children:"Modified"}),u.jsx("button",{className:`review-panel__toggle-btn${V&&w?" review-panel__toggle-btn--active":""}`,onClick:()=>V&&!w&&q(),disabled:!V,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:W,title:"Accept (a)",children:u.jsx(g0,{})}),u.jsx("button",{className:"review-panel__reject",onClick:$,title:"Reject (r)",children:u.jsx(y0,{})}),u.jsxs("button",{className:"review-panel__accept-all",onClick:U,title:"Accept all (Shift+A)",children:[u.jsx(g0,{}),u.jsx("span",{children:"All"})]}),u.jsxs("button",{className:"review-panel__reject-all",onClick:te,title:"Reject all (Shift+R)",children:[u.jsx(y0,{}),u.jsx("span",{children:"All"})]})]})]})}function b0(t,e){return t.indexOf(e)}function jc(t){return t.type==="doc"?t.file:t.id}function R1(t,e){for(const n of t)n.type==="doc"?e.add(n.file):n.type==="container"&&R1(n.items,e)}function Mo(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 bp(t){return/^[A-Z]:[/\\]|^\//.test(t)}function j1(t){const e=t.replace(/\\/g,"/").split("/");return e.length>=2?e[e.length-2]:""}function ZL(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 eD(t,e){const[n,r]=E.useState([]),[s,i]=E.useState([]),[l,c]=E.useState(new Set),d=E.useRef(null),f=E.useCallback(()=>{fetch("/api/documents").then(m=>m.json()).then(m=>{Array.isArray(m)&&r(m)}).catch(()=>{})},[]),p=E.useCallback(()=>{fetch("/api/workspaces").then(m=>m.json()).then(async m=>{if(!Array.isArray(m))return;const y=await Promise.all(m.map(async v=>{try{const w=await(await fetch(`/api/workspaces/${encodeURIComponent(v.filename)}`)).json();return{...v,workspace:w}}catch{return v}}));i(y);const b=new Set;for(const v of y)v.workspace&&R1(v.workspace.root,b);c(b)}).catch(()=>{})},[]);return E.useEffect(()=>{f()},[f,t]),E.useEffect(()=>{p()},[p,e,t]),E.useEffect(()=>{const m=requestAnimationFrame(()=>{var b;const y=(b=d.current)==null?void 0:b.querySelector(".sidebar-item.active");y==null||y.scrollIntoView({block:"nearest",behavior:"instant"})});return()=>cancelAnimationFrame(m)},[n]),{docs:n,workspaces:s,assignedFiles:l,fetchDocs:f,scrollRef:d}}function tD(t,e,n){const r=E.useCallback(M=>{fetch(`/api/documents/${encodeURIComponent(M)}`,{method:"DELETE"}).catch(()=>{})},[]),s=E.useCallback(M=>{fetch(`/api/documents/${encodeURIComponent(M)}/archive`,{method:"POST"}).then(()=>e()).catch(()=>{})},[e]),i=E.useCallback(M=>{fetch(`/api/documents/${encodeURIComponent(M)}/unarchive`,{method:"POST"}).then(()=>e()).catch(()=>{})},[e]),l=E.useCallback((M,R,D)=>{!D.trim()||D.trim()===R||fetch(`/api/documents/${encodeURIComponent(M)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:D.trim()})}).then(()=>e()).catch(()=>{})},[e]),c=E.useCallback(()=>{fetch("/api/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:"Untitled Workspace"})}).catch(()=>{})},[]),d=E.useCallback(M=>{fetch(`/api/workspaces/${encodeURIComponent(M)}`,{method:"DELETE"}).catch(()=>{})},[]),f=E.useCallback((M,R,D)=>{fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D?{metadata:D}:{})}).then(F=>F.json()).then(F=>{if(F.filename)return fetch(`/api/workspaces/${encodeURIComponent(M)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:F.filename,title:F.title||"Untitled",containerId:R})})}).catch(()=>{})},[]),p=E.useCallback((M,R)=>{fetch(`/api/workspaces/${encodeURIComponent(M)}/docs/${encodeURIComponent(R)}`,{method:"DELETE"}).catch(()=>{})},[]),m=E.useCallback((M,R)=>{fetch(`/api/workspaces/${encodeURIComponent(M)}/containers`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:"Untitled",parentContainerId:R})}).catch(()=>{})},[]),y=E.useCallback((M,R)=>{fetch(`/api/workspaces/${encodeURIComponent(M)}/containers/${encodeURIComponent(R)}`,{method:"DELETE"}).catch(()=>{})},[]),b=E.useCallback((M,R,D)=>{D.trim()&&fetch(`/api/workspaces/${encodeURIComponent(M)}/containers/${encodeURIComponent(R)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:D.trim()})}).catch(()=>{})},[]),v=E.useCallback((M,R)=>{R.trim()&&fetch(`/api/workspaces/${encodeURIComponent(M)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:R.trim()})}).catch(()=>{})},[]),[k,w]=E.useState({}),N=E.useRef(-1);E.useEffect(()=>{n!==N.current&&(N.current=n??0,fetch("/api/documents").then(M=>M.json()).then(M=>{const R={};return Promise.all(M.map(D=>fetch(`/api/doc-tags/${encodeURIComponent(D.filename)}`).then(F=>F.json()).then(F=>{var B;(B=F.tags)!=null&&B.length&&(R[D.filename]=F.tags)}).catch(()=>{}))).then(()=>w(R))}).catch(()=>{}))},[n]);const C=E.useCallback(M=>k[M]||[],[k]),O=E.useCallback((M,R)=>{R.trim()&&(w(D=>{const F=D[M]||[];return F.includes(R.trim())?D:{...D,[M]:[...F,R.trim()]}}),fetch(`/api/doc-tags/${encodeURIComponent(M)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag:R.trim()})}).catch(()=>{}))},[]),_=E.useCallback((M,R)=>{w(D=>{const B=(D[M]||[]).filter(V=>V!==R);if(B.length===0){const V={...D};return delete V[M],V}return{...D,[M]:B}}),fetch(`/api/doc-tags/${encodeURIComponent(M)}/${encodeURIComponent(R)}`,{method:"DELETE"}).catch(()=>{})},[]);return{fetchDocs:e,handleDelete:r,handleArchive:s,handleUnarchive:i,handleRename:l,handleCreateWorkspace:c,handleDeleteWorkspace:d,handleCreateInWorkspace:f,handleRemoveFromWorkspace:p,handleCreateContainer:m,handleDeleteContainer:y,handleRenameContainer:b,handleRenameWorkspace:v,getDocTags:C,handleAddTag:O,handleRemoveTag:_}}function nD({docs:t,workspaces:e,assignedFiles:n,scrollRef:r,setCollapsedSections:s}){const[i,l]=E.useState(null),[c,d]=E.useState(null),f=E.useRef(null),p=E.useRef(null),m=E.useRef(null),y=E.useRef(null),b=E.useRef(null),v=5,k=(V,q,Y)=>Y==="before"?q>0?jc(V[q-1]):null:jc(V[q]),w=E.useCallback((V,q)=>{if(q===null){const W=t.filter(U=>!n.has(U.filename)).map(U=>({type:"doc",file:U.filename,title:U.title})),$=W.findIndex(U=>jc(U)===V);return $>=0?{siblings:W,index:$,containerId:null}:null}const Y=e.find(W=>W.filename===q);if(!(Y!=null&&Y.workspace))return null;const le=(W,$)=>{for(let U=0;U<W.length;U++){if(jc(W[U])===V)return{siblings:W,index:U,containerId:$};if(W[U].type==="container"){const te=le(W[U].items,W[U].id);if(te)return te}}return null};return le(Y.workspace.root,null)},[t,n,e]),N=E.useCallback(()=>{l(null),d(null),b.current=null,y.current=null,m.current&&(m.current.remove(),m.current=null),f.current&&(clearTimeout(f.current),f.current=null),p.current&&(cancelAnimationFrame(p.current),p.current=null),document.body.style.userSelect=""},[]),C=E.useCallback((V,q)=>{if(!V||!q)return;if(V.type==="workspace"){const H=q.itemId;if(H===V.filename)return;const Z=e.map(j=>j.filename),G=Z.indexOf(V.filename);if(G<0)return;Z.splice(G,1);let A=Z.indexOf(H);if(A<0)return;q.position==="after"&&(A+=1),Z.splice(A,0,V.filename),fetch("/api/workspaces/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:Z})}).catch(()=>{});return}const{wsFilename:Y,containerId:le,afterId:W}=q,$=V.type==="doc"?V.file:V.id,U=V.sourceWs;if(q.itemId===$)return;if(V.type==="container"){if(U!==Y||!Y)return;fetch(`/api/workspaces/${encodeURIComponent(Y)}/docs/${encodeURIComponent($)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:le??null,afterFile:W})}).catch(()=>{});return}const te=V.file;if(U===null&&Y===null){const H=t.filter(Q=>!n.has(Q.filename)).map(Q=>Q.filename),Z=H.indexOf(te);if(Z<0)return;H.splice(Z,1);let G=W?H.indexOf(W):-1;G>=0?G+=1:G=0,H.splice(G,0,te);const A=[];let j=0;for(const Q of t)n.has(Q.filename)?A.push(Q.filename):A.push(H[j++]);fetch("/api/documents/reorder",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({order:A})}).catch(()=>{});return}if(U===null&&Y!==null){fetch(`/api/workspaces/${encodeURIComponent(Y)}/docs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:te,title:te.replace(/\.md$/,""),containerId:le??null,afterFile:W})}).catch(()=>{});return}if(U!==null&&Y===null){fetch(`/api/workspaces/${encodeURIComponent(U)}/docs/${encodeURIComponent(te)}`,{method:"DELETE"}).catch(()=>{});return}if(U===Y&&Y!==null){fetch(`/api/workspaces/${encodeURIComponent(Y)}/docs/${encodeURIComponent(te)}/move`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({targetContainerId:le??null,afterFile:W})}).catch(()=>{});return}U!==null&&Y!==null&&fetch(`/api/workspaces/${encodeURIComponent(Y)}/docs/${encodeURIComponent(te)}/cross-move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceWorkspace:U,containerId:le??null,afterFile:W,title:te.replace(/\.md$/,"")})}).catch(()=>{})},[e,t,n]),O=E.useCallback((V,q)=>{const Y=m.current;Y&&(Y.style.display="none");const le=document.elementFromPoint(V,q);if(Y&&(Y.style.display=""),!le)return null;if((i==null?void 0:i.type)==="workspace"){const Q=le.closest("[data-ws-drag]");if(Q){const se=Q.dataset.wsDrag,fe=Q.getBoundingClientRect(),ee=(q-fe.top)/fe.height;return{itemId:se,position:ee<.5?"before":"after",wsFilename:null,containerId:null,afterId:null}}return null}const W=le.closest("[data-drag-id]");if(!W){const Q=le.closest("[data-drop-ws]");return Q?{itemId:"__section__",position:"inside",wsFilename:Q.dataset.dropWs==="__docs__"?null:Q.dataset.dropWs,containerId:Q.dataset.dropContainer||null,afterId:null}:null}const $=W.dataset.dragId,U=W.dataset.dragType,te=W.dataset.dragWs==="__docs__"?null:W.dataset.dragWs,H=W.getBoundingClientRect(),Z=(q-H.top)/H.height;if(U==="container-header"){const Q=$,se=W.dataset.dragParent||null,fe=w(Q,te);return fe?Z<.25?{itemId:Q,position:"before",wsFilename:te,containerId:se,afterId:k(fe.siblings,fe.index,"before")}:Z>.75?{itemId:Q,position:"after",wsFilename:te,containerId:se,afterId:k(fe.siblings,fe.index,"after")}:{itemId:Q,position:"inside",wsFilename:te,containerId:Q,afterId:null}:null}const G=W.dataset.dragContainer||null,A=w($,te);if(!A)return null;const j=Z<.5?"before":"after";return{itemId:$,position:j,wsFilename:te,containerId:G,afterId:k(A.siblings,A.index,j)}},[w,i]),_=E.useCallback(V=>{const q=r.current;if(!q)return;const Y=q.getBoundingClientRect(),le=80,W=18;let $=0;if(V<Y.top+le?$=-W*Math.max(0,1-(V-Y.top)/le):V>Y.bottom-le&&($=W*Math.max(0,1-(Y.bottom-V)/le)),p.current&&(cancelAnimationFrame(p.current),p.current=null),$!==0){const U=()=>{q.scrollTop+=$,p.current=requestAnimationFrame(U)};p.current=requestAnimationFrame(U)}},[r]),M=E.useCallback((V,q)=>{const Y=m.current;Y&&(Y.style.display="none");const le=document.elementFromPoint(V,q);Y&&(Y.style.display="");const W=le==null?void 0:le.closest("[data-section-key]");if(!W){f.current&&(clearTimeout(f.current),f.current=null);return}const $=W.dataset.sectionKey;f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{s(U=>{if(!U.has($))return U;const te=new Set(U);return te.delete($),te})},500)},[s]);E.useEffect(()=>{if(!i)return;const V=Y=>{m.current&&(m.current.style.left=`${Y.clientX+12}px`,m.current.style.top=`${Y.clientY-8}px`),d(O(Y.clientX,Y.clientY)),_(Y.clientY),M(Y.clientX,Y.clientY)},q=Y=>{C(i,O(Y.clientX,Y.clientY)),N()};return window.addEventListener("pointermove",V),window.addEventListener("pointerup",q),()=>{window.removeEventListener("pointermove",V),window.removeEventListener("pointerup",q)}},[i,O,C,N,_,M]);const R=E.useCallback((V,q,Y)=>{if(V.button!==0||V.target.closest("input, button, .sidebar-tag-remove, .sidebar-tag-add, .sidebar-container-actions, .sidebar-delete-btn, .sidebar-confirm-delete, .sidebar-inline-confirm"))return;y.current={x:V.clientX,y:V.clientY},b.current=q;const W=U=>{if(!y.current||!b.current)return;const te=U.clientX-y.current.x,H=U.clientY-y.current.y;if(Math.abs(te)+Math.abs(H)>=v){document.body.style.userSelect="none",window.removeEventListener("pointermove",W),window.removeEventListener("pointerup",$),l(b.current),b.current=null;const Z=document.createElement("div");Z.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);",Z.textContent=Y,document.body.appendChild(Z),m.current=Z,Z.style.left=`${U.clientX+12}px`,Z.style.top=`${U.clientY-8}px`}},$=()=>{window.removeEventListener("pointermove",W),window.removeEventListener("pointerup",$),y.current=null,b.current=null,document.body.style.userSelect=""};window.addEventListener("pointermove",W),window.addEventListener("pointerup",$)},[]);return{draggedItem:i,dropIndicator:c,handlePointerDown:R,dropClass:V=>!c||c.itemId!==V?"":c.position==="before"?"drop-before":c.position==="after"?"drop-after":c.position==="inside"?"drop-inside":"",isDragging:V=>i?i.type==="doc"?i.file===V:i.type==="workspace"?i.filename===V:i.id===V:!1,isContainerDropTarget:V=>!c||!i?!1:c.containerId===V}}function rD({x:t,y:e,filename:n,title:r,onClose:s,onDuplicate:i,onRename:l,onArchive:c,onDelete:d,onPluginAction:f,pluginItems:p,onNewsletterSend:m,onSchedulePost:y,onViewAnalytics:b,viewAnalyticsLabel:v,onMarkSent:k,isAlreadySent:w}){const N=E.useRef(null),[C,O]=E.useState(!1),[_,M]=E.useState(!1),[R,D]=E.useState({left:t,top:e}),[F,B]=E.useState([]),[V,q]=E.useState(!1);E.useEffect(()=>{fetch("/api/connections").then(W=>W.json()).then(W=>{const $=(W.connections||[]).filter(U=>U.provider==="newsletter"&&U.status==="active");B($)}).catch(()=>{})},[]),E.useLayoutEffect(()=>{const W=N.current;if(!W)return;const $=W.getBoundingClientRect(),U=8;let te=t,H=e;e+$.height+U>window.innerHeight&&(H=e-$.height),t+$.width+U>window.innerWidth&&(te=t-$.width),H<U&&(H=U),te<U&&(te=U),D({left:te,top:H})},[t,e]),E.useEffect(()=>{const W=$=>{N.current&&!N.current.contains($.target)&&s()};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[s]),E.useEffect(()=>{const W=$=>{$.key==="Escape"&&s()};return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[s]);const Y=E.useCallback(W=>{f(W.action,W),s()},[f,s]),le=E.useCallback(()=>{m&&(F.length===1?(m(F[0].id),s()):q(!V))},[m,F,V,s]);return u.jsxs("div",{ref:N,className:"context-menu",style:{left:R.left,top:R.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:()=>{l(),s()},children:u.jsx("span",{children:"Rename"})}),_?u.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:W=>W.stopPropagation(),children:[u.jsx("span",{children:"Archive?"}),u.jsx("button",{onClick:()=>{c(),s()},children:"Yes"}),u.jsx("button",{onClick:()=>M(!1),children:"No"})]}):u.jsx("button",{className:"context-menu-item",onClick:()=>M(!0),children:u.jsx("span",{children:"Archive"})}),C?u.jsxs("div",{className:"context-menu-item sidebar-ctx-confirm",onClick:W=>W.stopPropagation(),children:[u.jsx("span",{children:"Delete?"}),u.jsx("button",{onClick:()=>{d(),s()},children:"Yes"}),u.jsx("button",{onClick:()=>O(!1),children:"No"})]}):u.jsx("button",{className:"context-menu-item sidebar-ctx-delete",onClick:()=>O(!0),children:u.jsx("span",{children:"Delete"})}),y&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{y(),s()},children:u.jsx("span",{children:"Schedule Post"})})]}),F.length>0&&m&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:le,children:u.jsx("span",{children:"Send as Newsletter"})}),V&&F.length>1&&u.jsx("div",{className:"context-menu-sub",children:F.map(W=>u.jsx("button",{className:"context-menu-item context-menu-sub-item",onClick:()=>{m(W.id),s()},children:u.jsx("span",{children:W.display_name})},W.id))})]}),k&&!w&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"context-menu-divider"}),u.jsx("button",{className:"context-menu-item",onClick:()=>{k(),s()},children:u.jsx("span",{children:"Mark as Sent"})})]}),b&&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:v||"View Analytics"})})]}),p.length>0&&u.jsx(u.Fragment,{children:(()=>{let W;return p.map($=>{const U=$.pluginDisplayName&&$.pluginDisplayName!==W;return W=$.pluginDisplayName,u.jsxs("span",{children:[U&&u.jsx("div",{className:"context-menu-divider"}),U&&u.jsx("div",{className:"context-menu-section-header",children:$.pluginDisplayName}),u.jsx("button",{className:"context-menu-item",onClick:()=>Y($),children:u.jsx("span",{children:$.label})})]},$.action)})})()})]})}function sD({actionLabel:t,docTitle:e,onConfirm:n,onClose:r}){const[s,i]=E.useState(""),l=E.useRef(null);E.useEffect(()=>{var d;(d=l.current)==null||d.focus()},[]),E.useEffect(()=>{const d=f=>{f.key==="Escape"&&r()};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const c=E.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:l,value:s,onChange:d=>i(d.target.value.slice(0,500)),placeholder:"Optional: guide the transformation (e.g. 'focus on the intro section', 'keep it professional')...",onKeyDown:d=>{d.key==="Enter"&&(d.ctrlKey||d.metaKey)&&c()}})]}),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:c,children:"Go"})]})]})]})})}function _h(t,e){if(!e)return[t];const n=[],r=t.toLowerCase(),s=e.toLowerCase();let i=0;for(;i<t.length;){const l=r.indexOf(s,i);if(l===-1){n.push(t.slice(i));break}l>i&&n.push(t.slice(i,l)),n.push(u.jsx("mark",{children:t.slice(l,l+e.length)},l)),i=l+e.length}return n}function v0({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"?_h(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: ",_h(t.matchedTag,e)]}),t.matchType==="content"&&t.snippet&&u.jsx("div",{className:"search-result-snippet",children:_h(t.snippet,e)}),u.jsxs("div",{className:"sidebar-item-meta",children:[t.wordCount.toLocaleString()," words · ",Mo(t.lastModified)]})]})}function Em({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(l=>!l.isArchived),i=t.filter(l=>l.isArchived);return u.jsx("div",{className:"sidebar-scroll",children:u.jsxs("div",{className:"search-results",children:[s.map(l=>u.jsx(v0,{r:l,query:e,onClick:()=>n(l.filename)},l.filename)),i.length>0&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"search-archived-divider",children:u.jsx("span",{children:"Archived"})}),i.map(l=>u.jsx(v0,{r:l,query:e,onClick:()=>r.handleUnarchive(l.filename)},l.filename))]})]})})}function I1({connectionId:t,subject:e,filename:n,onBeforeSend:r,onClose:s}){const[i,l]=E.useState("confirm"),[c,d]=E.useState("html"),[f,p]=E.useState(""),[m,y]=E.useState(null),[b,v]=E.useState(null),[k,w]=E.useState(0),[N,C]=E.useState(null),[O,_]=E.useState(null),[M,R]=E.useState("all"),[D,F]=E.useState([]),[B,V]=E.useState(""),q=E.useRef(null),Y=D.find(U=>U.id===B),le=M==="exclude_issue"&&Y&&O!=null?Math.max(0,O-Y.recipient_count):O;E.useEffect(()=>{fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"list_subscribers",arguments:{limit:1}})}).then(U=>U.json()).then(U=>{var H,Z;const te=(Z=(H=U.content)==null?void 0:H[0])!=null&&Z.text?JSON.parse(U.content[0].text):U;te.count!=null&&_(te.count)}).catch(()=>{}),fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"list_newsletter_issues",arguments:{limit:10}})}).then(U=>U.json()).then(U=>{var H,Z;const te=(Z=(H=U.content)==null?void 0:H[0])!=null&&Z.text?JSON.parse(U.content[0].text):U;te.issues&&F(te.issues)}).catch(()=>{})},[]);const W=()=>i==="sent"?{sentCount:k,issueId:N,sentAt:new Date().toISOString()}:void 0;E.useEffect(()=>{const U=te=>{i!=="sending"&&i!=="testing"&&q.current&&!q.current.contains(te.target)&&s(W())};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[s,i,k,N]),E.useEffect(()=>{const U=te=>{te.key==="Escape"&&i!=="sending"&&i!=="testing"&&s(W())};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[s,i,k,N]);async function $(U){var te,H;l(U?"testing":"sending"),v(null);try{r&&await r();const Z={subject:e,connectionId:t,format:c};U&&(Z.test_email=U),!U&&M==="exclude_issue"&&B&&(Z.exclude_issue_id=B);const A=await(await fetch("/api/mcp-call",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool:"send_newsletter",arguments:Z})})).json(),j=(H=(te=A.content)==null?void 0:te[0])!=null&&H.text?JSON.parse(A.content[0].text):A;if(j.error){v(j.error),l("error");return}if(j.test){y(j.sent_to),l("confirm");return}const Q=j.sent||0,se=j.issueId||null,fe=new Date().toISOString();w(Q),C(se),l("sent"),fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({newsletterContext:{lastSend:{sentCount:Q,sentAt:fe,issueId:se||void 0}}})}).catch(()=>{})}catch(Z){v(Z.message),l("error")}}return u.jsx("div",{className:"newsletter-modal-overlay",children:u.jsxs("div",{className:"newsletter-modal",ref:q,children:[u.jsxs("div",{className:"newsletter-modal__header",children:[u.jsx("h3",{children:"Send Newsletter"}),u.jsx("button",{className:"newsletter-modal__close",onClick:()=>s(W()),children:"×"})]}),u.jsxs("div",{className:"newsletter-modal__body",children:[i==="confirm"&&u.jsxs(u.Fragment,{children:[u.jsxs("p",{className:"newsletter-modal__confirm-text",style:le==null?{visibility:"hidden"}:void 0,children:['Send "',u.jsx("strong",{children:e}),'" to ',le!=null?le.toLocaleString():0," subscriber",le!==1?"s":"","?"]}),u.jsxs("div",{className:"newsletter-modal__audience",children:[u.jsx("label",{className:"newsletter-modal__label",children:"Audience"}),u.jsxs("select",{className:"newsletter-modal__select",value:M,onChange:U=>{const te=U.target.value;R(te),te==="all"&&V("")},children:[u.jsx("option",{value:"all",children:"All subscribers"}),D.length>0&&u.jsx("option",{value:"exclude_issue",children:"Exclude who received..."})]}),M==="exclude_issue"&&u.jsxs("select",{className:"newsletter-modal__select",value:B,onChange:U=>V(U.target.value),children:[u.jsx("option",{value:"",children:"Select a past issue"}),D.map(U=>u.jsxs("option",{value:U.id,children:[U.subject," (",U.recipient_count," sent)"]},U.id))]})]}),u.jsxs("div",{className:"newsletter-modal__format-toggle",children:[u.jsx("button",{className:`newsletter-modal__format-btn${c==="html"?" active":""}`,onClick:()=>d("html"),children:"HTML"}),u.jsx("button",{className:`newsletter-modal__format-btn${c==="plaintext"?" active":""}`,onClick:()=>d("plaintext"),children:"Plaintext"})]}),u.jsxs("div",{className:"newsletter-modal__test-section",children:[u.jsxs("div",{className:"newsletter-modal__test-row",children:[u.jsx("input",{type:"email",className:"newsletter-modal__test-input",placeholder:"Test email address",value:f,onChange:U=>p(U.target.value),onKeyDown:U=>{U.key==="Enter"&&f.trim()&&$(f.trim())}}),u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--test",disabled:!f.trim(),onClick:()=>$(f.trim()),children:"Send Test"})]}),m&&u.jsxs("p",{className:"newsletter-modal__test-success",children:["Test sent to ",m]})]}),u.jsxs("div",{className:"newsletter-modal__actions",children:[u.jsx("button",{className:"newsletter-modal__btn",onClick:s,children:"Cancel"}),u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",disabled:M==="exclude_issue"&&!B,onClick:()=>$(),children:"Send Now"})]})]}),(i==="sending"||i==="testing")&&u.jsxs("div",{className:"newsletter-modal__status",children:[u.jsx("div",{className:"newsletter-modal__spinner"}),u.jsx("span",{children:i==="testing"?"Sending test...":"Sending..."})]}),i==="sent"&&u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"newsletter-modal__status newsletter-modal__status--success",children:["Sent to ",k," subscriber",k!==1?"s":"","!"]}),u.jsx("div",{className:"newsletter-modal__actions",children:u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>s({sentCount:k,issueId:N,sentAt:new Date().toISOString()}),children:"Done"})})]}),i==="error"&&u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"newsletter-modal__error",children:b}),u.jsxs("div",{className:"newsletter-modal__actions",children:[u.jsx("button",{className:"newsletter-modal__btn",onClick:s,children:"Cancel"}),u.jsx("button",{className:"newsletter-modal__btn newsletter-modal__btn--primary",onClick:()=>$(),children:"Retry"})]})]})]})]})})}async function Th(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 Mh(t,e){return e?(t/e*100).toFixed(1)+"%":"0%"}function x0(t){return new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function k0(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 iD({docId:t,title:e,onClose:n}){const[r,s]=E.useState("loading"),[i,l]=E.useState([]),[c,d]=E.useState(""),[f,p]=E.useState(null),[m,y]=E.useState(null),[b,v]=E.useState("links"),[k,w]=E.useState("all"),[N,C]=E.useState(!1),[O,_]=E.useState(!1),[M,R]=E.useState(""),[D,F]=E.useState(!1),[B,V]=E.useState(null),q=E.useRef(null);E.useEffect(()=>{let ee=!1;return(async()=>{try{const me=await Th("list_newsletter_issues",{limit:20});if(ee)return;if(!me.issues||me.issues.length===0){s("no-data");return}l(me.issues);const Le=me.issues[0].id;d(Le)}catch(me){ee||(y(me.message),s("error"))}})(),()=>{ee=!0}},[]),E.useEffect(()=>{if(!c)return;let ee=!1;return C(!0),_(!1),V(null),R(""),(async()=>{try{const me=await Th("get_newsletter_analytics",{issue_id:c});if(ee)return;if(me.error){y(me.error),s("error");return}p(me),s("loaded")}catch(me){ee||(y(me.message),s("error"))}finally{ee||C(!1)}})(),()=>{ee=!0}},[c]),E.useEffect(()=>{const ee=me=>{q.current&&!q.current.contains(me.target)&&n()};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[n]),E.useEffect(()=>{const ee=me=>{me.key==="Escape"&&n()};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[n]);const Y=f?lD(f.subscriber_events):[],le=(f==null?void 0:f.issue.recipient_count)??0,W=f?f.stats.delivered||le-f.stats.bounces:0,$=f?new Set(f.subscriber_events.filter(ee=>{var me;return ee.event_type==="click"&&((me=ee.url)==null?void 0:me.includes("/newsletter/unsubscribe/"))}).map(ee=>ee.email)).size:0,U=f?f.stats.unsubscribes||$:0,te=f?f.subscriber_events.filter(ee=>ee.event_type==="dropped").length:0,H=f?Math.max(0,le-f.stats.unique_opens):0,Z=f!=null&&f.issue.sent_at?Date.now()-new Date(f.issue.sent_at).getTime():0,G=Math.floor(Z/36e5),A=!!(f!=null&&f.issue.resent_at||B),j=ee=>{const me=Math.floor(ee/36e5);return me<1?"just now":me<24?`${me}h ago`:`${Math.floor(me/24)}d ${me%24}h ago`},Q=async()=>{if(!(!M.trim()||D)){F(!0);try{const ee=await Th("resend_to_unopened",{issue_id:c,subject:M});ee.error?(y(ee.error),s("error")):(V({sent:ee.sent,failed:ee.failed}),_(!1))}catch(ee){y(ee.message),s("error")}finally{F(!1)}}},se=ee=>{var me;return ee.event_type==="unsubscribe"||ee.event_type==="click"&&!!((me=ee.url)!=null&&me.includes("/newsletter/unsubscribe/"))},fe=f?oD(f.subscriber_events.filter(ee=>k==="all"?!0:k==="unsubscribe"?se(ee):ee.event_type===k)):[];return u.jsx("div",{className:"newsletter-modal-overlay",children:u.jsxs("div",{className:"na-modal",ref:q,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:c,onChange:ee=>d(ee.target.value),children:i.map(ee=>u.jsxs("option",{value:ee.id,children:[ee.subject," — ",x0(ee.sent_at)]},ee.id))}),N?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:W.toLocaleString()}),u.jsx("div",{className:"na-kpi__label",children:"Delivered"}),u.jsxs("div",{className:"na-kpi__sub",children:[le.toLocaleString()," sent"]})]}),u.jsxs("div",{className:"na-kpi",children:[u.jsx("div",{className:"na-kpi__value",children:Mh(f.stats.unique_opens,W)}),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:Mh(f.stats.unique_clicks,W)}),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:U}),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:te}),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"})]})]}),H>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 ",j(Z),G<48?" · consider waiting 48h":""]})]}),u.jsx("input",{className:"na-resend-input",type:"text",value:M,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:Q,disabled:D||!M.trim(),children:D?"Sending...":`Send to ${H.toLocaleString()}`})]})]}):u.jsxs("button",{className:"na-resend-toggle",onClick:()=>{_(!0),R(f.issue.subject)},children:["Resend to ",H.toLocaleString()," non-openers ",u.jsx("span",{style:{float:"right"},children:"›"})]})}),A&&u.jsxs("div",{className:"na-resend-done",children:["Resent ",f.issue.resent_at?j(Date.now()-new Date(f.issue.resent_at).getTime()):"just now",B?` — ${B.sent} sent`:"",f.issue.resend_subject?` — "${f.issue.resend_subject}"`:""]}),u.jsxs("div",{className:"na-tabs",children:[u.jsxs("button",{className:`na-tab${b==="links"?" active":""}`,onClick:()=>v("links"),children:["Links (",Y.length,")"]}),u.jsxs("button",{className:`na-tab${b==="activity"?" active":""}`,onClick:()=>v("activity"),children:["Activity (",f.subscriber_events.length,")"]})]}),b==="links"&&u.jsx("div",{className:"na-table-wrap",children:Y.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:Y.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:k0(ee.url)})}),u.jsx("td",{children:ee.uniqueClicks}),u.jsx("td",{children:ee.totalClicks}),u.jsx("td",{children:Mh(ee.uniqueClicks,W)})]},ee.url))})]})}),b==="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${k===ee?" active":""}`,onClick:()=>w(ee),children:ee==="all"?"All":ee.charAt(0).toUpperCase()+ee.slice(1)+"s"},ee))}),u.jsxs("div",{className:"na-table-wrap",children:[fe.length===0?u.jsxs("div",{className:"na-empty",children:["No ",k==="all"?"":k+" ","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:fe.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:k0(ee.url,35)}):"—"}),u.jsx("td",{className:"na-table__time",children:x0(ee.latestTimestamp)})]},ee.key))})]}),fe.length>100&&u.jsxs("div",{className:"na-truncated",children:["Showing 100 of ",fe.length," events"]})]})]})]})]})]})})}function oD(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 lD(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 aD(t){return t.tweetContext?"tweet":t.articleContext?"article":t.linkedinContext?"linkedin":t.newsletterContext?"newsletter":t.blogContext?"blog":"tweet"}function rd({filename:t,title:e,onClose:n}){const[r,s]=E.useState("queue"),[i,l]=E.useState(null),[c,d]=E.useState(null),[f,p]=E.useState(""),[m,y]=E.useState(!1),[b,v]=E.useState(null),[k,w]=E.useState(null);E.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||""),l(aD(O.meta||{}))}).catch(O=>w(O.message))},[t]);const N=async()=>{var O;if(!(!c||!i)){y(!0);try{const _={content:c,content_type:i,mode:r};r==="custom"&&f&&(_.scheduled_at=new Date(f).toISOString());const M=await fetch("/api/scheduler/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)}),R=await M.json();if(M.ok){const D=(O=R.item)!=null&&O.scheduled_at?new Date(R.item.scheduled_at).toLocaleString():"now";v({success:!0,message:`Scheduled for ${D}`})}else v({success:!1,message:R.error||"Failed to schedule"})}catch(_){v({success:!1,message:_.message})}finally{y(!1)}}},C=i===null&&!k;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}),k?u.jsxs("div",{className:"schedule-post-modal-result error",children:[k,u.jsx("button",{className:"schedule-post-modal-done",onClick:n,children:"Done"})]}):b?u.jsxs("div",{className:`schedule-post-modal-result ${b.success?"success":"error"}`,children:[b.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=>p(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:N,disabled:m||C||r==="custom"&&!f,children:m?"Scheduling...":r==="now"?"Post Now":"Schedule"})]})]})]})})}const w0=[{key:"document",label:"Document"},{key:"tweet",label:"Tweet",metadata:{tweetContext:{mode:"tweet"}}},{key:"reply",label:"Reply",needsUrl:!0,urlPlaceholder:"Paste tweet URL...",metadata:{tweetContext:{mode:"reply"}}},{key:"quote",label:"Quote Tweet",needsUrl:!0,urlPlaceholder:"Paste tweet URL...",metadata:{tweetContext:{mode:"quote"}}},{key:"article",label:"Article",metadata:{articleContext:{active:!0}}},{key:"linkedin",label:"LinkedIn",metadata:{linkedinContext:{active:!0}}},{key:"newsletter",label:"Newsletter",metadata:{newsletterContext:{active:!0}}},{key:"blog",label:"Blog",metadata:{blogContext:{active:!0}}}];function cD({anchorRect:t,onSelect:e,onClose:n}){const r=E.useRef(null),[s,i]=E.useState(null),[l,c]=E.useState(""),d=E.useRef(null),[f,p]=E.useState({left:t.left,top:t.bottom+4});E.useLayoutEffect(()=>{const v=r.current;if(!v)return;const k=v.getBoundingClientRect(),w=8;let N=t.left,C=t.bottom+4;C+k.height+w>window.innerHeight&&(C=t.top-k.height-4),N+k.width+w>window.innerWidth&&(N=t.right-k.width),C<w&&(C=w),N<w&&(N=w),p({left:N,top:C})},[t]),E.useEffect(()=>{const v=k=>{r.current&&!r.current.contains(k.target)&&n()};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[n]),E.useEffect(()=>{const v=k=>{k.key==="Escape"&&n()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[n]),E.useEffect(()=>{s&&setTimeout(()=>{var v;return(v=d.current)==null?void 0:v.focus()},0)},[s]);const m=v=>{if(v.needsUrl){i(v.key),c("");return}e(v.metadata)},y=()=>{if(!s||!l.trim())return;const v=l.trim();if(!v.includes("x.com")&&!v.includes("twitter.com"))return;const k=w0.find(N=>N.key===s);if(!(k!=null&&k.metadata))return;const w=JSON.parse(JSON.stringify(k.metadata));w.tweetContext&&(w.tweetContext.url=v),e(w)},b=l.trim().includes("x.com")||l.trim().includes("twitter.com");return u.jsx("div",{ref:r,className:"create-doc-dropdown",style:{left:f.left,top:f.top},children:w0.map(v=>u.jsxs("div",{children:[u.jsx("button",{className:`create-doc-dropdown-item${s===v.key?" active":""}`,onClick:()=>m(v),children:v.label}),s===v.key&&u.jsxs("div",{className:"create-doc-dropdown-url",children:[u.jsx("input",{ref:d,type:"text",placeholder:v.urlPlaceholder,value:l,onChange:k=>c(k.target.value),onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),y()),k.key==="Escape"&&(i(null),c(""))}}),u.jsx("button",{onClick:y,disabled:!b,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"})})})]})]},v.key))})}function L1(t,e){if(!e)return!0;for(const n of t)if(n.type==="container"&&(n.id===e||L1(n.items,e)))return!0;return!1}function D1(t,e){for(const n of t){if(n.type==="doc"&&n.file===e)return[];if(n.type==="container"){const r=D1(n.items,e);if(r)return[n.id,...r]}}return null}function uD({docs:t,archivedDocs:e,workspaces:n,assignedFiles:r,pendingDocs:s,onSwitchDocument:i,onCreateDocument:l,actions:c,scrollRef:d,writingTitle:f,writingTarget:p,searchQuery:m,searchResults:y,onSearchChange:b}){const[v,k]=E.useState(null),[w,N]=E.useState(""),[C,O]=E.useState(null),[_,M]=E.useState(()=>{try{const ne=localStorage.getItem("ow-collapsed-sections");return ne?new Set(JSON.parse(ne)):new Set}catch{return new Set}}),[R,D]=E.useState(null),[F,B]=E.useState(null),[V,q]=E.useState(""),[Y,le]=E.useState(null),[W,$]=E.useState(""),[U,te]=E.useState(null),[H,Z]=E.useState(""),[G,A]=E.useState(null),[j,Q]=E.useState(null),[se,fe]=E.useState([]),[ee,me]=E.useState(null),[Le,Xe]=E.useState(null),[ce,be]=E.useState(null),[ie,Be]=E.useState(null),{draggedItem:Te,dropIndicator:Fe,handlePointerDown:Ee,dropClass:Ye,isDragging:et,isContainerDropTarget:vt}=nD({docs:t,workspaces:n,assignedFiles:r,scrollRef:d,setCollapsedSections:M}),Ce=E.useCallback(()=>{fetch("/api/plugins").then(ne=>ne.json()).then(ne=>{const Ue=[];for(const He of ne.plugins||[]){const _t=He.displayName||void 0;for(const tt of He.sidebarMenuItems||[])Ue.push({...tt,pluginDisplayName:_t})}fe(Ue)}).catch(()=>{})},[]);E.useEffect(()=>{Ce()},[Ce]),E.useEffect(()=>{const ne=()=>Ce();return window.addEventListener("ow-plugins-changed",ne),()=>window.removeEventListener("ow-plugins-changed",ne)},[Ce]);const we=E.useCallback((ne,Ue)=>{ne.preventDefault(),ne.stopPropagation(),A({x:ne.clientX,y:ne.clientY,filename:Ue.filename,title:Ue.title,docId:Ue.docId,lastSent:Ue.lastSent,postedUrl:Ue.postedUrl})},[]),it=E.useCallback(ne=>{fetch("/api/documents/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:ne})}).catch(()=>{})},[]),ut=E.useCallback((ne,Ue,He,_t,tt)=>{if(Ue.promptForFocus&&tt===void 0){me({action:ne,label:Ue.label,filename:He,title:_t});return}fetch("/api/plugins/sidebar-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:ne,filename:He,title:_t,instructions:tt||"",label:Ue.label})}).catch(()=>{})},[]),rt=ne=>{M(Ue=>{const He=new Set(Ue);return He.has(ne)?He.delete(ne):He.add(ne),localStorage.setItem("ow-collapsed-sections",JSON.stringify([...He])),He})},ht=t.find(ne=>ne.isActive),zt=E.useRef(n);if(zt.current=n,E.useEffect(()=>{var ne;if(ht)for(const Ue of zt.current){const He=D1(((ne=Ue.workspace)==null?void 0:ne.root)||[],ht.filename);if(He){M(_t=>{const tt=[Ue.filename,...He.map(Ge=>`container-${Ge}`)];if(tt.every(Ge=>!_t.has(Ge)))return _t;const st=new Set(_t);for(const Ge of tt)st.delete(Ge);return localStorage.setItem("ow-collapsed-sections",JSON.stringify([...st])),st});break}}},[ht==null?void 0:ht.filename]),y!==null)return u.jsx(Em,{results:y,query:m,onSwitchDocument:i,actions:c});const Ct=t.filter(ne=>!r.has(ne.filename)),Vt=(ne,Ue,He,_t,tt)=>u.jsxs("div",{className:`sidebar-item ${ne.isActive?"active":""} ${et(ne.filename)?"dragging":""} ${Ye(ne.filename)}`,"data-drag-id":ne.filename,"data-drag-type":"doc","data-drag-ws":Ue||"__docs__","data-drag-container":He||"",onPointerDown:st=>Ee(st,{type:"doc",file:ne.filename,sourceWs:Ue||null},ne.title),onClick:()=>!ne.isActive&&!Te&&i(ne.filename),onDoubleClick:()=>{k(ne.filename),N(ne.title)},onContextMenu:st=>we(st,ne),children:[v===ne.filename?u.jsx("input",{className:"sidebar-rename-input",value:w,onChange:st=>N(st.target.value),onBlur:()=>{c.handleRename(ne.filename,ne.title,w),k(null)},onKeyDown:st=>{st.key==="Enter"&&(c.handleRename(ne.filename,ne.title,w),k(null)),st.key==="Escape"&&k(null)},autoFocus:!0,onClick:st=>st.stopPropagation()}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"sidebar-item-title",children:[u.jsx("span",{className:"sidebar-item-title-text",children:ne.title}),ne.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"})}),s.filenames.includes(ne.filename)&&u.jsx("span",{className:"sidebar-pending-dot"})]}),bp(ne.filename)&&u.jsx("div",{className:"sidebar-item-context",children:j1(ne.filename)}),u.jsxs("div",{className:"sidebar-item-meta",children:[ne.wordCount.toLocaleString()," words · ",Mo(ne.lastModified)]}),u.jsxs("div",{className:"sidebar-tags",children:[c.getDocTags(ne.filename).map(st=>u.jsxs("span",{className:"sidebar-tag",onClick:Ge=>Ge.stopPropagation(),children:[st,u.jsx("span",{className:"sidebar-tag-remove",onClick:Ge=>{Ge.stopPropagation(),c.handleRemoveTag(ne.filename,st)},children:"×"})]},st)),U===ne.filename?u.jsx("input",{className:"sidebar-tag-input",value:H,onChange:st=>Z(st.target.value),onBlur:()=>{H.trim()&&c.handleAddTag(ne.filename,H),te(null)},onKeyDown:st=>{st.key==="Enter"&&(c.handleAddTag(ne.filename,H),te(null),Z("")),st.key==="Escape"&&(te(null),Z(""))},autoFocus:!0,onClick:st=>st.stopPropagation(),placeholder:"tag..."}):u.jsx("button",{className:"sidebar-tag-add",onClick:st=>{st.stopPropagation(),te(ne.filename),Z("")},children:"+"})]})]}),C===ne.filename?u.jsxs("div",{className:"sidebar-confirm-delete",onClick:st=>st.stopPropagation(),children:[u.jsx("span",{children:"Delete?"}),u.jsx("button",{onClick:()=>{c.handleDelete(ne.filename),O(null)},children:"Yes"}),u.jsx("button",{onClick:()=>O(null),children:"No"})]}):u.jsx("button",{className:"sidebar-delete-btn",onClick:st=>{st.stopPropagation(),O(ne.filename)},title:"Delete document",children:"×"})]},ne.filename),vn=(ne,Ue,He,_t,tt,st)=>{if(ne.type==="doc"){const re=t.find(ke=>ke.filename===ne.file);return re?Vt(re,He,_t):bp(ne.file)?u.jsx("div",{className:"sidebar-item sidebar-unavailable",children:u.jsxs("div",{className:"sidebar-item-title",children:[ne.title||ne.file," (unavailable)"]})},ne.file):u.jsxs("div",{className:"sidebar-item sidebar-missing",children:[u.jsxs("div",{className:"sidebar-item-title",children:[ne.title||ne.file," (missing)"]}),u.jsx("button",{className:"sidebar-delete-btn",onClick:()=>c.handleRemoveFromWorkspace(He,ne.file),title:"Remove",children:"×"})]},ne.file)}const Ge=ne,Wn=`container-${Ge.id}`,cn=_.has(Wn),Tn=Ue<=2?`depth-${Ue}`:"depth-2";return u.jsxs("div",{className:`sidebar-container ${Tn} ${cn?"collapsed":""} ${Ye(Ge.id)} ${vt(Ge.id)?"drop-inside":""}`,children:[u.jsxs("div",{className:`sidebar-container-header ${(Fe==null?void 0:Fe.itemId)===Ge.id&&Fe.position==="inside"?"drop-inside":""}`,"data-drag-id":Ge.id,"data-drag-type":"container-header","data-drag-ws":He,"data-drag-parent":_t||"","data-section-key":Wn,onPointerDown:re=>Ee(re,{type:"container",id:Ge.id,sourceWs:He},Ge.name),onClick:()=>!Te&&rt(Wn),children:[u.jsx("span",{className:`sidebar-chevron ${cn?"collapsed":""}`,children:"▾"}),F===Ge.id?u.jsx("input",{className:"sidebar-rename-input",value:V,onChange:re=>q(re.target.value),onBlur:()=>{c.handleRenameContainer(He,Ge.id,V),B(null)},onKeyDown:re=>{re.key==="Enter"&&(c.handleRenameContainer(He,Ge.id,V),B(null)),re.key==="Escape"&&B(null)},autoFocus:!0,onClick:re=>re.stopPropagation()}):u.jsx("span",{className:"sidebar-container-name",onDoubleClick:re=>{re.stopPropagation(),B(Ge.id),q(Ge.name)},children:Ge.name}),u.jsxs("div",{className:"sidebar-container-actions",children:[u.jsx("button",{className:"sidebar-new-btn",onClick:re=>{re.stopPropagation(),Be({anchor:re.target.getBoundingClientRect(),wsFilename:He,containerId:Ge.id})},title:"New doc",children:"+"}),Ue<2&&u.jsx("button",{className:"sidebar-new-btn",onClick:re=>{re.stopPropagation(),c.handleCreateContainer(He,Ge.id)},title:"New sub-container",children:"☐"}),u.jsx("button",{className:"sidebar-new-btn sidebar-container-delete",onClick:re=>{re.stopPropagation(),c.handleDeleteContainer(He,Ge.id)},title:"Delete container",children:"×"})]})]}),!cn&&u.jsxs("div",{className:"sidebar-container-list","data-drop-ws":He,"data-drop-container":Ge.id,children:[f&&(p==null?void 0:p.wsFilename)===He&&p.containerId===Ge.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..."})]}),(f&&(p==null?void 0:p.wsFilename)===He&&p.containerId===Ge.id?Ge.items.filter(re=>re.type!=="doc"||re.title!==f):Ge.items).map((re,ke)=>vn(re,Ue+1,He,Ge.id,Ge.items)),Ge.items.length===0&&!f&&u.jsx("div",{className:"sidebar-empty",children:Te?"Drop here":"Empty"})]})]},Ge.id)};return u.jsxs("div",{className:"sidebar-scroll",ref:d,children:[u.jsxs("div",{className:`sidebar-section sidebar-docs-section ${_.has("docs")?"docs-collapsed":""}`,children:[u.jsxs("div",{className:"sidebar-section-header","data-section-key":"docs",onClick:()=>rt("docs"),children:[u.jsx("span",{className:`sidebar-chevron ${_.has("docs")?"collapsed":""}`,children:"▾"}),u.jsx("span",{className:"sidebar-label",children:"Documents"}),u.jsx("button",{className:"sidebar-new-btn",onClick:ne=>{ne.stopPropagation(),Be({anchor:ne.target.getBoundingClientRect()})},title:"New document",children:"+"})]}),!_.has("docs")&&u.jsxs("div",{className:"sidebar-section-list","data-drop-ws":"__docs__",children:[f&&(!p||!n.some(ne=>ne.filename===(p==null?void 0:p.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..."})]}),(f?Ct.filter(ne=>ne.title!==f):Ct).map((ne,Ue)=>(Ct.map(He=>({type:"doc",file:He.filename,title:He.title})),Vt(ne,void 0,null))),Ct.length===0&&u.jsx("div",{className:"sidebar-empty",children:Te?"Drop here to unassign":"No unassigned documents"})]})]}),n.map(ne=>{var _t;const Ue=((_t=ne.workspace)==null?void 0:_t.root)||[],He=_.has(ne.filename);return u.jsxs("div",{className:`sidebar-section sidebar-workspace-section ${He?"ws-collapsed":""} ${et(ne.filename)?"dragging":""} ${(Fe==null?void 0:Fe.itemId)===ne.filename?Fe.position==="before"?"drop-before":"drop-after":""}`,children:[u.jsxs("div",{className:"sidebar-section-header","data-section-key":ne.filename,"data-ws-drag":ne.filename,onPointerDown:tt=>Ee(tt,{type:"workspace",filename:ne.filename},ne.title),onClick:()=>!Te&&rt(ne.filename),children:[u.jsx("span",{className:`sidebar-chevron ${He?"collapsed":""}`,children:"▾"}),Y===ne.filename?u.jsx("input",{className:"sidebar-rename-input",value:W,onChange:tt=>$(tt.target.value),onBlur:()=>{c.handleRenameWorkspace(ne.filename,W),le(null)},onKeyDown:tt=>{tt.key==="Enter"&&(c.handleRenameWorkspace(ne.filename,W),le(null)),tt.key==="Escape"&&le(null)},autoFocus:!0,onClick:tt=>tt.stopPropagation()}):u.jsx("span",{className:"sidebar-label sidebar-workspace-label",onDoubleClick:tt=>{tt.stopPropagation(),le(ne.filename),$(ne.title)},children:ne.title}),u.jsxs("div",{className:"sidebar-workspace-actions",children:[u.jsx("button",{className:"sidebar-new-btn",onClick:tt=>{tt.stopPropagation(),Be({anchor:tt.target.getBoundingClientRect(),wsFilename:ne.filename,containerId:null})},title:"New document",children:"+"}),u.jsx("button",{className:"sidebar-new-btn",onClick:tt=>{tt.stopPropagation(),c.handleCreateContainer(ne.filename,null)},title:"New container",children:"☐"}),R===ne.filename?u.jsxs("span",{className:"sidebar-inline-confirm",onClick:tt=>tt.stopPropagation(),children:[u.jsx("button",{onClick:()=>{c.handleDeleteWorkspace(ne.filename),D(null)},children:"Yes"}),u.jsx("button",{onClick:()=>D(null),children:"No"})]}):u.jsx("button",{className:"sidebar-new-btn sidebar-workspace-delete",onClick:tt=>{tt.stopPropagation(),D(ne.filename)},title:"Delete workspace",children:"×"})]})]}),!He&&u.jsxs("div",{className:"sidebar-section-list","data-drop-ws":ne.filename,children:[f&&(p==null?void 0:p.wsFilename)===ne.filename&&(p.containerId===null||!L1(Ue,p.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..."})]}),(f&&(p==null?void 0:p.wsFilename)===ne.filename&&p.containerId===null?Ue.filter(tt=>tt.type!=="doc"||tt.title!==f):Ue).map((tt,st)=>vn(tt,0,ne.filename,null)),Ue.length===0&&!f&&u.jsx("div",{className:"sidebar-empty",children:Te?"Drop here to add":"Empty workspace"})]})]},ne.filename)}),u.jsx("div",{className:"sidebar-new-workspace",children:u.jsx("button",{onClick:c.handleCreateWorkspace,children:"+ New Workspace"})}),G&&u.jsx(rD,{x:G.x,y:G.y,filename:G.filename,title:G.title,onClose:()=>A(null),onDuplicate:()=>it(G.filename),onRename:()=>{k(G.filename),N(G.title)},onArchive:()=>c.handleArchive(G.filename),onDelete:()=>c.handleDelete(G.filename),onPluginAction:(ne,Ue)=>ut(ne,Ue,G.filename,G.title),pluginItems:se,onNewsletterSend:ne=>{Xe({connectionId:ne,filename:G.filename,title:G.title}),A(null)},onSchedulePost:()=>{be({filename:G.filename,title:G.title}),A(null)},onViewAnalytics:G.docId&&G.lastSent?()=>{G.postedUrl?window.open(G.postedUrl,"_blank"):Q({docId:G.docId,title:G.title}),A(null)}:void 0,viewAnalyticsLabel:G.postedUrl?"View on X":"View Analytics",isAlreadySent:!!G.lastSent,onMarkSent:()=>{const ne=G.filename;i(ne),setTimeout(()=>{fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualPost:{postedAt:new Date().toISOString()}})}).then(()=>c.fetchDocs()).catch(()=>{})},100),A(null)}}),ee&&u.jsx(sD,{actionLabel:ee.label,docTitle:ee.title,onClose:()=>me(null),onConfirm:ne=>{const Ue=se.find(He=>He.action===ee.action);Ue&&ut(ee.action,Ue,ee.filename,ee.title,ne),me(null)}}),Le&&u.jsx(I1,{connectionId:Le.connectionId,subject:Le.title,filename:Le.filename,onClose:()=>Xe(null)}),j&&u.jsx(iD,{docId:j.docId,title:j.title,onClose:()=>Q(null)}),ce&&u.jsx(rd,{filename:ce.filename,title:ce.title,onClose:()=>be(null)}),ie&&u.jsx(cD,{anchorRect:ie.anchor,onClose:()=>Be(null),onSelect:ne=>{Be(null),ie.wsFilename?c.handleCreateInWorkspace(ie.wsFilename,ie.containerId??null,ne):ne?fetch("/api/documents",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:ne})}).catch(()=>{}):l()}})]})}function dD({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,onCreateDocument:i,actions:l,scrollRef:c,searchQuery:d,searchResults:f}){const[p,m]=E.useState(null);if(f!==null)return u.jsx(Em,{results:f,query:d,onSwitchDocument:s});const y=[...t].sort((w,N)=>new Date(N.lastModified).getTime()-new Date(w.lastModified).getTime()),b=[];let v="";for(const w of y){const N=ZL(w.lastModified);N!==v&&(b.push({label:N,docs:[]}),v=N),b[b.length-1].docs.push(w)}const k=w=>{for(const N of e){if(!N.workspace)continue;const C=O=>{for(const _ of O)if(_.type==="doc"&&_.file===w||_.type==="container"&&C(_.items))return!0;return!1};if(C(N.workspace.root))return N.title}return null};return u.jsxs("div",{className:"sidebar-scroll tl-scroll",ref:c,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:"+"})]}),b.map(w=>u.jsxs("div",{className:"tl-group",children:[u.jsx("div",{className:"tl-date",children:w.label}),w.docs.map(N=>{const C=k(N.filename);return u.jsxs("div",{className:`tl-item ${N.isActive?"active":""}`,onClick:()=>!N.isActive&&s(N.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:N.title}),r.filenames.includes(N.filename)&&u.jsx("span",{className:"sidebar-pending-dot"})]}),bp(N.filename)&&u.jsx("div",{className:"tl-item-context",children:j1(N.filename)}),u.jsxs("div",{className:"tl-item-meta",children:[N.wordCount.toLocaleString()," words · ",Mo(N.lastModified)]}),C&&u.jsx("div",{className:"tl-badge",children:C})]}),p===N.filename?u.jsxs("div",{className:"sidebar-confirm-delete",onClick:O=>O.stopPropagation(),children:[u.jsx("span",{children:"Delete?"}),u.jsx("button",{onClick:()=>{l.handleDelete(N.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(N.filename)},title:"Delete",children:"×"})]},N.filename)})]},w.label)),t.length===0&&u.jsx("div",{className:"sidebar-empty",children:"No documents yet"})]})}function fD({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:l,searchQuery:c,searchResults:d,onSearchChange:f}){const[p,m]=E.useState([]),[y,b]=E.useState(null),[v,k]=E.useState(null),w=E.useRef(null);E.useEffect(()=>{if(!y)return;const A=j=>{w.current&&!w.current.contains(j.target)&&b(null)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[y]);const N=(A,j)=>{for(const Q of A)if(Q.type==="container"){if(Q.id===j)return Q;const se=N(Q.items,j);if(se)return se}return null},C=A=>{let j=0;for(const Q of A)Q.type==="doc"?j++:Q.type==="container"&&(j+=C(Q.items));return j},O=A=>{const j=[];for(const Q of A)Q.type==="doc"?j.push(Q.file):Q.type==="container"&&j.push(...O(Q.items));return j},_=E.useMemo(()=>{if(p.length===0)return[];const A=p[p.length-1],j=e.find(se=>se.filename===A.wsFilename);if(!(j!=null&&j.workspace))return[];if(A.type==="workspace")return j.workspace.root;const Q=N(j.workspace.root,A.key);return Q?Q.items:[]},[p,e]),M=_.filter(A=>A.type==="container"),R=E.useMemo(()=>{const A=_.filter(j=>j.type==="doc").map(j=>j.file);return t.filter(j=>A.includes(j.filename))},[_,t]),D=A=>{const j=O(A.items);return t.filter(Q=>j.includes(Q.filename))},F=A=>{const j=e.find(se=>se.filename===A);if(!(j!=null&&j.workspace))return[];const Q=O(j.workspace.root);return t.filter(se=>Q.includes(se.filename))},B=E.useMemo(()=>t.filter(A=>!n.has(A.filename)),[t,n]),V=A=>{m(j=>[...j,A]),b(null)},q=()=>{m(A=>A.slice(0,-1)),b(null)},Y=(A,j)=>{if(y===A){b(null);return}const se=j.currentTarget.getBoundingClientRect();k({top:se.bottom+4,left:se.left}),b(A)},le=A=>{s(A),b(null)},W=p.length>1?p[p.length-2].title:"All",$=E.useRef(null),U=E.useRef(null),[te,H]=E.useState(null),Z=E.useCallback(A=>{const Q=A.currentTarget.getBoundingClientRect();H({top:Q.bottom+4,left:Q.left})},[]);E.useEffect(()=>{if(!d)return;const A=j=>{U.current&&!U.current.contains(j.target)&&$.current&&!$.current.contains(j.target)&&f("")};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[d,f]);const G=()=>{if(!y)return[];if(y==="__unassigned__")return B;if(y==="__level-docs__")return R;const A=e.find(j=>j.filename===y);if(A)return F(A.filename);for(const j of e){if(!j.workspace)continue;const Q=N(j.workspace.root,y);if(Q)return D(Q)}return[]};return u.jsxs("div",{className:"board-scroll",ref:l,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:$,className:"board-search-input",type:"text",placeholder:"Search...",value:c,onChange:A=>f(A.target.value),onFocus:Z}),c&&u.jsx("button",{className:"board-search-clear",onClick:()=>f(""),children:"×"})]}),p.length===0?u.jsx("button",{className:"board-back board-back--static",tabIndex:-1,children:"All"}):u.jsxs("button",{className:"board-back",onClick:q,title:`Back to ${W}`,children:["← ",W]}),p.length===0&&u.jsxs(u.Fragment,{children:[B.length>0&&u.jsxs("button",{className:`board-chip ${y==="__unassigned__"?"open":""}`,onClick:A=>Y("__unassigned__",A),children:["Documents ",u.jsx("span",{className:"board-chip-count",children:B.length})]}),e.map(A=>{var Q;const j=(Q=A.workspace)==null?void 0:Q.root.some(se=>se.type==="container");return u.jsxs("button",{className:`board-chip ${y===A.filename?"open":""}`,onClick:se=>j?V({type:"workspace",key:A.filename,title:A.title,wsFilename:A.filename}):Y(A.filename,se),children:[A.title," ",u.jsx("span",{className:"board-chip-count",children:A.docCount}),j&&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:"+"})]}),p.length>0&&u.jsxs(u.Fragment,{children:[R.length>0&&u.jsxs("button",{className:`board-chip board-chip-docs ${y==="__level-docs__"?"open":""}`,onClick:A=>Y("__level-docs__",A),children:["Docs ",u.jsx("span",{className:"board-chip-count",children:R.length})]}),M.map(A=>{const j=A.items.some(Q=>Q.type==="container");return u.jsxs("button",{className:`board-chip ${y===A.id?"open":""}`,onClick:Q=>j?V({type:"container",key:A.id,title:A.name,wsFilename:p[p.length-1].wsFilename}):Y(A.id,Q),children:[A.name," ",u.jsx("span",{className:"board-chip-count",children:C(A.items)}),j&&u.jsx("span",{className:"board-chip-arrow",children:"›"})]},A.id)})]}),y&&v&&(()=>{const A=G();return u.jsxs("div",{className:"board-dropdown",ref:w,style:{position:"fixed",top:v.top,left:v.left},children:[A.map(j=>u.jsxs("div",{className:`board-dropdown-item ${j.isActive?"active":""}`,onClick:()=>le(j.filename),children:[u.jsxs("span",{className:"board-dropdown-title",children:[j.title,r.filenames.includes(j.filename)&&u.jsx("span",{className:"board-pending-dot"})]}),u.jsxs("span",{className:"board-dropdown-meta",children:[j.wordCount.toLocaleString()," words · ",Mo(j.lastModified)]})]},j.filename)),A.length===0&&u.jsx("div",{className:"board-dropdown-empty",children:"No documents"})]})})(),d&&te&&u.jsxs("div",{className:"board-dropdown board-search-dropdown",ref:U,style:{position:"fixed",top:te.top,left:te.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 · ",Mo(A.lastModified)]})]},A.filename)),d.length===0&&u.jsx("div",{className:"board-dropdown-empty",children:"No results"})]})]})}function hD({docs:t,workspaces:e,assignedFiles:n,pendingDocs:r,onSwitchDocument:s,actions:i,scrollRef:l,searchQuery:c,searchResults:d}){const[f,p]=E.useState([]);if(d!==null)return u.jsx(Em,{results:d,query:c,onSwitchDocument:s});const m=(_,M)=>{for(const R of _)if(R.type==="container"){if(R.id===M)return R;const D=m(R.items,M);if(D)return D}return null},y=_=>{let M=0;for(const R of _)R.type==="doc"?M++:R.type==="container"&&(M+=y(R.items));return M},b=E.useMemo(()=>{if(f.length===0)return[];const _=f[f.length-1],M=e.find(D=>D.filename===_.wsFilename);if(!(M!=null&&M.workspace))return[];if(_.type==="workspace")return M.workspace.root;const R=m(M.workspace.root,_.key);return R?R.items:[]},[f,e]),v=b.filter(_=>_.type==="container"),k=E.useMemo(()=>{if(f.length===0)return t.filter(M=>!n.has(M.filename));const _=b.filter(M=>M.type==="doc").map(M=>M.file);return t.filter(M=>_.includes(M.filename))},[f,b,t,n]),w=_=>p(M=>[...M,_]),N=()=>p(_=>_.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:l,children:[f.length>0&&u.jsxs("button",{className:"shelf-back",onClick:N,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:()=>w({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&&v.map(_=>u.jsxs("div",{className:"shelf-section-spine shelf-section-container",onClick:()=>w({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:y(_.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:[k.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 · ",Mo(_.lastModified)]})]},_.filename)),k.length===0&&u.jsx("div",{className:"shelf-docs-empty",children:"No documents"})]})]})]})}const pD=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],mD=[{value:"any",label:"Any"},{value:"content_type",label:"Content Type"},{value:"connection",label:"Connection"}];function gD({slots:t,onBack:e}){const[n,r]=E.useState(t),[s,i]=E.useState("09:00"),[l,c]=E.useState(["default"]),[d,f]=E.useState("any"),[p,m]=E.useState(!1);async function y(){const k=await fetch("/api/scheduler/slots",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({time:s,days:l.includes("default")?["default"]:l,filter_type:d})});if(k.ok){const w=await k.json();r(N=>[...N,w.slot]),m(!1),i("09:00"),c(["default"]),f("any")}}async function b(k){(await fetch(`/api/scheduler/slots/${k}`,{method:"DELETE"})).ok&&r(N=>N.filter(C=>C.id!==k))}function v(k){c(w=>{if(k==="default")return["default"];const N=w.filter(C=>C!=="default");if(N.includes(k)){const C=N.filter(O=>O!==k);return C.length===0?["default"]:C}return[...N,k]})}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:()=>m(!p),children:p?"Cancel":"+ Add"})]}),p&&u.jsxs("div",{style:{padding:"12px",borderBottom:"1px solid var(--sidebar-border)"},children:[u.jsxs("div",{style:{display:"flex",gap:"8px",marginBottom:"8px",alignItems:"center"},children:[u.jsx("input",{type:"time",value:s,onChange:k=>i(k.target.value),style:{background:"var(--sidebar-bg)",border:"1px solid var(--sidebar-border)",borderRadius:"4px",padding:"4px 8px",color:"var(--sidebar-text)",fontSize:"12px"}}),u.jsx("select",{value:d,onChange:k=>f(k.target.value),style:{background:"var(--sidebar-bg)",border:"1px solid var(--sidebar-border)",borderRadius:"4px",padding:"4px 8px",color:"var(--sidebar-text)",fontSize:"12px"},children:mD.map(k=>u.jsx("option",{value:k.value,children:k.label},k.value))})]}),u.jsxs("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginBottom:"8px"},children:[u.jsx("button",{className:`sidebar-schedule-btn ${l.includes("default")?"sidebar-schedule-btn--active":""}`,onClick:()=>v("default"),style:{fontSize:"10px",padding:"2px 6px"},children:"Every day"}),pD.map(k=>u.jsx("button",{className:`sidebar-schedule-btn ${l.includes(k.toLowerCase())?"sidebar-schedule-btn--active":""}`,onClick:()=>v(k.toLowerCase()),style:{fontSize:"10px",padding:"2px 6px"},children:k},k))]}),u.jsx("button",{className:"sidebar-schedule-btn sidebar-schedule-btn--active",onClick:y,style:{width:"100%"},children:"Create Slot"})]}),u.jsx("div",{style:{flex:1,overflow:"auto"},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(k=>u.jsxs("div",{className:"schedule-item",style:{cursor:"default"},children:[u.jsx("div",{className:"schedule-item-time",style:{width:"60px",fontWeight:600},children:yD(k.time)}),u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:k.days.includes("default")?"Every day":k.days.join(", ")}),u.jsxs("div",{className:"schedule-item-meta",children:[u.jsxs("span",{children:["Filter: ",k.filter_type]}),k.filter_value&&u.jsxs("span",{children:["(",k.filter_value,")"]}),u.jsx("span",{children:k.timezone})]})]}),u.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:()=>b(k.id),title:"Delete slot",style:{alignSelf:"center"},children:"×"})]},k.id))})]})}function yD(t){const[e,n]=t.split(":").map(Number),r=e>=12?"PM":"AM";return`${e%12||12}:${String(n).padStart(2,"0")} ${r}`}function bD({onBack:t}){const[e,n]=E.useState([]),[r,s]=E.useState([]),[i,l]=E.useState(null),[c,d]=E.useState(!1),[f,p]=E.useState(!0),m=E.useCallback(async()=>{try{const[N,C]=await Promise.all([fetch("/api/scheduler/autoplugs/goals"),fetch("/api/scheduler/autoplugs/tracking")]);if(N.ok){const O=await N.json();n(O.goals||[])}if(C.ok){const O=await C.json();s(O.tracking||[])}}catch{}p(!1)},[]);E.useEffect(()=>{m()},[m]);const y=async N=>{(await fetch(`/api/scheduler/autoplugs/goals/${N.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!N.enabled})})).ok&&n(O=>O.map(_=>_.id===N.id?{..._,enabled:!_.enabled}:_))},b=async N=>{(await fetch(`/api/scheduler/autoplugs/goals/${N}`,{method:"DELETE"})).ok&&(n(O=>O.filter(_=>_.id!==N)),l(null))},v=async N=>{(await fetch(`/api/scheduler/autoplugs/tracking/${N}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({skipped:!0})})).ok&&s(O=>O.map(_=>_.id===N?{..._,skipped:!0}:_))},k=e.reduce((N,C)=>C.rule&&C.enabled?Math.min(N,C.rule.threshold):N,1/0),w=k===1/0?50:k;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(!c),children:c?"Cancel":"+ Add"})]}),c&&u.jsx(vD,{onCreated:N=>{n(C=>[...C,N]),d(!1)}}),f?null:u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"autoplug-section-header",children:"Goals"}),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(N=>u.jsxs("div",{children:[u.jsxs("div",{className:"schedule-item",onClick:()=>l(i===N.id?null:N.id),children:[u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:N.name}),N.link&&u.jsx("div",{className:"autoplug-goal-summary",children:N.link}),u.jsxs("div",{className:"schedule-item-meta",children:[N.rule&&u.jsxs(u.Fragment,{children:[u.jsxs("span",{children:[N.rule.threshold,"+ ",N.rule.metric]}),u.jsx("span",{children:N.rule.mode.toUpperCase()}),u.jsxs("span",{children:[N.rule.delay_minutes,"m delay"]})]}),u.jsxs("span",{children:[N.pool_count," pool msg",N.pool_count!==1?"s":""]})]})]}),u.jsx("button",{className:`autoplug-toggle ${N.enabled?"autoplug-toggle--on":"autoplug-toggle--off"}`,onClick:C=>{C.stopPropagation(),y(N)},title:N.enabled?"Disable":"Enable"})]}),i===N.id&&u.jsx(xD,{goal:N,onSaved:C=>{n(O=>O.map(_=>_.id===C.id?C:_))},onDeleted:()=>b(N.id),onRefresh:m})]},N.id)),u.jsx("div",{className:"autoplug-section-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(N=>u.jsxs("div",{className:"autoplug-tracking-item",children:[u.jsxs("div",{className:"autoplug-tracking-header",children:[u.jsx("div",{className:"autoplug-tracking-text",children:N.original_text||`Tweet ${N.tweet_id}`}),!N.triggered&&!N.skipped&&u.jsx("button",{className:"autoplug-tracking-skip",onClick:()=>v(N.id),title:"Skip autoplug for this tweet",children:"×"})]}),u.jsxs("div",{className:"autoplug-tracking-meta",children:[u.jsx("span",{children:kD(N.posted_at)}),u.jsxs("span",{children:[N.likes," likes"]}),u.jsxs("span",{children:[N.retweets," RTs"]}),N.views>0&&u.jsxs("span",{children:[wD(N.views)," views"]}),u.jsx("span",{children:N.source})]}),N.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 ",N.goal_name?`→ ${N.goal_name}`:""]}):N.skipped?u.jsx("div",{style:{fontSize:"10px",color:"var(--sidebar-text-secondary)",opacity:.6},children:"Skipped"}):u.jsx("div",{className:"autoplug-tracking-bar",children:u.jsx("div",{className:"autoplug-tracking-bar-fill",style:{width:`${Math.min(100,N.likes/w*100)}%`}})})]},N.id))]})]})}function vD({onCreated:t}){const[e,n]=E.useState(""),[r,s]=E.useState(""),[i,l]=E.useState(""),[c,d]=E.useState("likes"),[f,p]=E.useState(50),[m,y]=E.useState(30),[b,v]=E.useState("static"),[k,w]=E.useState(!1),N=async()=>{if(e.trim()){w(!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){w(!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:c,threshold:f,delay_minutes:m,mode:b})});const _=await fetch("/api/scheduler/autoplugs/goals");if(_.ok){const R=((await _.json()).goals||[]).find(D=>D.id===O.id);if(R){t(R);return}}t({...O,rule_count:1,pool_count:0,rule:{metric:c,threshold:f,delay_minutes:m,mode:b,id:""}})}finally{w(!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=>l(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=>p(Number(C.target.value)),min:1}),u.jsxs("select",{value:c,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",{style:{fontSize:"11px",color:"var(--sidebar-text-secondary)"},children:"wait"}),u.jsx("input",{type:"number",value:m,onChange:C=>y(Number(C.target.value)),min:0,style:{width:"50px"}}),u.jsx("span",{style:{fontSize:"11px",color:"var(--sidebar-text-secondary)"},children:"min"})]}),u.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map(C=>u.jsx("button",{className:b===C?"active":"",onClick:()=>v(C),children:C==="llm"?"LLM":C.charAt(0).toUpperCase()+C.slice(1)},C))}),u.jsx("button",{className:"sidebar-schedule-btn sidebar-schedule-btn--active",onClick:N,disabled:k||!e.trim(),style:{width:"100%"},children:k?"Creating...":"Create Goal"})]})}function xD({goal:t,onSaved:e,onDeleted:n,onRefresh:r}){var q,Y,le,W;const[s,i]=E.useState(t.name),[l,c]=E.useState(t.link||""),[d,f]=E.useState(t.description||""),[p,m]=E.useState(((q=t.rule)==null?void 0:q.metric)||"likes"),[y,b]=E.useState(((Y=t.rule)==null?void 0:Y.threshold)||50),[v,k]=E.useState(((le=t.rule)==null?void 0:le.delay_minutes)||30),[w,N]=E.useState(((W=t.rule)==null?void 0:W.mode)||"static"),[C,O]=E.useState([]),[_,M]=E.useState(""),[R,D]=E.useState(!1);E.useEffect(()=>{fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`).then($=>$.json()).then($=>O($.pool||[])).catch(()=>{})},[t.id]);const F=async()=>{var $;D(!0);try{await fetch(`/api/scheduler/autoplugs/goals/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s,link:l||null,description:d||null})}),($=t.rule)!=null&&$.id?await fetch(`/api/scheduler/autoplugs/rules/${t.rule.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({metric:p,threshold:y,delay_minutes:v,mode:w})}):await fetch("/api/scheduler/autoplugs/rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({goal_id:t.id,metric:p,threshold:y,delay_minutes:v,mode:w})}),r()}finally{D(!1)}},B=async()=>{if(!_.trim())return;const $=await fetch(`/api/scheduler/autoplugs/goals/${t.id}/pool`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:_.trim()})});if($.ok){const U=await $.json();O(te=>[...te,U.message]),M("")}},V=async $=>{(await fetch(`/api/scheduler/autoplugs/pool/${$}`,{method:"DELETE"})).ok&&O(te=>te.filter(H=>H.id!==$))};return u.jsxs("div",{className:"autoplug-editor",children:[u.jsxs("label",{children:["Name",u.jsx("input",{value:s,onChange:$=>i($.target.value)})]}),u.jsxs("label",{children:["Link",u.jsx("input",{value:l,onChange:$=>c($.target.value),placeholder:"https://..."})]}),u.jsxs("label",{children:["Description",u.jsx("textarea",{value:d,onChange:$=>f($.target.value),rows:2})]}),u.jsx("div",{style:{fontSize:"10px",fontWeight:600,color:"var(--sidebar-text-secondary)",textTransform:"uppercase",letterSpacing:"0.3px"},children:"Trigger"}),u.jsxs("div",{className:"autoplug-editor-row",children:[u.jsx("input",{type:"number",value:y,onChange:$=>b(Number($.target.value)),min:1}),u.jsxs("select",{value:p,onChange:$=>m($.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",{style:{fontSize:"11px",color:"var(--sidebar-text-secondary)"},children:"wait"}),u.jsx("input",{type:"number",value:v,onChange:$=>k(Number($.target.value)),min:0,style:{width:"50px"}}),u.jsx("span",{style:{fontSize:"11px",color:"var(--sidebar-text-secondary)"},children:"min"})]}),u.jsx("div",{className:"autoplug-mode-toggle",children:["static","llm","hybrid"].map($=>u.jsx("button",{className:w===$?"active":"",onClick:()=>N($),children:$==="llm"?"LLM":$.charAt(0).toUpperCase()+$.slice(1)},$))}),u.jsxs("div",{className:"autoplug-pool-section",children:[u.jsx("div",{className:"autoplug-pool-label",children:"Static Pool"}),C.map($=>u.jsxs("div",{className:"autoplug-pool-item",children:[u.jsx("span",{children:$.content}),u.jsx("button",{onClick:()=>V($.id),title:"Remove",children:"×"})]},$.id)),u.jsxs("div",{className:"autoplug-pool-add",children:[u.jsx("input",{value:_,onChange:$=>M($.target.value),placeholder:"Add message... (use {{link}} for link)",onKeyDown:$=>$.key==="Enter"&&B()}),u.jsx("button",{onClick:B,children:"+"})]})]}),(w==="llm"||w==="hybrid")&&u.jsx("div",{style:{fontSize:"11px",color:"var(--sidebar-text-secondary)",padding:"4px 0"},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:"sidebar-schedule-btn sidebar-schedule-btn--active",onClick:F,disabled:R,children:R?"Saving...":"Save"}),u.jsx("button",{className:"schedule-item-action schedule-item-action--danger",onClick:n,children:"Delete"})]})]})}function kD(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 wD(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function SD({onBack:t}){const[e,n]=E.useState([]),[r,s]=E.useState([]),[i,l]=E.useState(!1),[c,d]=E.useState(!1),[f,p]=E.useState(null),[m,y]=E.useState(!0),b=E.useCallback(async()=>{try{const[w,N]=await Promise.all([fetch("/api/scheduler/queue"),fetch("/api/scheduler/slots")]);if(w.ok){const C=await w.json();n(C.items||[])}if(N.ok){const C=await N.json();s(C.slots||[])}}catch{}y(!1)},[]);E.useEffect(()=>{b()},[b]);const v=async w=>{(await fetch(`/api/scheduler/queue/${w}`,{method:"DELETE"})).ok&&(n(C=>C.filter(O=>O.id!==w)),p(null))};if(c)return u.jsx(bD,{onBack:()=>{d(!1),b()}});if(i)return u.jsx(gD,{slots:r,onBack:()=>{l(!1),b()}});const k=ED(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:()=>l(!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."})]}):k.map(({label:w,entries:N})=>u.jsxs("div",{className:"schedule-day",children:[u.jsx("div",{className:"schedule-day-header",children:w}),N.map((C,O)=>{var _,M,R,D,F;return C.type==="empty"?u.jsxs("div",{className:"schedule-slot-empty",children:[u.jsx("div",{className:"schedule-item-time",children:E0(C.time)}),u.jsx("div",{className:"schedule-slot-empty-label",children:((_=C.slot)==null?void 0:_.filter_type)==="any"?"Open slot":`${(M=C.slot)==null?void 0:M.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:()=>p(f===C.item.id?null:C.item.id),children:[u.jsx("div",{className:"schedule-item-time",children:E0(C.time)}),u.jsxs("div",{className:"schedule-item-content",children:[u.jsx("div",{className:"schedule-item-text",children:((D=C.item.content)==null?void 0:D.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:((F=C.item.content)==null?void 0:F.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:()=>v(C.item.id),children:"Cancel"})})]})]},C.item.id)})]},w))]})}function ED(t,e){const n=new Date,r=[];for(let c=0;c<7;c++){const d=new Date(n);d.setDate(d.getDate()+c),d.setHours(0,0,0,0);let f;c===0?f="Today":c===1?f="Tomorrow":f=d.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}),r.push({label:f,date:d})}const s=new Map;for(const c of e){const d=new Date(c.scheduled_at),f=`${d.getFullYear()}-${d.getMonth()}-${d.getDate()}-${d.getHours()}-${d.getMinutes()}`;s.set(f,c)}const i=new Set,l=[];for(const{label:c,date:d}of r){const f=[],p=d.getDay(),y=["sun","mon","tue","wed","thu","fri","sat"][p];for(const b of t){if(!(b.days.includes("default")||b.days.includes(y)))continue;const[k,w]=b.time.split(":").map(Number),N=new Date(d);if(N.setHours(k,w,0,0),S0(d,n)&&N<n)continue;const C=`${N.getFullYear()}-${N.getMonth()}-${N.getDate()}-${k}-${w}`,O=s.get(C);O?(f.push({type:"filled",time:N,item:O,slot:b}),i.add(O.id)):f.push({type:"empty",time:N,slot:b})}for(const b of e){if(i.has(b.id))continue;const v=new Date(b.scheduled_at);S0(v,d)&&(f.push({type:"filled",time:v,item:b}),i.add(b.id))}f.sort((b,v)=>b.time.getTime()-v.time.getTime()),f.length>0&&l.push({label:c,entries:f})}return l}function S0(t,e){return t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate()}function E0(t){return t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function ND({profiles:t,activeProfile:e,trashedProfiles:n,onSwitch:r,onCreate:s,onDelete:i,onRestore:l}){const[c,d]=E.useState(!1),[f,p]=E.useState(!1),[m,y]=E.useState(""),[b,v]=E.useState(null),k=E.useRef(null),w=E.useRef(null);E.useEffect(()=>{if(!c)return;const C=O=>{k.current&&!k.current.contains(O.target)&&(d(!1),p(!1),y(""),v(null))};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[c]),E.useEffect(()=>{f&&w.current&&w.current.focus()},[f]);const N=()=>{const C=m.trim();C&&(s(C),y(""),p(!1))};return u.jsxs("div",{className:"sidebar-profile-wrapper",ref:k,children:[u.jsx("button",{className:"sidebar-collapse-btn",onClick:()=>d(!c),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"})]})}),c&&u.jsxs("div",{className:"sidebar-profile-dropdown",children:[t.map(C=>u.jsxs("div",{className:"sidebar-profile-row",children:[b===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),v(null)},children:"Yes"}),u.jsx("button",{onClick:()=>v(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&&b!==C&&u.jsx("button",{className:"sidebar-profile-delete-btn",onClick:O=>{O.stopPropagation(),v(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:()=>l(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:w,type:"text",value:m,onChange:C=>y(C.target.value),onKeyDown:C=>{C.key==="Enter"&&N(),C.key==="Escape"&&(p(!1),y(""))},placeholder:"Profile name..."})}):u.jsxs("button",{className:"sidebar-profile-option sidebar-profile-add",onClick:()=>p(!0),children:[u.jsx("span",{className:"sidebar-profile-check",children:"+"}),u.jsx("span",{children:"New Profile"})]})]})]})}const CD=[{id:"full",label:"Full",lines:3},{id:"compact",label:"Compact",lines:2},{id:"minimal",label:"Minimal",lines:1}];function _D(){const[t,e]=E.useState(!1),[n,r]=E.useState(V0),s=E.useRef(null);E.useEffect(()=>{if(!t)return;const l=c=>{s.current&&!s.current.contains(c.target)&&e(!1)};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[t]);const i=l=>{r(l),_E(l),e(!1)};return u.jsxs("div",{className:"sidebar-density-wrapper",ref:s,children:[u.jsx("button",{className:"sidebar-collapse-btn",onClick:()=>e(!t),title:"Card density",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:"M21 9H3"}),u.jsx("path",{d:"M21 15H3"})]})}),t&&u.jsx("div",{className:"sidebar-density-dropdown",children:CD.map(l=>u.jsxs("button",{className:`sidebar-density-option ${n===l.id?"active":""}`,onClick:()=>i(l.id),children:[u.jsx("span",{className:"sidebar-density-icon",children:Array.from({length:l.lines},(c,d)=>u.jsx("span",{className:"sidebar-density-line"},d))}),u.jsx("span",{children:l.label})]},l.id))})]})}function N0({open:t,onSwitchDocument:e,onCreateDocument:n,refreshKey:r,workspacesRefreshKey:s,pendingDocs:i,writingTitle:l,writingTarget:c,onClose:d}){const{docs:f,workspaces:p,assignedFiles:m,fetchDocs:y,scrollRef:b}=eD(r,s),v=tD(p,y,r),k=zu(),[w,N]=E.useState(!1),[C,O]=E.useState([]),[_,M]=E.useState("Default"),R=E.useCallback(async()=>{try{const se=await fetch("/api/profiles");if(se.ok){const fe=await se.json();O(fe.profiles),M(fe.active)}}catch{}},[]);E.useEffect(()=>{R()},[R]);const D=E.useCallback(async se=>{try{(await fetch("/api/profiles/switch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:se})})).ok&&(M(se),R())}catch{}},[R]),F=E.useCallback(async se=>{try{(await fetch("/api/profiles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:se})})).ok&&R()}catch{}},[R]),[B,V]=E.useState([]),q=E.useCallback(async()=>{try{const se=await fetch("/api/profiles/trash");if(se.ok){const fe=await se.json();V(fe.profiles)}}catch{}},[]);E.useEffect(()=>{q()},[q]);const Y=E.useCallback(async se=>{try{(await fetch(`/api/profiles/${encodeURIComponent(se)}`,{method:"DELETE"})).ok&&(R(),q())}catch{}},[R,q]),le=E.useCallback(async se=>{try{(await fetch("/api/profiles/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:se})})).ok&&(R(),q())}catch{}},[R,q]),[W,$]=E.useState(""),[U,te]=E.useState(null),H=E.useRef(),Z=E.useRef(null),G=E.useCallback(se=>{if($(se),H.current&&clearTimeout(H.current),!se.trim()){te(null);return}H.current=setTimeout(async()=>{try{const fe=await fetch(`/api/documents/search?q=${encodeURIComponent(se.trim())}&archived=true`);fe.ok&&te(await fe.json())}catch{}},250)},[]);E.useEffect(()=>()=>{H.current&&clearTimeout(H.current)},[]);const A={docs:f,archivedDocs:[],workspaces:p,assignedFiles:m,pendingDocs:i,writingTitle:l,writingTarget:c,onSwitchDocument:e,onCreateDocument:n,actions:v,scrollRef:b,searchQuery:W,searchResults:U,onSearchChange:G},j=()=>{switch(k){case"timeline":return u.jsx(dD,{...A});case"board":return u.jsx(fD,{...A});case"shelf":return u.jsx(hD,{...A});default:return u.jsx(uD,{...A})}},Q=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:Z,className:"sidebar-search-input",type:"text",placeholder:"Search...",value:W,onChange:se=>G(se.target.value)}),W&&u.jsx("button",{className:"sidebar-search-clear",onClick:()=>G(""),title:"Clear search",children:"×"})]});return k==="board"?u.jsx("div",{className:`sidebar sidebar-board-mode ${t?"open":""}`,children:j()}):u.jsxs("div",{className:`sidebar ${t?"open":""}`,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(ND,{profiles:C,activeProfile:_,trashedProfiles:B,onSwitch:D,onCreate:F,onDelete:Y,onRestore:le}),u.jsx("button",{className:`sidebar-collapse-btn${w?" sidebar-collapse-btn--active":""}`,onClick:()=>N(!w),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(_D,{}),d&&u.jsx("button",{className:"sidebar-collapse-btn",onClick:d,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"})]})})]})]}),w?u.jsx(SD,{onBack:()=>N(!1)}):u.jsxs(u.Fragment,{children:[Q,j()]})]})}function TD({onClose:t,onSetupComplete:e}){const[n,r]=E.useState("detecting"),[s,i]=E.useState(null),[l,c]=E.useState("gh"),[d,f]=E.useState("openwriter-docs"),[p,m]=E.useState(!0),[y,b]=E.useState(""),[v,k]=E.useState(""),[w,N]=E.useState(""),[C,O]=E.useState("");E.useEffect(()=>{fetch("/api/sync/capabilities").then(M=>M.json()).then(M=>{i(M),M.ghAuthenticated?c("gh"):(M.gitInstalled,c("pat")),r("setup")}).catch(()=>{N("Failed to detect git capabilities"),r("error")})},[]);const _=E.useCallback(async()=>{r("progress"),O(l==="connect"?"Connecting to repository...":"Creating repository and syncing...");try{const M={method:l,repoName:d,isPrivate:p};l==="pat"&&(M.pat=y),l==="connect"&&(M.remoteUrl=v,M.pat=y||void 0);const R=await fetch("/api/sync/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!R.ok){const D=await R.json().catch(()=>({}));throw new Error(D.error||`Setup failed (${R.status})`)}r("done"),e()}catch(M){N(M.message),r("error")}},[l,d,p,y,v,e]);return u.jsx("div",{className:"sync-modal-overlay",onClick:t,children:u.jsxs("div",{className:"sync-modal",onClick:M=>M.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${l==="gh"?" active":""}`,onClick:()=>c("gh"),children:"GitHub CLI"}),u.jsx("button",{className:`sync-tab${l==="pat"?" active":""}`,onClick:()=>c("pat"),children:"Personal Access Token"}),u.jsx("button",{className:`sync-tab${l==="connect"?" active":""}`,onClick:()=>c("connect"),children:"Connect Existing"})]}),l==="gh"&&u.jsxs("div",{className:"sync-form",children:[u.jsxs("label",{children:["Repository name",u.jsx("input",{type:"text",value:d,onChange:M=>f(M.target.value),placeholder:"openwriter-docs"})]}),u.jsxs("label",{className:"sync-checkbox",children:[u.jsx("input",{type:"checkbox",checked:p,onChange:M=>m(M.target.checked)}),"Private repository"]})]}),l==="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:y,onChange:M=>b(M.target.value),placeholder:"ghp_..."})]}),u.jsxs("label",{children:["Repository name",u.jsx("input",{type:"text",value:d,onChange:M=>f(M.target.value),placeholder:"openwriter-docs"})]}),u.jsxs("label",{className:"sync-checkbox",children:[u.jsx("input",{type:"checkbox",checked:p,onChange:M=>m(M.target.checked)}),"Private repository"]})]}),l==="connect"&&u.jsxs("div",{className:"sync-form",children:[u.jsxs("label",{children:["Remote URL",u.jsx("input",{type:"text",value:v,onChange:M=>k(M.target.value),placeholder:"https://github.com/user/repo.git"})]}),u.jsxs("label",{children:["PAT (optional, for private repos)",u.jsx("input",{type:"password",value:y,onChange:M=>b(M.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:l==="pat"&&!y||l==="connect"&&!v||l!=="connect"&&!d,children:l==="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:w}),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 MD({onNodeChanges:t,onAgentStatus:e,onDocumentSwitched:n,onDocumentsChanged:r,onWorkspacesChanged:s,onTitleChanged:i,onPendingDocsChanged:l,onMetadataChanged:c,onSyncStatus:d,onWritingStarted:f,onWritingFinished:p,getEditorState:m}){const y=E.useRef(null),[b,v]=E.useState(!1),k=E.useRef(t),w=E.useRef(e),N=E.useRef(n),C=E.useRef(r),O=E.useRef(s),_=E.useRef(i),M=E.useRef(l),R=E.useRef(d),D=E.useRef(c),F=E.useRef(f),B=E.useRef(p),V=E.useRef(m);k.current=t,w.current=e,N.current=n,C.current=r,O.current=s,_.current=i,M.current=l,D.current=c,R.current=d,F.current=f,B.current=p,V.current=m,E.useEffect(()=>{const le=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;let W,$=!1,U=1e3;function te(){const Z=new WebSocket(le);y.current=Z,Z.onopen=()=>{v(!0),U=1e3,$&&Z.send(JSON.stringify({type:"request-document"})),$=!0},Z.onmessage=G=>{var A,j,Q,se,fe,ee,me,Le,Xe,ce,be;try{const ie=JSON.parse(G.data);ie.type==="node-changes"&&ie.changes&&((A=k.current)==null||A.call(k,ie.changes)),ie.type==="agent-status"&&((j=w.current)==null||j.call(w,!!ie.agentConnected)),ie.type==="document-switched"&&((Q=N.current)==null||Q.call(N,{document:ie.document,title:ie.title,filename:ie.filename,docId:ie.docId,metadata:ie.metadata})),ie.type==="metadata-changed"&&ie.metadata&&((se=D.current)==null||se.call(D,ie.metadata)),ie.type==="documents-changed"&&((fe=C.current)==null||fe.call(C)),ie.type==="workspaces-changed"&&((ee=O.current)==null||ee.call(O)),ie.type==="title-changed"&&ie.title&&((me=_.current)==null||me.call(_,ie.title)),ie.type==="pending-docs-changed"&&ie.pendingDocs&&((Le=M.current)==null||Le.call(M,ie.pendingDocs)),ie.type==="sync-status"&&((Xe=R.current)==null||Xe.call(R,{state:ie.state,lastSyncTime:ie.lastSyncTime,pendingFiles:ie.pendingFiles,error:ie.error})),ie.type==="writing-started"&&ie.title&&((ce=F.current)==null||ce.call(F,ie.title,ie.target||null)),ie.type==="writing-finished"&&((be=B.current)==null||be.call(B)),ie.type==="plugins-changed"&&window.dispatchEvent(new CustomEvent("ow-plugins-changed")),ie.type==="marks-changed"&&ie.filename&&window.dispatchEvent(new CustomEvent("ow-marks-changed",{detail:{filename:ie.filename}}))}catch{}},Z.onclose=()=>{v(!1),W=setTimeout(te,U),U=Math.min(U*1.5,8e3)},Z.onerror=()=>{Z.close()}}te();function H(){var Z;document.visibilityState==="visible"&&((Z=y.current)==null?void 0:Z.readyState)!==WebSocket.OPEN&&(clearTimeout(W),U=1e3,te())}return document.addEventListener("visibilitychange",H),()=>{var Z;clearTimeout(W),document.removeEventListener("visibilitychange",H),(Z=y.current)==null||Z.close()}},[]);const q=E.useCallback(Y=>{var le;((le=y.current)==null?void 0:le.readyState)===WebSocket.OPEN&&y.current.send(JSON.stringify(Y))},[]);return{connected:b,sendMessage:q}}function AD(t){const[e,n]=E.useState(null),[r,s]=E.useState(!1),[i,l]=E.useState(null),c=E.useRef(void 0);return E.useEffect(()=>{if(!t){n(null),s(!1),l(null),c.current=void 0;return}t!==c.current&&(c.current=t,s(!0),l(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=>{l(d.message),s(!1)}))},[t]),{tweet:e,loading:r,error:i}}function OD(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(`
205
205
 
206
206
  `)}function RD(t,e){const[n,r]=E.useState("idle"),s=E.useRef();return{copyText:E.useCallback(async()=>{const l=t.current[e];if(!l)return;const c=OD(l);if(c){try{await navigator.clipboard.writeText(c)}catch{const d=document.createElement("textarea");d.value=c,d.style.position="fixed",d.style.opacity="0",document.body.appendChild(d),d.select(),document.execCommand("copy"),document.body.removeChild(d)}r("copied"),s.current&&clearTimeout(s.current),s.current=setTimeout(()=>r("idle"),2e3)}},[t,e]),copyState:n}}function Ah(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 jD(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 ID=()=>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"})}),LD=()=>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"})}),DD=()=>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"})}),PD=()=>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"})}),BD=()=>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 P1({tweet:t,nested:e,url:n}){const r=jD(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",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(P1,{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(ID,{}),t.metrics.replies>0&&Ah(t.metrics.replies)]}),u.jsxs("span",{className:"tweet-action tweet-action-retweet",children:[u.jsx(LD,{}),t.metrics.retweets>0&&Ah(t.metrics.retweets)]}),u.jsxs("span",{className:"tweet-action tweet-action-like",children:[u.jsx(DD,{}),t.metrics.likes>0&&Ah(t.metrics.likes)]}),u.jsx("span",{className:"tweet-action tweet-action-bookmark",children:u.jsx(PD,{})}),u.jsx("span",{className:"tweet-action tweet-action-share",children:u.jsx(BD,{})})]})]})}function zD({tweet:t,url:e}){return u.jsx(P1,{tweet:t,url:e})}function $D({initialContent:t,placeholder:e="What is happening?!",onUpdate:n,onReady:r,onFocus:s}){const i=ow({extensions:[...v1,ed.configure({placeholder:e})],content:t||"<p></p>",onUpdate:({editor:l})=>{n==null||n(l)},onFocus:()=>{s==null||s()}},[t]);return E.useEffect(()=>{if(!i)return;const{state:l}=i.view;if(l.plugins.some(f=>f.key==="pendingDecoration$"))return;const c=E1(),d=l.reconfigure({plugins:[...l.plugins,c]});i.view.updateState(d)},[i]),E.useEffect(()=>{if(!i)return;const{state:l}=i.view;if(l.plugins.some(f=>f.key==="markDecoration$"))return;const c=N1(),d=l.reconfigure({plugins:[...l.plugins,c]});i.view.updateState(d)},[i]),E.useEffect(()=>{i&&(r==null||r(i))},[i,r]),i?u.jsx(Qp,{editor:i}):null}function FD({count:t,softLimit:e=280}){const n=e-t,r=Math.min(t/e,1),s=26,i=2,l=(s-i)/2,c=2*Math.PI*l,d=c*(1-r);let f="var(--x-blue, #1d9bf0)";n<=0?f="var(--x-red, #f4212e)":n<=20&&(f="var(--x-yellow, #ffd400)");const p=n<=20;return t===0?null:u.jsxs("div",{className:"tweet-char-counter",title:`${t} / ${e}`,style:{width:s,height:s},children:[u.jsxs("svg",{width:s,height:s,viewBox:`0 0 ${s} ${s}`,children:[u.jsx("circle",{cx:s/2,cy:s/2,r:l,fill:"none",stroke:"var(--x-border, #eff3f4)",strokeWidth:i}),u.jsx("circle",{cx:s/2,cy:s/2,r:l,fill:"none",stroke:f,strokeWidth:i,strokeDasharray:c,strokeDashoffset:d,strokeLinecap:"round",transform:`rotate(-90 ${s/2} ${s/2})`,style:{transition:"stroke-dashoffset 0.15s ease, stroke 0.15s ease"}})]}),p&&u.jsx("span",{className:"tweet-char-number",style:{color:f},children:n})]})}const C0="@openwriter/plugin-x-api",_0=[{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 UD({onConnected:t,onCancel:e}){const[n,r]=E.useState({"api-key":"","api-secret":"","access-token":"","access-token-secret":""}),[s,i]=E.useState(!1),[l,c]=E.useState(""),d=_0.every(p=>n[p.key].trim()),f=async()=>{i(!0),c("");try{if(!(await fetch("/api/plugins/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:C0,config:n})})).ok)throw new Error("Failed to save config");const y=await(await fetch("/api/plugins/enable",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:C0})})).json();if(!y.success)throw new Error(y.error||"Failed to enable plugin");const v=await(await fetch("/api/x/status")).json();v.connected?t():c(v.error||"Could not verify X credentials. Check your API keys.")}catch(p){c(p.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:_0.map(p=>u.jsxs("div",{className:"x-connect-field",children:[u.jsx("label",{className:"x-connect-label",children:p.label}),u.jsx("input",{type:"password",className:"x-connect-input",value:n[p.key],onChange:m=>r(y=>({...y,[p.key]:m.target.value})),placeholder:p.env,spellCheck:!1,autoComplete:"off"})]},p.key))}),l&&u.jsx("div",{className:"x-connect-error",children:l}),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"})]})]})}const T0="ow-x-handle";function HD(){const[t,e]=E.useState(()=>localStorage.getItem(T0)||""),[n,r]=E.useState(!1),[s,i]=E.useState(""),l=E.useRef(null),c=E.useRef(null),d=()=>{const m=s.replace(/^@/,"").trim();m&&(localStorage.setItem(T0,m),e(m)),r(!1)},f=()=>{i(t),r(!0),setTimeout(()=>{var m;return(m=l.current)==null?void 0:m.focus()},0)};E.useEffect(()=>{if(!n)return;const m=y=>{c.current&&!c.current.contains(y.target)&&d()};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[n,s]);const p=t?`https://unavatar.io/twitter/${t}`:"";return u.jsxs("div",{className:"tweet-compose-avatar-wrapper",ref:c,children:[t?u.jsx("img",{className:"tweet-compose-avatar tweet-compose-avatar-img",src:p,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:l,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 M0(){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 WD(t){var e;if(t)return(e=t.match(/\/status\/(\d+)/))==null?void 0:e[1]}function A0(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 Oh(t){const e=[],n=t.filter(Boolean);return n.forEach((r,s)=>{const i=r.getJSON();i.content&&e.push(...i.content),s<n.length-1&&e.push({type:"horizontalRule"})}),{type:"doc",content:e}}function O0(t){const e=[],n=r=>{var s;r.type==="image"&&((s=r.attrs)!=null&&s.src)&&e.push(r.attrs.src),r.content&&r.content.forEach(n)};return n(t.getJSON()),e.slice(0,4)}function Rh(t){fetch("/api/metadata",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tweetContext:t}),keepalive:!0}).catch(()=>{})}function VD({tweetContext:t,initialContent:e,onUpdate:n,onEditorReady:r,onEditorsChange:s,filename:i,title:l}){const{tweet:c,loading:d,error:f}=AD(t==null?void 0:t.url),[p,m]=E.useState(()=>A0(e)),[y,b]=E.useState(0),v=E.useRef([]),k=E.useRef(null),w=E.useRef(!0),N=E.useRef(!1),C=E.useRef(p.length),[O,_]=E.useState(()=>p.map(()=>0)),[M,R]=E.useState(0),[D,F]=E.useState(0),[B,V]=E.useState(null),[q,Y]=E.useState(),[le,W]=E.useState(!1),[$,U]=E.useState("idle"),[te,H]=E.useState(""),Z=E.useRef(),{copyText:G,copyState:A}=RD(v,M),[j,Q]=E.useState(!1);E.useEffect(()=>{let Ce=!1;return(async()=>{try{const we=await fetch("/api/x/status");if(Ce)return;if(we.ok){const it=await we.json();V(it.connected),Y(it.username)}else V(!1)}catch{Ce||V(!1)}})(),()=>{Ce=!0}},[]),E.useEffect(()=>{if(w.current){w.current=!1;return}if(!e||JSON.stringify(e)===k.current)return;const we=A0(e);N.current=!0,C.current=we.length,v.current=[],m(we),_(we.map(()=>0)),b(it=>it+1)},[e]);const se=E.useCallback((Ce,we)=>{if(v.current[Ce]=we,_(ut=>{const rt=[...ut];return rt[Ce]=we.getText().length,rt}),N.current)return;const it=Oh(v.current);k.current=JSON.stringify(it),n==null||n(it)},[n]),fe=E.useCallback((Ce,we)=>{if(v.current[Ce]=we,_(it=>{const ut=[...it];return ut[Ce]=we.getText().length,ut}),F(it=>it+1),N.current&&v.current.filter(Boolean).length>=C.current){N.current=!1;const ut=Oh(v.current);k.current=JSON.stringify(ut)}Ce===0&&(r==null||r(we)),s==null||s(v.current.filter(Boolean))},[r,s]),ee=p.length>1;O.reduce((Ce,we)=>Ce+we,0);const me=E.useCallback(()=>{const Ce=M+1;m(we=>[...we.slice(0,Ce),"<p></p>",...we.slice(Ce)]),_(we=>[...we.slice(0,Ce),0,...we.slice(Ce)]),R(Ce)},[M]),Le=E.useCallback(Ce=>{Ce!==0&&(v.current.splice(Ce,1),m(we=>we.filter((it,ut)=>ut!==Ce)),_(we=>we.filter((it,ut)=>ut!==Ce)),setTimeout(()=>{const we=Oh(v.current);n==null||n(we),s==null||s(v.current.filter(Boolean))},0))},[n,s]),Xe=!!(t!=null&&t.url),ce=(t==null?void 0:t.mode)==="reply",be=v.current.filter(Boolean).some(we=>we.getText().trim()||O0(we).length>0),ie=B&&be&&$==="idle",Be=async()=>{if(!B){W(!0);return}if(ie){U("uploading"),H("");try{const Ce=v.current.filter(Boolean),we=[];for(const ut of Ce){const rt=ut.getText().trim(),ht=O0(ut);if(!rt&&ht.length===0)continue;const zt=[];for(const Ct of ht){const vn=await(await fetch("/api/x/upload-media",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({src:Ct})})).json();if(!vn.success)throw new Error(vn.error||"Image upload failed");zt.push(vn.mediaId)}we.push({text:rt,mediaIds:zt})}if(we.length===0)return;U("posting");const it=WD(t==null?void 0:t.url);if(we.length===1){const ut={};we[0].text&&(ut.text=we[0].text),we[0].mediaIds.length>0&&(ut.mediaIds=we[0].mediaIds),(t==null?void 0:t.mode)==="reply"&&it?ut.replyTo=it:(t==null?void 0:t.mode)==="quote"&&it&&(ut.quoteTweetId=it);const ht=await(await fetch("/api/x/post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ut)})).json();ht.success?(Rh({lastPost:{postedAt:new Date().toISOString(),tweetUrl:ht.tweetUrl}}),U("success"),Z.current=setTimeout(()=>U("idle"),2500)):(console.error("[TweetCompose] Post error:",ht.error),H(ht.error||"Post failed"),U("error"),setTimeout(()=>U("idle"),3e3))}else{const rt={tweets:we.map(Ct=>({text:Ct.text,...Ct.mediaIds.length>0?{mediaIds:Ct.mediaIds}:{}}))};(t==null?void 0:t.mode)==="reply"&&it&&(rt.replyTo=it);const zt=await(await fetch("/api/x/post-thread",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(rt)})).json();zt.success?(Rh({lastPost:{postedAt:new Date().toISOString(),tweetUrl:zt.threadUrl}}),U("success"),Z.current=setTimeout(()=>U("idle"),2500)):(H(zt.error||"Thread post failed"),U("error"),setTimeout(()=>U("idle"),3e3))}}catch(Ce){H(Ce.message||"Network error"),U("error"),setTimeout(()=>U("idle"),3e3)}}};E.useEffect(()=>()=>{Z.current&&clearTimeout(Z.current)},[]);const Te=()=>{V(!0),W(!1),fetch("/api/x/status").then(Ce=>Ce.json()).then(Ce=>{Ce.username&&Y(Ce.username)}).catch(()=>{})},Fe=$==="uploading"?"Uploading...":$==="posting"?"Posting...":$==="success"?"Posted!":$==="error"?"Failed":ee?M===0?"Post Thread":"Post All":"Post",Ee=p.map((Ce,we)=>we===0?ce?"Post your reply":"What is happening?!":"Add another tweet"),Ye=Ce=>{var we;return u.jsxs("div",{className:`tweet-compose-footer${Ce?" tweet-compose-footer--inline":""}`,children:[M===0&&((we=t==null?void 0:t.lastPost)==null?void 0:we.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"})," on X"]}),$==="error"&&te&&u.jsx("span",{className:"tweet-post-error",children:te}),u.jsx(FD,{count:O[M]||0}),u.jsx("button",{className:"tweet-thread-add",onClick:me,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${A==="copied"?" tweet-copy-btn--copied":""}`,disabled:!be,onClick:G,title:"Copy tweet text to clipboard",children:A==="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"]})}),M===0&&(()=>{var ut;const it=!!((ut=t==null?void 0:t.lastPost)!=null&&ut.postedAt);return u.jsx("button",{className:`tweet-mark-sent-btn${it?" tweet-mark-sent-btn--done":""}`,onClick:()=>{it||Rh({lastPost:{postedAt:new Date().toISOString()}})},title:it?"Posted":"Mark as manually posted",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:it?"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:it?"#fff":"currentColor"})]})})})(),i&&u.jsx("button",{className:"tweet-schedule-btn",onClick:()=>Q(!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${ie||!B&&B!==null?" tweet-post-btn--active":""}${$==="success"?" tweet-post-btn--success":""}${$==="error"?" tweet-post-btn--error":""}`,disabled:B?!ie:!1,onClick:Be,title:B?q?`Post as @${q}`:"Post to X":"Connect X to post",children:Fe})]})},et=Xe&&!ce,vt=()=>u.jsx("div",{className:"tweet-thread-editors",children:p.map((Ce,we)=>u.jsxs("div",{className:`tweet-thread-item${we===M?" tweet-thread-item--active":" tweet-thread-item--inactive"}`,children:[u.jsxs("div",{className:"tweet-thread-item-left",children:[u.jsx(HD,{}),we<p.length-1&&u.jsx("div",{className:"tweet-thread-line"})]}),u.jsxs("div",{className:"tweet-thread-item-right",children:[we>0&&u.jsx("button",{className:"tweet-thread-remove",onClick:()=>Le(we),title:"Remove this tweet",children:"×"}),u.jsx("div",{className:`tweet-compose-box${we===0&&!ee?" tweet-compose-box--standalone":""}`,children:u.jsx($D,{initialContent:Ce,placeholder:Ee[we],onUpdate:it=>se(we,it),onReady:it=>fe(we,it),onFocus:()=>R(we)})}),we===M&&!et&&Ye(we<p.length-1)]})]},`${y}-${we}`))});return u.jsxs("div",{className:"tweet-compose-wrapper",children:[Xe&&ce&&u.jsxs(u.Fragment,{children:[d&&u.jsx("div",{className:"tweet-context-section",children:u.jsx(M0,{})}),f&&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})]})}),c&&u.jsx("div",{className:"tweet-reply-parent-section",children:u.jsxs("div",{className:"tweet-reply-thread",children:[u.jsxs("div",{className:"tweet-reply-thread-left",children:[c.author.avatarUrl?u.jsx("img",{className:"tweet-avatar",src:c.author.avatarUrl,alt:""}):u.jsx("div",{className:"tweet-avatar tweet-avatar-placeholder"}),u.jsx("div",{className:"tweet-reply-thread-line"})]}),u.jsxs("div",{className:"tweet-reply-thread-right",children:[u.jsxs("div",{className:"tweet-reply-parent",children:[u.jsxs("div",{className:"tweet-author-info",children:[u.jsx("span",{className:"tweet-author-name",children:c.author.name}),u.jsxs("span",{className:"tweet-author-handle",children:["@",c.author.username]})]}),u.jsx("div",{className:"tweet-text",children:c.text}),c.media&&c.media.length>0&&u.jsx("div",{className:"tweet-media",children:c.media.map((Ce,we)=>Ce.type==="photo"?u.jsx("img",{className:"tweet-media-img",src:Ce.url,alt:"",loading:"lazy"},we):u.jsx("div",{className:"tweet-media-video-placeholder",children:u.jsx("span",{children:"Video"})},we))})]}),u.jsxs("div",{className:"tweet-replying-to-inline",children:["Replying to ",u.jsxs("span",{className:"tweet-reply-handle",children:["@",c.author.username]})]})]})]})}),vt()]}),et&&u.jsxs(u.Fragment,{children:[vt(),u.jsxs("div",{className:"tweet-quote-section",style:{padding:"0 16px 12px"},children:[d&&u.jsx(M0,{}),f&&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})]}),c&&u.jsx(zD,{tweet:c,url:t==null?void 0:t.url})]}),u.jsx("div",{className:"tweet-quote-footer",children:Ye()})]}),!Xe&&vt(),le&&u.jsx(UD,{onConnected:Te,onCancel:()=>W(!1)}),j&&i&&u.jsx(rd,{filename:i,title:l||"Untitled",onClose:()=>Q(!1)})]})}function KD(){const[t,e]=E.useState("idle"),n=E.useRef();return{copyAsHtml:E.useCallback(async()=>{const s=document.querySelector(".ProseMirror");if(!s)return;const i=s.cloneNode(!0);i.querySelectorAll(".ProseMirror-widget, [data-widget], .ProseMirror-gapcursor").forEach(p=>p.remove());let l="";const c=document.querySelector(".article-title-input");c!=null&&c.value&&c.value!=="Untitled"&&(l+=`<h1>${c.value}</h1>
207
207
  `);const d=l+i.innerHTML,f=GD(i);try{const p=new ClipboardItem({"text/html":new Blob([d],{type:"text/html"}),"text/plain":new Blob([f],{type:"text/plain"})});await navigator.clipboard.write([p])}catch{try{await navigator.clipboard.writeText(f)}catch{const p=document.createElement("textarea");p.value=f,p.style.position="fixed",p.style.opacity="0",document.body.appendChild(p),p.select(),document.execCommand("copy"),document.body.removeChild(p)}}e("copied"),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>e("idle"),2e3)},[]),copyState:t}}function GD(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(`