From e97a31c0d17b96eea1e628e92dd4c1c7b34ca5ac Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Sat, 22 Aug 2026 14:11:49 +0200 Subject: [PATCH] feat(frontend): add text-capture form to CaptureDialog - Add submitTextCapture API client function with same error handling as submitCapture - Create makeTextItem() factory for text capture state - Implement CaptureTextRow component with title, body textarea, and MIME selector - Add 'Add text' button in capture dialog toolbar - Update handleArchive to filter and route text submissions - Modify submitBgJob to detect and submit text items via submitTextCapture - Skip probe and conflict checks for text items - Reuse job tracking and batch settlement for text captures Co-Authored-By: Claude Haiku 4.5 --- .../static/assets/index-B67momER.js | 47 ----- .../static/assets/index-CthL4K20.js | 47 +++++ crates/archivr-server/static/index.html | 2 +- frontend/src/api.js | 18 ++ frontend/src/components/CaptureDialog.jsx | 164 ++++++++++++++++-- 5 files changed, 213 insertions(+), 65 deletions(-) delete mode 100644 crates/archivr-server/static/assets/index-B67momER.js create mode 100644 crates/archivr-server/static/assets/index-CthL4K20.js diff --git a/crates/archivr-server/static/assets/index-B67momER.js b/crates/archivr-server/static/assets/index-B67momER.js deleted file mode 100644 index 0bff979..0000000 --- a/crates/archivr-server/static/assets/index-B67momER.js +++ /dev/null @@ -1,47 +0,0 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(l){if(l.ep)return;l.ep=!0;const i=n(l);fetch(l.href,i)}})();var $u={exports:{}},ks={},Ou={exports:{}},ne={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var dl=Symbol.for("react.element"),cf=Symbol.for("react.portal"),df=Symbol.for("react.fragment"),ff=Symbol.for("react.strict_mode"),pf=Symbol.for("react.profiler"),hf=Symbol.for("react.provider"),mf=Symbol.for("react.context"),gf=Symbol.for("react.forward_ref"),yf=Symbol.for("react.suspense"),vf=Symbol.for("react.memo"),xf=Symbol.for("react.lazy"),po=Symbol.iterator;function wf(e){return e===null||typeof e!="object"?null:(e=po&&e[po]||e["@@iterator"],typeof e=="function"?e:null)}var Au={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Mu=Object.assign,Fu={};function yr(e,t,n){this.props=e,this.context=t,this.refs=Fu,this.updater=n||Au}yr.prototype.isReactComponent={};yr.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};yr.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Bu(){}Bu.prototype=yr.prototype;function da(e,t,n){this.props=e,this.context=t,this.refs=Fu,this.updater=n||Au}var fa=da.prototype=new Bu;fa.constructor=da;Mu(fa,yr.prototype);fa.isPureReactComponent=!0;var ho=Array.isArray,Uu=Object.prototype.hasOwnProperty,pa={current:null},Hu={key:!0,ref:!0,__self:!0,__source:!0};function Wu(e,t,n){var r,l={},i=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(i=""+t.key),t)Uu.call(t,r)&&!Hu.hasOwnProperty(r)&&(l[r]=t[r]);var o=arguments.length-2;if(o===1)l.children=n;else if(1>>1,ee=D[te];if(0>>1;tel(ye,H))cel(Ee,ye)?(D[te]=Ee,D[ce]=H,te=ce):(D[te]=ye,D[Y]=H,te=Y);else if(cel(Ee,H))D[te]=Ee,D[ce]=H,te=ce;else break e}}return P}function l(D,P){var H=D.sortIndex-P.sortIndex;return H!==0?H:D.id-P.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var a=Date,o=a.now();e.unstable_now=function(){return a.now()-o}}var u=[],c=[],y=1,g=null,h=3,v=!1,x=!1,S=!1,N=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,f=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function m(D){for(var P=n(c);P!==null;){if(P.callback===null)r(c);else if(P.startTime<=D)r(c),P.sortIndex=P.expirationTime,t(u,P);else break;P=n(c)}}function w(D){if(S=!1,m(D),!x)if(n(u)!==null)x=!0,Ae(C);else{var P=n(c);P!==null&&ge(w,P.startTime-D)}}function C(D,P){x=!1,S&&(S=!1,p(k),k=-1),v=!0;var H=h;try{for(m(P),g=n(u);g!==null&&(!(g.expirationTime>P)||D&&!q());){var te=g.callback;if(typeof te=="function"){g.callback=null,h=g.priorityLevel;var ee=te(g.expirationTime<=P);P=e.unstable_now(),typeof ee=="function"?g.callback=ee:g===n(u)&&r(u),m(P)}else r(u);g=n(u)}if(g!==null)var Re=!0;else{var Y=n(c);Y!==null&&ge(w,Y.startTime-P),Re=!1}return Re}finally{g=null,h=H,v=!1}}var E=!1,b=null,k=-1,T=5,L=-1;function q(){return!(e.unstable_now()-LD||125te?(D.sortIndex=H,t(c,D),n(u)===null&&D===n(c)&&(S?(p(k),k=-1):S=!0,ge(w,H-te))):(D.sortIndex=ee,t(u,D),x||v||(x=!0,Ae(C))),D},e.unstable_shouldYield=q,e.unstable_wrapCallback=function(D){var P=h;return function(){var H=h;h=P;try{return D.apply(this,arguments)}finally{h=H}}}})(Xu);qu.exports=Xu;var Lf=qu.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Rf=d,ht=Lf;function R(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),vi=Object.prototype.hasOwnProperty,zf=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,go={},yo={};function If(e){return vi.call(yo,e)?!0:vi.call(go,e)?!1:zf.test(e)?yo[e]=!0:(go[e]=!0,!1)}function Df(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function $f(e,t,n,r){if(t===null||typeof t>"u"||Df(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function nt(e,t,n,r,l,i,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=a}var We={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){We[e]=new nt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];We[t]=new nt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){We[e]=new nt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){We[e]=new nt(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){We[e]=new nt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){We[e]=new nt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){We[e]=new nt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){We[e]=new nt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){We[e]=new nt(e,5,!1,e.toLowerCase(),null,!1,!1)});var ma=/[\-:]([a-z])/g;function ga(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(ma,ga);We[t]=new nt(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ma,ga);We[t]=new nt(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ma,ga);We[t]=new nt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){We[e]=new nt(e,1,!1,e.toLowerCase(),null,!1,!1)});We.xlinkHref=new nt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){We[e]=new nt(e,1,!1,e.toLowerCase(),null,!0,!0)});function ya(e,t,n,r){var l=We.hasOwnProperty(t)?We[t]:null;(l!==null?l.type!==0:r||!(2o||l[a]!==i[o]){var u=` -`+l[a].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=a&&0<=o);break}}}finally{Us=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Rr(e):""}function Of(e){switch(e.tag){case 5:return Rr(e.type);case 16:return Rr("Lazy");case 13:return Rr("Suspense");case 19:return Rr("SuspenseList");case 0:case 2:case 15:return e=Hs(e.type,!1),e;case 11:return e=Hs(e.type.render,!1),e;case 1:return e=Hs(e.type,!0),e;default:return""}}function ji(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Qn:return"Fragment";case Vn:return"Portal";case xi:return"Profiler";case va:return"StrictMode";case wi:return"Suspense";case ki:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Yu:return(e.displayName||"Context")+".Consumer";case Gu:return(e._context.displayName||"Context")+".Provider";case xa:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case wa:return t=e.displayName||null,t!==null?t:ji(e.type)||"Memo";case ln:t=e._payload,e=e._init;try{return ji(e(t))}catch{}}return null}function Af(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ji(t);case 8:return t===va?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function xn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function ec(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Mf(e){var t=ec(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(a){r=""+a,i.call(this,a)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function xl(e){e._valueTracker||(e._valueTracker=Mf(e))}function tc(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=ec(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Xl(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Si(e,t){var n=t.checked;return Se({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function xo(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=xn(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function nc(e,t){t=t.checked,t!=null&&ya(e,"checked",t,!1)}function Ni(e,t){nc(e,t);var n=xn(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?_i(e,t.type,n):t.hasOwnProperty("defaultValue")&&_i(e,t.type,xn(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function wo(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function _i(e,t,n){(t!=="number"||Xl(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var zr=Array.isArray;function rr(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=wl.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function qr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Ar={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Ff=["Webkit","ms","Moz","O"];Object.keys(Ar).forEach(function(e){Ff.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Ar[t]=Ar[e]})});function ic(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Ar.hasOwnProperty(e)&&Ar[e]?(""+t).trim():t+"px"}function ac(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=ic(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Bf=Se({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function bi(e,t){if(t){if(Bf[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(R(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(R(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(R(61))}if(t.style!=null&&typeof t.style!="object")throw Error(R(62))}}function Ti(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Pi=null;function ka(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Li=null,lr=null,sr=null;function So(e){if(e=hl(e)){if(typeof Li!="function")throw Error(R(280));var t=e.stateNode;t&&(t=Cs(t),Li(e.stateNode,e.type,t))}}function oc(e){lr?sr?sr.push(e):sr=[e]:lr=e}function uc(){if(lr){var e=lr,t=sr;if(sr=lr=null,So(e),t)for(e=0;e>>=0,e===0?32:31-(Yf(e)/Zf|0)|0}var kl=64,jl=4194304;function Ir(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Zl(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,a=n&268435455;if(a!==0){var o=a&~l;o!==0?r=Ir(o):(i&=a,i!==0&&(r=Ir(i)))}else a=n&~l,a!==0?r=Ir(a):i!==0&&(r=Ir(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function fl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Rt(t),e[t]=n}function rp(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Fr),Ro=" ",zo=!1;function Tc(e,t){switch(e){case"keyup":return Lp.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Pc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Kn=!1;function zp(e,t){switch(e){case"compositionend":return Pc(t);case"keypress":return t.which!==32?null:(zo=!0,Ro);case"textInput":return e=t.data,e===Ro&&zo?null:e;default:return null}}function Ip(e,t){if(Kn)return e==="compositionend"||!Ta&&Tc(e,t)?(e=Ec(),Ml=Ca=un=null,Kn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Oo(n)}}function Ic(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Ic(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Dc(){for(var e=window,t=Xl();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Xl(e.document)}return t}function Pa(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Hp(e){var t=Dc(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Ic(n.ownerDocument.documentElement,n)){if(r!==null&&Pa(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=Ao(n,i);var a=Ao(n,r);l&&a&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,qn=null,Oi=null,Ur=null,Ai=!1;function Mo(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ai||qn==null||qn!==Xl(r)||(r=qn,"selectionStart"in r&&Pa(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ur&&el(Ur,r)||(Ur=r,r=ns(Oi,"onSelect"),0Gn||(e.current=Wi[Gn],Wi[Gn]=null,Gn--)}function fe(e,t){Gn++,Wi[Gn]=e.current,e.current=t}var wn={},Ge=jn(wn),it=jn(!1),zn=wn;function dr(e,t){var n=e.type.contextTypes;if(!n)return wn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function at(e){return e=e.childContextTypes,e!=null}function ls(){me(it),me(Ge)}function Qo(e,t,n){if(Ge.current!==wn)throw Error(R(168));fe(Ge,t),fe(it,n)}function Wc(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(R(108,Af(e)||"Unknown",l));return Se({},n,r)}function ss(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||wn,zn=Ge.current,fe(Ge,e),fe(it,it.current),!0}function Ko(e,t,n){var r=e.stateNode;if(!r)throw Error(R(169));n?(e=Wc(e,t,zn),r.__reactInternalMemoizedMergedChildContext=e,me(it),me(Ge),fe(Ge,e)):me(it),fe(it,n)}var Qt=null,Es=!1,ri=!1;function Vc(e){Qt===null?Qt=[e]:Qt.push(e)}function th(e){Es=!0,Vc(e)}function Sn(){if(!ri&&Qt!==null){ri=!0;var e=0,t=oe;try{var n=Qt;for(oe=1;e>=a,l-=a,Kt=1<<32-Rt(t)+l|n<k?(T=b,b=null):T=b.sibling;var L=h(p,b,m[k],w);if(L===null){b===null&&(b=T);break}e&&b&&L.alternate===null&&t(p,b),f=i(L,f,k),E===null?C=L:E.sibling=L,E=L,b=T}if(k===m.length)return n(p,b),ve&&_n(p,k),C;if(b===null){for(;kk?(T=b,b=null):T=b.sibling;var q=h(p,b,L.value,w);if(q===null){b===null&&(b=T);break}e&&b&&q.alternate===null&&t(p,b),f=i(q,f,k),E===null?C=q:E.sibling=q,E=q,b=T}if(L.done)return n(p,b),ve&&_n(p,k),C;if(b===null){for(;!L.done;k++,L=m.next())L=g(p,L.value,w),L!==null&&(f=i(L,f,k),E===null?C=L:E.sibling=L,E=L);return ve&&_n(p,k),C}for(b=r(p,b);!L.done;k++,L=m.next())L=v(b,p,k,L.value,w),L!==null&&(e&&L.alternate!==null&&b.delete(L.key===null?k:L.key),f=i(L,f,k),E===null?C=L:E.sibling=L,E=L);return e&&b.forEach(function(F){return t(p,F)}),ve&&_n(p,k),C}function N(p,f,m,w){if(typeof m=="object"&&m!==null&&m.type===Qn&&m.key===null&&(m=m.props.children),typeof m=="object"&&m!==null){switch(m.$$typeof){case vl:e:{for(var C=m.key,E=f;E!==null;){if(E.key===C){if(C=m.type,C===Qn){if(E.tag===7){n(p,E.sibling),f=l(E,m.props.children),f.return=p,p=f;break e}}else if(E.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===ln&&Jo(C)===E.type){n(p,E.sibling),f=l(E,m.props),f.ref=br(p,E,m),f.return=p,p=f;break e}n(p,E);break}else t(p,E);E=E.sibling}m.type===Qn?(f=Rn(m.props.children,p.mode,w,m.key),f.return=p,p=f):(w=Kl(m.type,m.key,m.props,null,p.mode,w),w.ref=br(p,f,m),w.return=p,p=w)}return a(p);case Vn:e:{for(E=m.key;f!==null;){if(f.key===E)if(f.tag===4&&f.stateNode.containerInfo===m.containerInfo&&f.stateNode.implementation===m.implementation){n(p,f.sibling),f=l(f,m.children||[]),f.return=p,p=f;break e}else{n(p,f);break}else t(p,f);f=f.sibling}f=di(m,p.mode,w),f.return=p,p=f}return a(p);case ln:return E=m._init,N(p,f,E(m._payload),w)}if(zr(m))return x(p,f,m,w);if(Sr(m))return S(p,f,m,w);Tl(p,m)}return typeof m=="string"&&m!==""||typeof m=="number"?(m=""+m,f!==null&&f.tag===6?(n(p,f.sibling),f=l(f,m),f.return=p,p=f):(n(p,f),f=ci(m,p.mode,w),f.return=p,p=f),a(p)):n(p,f)}return N}var pr=Xc(!0),Jc=Xc(!1),os=jn(null),us=null,er=null,Ia=null;function Da(){Ia=er=us=null}function $a(e){var t=os.current;me(os),e._currentValue=t}function Ki(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function ar(e,t){us=e,Ia=er=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(st=!0),e.firstContext=null)}function Nt(e){var t=e._currentValue;if(Ia!==e)if(e={context:e,memoizedValue:t,next:null},er===null){if(us===null)throw Error(R(308));er=e,us.dependencies={lanes:0,firstContext:e}}else er=er.next=e;return t}var bn=null;function Oa(e){bn===null?bn=[e]:bn.push(e)}function Gc(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Oa(t)):(n.next=l.next,l.next=n),t.interleaved=n,Yt(e,r)}function Yt(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var sn=!1;function Aa(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Yc(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Xt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function mn(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,se&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,Yt(e,n)}return l=r.interleaved,l===null?(t.next=t,Oa(r)):(t.next=l.next,l.next=t),r.interleaved=t,Yt(e,n)}function Bl(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Sa(e,n)}}function Go(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=a:i=i.next=a,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function cs(e,t,n,r){var l=e.updateQueue;sn=!1;var i=l.firstBaseUpdate,a=l.lastBaseUpdate,o=l.shared.pending;if(o!==null){l.shared.pending=null;var u=o,c=u.next;u.next=null,a===null?i=c:a.next=c,a=u;var y=e.alternate;y!==null&&(y=y.updateQueue,o=y.lastBaseUpdate,o!==a&&(o===null?y.firstBaseUpdate=c:o.next=c,y.lastBaseUpdate=u))}if(i!==null){var g=l.baseState;a=0,y=c=u=null,o=i;do{var h=o.lane,v=o.eventTime;if((r&h)===h){y!==null&&(y=y.next={eventTime:v,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var x=e,S=o;switch(h=t,v=n,S.tag){case 1:if(x=S.payload,typeof x=="function"){g=x.call(v,g,h);break e}g=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=S.payload,h=typeof x=="function"?x.call(v,g,h):x,h==null)break e;g=Se({},g,h);break e;case 2:sn=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,h=l.effects,h===null?l.effects=[o]:h.push(o))}else v={eventTime:v,lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},y===null?(c=y=v,u=g):y=y.next=v,a|=h;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;h=o,o=h.next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}while(!0);if(y===null&&(u=g),l.baseState=u,l.firstBaseUpdate=c,l.lastBaseUpdate=y,t=l.shared.interleaved,t!==null){l=t;do a|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);$n|=a,e.lanes=a,e.memoizedState=g}}function Yo(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=si.transition;si.transition={};try{e(!1),t()}finally{oe=n,si.transition=r}}function md(){return _t().memoizedState}function sh(e,t,n){var r=yn(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},gd(e))yd(t,n);else if(n=Gc(e,t,n,r),n!==null){var l=et();zt(n,e,r,l),vd(n,t,r)}}function ih(e,t,n){var r=yn(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(gd(e))yd(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var a=t.lastRenderedState,o=i(a,n);if(l.hasEagerState=!0,l.eagerState=o,It(o,a)){var u=t.interleaved;u===null?(l.next=l,Oa(t)):(l.next=u.next,u.next=l),t.interleaved=l;return}}catch{}finally{}n=Gc(e,t,l,r),n!==null&&(l=et(),zt(n,e,r,l),vd(n,t,r))}}function gd(e){var t=e.alternate;return e===je||t!==null&&t===je}function yd(e,t){Hr=fs=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function vd(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Sa(e,n)}}var ps={readContext:Nt,useCallback:qe,useContext:qe,useEffect:qe,useImperativeHandle:qe,useInsertionEffect:qe,useLayoutEffect:qe,useMemo:qe,useReducer:qe,useRef:qe,useState:qe,useDebugValue:qe,useDeferredValue:qe,useTransition:qe,useMutableSource:qe,useSyncExternalStore:qe,useId:qe,unstable_isNewReconciler:!1},ah={readContext:Nt,useCallback:function(e,t){return Mt().memoizedState=[e,t===void 0?null:t],e},useContext:Nt,useEffect:eu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Hl(4194308,4,cd.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Hl(4194308,4,e,t)},useInsertionEffect:function(e,t){return Hl(4,2,e,t)},useMemo:function(e,t){var n=Mt();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Mt();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=sh.bind(null,je,e),[r.memoizedState,e]},useRef:function(e){var t=Mt();return e={current:e},t.memoizedState=e},useState:Zo,useDebugValue:Qa,useDeferredValue:function(e){return Mt().memoizedState=e},useTransition:function(){var e=Zo(!1),t=e[0];return e=lh.bind(null,e[1]),Mt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=je,l=Mt();if(ve){if(n===void 0)throw Error(R(407));n=n()}else{if(n=t(),Fe===null)throw Error(R(349));Dn&30||nd(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,eu(ld.bind(null,r,i,e),[e]),r.flags|=2048,ol(9,rd.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Mt(),t=Fe.identifierPrefix;if(ve){var n=qt,r=Kt;n=(r&~(1<<32-Rt(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=il++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=a.createElement(n,{is:r.is}):(e=a.createElement(n),n==="select"&&(a=e,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):e=a.createElementNS(e,n),e[Ft]=t,e[rl]=r,bd(e,t,!1,!1),t.stateNode=e;e:{switch(a=Ti(n,r),n){case"dialog":he("cancel",e),he("close",e),l=r;break;case"iframe":case"object":case"embed":he("load",e),l=r;break;case"video":case"audio":for(l=0;lgr&&(t.flags|=128,r=!0,Tr(i,!1),t.lanes=4194304)}else{if(!r)if(e=ds(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Tr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!ve)return Xe(t),null}else 2*Ce()-i.renderingStartTime>gr&&n!==1073741824&&(t.flags|=128,r=!0,Tr(i,!1),t.lanes=4194304);i.isBackwards?(a.sibling=t.child,t.child=a):(n=i.last,n!==null?n.sibling=a:t.child=a,i.last=a)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Ce(),t.sibling=null,n=ke.current,fe(ke,r?n&1|2:n&1),t):(Xe(t),null);case 22:case 23:return Ya(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?ct&1073741824&&(Xe(t),t.subtreeFlags&6&&(t.flags|=8192)):Xe(t),null;case 24:return null;case 25:return null}throw Error(R(156,t.tag))}function mh(e,t){switch(Ra(t),t.tag){case 1:return at(t.type)&&ls(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return hr(),me(it),me(Ge),Ba(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Fa(t),null;case 13:if(me(ke),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(R(340));fr()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return me(ke),null;case 4:return hr(),null;case 10:return $a(t.type._context),null;case 22:case 23:return Ya(),null;case 24:return null;default:return null}}var Ll=!1,Je=!1,gh=typeof WeakSet=="function"?WeakSet:Set,U=null;function tr(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){_e(e,t,r)}else n.current=null}function na(e,t,n){try{n()}catch(r){_e(e,t,r)}}var du=!1;function yh(e,t){if(Mi=es,e=Dc(),Pa(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var a=0,o=-1,u=-1,c=0,y=0,g=e,h=null;t:for(;;){for(var v;g!==n||l!==0&&g.nodeType!==3||(o=a+l),g!==i||r!==0&&g.nodeType!==3||(u=a+r),g.nodeType===3&&(a+=g.nodeValue.length),(v=g.firstChild)!==null;)h=g,g=v;for(;;){if(g===e)break t;if(h===n&&++c===l&&(o=a),h===i&&++y===r&&(u=a),(v=g.nextSibling)!==null)break;g=h,h=g.parentNode}g=v}n=o===-1||u===-1?null:{start:o,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(Fi={focusedElem:e,selectionRange:n},es=!1,U=t;U!==null;)if(t=U,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,U=e;else for(;U!==null;){t=U;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var S=x.memoizedProps,N=x.memoizedState,p=t.stateNode,f=p.getSnapshotBeforeUpdate(t.elementType===t.type?S:Tt(t.type,S),N);p.__reactInternalSnapshotBeforeUpdate=f}break;case 3:var m=t.stateNode.containerInfo;m.nodeType===1?m.textContent="":m.nodeType===9&&m.documentElement&&m.removeChild(m.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(R(163))}}catch(w){_e(t,t.return,w)}if(e=t.sibling,e!==null){e.return=t.return,U=e;break}U=t.return}return x=du,du=!1,x}function Wr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&na(t,n,i)}l=l.next}while(l!==r)}}function Ps(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function ra(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Ld(e){var t=e.alternate;t!==null&&(e.alternate=null,Ld(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Ft],delete t[rl],delete t[Hi],delete t[Zp],delete t[eh])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Rd(e){return e.tag===5||e.tag===3||e.tag===4}function fu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Rd(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function la(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=rs));else if(r!==4&&(e=e.child,e!==null))for(la(e,t,n),e=e.sibling;e!==null;)la(e,t,n),e=e.sibling}function sa(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(sa(e,t,n),e=e.sibling;e!==null;)sa(e,t,n),e=e.sibling}var Ue=null,Pt=!1;function rn(e,t,n){for(n=n.child;n!==null;)zd(e,t,n),n=n.sibling}function zd(e,t,n){if(Bt&&typeof Bt.onCommitFiberUnmount=="function")try{Bt.onCommitFiberUnmount(js,n)}catch{}switch(n.tag){case 5:Je||tr(n,t);case 6:var r=Ue,l=Pt;Ue=null,rn(e,t,n),Ue=r,Pt=l,Ue!==null&&(Pt?(e=Ue,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Ue.removeChild(n.stateNode));break;case 18:Ue!==null&&(Pt?(e=Ue,n=n.stateNode,e.nodeType===8?ni(e.parentNode,n):e.nodeType===1&&ni(e,n),Yr(e)):ni(Ue,n.stateNode));break;case 4:r=Ue,l=Pt,Ue=n.stateNode.containerInfo,Pt=!0,rn(e,t,n),Ue=r,Pt=l;break;case 0:case 11:case 14:case 15:if(!Je&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,a=i.destroy;i=i.tag,a!==void 0&&(i&2||i&4)&&na(n,t,a),l=l.next}while(l!==r)}rn(e,t,n);break;case 1:if(!Je&&(tr(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){_e(n,t,o)}rn(e,t,n);break;case 21:rn(e,t,n);break;case 22:n.mode&1?(Je=(r=Je)||n.memoizedState!==null,rn(e,t,n),Je=r):rn(e,t,n);break;default:rn(e,t,n)}}function pu(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new gh),t.forEach(function(r){var l=Ch.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function bt(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=a),r&=~i}if(r=l,r=Ce()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*xh(r/1960))-r,10e?16:e,cn===null)var r=!1;else{if(e=cn,cn=null,gs=0,se&6)throw Error(R(331));var l=se;for(se|=4,U=e.current;U!==null;){var i=U,a=i.child;if(U.flags&16){var o=i.deletions;if(o!==null){for(var u=0;uCe()-Ja?Ln(e,0):Xa|=n),ot(e,t)}function Bd(e,t){t===0&&(e.mode&1?(t=jl,jl<<=1,!(jl&130023424)&&(jl=4194304)):t=1);var n=et();e=Yt(e,t),e!==null&&(fl(e,t,n),ot(e,n))}function _h(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Bd(e,n)}function Ch(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(R(314))}r!==null&&r.delete(t),Bd(e,n)}var Ud;Ud=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||it.current)st=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return st=!1,ph(e,t,n);st=!!(e.flags&131072)}else st=!1,ve&&t.flags&1048576&&Qc(t,as,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Wl(e,t),e=t.pendingProps;var l=dr(t,Ge.current);ar(t,n),l=Ha(null,t,r,e,l,n);var i=Wa();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,at(r)?(i=!0,ss(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Aa(t),l.updater=Ts,t.stateNode=l,l._reactInternals=t,Xi(t,r,e,n),t=Yi(null,t,r,!0,i,n)):(t.tag=0,ve&&i&&La(t),Ze(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Wl(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=bh(r),e=Tt(r,e),l){case 0:t=Gi(null,t,r,e,n);break e;case 1:t=ou(null,t,r,e,n);break e;case 11:t=iu(null,t,r,e,n);break e;case 14:t=au(null,t,r,Tt(r.type,e),n);break e}throw Error(R(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Tt(r,l),Gi(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Tt(r,l),ou(e,t,r,l,n);case 3:e:{if(_d(t),e===null)throw Error(R(387));r=t.pendingProps,i=t.memoizedState,l=i.element,Yc(e,t),cs(t,r,null,n);var a=t.memoizedState;if(r=a.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=mr(Error(R(423)),t),t=uu(e,t,r,n,l);break e}else if(r!==l){l=mr(Error(R(424)),t),t=uu(e,t,r,n,l);break e}else for(ft=hn(t.stateNode.containerInfo.firstChild),pt=t,ve=!0,Lt=null,n=Jc(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(fr(),r===l){t=Zt(e,t,n);break e}Ze(e,t,r,n)}t=t.child}return t;case 5:return Zc(t),e===null&&Qi(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,a=l.children,Bi(r,l)?a=null:i!==null&&Bi(r,i)&&(t.flags|=32),Nd(e,t),Ze(e,t,a,n),t.child;case 6:return e===null&&Qi(t),null;case 13:return Cd(e,t,n);case 4:return Ma(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=pr(t,null,r,n):Ze(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Tt(r,l),iu(e,t,r,l,n);case 7:return Ze(e,t,t.pendingProps,n),t.child;case 8:return Ze(e,t,t.pendingProps.children,n),t.child;case 12:return Ze(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,a=l.value,fe(os,r._currentValue),r._currentValue=a,i!==null)if(It(i.value,a)){if(i.children===l.children&&!it.current){t=Zt(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){a=i.child;for(var u=o.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=Xt(-1,n&-n),u.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var y=c.pending;y===null?u.next=u:(u.next=y.next,y.next=u),c.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),Ki(i.return,n,t),o.lanes|=n;break}u=u.next}}else if(i.tag===10)a=i.type===t.type?null:i.child;else if(i.tag===18){if(a=i.return,a===null)throw Error(R(341));a.lanes|=n,o=a.alternate,o!==null&&(o.lanes|=n),Ki(a,n,t),a=i.sibling}else a=i.child;if(a!==null)a.return=i;else for(a=i;a!==null;){if(a===t){a=null;break}if(i=a.sibling,i!==null){i.return=a.return,a=i;break}a=a.return}i=a}Ze(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,ar(t,n),l=Nt(l),r=r(l),t.flags|=1,Ze(e,t,r,n),t.child;case 14:return r=t.type,l=Tt(r,t.pendingProps),l=Tt(r.type,l),au(e,t,r,l,n);case 15:return jd(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Tt(r,l),Wl(e,t),t.tag=1,at(r)?(e=!0,ss(t)):e=!1,ar(t,n),xd(t,r,l),Xi(t,r,l,n),Yi(null,t,r,!0,e,n);case 19:return Ed(e,t,n);case 22:return Sd(e,t,n)}throw Error(R(156,t.tag))};function Hd(e,t){return gc(e,t)}function Eh(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function jt(e,t,n,r){return new Eh(e,t,n,r)}function eo(e){return e=e.prototype,!(!e||!e.isReactComponent)}function bh(e){if(typeof e=="function")return eo(e)?1:0;if(e!=null){if(e=e.$$typeof,e===xa)return 11;if(e===wa)return 14}return 2}function vn(e,t){var n=e.alternate;return n===null?(n=jt(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Kl(e,t,n,r,l,i){var a=2;if(r=e,typeof e=="function")eo(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case Qn:return Rn(n.children,l,i,t);case va:a=8,l|=8;break;case xi:return e=jt(12,n,t,l|2),e.elementType=xi,e.lanes=i,e;case wi:return e=jt(13,n,t,l),e.elementType=wi,e.lanes=i,e;case ki:return e=jt(19,n,t,l),e.elementType=ki,e.lanes=i,e;case Zu:return Rs(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Gu:a=10;break e;case Yu:a=9;break e;case xa:a=11;break e;case wa:a=14;break e;case ln:a=16,r=null;break e}throw Error(R(130,e==null?e:typeof e,""))}return t=jt(a,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function Rn(e,t,n,r){return e=jt(7,e,r,t),e.lanes=n,e}function Rs(e,t,n,r){return e=jt(22,e,r,t),e.elementType=Zu,e.lanes=n,e.stateNode={isHidden:!1},e}function ci(e,t,n){return e=jt(6,e,null,t),e.lanes=n,e}function di(e,t,n){return t=jt(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Th(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Vs(0),this.expirationTimes=Vs(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Vs(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function to(e,t,n,r,l,i,a,o,u){return e=new Th(e,t,n,o,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=jt(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Aa(i),e}function Ph(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Kd)}catch(e){console.error(e)}}Kd(),Ku.exports=mt;var Dh=Ku.exports,qd,ku=Dh;qd=ku.createRoot,ku.hydrateRoot;async function Le(e){const t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return t.json()}async function ju(){return Le("/api/archives")}async function Su(e,t=null){const n=t?`/api/archives/${e}/entries?collection=${encodeURIComponent(t)}`:`/api/archives/${e}/entries`;return Le(n)}async function $h(e,t,n,r=null){const l=new URLSearchParams;return t&&l.set("q",t),n&&l.set("tag",n),r&&l.set("collection",r),Le(`/api/archives/${e}/entries/search?${l}`)}async function $r(e,t){return Le(`/api/archives/${e}/entries/${t}`)}async function Oh(e,t){return Le(`/api/archives/${e}/entries/${t}/children`)}function Ah(e,t,n){return Promise.all(n.map(r=>Le(`/api/archives/${e}/entries/${t}/artifacts/${r}`)))}async function Mh(e){if(!e||e.length===0)return{};const t=await fetch("/api/util/resolve-tco",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return t.ok?t.json():{}}async function Fh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:n??null})});if(!r.ok)throw new Error(await r.text())}async function Il(e,t){return Le(`/api/archives/${e}/entries/${t}/tags`)}async function Nu(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag_path:n})});if(!r.ok)throw new Error(`Failed to add tag (${r.status})`)}async function Bh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags/${n}`,{method:"DELETE"});if(!r.ok)throw new Error(`Remove failed (${r.status})`)}async function _u(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`Delete failed (${n.status})`)}async function Uh(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n})});if(!r.ok)throw new Error(await r.text());return r.json()}async function Hh(e,t){const n=await fetch(`/api/archives/${e}/tags/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(await n.text())}async function Wh(e,t){const n=await fetch(`/api/archives/${e}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok)throw new Error(await n.text());return n.json()}async function Vh(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}/move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parent_uid:n??null})});if(!r.ok)throw new Error(await r.text());return r.json()}async function fi(e){return Le(`/api/archives/${e}/runs`)}async function Dl(e){return Le(`/api/archives/${e}/tags`)}async function Qh(e,t,n=null,r=null){const l={locator:t};n&&n!=="best"&&(l.quality=n),r&&(typeof r.ublock_enabled=="boolean"&&(l.ublock_enabled=r.ublock_enabled),typeof r.reader_mode=="boolean"&&(l.reader_mode=r.reader_mode),typeof r.cookie_ext_enabled=="boolean"&&(l.cookie_ext_enabled=r.cookie_ext_enabled),typeof r.modal_closer_enabled=="boolean"&&(l.modal_closer_enabled=r.modal_closer_enabled),typeof r.via_freedium=="boolean"&&(l.via_freedium=r.via_freedium),r.per_item_quality&&typeof r.per_item_quality=="object"&&Object.keys(r.per_item_quality).length>0&&(l.per_item_quality=r.per_item_quality),r.sync===!0&&(l.sync=!0));const i=await fetch(`/api/archives/${e}/captures`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok){const a=await i.json().catch(()=>({})),o=new Error(a.error||`HTTP ${i.status}`);throw o.status=i.status,o}return i.json()}async function Kh(e,t){return Le(`/api/archives/${e}/captures/probe?locator=${encodeURIComponent(t)}`)}async function qh(e,t){const n=await fetch(`/api/archives/${e}/captures/probe-playlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({locator:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function Xd(e,t){return Le(`/api/archives/${e}/capture_jobs/${t}`)}async function Xh(){return(await(await fetch("/api/auth/setup")).json()).setup_required===!0}async function Jh(e,t){const n=await fetch("/api/auth/setup",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Setup failed");return n.json()}async function Gh(e,t){const n=await fetch("/api/auth/login",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Login failed");return n.json()}async function Yh(){await fetch("/api/auth/logout",{method:"POST"})}async function Zh(){const e=await fetch("/api/auth/me");return e.status===401?null:e.json()}async function em(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:e})});if(!t.ok)throw new Error(await t.text())}async function tm(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function nm(e,t){const n=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({current_password:e,new_password:t})});if(!n.ok){let r=await n.text();try{r=JSON.parse(r).error??r}catch{}throw new Error(r)}}async function rm(){return Le("/api/auth/tokens")}async function lm(e){const t=await fetch("/api/auth/tokens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})});if(!t.ok)throw new Error(await t.text());return t.json()}async function sm(e){const t=await fetch(`/api/auth/tokens/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(await t.text())}async function so(){return Le("/api/admin/instance-settings")}async function ql(e){const t=await fetch("/api/admin/instance-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function im(){return Le("/api/admin/users")}async function am(e,t,n){const r=await fetch("/api/admin/users",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t,email:n||void 0})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error||`HTTP ${r.status}`)}return r.json()}async function om(e,t){const n=await fetch(`/api/admin/users/${e}/status`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function um(){return Le("/api/admin/roles")}async function cm(e,t){const n=await fetch("/api/admin/roles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:e,name:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function io(e){return Le(`/api/archives/${e}/collections`)}async function dm(e,t,n,r=2,l=!0){const i=await fetch(`/api/archives/${e}/collections`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:t,slug:n,default_visibility_bits:r,requires_auth:l})});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error||i.statusText)}return i.json()}async function fm(e,t){return Le(`/api/archives/${e}/collections/${t}`)}async function ca(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections/${t}/entries`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({entry_uid:n,visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function pm(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"DELETE"});if(!r.ok){const l=await r.json().catch(()=>({error:r.statusText}));throw new Error(l.error||r.statusText)}}async function hm(e,t,n,r){const l=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function Cu(e,t){return Le(`/api/archives/${e}/entries/${t}/collections`)}async function pi(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error??r.statusText)}}async function mm(e,t){const n=await fetch(`/api/archives/${e}/collections/${t}`,{method:"DELETE"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error??n.statusText)}}async function gm(e){return Le(`/api/archives/${e}/blob-cleanup`)}async function ym(e){const t=await fetch(`/api/archives/${e}/blob-cleanup`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error??t.statusText)}return t.json()}async function vm(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}/rearchive`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`rearchive failed: ${n.status}`)}return n.json()}async function xm(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/artifacts/${n}/media-token`,{method:"POST"});if(!r.ok)throw new Error(`media-token ${r.status}`);return r.json()}async function wm(){return Le("/api/admin/cookie-rules")}async function km(e,t,n){const r=await fetch("/api/admin/cookie-rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url_pattern:e||null,pattern_kind:t,cookies_json:n})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.message||`HTTP ${r.status}`)}return r.json()}async function jm(e,t){const n=await fetch(`/api/admin/cookie-rules/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`HTTP ${n.status}`)}}async function Sm(e){const t=await fetch(`/api/admin/cookie-rules/${e}`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.message||`HTTP ${t.status}`)}}function Nm(e,t,n){let r;return{promise:new Promise((i,a)=>{const o=new FormData;o.append("file",t),r=new XMLHttpRequest,r.open("POST",`/api/archives/${e}/uploads`),r.upload.addEventListener("progress",u=>{u.lengthComputable&&n&&n(Math.round(u.loaded/u.total*100))}),r.addEventListener("load",()=>{if(r.status>=200&&r.status<300)try{i(JSON.parse(r.responseText))}catch{a(new Error("Invalid server response"))}else{let u=`Upload failed (${r.status})`;try{u=JSON.parse(r.responseText).message||u}catch{}a(new Error(u))}}),r.addEventListener("error",()=>a(new Error("Network error during upload"))),r.addEventListener("abort",()=>a(new Error("Upload cancelled"))),r.send(o)}),abort:()=>r==null?void 0:r.abort()}}async function hi(e,t){try{await fetch(`/api/archives/${e}/uploads`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({locator:t})})}catch{}}const _m=window.fetch;window.fetch=async(...e)=>{var n;const t=await _m(...e);return t.status===401&&((typeof e[0]=="string"?e[0]:((n=e[0])==null?void 0:n.url)??"").includes("/api/auth/")||window.dispatchEvent(new CustomEvent("auth:expired"))),t};function Cm({onLogin:e}){const[t,n]=d.useState(""),[r,l]=d.useState(""),[i,a]=d.useState(null),[o,u]=d.useState(!1);async function c(y){y.preventDefault(),a(null),u(!0);try{const g=await Gh(t,r);e(g)}catch(g){a(g.message)}finally{u(!1)}}return s.jsx("div",{className:"login-page",children:s.jsxs("div",{className:"login-card",children:[s.jsx("h1",{className:"login-brand",children:"Archivr"}),s.jsx("p",{className:"login-tagline",children:"Sign in to your archive"}),s.jsxs("form",{onSubmit:c,children:[s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-username",children:"Username"}),s.jsx("input",{className:"login-input",id:"login-username",type:"text",value:t,onChange:y=>n(y.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-password",children:"Password"}),s.jsx("input",{className:"login-input",id:"login-password",type:"password",value:r,onChange:y=>l(y.target.value),required:!0,autoComplete:"current-password"})]}),i&&s.jsx("p",{className:"login-error",children:i}),s.jsx("button",{className:"login-submit",type:"submit",disabled:o,children:o?"Signing in…":"Sign in"})]})]})})}function Em({onComplete:e}){const[t,n]=d.useState(""),[r,l]=d.useState(""),[i,a]=d.useState(""),[o,u]=d.useState(null),[c,y]=d.useState(!1);async function g(h){if(h.preventDefault(),r!==i){u("Passwords do not match");return}if(r.length<8){u("Password must be at least 8 characters");return}u(null),y(!0);try{await Jh(t,r),e()}catch(v){u(v.message)}finally{y(!1)}}return s.jsx("div",{className:"setup-page",children:s.jsxs("div",{className:"setup-card",children:[s.jsx("h1",{className:"setup-brand",children:"Archivr"}),s.jsx("p",{className:"setup-tagline",children:"Create your owner account to get started."}),s.jsxs("form",{onSubmit:g,children:[s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-username",children:"Username"}),s.jsx("input",{className:"setup-input",id:"setup-username",type:"text",value:t,onChange:h=>n(h.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-password",children:"Password"}),s.jsx("input",{className:"setup-input",id:"setup-password",type:"password",value:r,onChange:h=>l(h.target.value),required:!0,autoComplete:"new-password"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-confirm",children:"Confirm password"}),s.jsx("input",{className:"setup-input",id:"setup-confirm",type:"password",value:i,onChange:h=>a(h.target.value),required:!0,autoComplete:"new-password"})]}),o&&s.jsx("p",{className:"setup-error",children:o}),s.jsx("button",{className:"setup-submit",type:"submit",disabled:c,children:c?"Creating account…":"Create account"})]})]})})}function bm({archives:e,archiveId:t,onArchiveChange:n,view:r,onViewChange:l,onCaptureClick:i,collections:a,selectedCollectionUid:o,onCollectionChange:u,isPublicSession:c,onSignInClick:y}){const{currentUser:g,setCurrentUser:h}=d.useContext(As)??{},[v,x]=d.useState(!1);async function S(){x(!0),await Yh(),h(null),window.location.reload()}const N=a.find(m=>m.slug==="_default_"),p=!c||!!N&&!N.requires_auth,f=a.filter(m=>m.slug!=="_default_").filter(m=>!c||!m.requires_auth);return s.jsxs("header",{className:"topbar",children:[s.jsx("div",{className:"brand",children:"Archivr"}),s.jsxs("div",{className:"switchers",children:[!c&&s.jsx("div",{className:"switcher",children:s.jsx("select",{"aria-label":"Select archive",value:t??"",onChange:m=>n(m.target.value),children:e.map(m=>s.jsx("option",{value:m.id,children:m.label},m.id))})}),f.length>0&&s.jsx("div",{className:"switcher",children:s.jsxs("select",{"aria-label":"Select collection",value:o??"",onChange:m=>u(m.target.value||null),children:[p&&s.jsx("option",{value:"",children:"All entries"}),f.map(m=>s.jsx("option",{value:m.collection_uid,children:m.name},m.collection_uid))]})})]}),c?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1}}),s.jsx("button",{className:"logout-btn",onClick:y,children:"Sign in"})]}):s.jsxs(s.Fragment,{children:[s.jsx("nav",{className:"nav","aria-label":"Primary",children:["archive","tags","collections","runs","admin","settings"].map(m=>s.jsx("button",{className:`nav-link${r===m?" is-active":""}`,onClick:()=>l(m),children:m.charAt(0).toUpperCase()+m.slice(1)},m))}),s.jsx("button",{className:"capture-button",onClick:i,children:"Capture"}),g&&s.jsxs("div",{className:"user-menu",children:[s.jsx("span",{className:"user-name",children:g.display_name||g.username}),s.jsx("button",{className:"logout-btn",onClick:S,disabled:v,children:v?"Logging out…":"Log out"})]})]})]})}let xs=1;function Jd(e){const t=e.trim(),n=t.toLowerCase();for(const r of["yt:","youtube:"])if(n.startsWith(r)){const l=n.slice(r.length);return!!(l.startsWith("video/")||l.startsWith("short/")||l.startsWith("shorts/")||/^[a-z0-9_-]{11}$/i.test(l))}if(n.startsWith("ytm:"))return!n.slice(4).startsWith("playlist/");for(const r of["x:","twitter:","tweet:"])if(n.startsWith(r))return n.slice(r.length).startsWith("media:");if(n.startsWith("spotify:"))return!1;if(n.startsWith("instagram:")||n.startsWith("facebook:")||n.startsWith("tiktok:")||n.startsWith("reddit:")||n.startsWith("snapchat:"))return!0;if(n.startsWith("http://")||n.startsWith("https://")){if(/^https?:\/\/music\.youtube\.com\/watch/.test(n)||/^https?:\/\/(?:www\.)?(?:youtu\.be\/[0-9A-Za-z_-]+|youtube\.com\/watch\?v=[0-9A-Za-z_-]+|youtube\.com\/shorts\/[0-9A-Za-z_-]+)/.test(t)||n.startsWith("https://x.com/")||n.startsWith("http://x.com/")||/^https?:\/\/(?:www\.)?instagram\.com\//.test(n)||/^https?:\/\/(?:www\.)?facebook\.com\//.test(n)||n.startsWith("https://fb.watch/")||n.startsWith("http://fb.watch/")||/^https?:\/\/(?:www\.)?tiktok\.com\//.test(n)||/^https?:\/\/(?:www\.)?reddit\.com\//.test(n)||n.startsWith("https://redd.it/")||n.startsWith("http://redd.it/")||/^https?:\/\/(?:www\.)?snapchat\.com\//.test(n))return!0;if(n.startsWith("https://open.spotify.com/")||n.startsWith("http://open.spotify.com/"))return!1}return!1}function Pn(e){const t=e.trim(),n=t.toLowerCase();for(const r of["yt:","youtube:"])if(n.startsWith(r)){const l=n.slice(r.length);return l.startsWith("playlist/")||l.startsWith("@")||l.startsWith("channel/")||l.startsWith("c/")||l.startsWith("user/")}if(n.startsWith("ytm:"))return n.slice(4).startsWith("playlist/");if(n.startsWith("spotify:")){const r=n.slice(8);return r.startsWith("album:")||r.startsWith("playlist:")}if(n.startsWith("http://")||n.startsWith("https://"))try{const r=new URL(t),l=r.hostname;if((l==="youtube.com"||l==="www.youtube.com")&&(r.pathname==="/playlist"&&r.searchParams.has("list")||r.pathname.startsWith("/@")||r.pathname.startsWith("/channel/")||r.pathname.startsWith("/c/")||r.pathname.startsWith("/user/"))||l==="music.youtube.com"&&r.pathname==="/playlist"&&r.searchParams.has("list")||l==="open.spotify.com"&&(r.pathname.startsWith("/album/")||r.pathname.startsWith("/playlist/")))return!0}catch{}return!1}function Wn(e=""){return{id:xs++,locator:e,quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,status:"idle",error:null,jobUid:null,archiveId:null,playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1,syncEnabled:!1}}function Tm(e){return{id:xs++,kind:"file",filename:e,uploadProgress:0,uploadStatus:"uploading",uploadLocator:null,uploadError:null,locator:"",quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1,syncEnabled:!1,error:null,status:"idle"}}function Pm(e,t){return e==="best"?t.map(n=>({...n,quality:"best"})):e==="audio"?t.map(n=>n.has_audio?{...n,quality:"audio"}:n.quality!==null?n:{...n,quality:null}):t.map(n=>n.qualities.includes(e)?{...n,quality:e}:n.quality!==null?n:{...n,quality:null})}function Eu(e){return Array.isArray(e.playlistItems)&&e.playlistItems.some(t=>t.quality===null)}function Lm({open:e,archiveId:t,onClose:n,onCaptured:r,onToast:l,onJobStarted:i,onJobSettled:a,activeJobs:o=[]}){const u=d.useRef(null),c=d.useRef(!0),y=d.useRef(new Map),g=d.useRef(new Map),h=d.useRef(new Map),v=d.useRef(t);d.useEffect(()=>{v.current=t},[t]);const x=d.useRef(null),[S,N]=d.useState(!1),p=d.useRef([]),f=d.useRef(!1),m=d.useRef(new Map),w=d.useRef(r),C=d.useRef(l);d.useEffect(()=>{w.current=r},[r]),d.useEffect(()=>{C.current=l},[l]);const E=d.useRef(i),b=d.useRef(a);d.useEffect(()=>{E.current=i},[i]),d.useEffect(()=>{b.current=a},[a]);const[k,T]=d.useState(()=>{try{const j=JSON.parse(sessionStorage.getItem("captureItems")||"null");if(Array.isArray(j)&&j.length>0){const B=j.filter(M=>!M.status||M.status==="idle");if(B.length>0)return B.forEach(M=>{M.id>=xs&&(xs=M.id+1)}),B.map(M=>({...Wn(M.locator),...M}))}}catch{}return[Wn()]});d.useEffect(()=>{sessionStorage.setItem("captureItems",JSON.stringify(k.filter(j=>j.kind!=="file")))},[k]),d.useEffect(()=>{p.current=k},[k]);const[L,q]=d.useState(!1),[F,X]=d.useState(null),[Z,ue]=d.useState(null),[Ae,ge]=d.useState(!0),[D,P]=d.useState(!0),[H,te]=d.useState(!0);d.useEffect(()=>{so().then(j=>{ue(j),ge(j.cookie_ext_enabled??!0),P(j.modal_closer_enabled??!0)}).catch(()=>ue({}))},[]);const ee=F!==null?F:(Z==null?void 0:Z.ublock_enabled)??!0,[Re,Y]=d.useState(!1);d.useEffect(()=>{["captureDialogLocator","captureDialogError","captureDialogBusy","captureDialogJobStatus","captureDialogJobUid"].forEach(j=>sessionStorage.removeItem(j)),o.forEach(j=>{j.jobUid&&!y.current.has(j.jobUid)&&ye(j.id,j.jobUid,j.locator,j.archiveId,null)})},[]),d.useEffect(()=>{const j=u.current;if(!j)return;const B=()=>{if(g.current.forEach(M=>clearTimeout(M)),g.current.clear(),!f.current){const M=v.current;p.current.forEach(A=>{var W;A.kind==="file"&&(A.uploadStatus==="uploading"?((W=m.current.get(A.id))==null||W(),m.current.delete(A.id)):A.uploadStatus==="done"&&A.uploadLocator&&hi(M,A.uploadLocator).catch(()=>{}))})}f.current=!1,n()};return j.addEventListener("close",B),()=>j.removeEventListener("close",B)},[n]),d.useEffect(()=>{const j=u.current;j&&(e?(c.current||T([Wn()]),c.current=!1,j.open||j.showModal()):(g.current.forEach(B=>clearTimeout(B)),g.current.clear(),j.open&&j.close()))},[e]),d.useEffect(()=>()=>{y.current.forEach(j=>clearInterval(j)),g.current.forEach(j=>clearTimeout(j))},[]);function ye(j,B,M,A,W=null){if(y.current.has(B))return;const V=setInterval(async()=>{var pe,ae,xe,ie;try{const Qe=await Xd(A,B);if(Qe.status==="completed"){clearInterval(y.current.get(B)),y.current.delete(B),await Promise.resolve((pe=w.current)==null?void 0:pe.call(w)),(ae=b.current)==null||ae.call(b,j);try{const we=Qe.notes_json?JSON.parse(Qe.notes_json):null;if(we!=null&&we.ublock_skipped||we!=null&&we.cookie_ext_skipped){const xt=we.ublock_skipped&&we.cookie_ext_skipped?"Captured without ad-blocking or cookie-consent extension. Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config.":we.ublock_skipped?"Captured without ad-blocking. ARCHIVR_UBLOCK=true but ARCHIVR_UBLOCK_EXT is not set or the path is invalid.":"Captured without cookie-consent extension. ARCHIVR_COOKIE_EXT is not set or the path is invalid.";C.current(xt,M,"warning"),ce(W,"warning",M)}else W||C.current(null,M,"success"),ce(W,"archived")}catch{W||C.current(null,M,"success"),ce(W,"archived")}}else if(Qe.status==="failed"){clearInterval(y.current.get(B)),y.current.delete(B),(xe=b.current)==null||xe.call(b,j);const we=Qe.error_text||"Capture failed.";C.current(we,M),ce(W,"failed",M)}}catch(Qe){clearInterval(y.current.get(B)),y.current.delete(B),(ie=b.current)==null||ie.call(b,j);const we=Qe.message||"Network error";C.current(we,M),ce(W,"failed",M)}},500);y.current.set(B,V)}function ce(j,B,M=null){if(!j)return;const A=h.current.get(j);if(!A||(B==="archived"||B==="warning"?(A.archived++,B==="warning"&&(A.warnings++,M&&A.warningLocators.push(M))):(A.failed++,M&&A.failedLocators.push(M)),A.archived+A.failed0?`${W} archived (${V} with warnings)`:`${W} archived`;ie=pe>0?`${xt}, ${pe} failed`:xt}const Qe=W===0?"error":pe>0||V>0?"warning":"success",we=[];ae.length>0&&we.push(`Failed: -${ae.map(xt=>` ${xt}`).join(` -`)}`),xe.length>0&&we.push(`With warnings: -${xe.map(xt=>` ${xt}`).join(` -`)}`);const Un=we.length>0?we.join(` -`):null;C.current(Un,null,Qe,ie)}async function Ee(j,B,M,A={}){var ae,xe;const W=v.current,V=((ae=crypto.randomUUID)==null?void 0:ae.call(crypto))??`job-${Date.now()}-${Math.random()}`,pe={ublock_enabled:ee,reader_mode:Re,cookie_ext_enabled:Ae,modal_closer_enabled:D,via_freedium:H,...A};try{const ie=await Qh(W,j,B,pe);(xe=E.current)==null||xe.call(E,{id:V,jobUid:ie.job_uid,locator:j,archiveId:W}),ye(V,ie.job_uid,j,W,M)}catch(ie){const Qe=ie.message||"Submission failed.";C.current(Qe,j),ce(M,"failed",j),j.startsWith("file://")&&ie.status&&hi(W,j).catch(()=>{})}}function Ye(){var A,W;if(k.some(V=>V.kind==="file"&&V.uploadStatus==="uploading"))return;const j=k.filter(V=>V.kind==="file"?V.uploadStatus==="done"&&V.uploadLocator:V.locator.trim());if(j.length===0||j.some(V=>V.kind!=="file"&&Eu(V))||j.some(V=>V.kind!=="file"&&(V.probeState==="probing"||Pn(V.locator)&&V.playlistProbeState!=="done"))||j.some(V=>V.kind!=="file"&&Array.isArray(V.playlistItems)&&V.playlistItems.length===0))return;const B=j.length>1?((A=crypto.randomUUID)==null?void 0:A.call(crypto))??`batch-${Date.now()}`:null;B&&h.current.set(B,{total:j.length,archived:0,warnings:0,failed:0,failedLocators:[],warningLocators:[]});const M=j.map(V=>V.kind==="file"?{locator:V.uploadLocator,quality:"best",extraExtensions:{}}:{locator:V.locator.trim(),quality:V.playlistItems!==null?null:V.quality||"best",extraExtensions:V.playlistItems!==null?{per_item_quality:Object.fromEntries(V.playlistItems.map(pe=>[pe.id,pe.quality])),sync:V.syncEnabled}:{}});f.current=!0,T([Wn()]),(W=u.current)==null||W.close(),M.forEach(({locator:V,quality:pe,extraExtensions:ae})=>Ee(V,pe,B,ae))}function Ct(){T(j=>[...j,Wn()])}function yt(j){var M;clearTimeout(g.current.get(j)),g.current.delete(j);const B=p.current.find(A=>A.id===j);(B==null?void 0:B.kind)==="file"&&(B.uploadStatus==="uploading"?((M=m.current.get(j))==null||M(),m.current.delete(j)):B.uploadStatus==="done"&&B.uploadLocator&&hi(v.current,B.uploadLocator).catch(()=>{})),T(A=>{const W=A.filter(V=>V.id!==j);return W.length===0?[Wn()]:W})}function Ht(j,B){if(clearTimeout(g.current.get(j)),T(M=>M.map(A=>A.id===j?{...A,locator:B,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best",playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1}:A)),Jd(B)){const M=setTimeout(async()=>{g.current.delete(j),T(A=>A.map(W=>W.id===j?{...W,probeState:"probing"}:W));try{const A=await Kh(v.current,B.trim());T(W=>W.map(V=>{if(V.id!==j||V.locator!==B)return V;const pe=A.qualities??[],ae=A.has_audio??!1,xe=pe.length===0&&ae?"audio":"best";return{...V,probeState:"done",probeQualities:pe,probeHasAudio:ae,quality:xe}}))}catch{T(A=>A.map(W=>W.id===j?{...W,probeState:"idle",probeQualities:null}:W))}},600);g.current.set(j,M)}else if(Pn(B)){const M=setTimeout(async()=>{g.current.delete(j),T(A=>A.map(W=>W.id===j?{...W,playlistProbeState:"probing"}:W));try{const A=await qh(v.current,B.trim());T(W=>W.map(V=>V.id!==j||V.locator!==B?V:{...V,playlistProbeState:"done",playlistInfo:A,playlistItems:A.items.map(pe=>({...pe,quality:null})),playlistQuality:null}))}catch{T(A=>A.map(W=>W.id===j?{...W,playlistProbeState:"error"}:W))}},800);g.current.set(j,M)}}function ut(j,B){T(M=>M.map(A=>A.id===j?{...A,quality:B}:A))}function rt(j,B){T(M=>M.map(A=>{if(A.id!==j)return A;const W=Pm(B,A.playlistItems);return{...A,playlistQuality:B,playlistItems:W}}))}function vt(j,B,M){T(A=>A.map(W=>W.id!==j?W:{...W,playlistItems:W.playlistItems.map(V=>V.id===B?{...V,quality:M}:V)}))}function Et(j){T(B=>B.map(M=>M.id===j?{...M,playlistExpanded:!M.playlistExpanded}:M))}function O(j,B){T(M=>M.map(A=>A.id===j?{...A,syncEnabled:B}:A))}function K(j,B){T(M=>M.map(A=>A.id!==j?A:{...A,playlistItems:A.playlistItems.filter(W=>W.id!==B)}))}function de(j){const B=Array.from(j);B.length!==0&&B.forEach(M=>{const A=Tm(M.name);T(ae=>ae.length===1&&ae[0].kind!=="file"&&!ae[0].locator.trim()?[A]:[...ae,A]);const W=v.current,{promise:V,abort:pe}=Nm(W,M,ae=>{T(xe=>xe.map(ie=>ie.id===A.id?{...ie,uploadProgress:ae}:ie))});m.current.set(A.id,pe),V.then(ae=>{m.current.delete(A.id),T(xe=>xe.map(ie=>ie.id===A.id?{...ie,uploadStatus:"done",uploadLocator:ae.locator,uploadProgress:100}:ie))}).catch(ae=>{m.current.delete(A.id),ae.message!=="Upload cancelled"&&T(xe=>xe.map(ie=>ie.id===A.id?{...ie,uploadStatus:"error",uploadError:ae.message}:ie))})})}function Be(j){j.preventDefault(),j.stopPropagation(),j.dataTransfer.types.includes("Files")&&N(!0)}function Dt(j){j.currentTarget.contains(j.relatedTarget)||N(!1)}function ze(j){j.preventDefault(),j.stopPropagation(),N(!1),de(j.dataTransfer.files)}function Fn(j){de(j.target.files),j.target.value=""}const Nn=k.some(j=>j.kind==="file"&&j.uploadStatus==="uploading"),tn=k.filter(j=>j.kind==="file"?j.uploadStatus==="done"&&j.uploadLocator:j.locator.trim()).length,Ve=k.some(j=>j.kind!=="file"&&Eu(j)),wr=k.some(j=>j.kind!=="file"&&Array.isArray(j.playlistItems)&&j.playlistItems.length===0),Bn=k.some(j=>j.kind!=="file"&&(j.probeState==="probing"||Pn(j.locator)&&j.playlistProbeState!=="done"));return s.jsx("dialog",{ref:u,className:`capture-dialog${S?" capture-dialog--dragover":""}`,onDragOver:Be,onDragLeave:Dt,onDrop:ze,children:s.jsxs("div",{className:"capture-dialog-inner",children:[s.jsxs("div",{className:"capture-dialog-header",children:[s.jsx("h2",{className:"capture-dialog-title",children:"Capture"}),s.jsx("button",{type:"button",className:"capture-dialog-close",onClick:()=>{var j;return(j=u.current)==null?void 0:j.close()},"aria-label":"Close",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),s.jsx("div",{className:"capture-rows",children:k.map((j,B)=>j.kind==="file"?s.jsx(zm,{item:j,onRemove:()=>yt(j.id)},j.id):s.jsx(Rm,{item:j,autoFocus:B===k.length-1,onLocatorChange:M=>Ht(j.id,M),onQualityChange:M=>ut(j.id,M),onRemove:()=>yt(j.id),onSubmit:Ye,onPlaylistQualityChange:M=>rt(j.id,M),onPlaylistItemQualityChange:(M,A)=>vt(j.id,M,A),onPlaylistToggle:()=>Et(j.id),onSyncChange:M=>O(j.id,M),onPlaylistItemDelete:M=>K(j.id,M)},j.id))}),s.jsx("input",{ref:x,type:"file",multiple:!0,hidden:!0,onChange:Fn,"aria-hidden":"true",tabIndex:-1}),s.jsxs("div",{className:"capture-add-row-group",children:[s.jsxs("button",{type:"button",className:"capture-add-row",onClick:Ct,children:[s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"8",y1:"2",x2:"8",y2:"14"}),s.jsx("line",{x1:"2",y1:"8",x2:"14",y2:"8"})]}),"Add URL"]}),s.jsxs("button",{type:"button",className:"capture-add-row capture-add-file",onClick:()=>{var j;return(j=x.current)==null?void 0:j.click()},children:[s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"3",y:"1",width:"10",height:"14",rx:"1.5"}),s.jsx("line",{x1:"5.5",y1:"5.5",x2:"10.5",y2:"5.5"}),s.jsx("line",{x1:"5.5",y1:"8",x2:"10.5",y2:"8"}),s.jsx("line",{x1:"5.5",y1:"10.5",x2:"8.5",y2:"10.5"})]}),"Upload file"]})]}),s.jsxs("div",{className:"capture-advanced",children:[s.jsxs("button",{type:"button",className:"capture-advanced-toggle",onClick:()=>q(j=>!j),"aria-expanded":L,children:[s.jsx("svg",{className:`capture-chevron${L?" capture-chevron--open":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("polyline",{points:"4 6 8 10 12 6"})}),"Advanced options"]}),L&&s.jsxs("div",{className:"capture-advanced-panel",children:[s.jsxs("label",{className:"capture-ext-row",children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"capture-ext-desc",children:"Block ads during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":ee,className:`ext-toggle ext-toggle--sm${ee?" ext-toggle--on":""}`,onClick:()=>X(j=>j===null?!ee:!j),"aria-label":"Toggle uBlock for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Block cookie banners"}),s.jsx("span",{className:"capture-ext-desc",children:"Dismiss cookie consent banners during this capture"}),!(Z!=null&&Z.cookie_ext_available)&&s.jsxs("span",{className:"capture-ext-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":Ae,className:`ext-toggle ext-toggle--sm${Ae?" ext-toggle--on":""}`,onClick:()=>ge(j=>!j),"aria-label":"Toggle cookie banner blocking for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Reader mode"}),s.jsx("span",{className:"capture-ext-desc",children:"Distil to article text via Readability (off by default)"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":Re,className:`ext-toggle ext-toggle--sm${Re?" ext-toggle--on":""}`,onClick:()=>Y(j=>!j),"aria-label":"Toggle reader mode for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Close modals and dialogs"}),s.jsx("span",{className:"capture-ext-desc",children:"Auto-dismiss cookie banners and overlays during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":D,className:`ext-toggle ext-toggle--sm${D?" ext-toggle--on":""}`,onClick:()=>P(j=>!j),"aria-label":"Toggle modal closer for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Freedium mirror"}),s.jsx("span",{className:"capture-ext-desc",children:"Route paywalled articles through a Freedium mirror (Medium, NYT, WaPo, etc.)"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":H,className:`ext-toggle ext-toggle--sm${H?" ext-toggle--on":""}`,onClick:()=>te(j=>!j),"aria-label":"Toggle Freedium mirror for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]})]})]}),s.jsxs("div",{className:"capture-actions",children:[s.jsx("button",{type:"button",className:"capture-submit",onClick:Ye,disabled:tn===0||Ve||Bn||wr||Nn,children:tn>1?`Archive ${tn}`:"Archive"}),s.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var j;return(j=u.current)==null?void 0:j.close()},children:"Cancel"})]})]})})}function Rm({item:e,autoFocus:t,onLocatorChange:n,onQualityChange:r,onRemove:l,onSubmit:i,onPlaylistQualityChange:a,onPlaylistItemQualityChange:o,onPlaylistToggle:u,onSyncChange:c,onPlaylistItemDelete:y}){const g=d.useRef(null);d.useEffect(()=>{var x;t&&((x=g.current)==null||x.focus())},[t]);const h=(()=>{if(Pn(e.locator)){if(e.playlistProbeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Probing playlist…",children:"…"});if(e.playlistProbeState==="done"){const x=[...new Set(e.playlistItems.flatMap(p=>p.qualities.map(f=>parseInt(f))))].sort((p,f)=>f-p),S=e.playlistItems.every(p=>p.has_audio),N=e.playlistItems.filter(p=>p.quality===null).length;return s.jsxs(s.Fragment,{children:[s.jsxs("select",{className:"capture-quality",value:e.playlistQuality??"",onChange:p=>a(p.target.value),"aria-label":"Playlist quality",children:[!e.playlistQuality&&s.jsx("option",{value:"",disabled:!0,children:"Select quality…"}),s.jsx("option",{value:"best",children:"Best quality"}),x.map(p=>s.jsxs("option",{value:`${p}p`,children:[p,"p"]},p)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]}),N>0&&s.jsxs("span",{className:"capture-conflict-badge",children:[N," need selection"]})]})}return e.playlistProbeState==="error"?s.jsx("span",{className:"capture-quality-hint capture-quality-hint--error",children:"Probe failed — edit URL to retry"}):null}if(!Jd(e.locator))return null;if(e.probeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Checking available qualities",children:"…"});if(e.probeState==="done"){const x=e.probeQualities??[],S=e.probeHasAudio??!1;return x.length===0&&!S?s.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):x.length===0&&S?s.jsx("select",{className:"capture-quality",value:"audio",onChange:N=>r(N.target.value),"aria-label":"Video quality",children:s.jsx("option",{value:"audio",children:"Audio only"})}):s.jsxs("select",{className:"capture-quality",value:e.quality||"best",onChange:N=>r(N.target.value),"aria-label":"Video quality",children:[s.jsx("option",{value:"best",children:"Best quality"}),x.map(N=>s.jsx("option",{value:N,children:N},N)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]})}return null})(),v=Pn(e.locator)&&e.playlistProbeState==="done"?s.jsxs("label",{className:"capture-sync-row",children:[s.jsx("input",{type:"checkbox",checked:e.syncEnabled,onChange:x=>c(x.target.checked)}),s.jsx("span",{children:"Sync — skip already-archived videos"})]}):null;return s.jsxs("div",{className:"capture-row",children:[s.jsxs("div",{className:"capture-row-main",children:[Pn(e.locator)&&e.playlistProbeState==="done"?s.jsx("button",{type:"button",className:"capture-playlist-toggle capture-playlist-toggle--left",onClick:u,"aria-label":e.playlistExpanded?"Collapse video list":"Expand video list","aria-expanded":e.playlistExpanded,children:e.playlistExpanded?"▲":"▼"}):null,s.jsx("input",{ref:g,className:"capture-input",type:"text",placeholder:"https://… · yt:ID · ytm:ID · tweet:ID · x:ID",value:e.locator,onChange:x=>n(x.target.value),onKeyDown:x=>{x.key==="Enter"&&i()},autoComplete:"off",spellCheck:!1}),h,s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:l,"aria-label":"Remove",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),e.error&&s.jsx("p",{className:"capture-row-error",children:e.error}),Pn(e.locator)&&e.playlistProbeState==="done"&&e.playlistExpanded?s.jsxs("div",{className:"capture-playlist-items",children:[e.playlistItems.map(x=>s.jsxs("div",{className:`capture-playlist-item${x.quality===null?" capture-playlist-item--conflict":""}`,children:[s.jsx("span",{className:"capture-playlist-item-title",children:x.title||x.url}),s.jsxs("select",{className:"capture-item-quality",value:x.quality??"",onChange:S=>o(x.id,S.target.value),"aria-label":`Quality for ${x.title||x.url}`,children:[x.quality===null&&s.jsx("option",{value:"",disabled:!0,children:"Choose…"}),s.jsx("option",{value:"best",children:"Best quality"}),x.qualities.map(S=>s.jsx("option",{value:S,children:S},S)),x.has_audio&&s.jsx("option",{value:"audio",children:"Audio only"})]}),x.quality===null&&s.jsx("span",{className:"capture-playlist-conflict-badge",children:"Choose quality"}),s.jsx("button",{type:"button",className:"capture-playlist-item-remove","aria-label":`Remove ${x.title||x.url}`,onClick:()=>y(x.id),children:"×"})]},x.id)),v]}):v]})}function zm({item:e,onRemove:t}){const n=e.uploadStatus==="uploading",r=e.uploadStatus==="done",l=e.uploadStatus==="error";return s.jsxs("div",{className:"capture-row",children:[s.jsxs("div",{className:"capture-row-main",children:[s.jsx("span",{className:"capture-file-icon","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",style:{width:14,height:14},children:[s.jsx("rect",{x:"3",y:"1",width:"10",height:"14",rx:"1.5"}),s.jsx("line",{x1:"5.5",y1:"5.5",x2:"10.5",y2:"5.5"}),s.jsx("line",{x1:"5.5",y1:"8",x2:"10.5",y2:"8"}),s.jsx("line",{x1:"5.5",y1:"10.5",x2:"8.5",y2:"10.5"})]})}),s.jsx("span",{className:`capture-file-name${l?" capture-file-name--error":""}`,children:e.filename}),n&&s.jsxs("span",{className:"capture-file-progress-wrap","aria-label":`Uploading ${e.uploadProgress}%`,children:[s.jsx("span",{className:"capture-file-progress-bar",children:s.jsx("span",{className:"capture-file-progress-fill",style:{width:`${e.uploadProgress}%`}})}),s.jsxs("span",{className:"capture-file-progress-pct",children:[e.uploadProgress,"%"]})]}),r&&s.jsx("span",{className:"capture-file-badge capture-file-badge--done","aria-label":"Upload complete",children:s.jsx("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{width:11,height:11},children:s.jsx("polyline",{points:"3 8.5 6.5 12 13 5"})})}),l&&s.jsx("span",{className:"capture-file-badge capture-file-badge--error",children:"!"}),s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:t,"aria-label":"Remove",disabled:n,children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),l&&s.jsx("p",{className:"capture-row-error",children:e.uploadError||"Upload failed"})]})}function Im(){return s.jsxs("div",{className:"skeleton-row",children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:s.jsx("span",{className:"skeleton-cell",style:{width:108,height:13}})}),s.jsxs("div",{className:"col-title",style:{gap:"0.42em",display:"flex",alignItems:"center"},children:[s.jsx("span",{className:"skeleton-cell",style:{width:14,height:14,borderRadius:"50%",flexShrink:0}}),s.jsx("span",{className:"skeleton-cell",style:{width:"58%",height:13}})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"skeleton-cell",style:{width:58,height:20,borderRadius:99}})}),s.jsx("div",{className:"col-size",children:s.jsx("span",{className:"skeleton-cell",style:{width:44,height:12}})}),s.jsx("div",{className:"col-url",children:s.jsx("span",{className:"skeleton-cell",style:{width:"65%",height:12}})})]})}function cl(e){if(!e)return"0 B";const t=["B","KB","MB","GB"];let n=e,r=0;for(;n>=1024&&r").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}function dt(e){return Dm(e)??""}function ao(e){if(!e)return"";const t=new Date(e);if(isNaN(t))return e;const n=r=>String(r).padStart(2,"0");return`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())} ${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}const bu={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function Os(e){return bu[e]??bu.other}function Gd(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function $m({entry:e,index:t,onRowClick:n,selectedUids:r}){const l=(r==null?void 0:r.size)===1&&r.has(e.entry_uid),i=(r==null?void 0:r.size)>=2&&r.has(e.entry_uid),a=["child-entry-row",t%2===0?"child-entry-row--light":"child-entry-row--dark",l&&"is-selected",i&&"is-multi-selected"].filter(Boolean).join(" ");return s.jsxs("div",{className:a,tabIndex:0,"data-entry-uid":e.entry_uid,onMouseDown:o=>{o.shiftKey&&o.preventDefault()},onClick:o=>n(e,o),onKeyDown:o=>{o.key==="Enter"&&n(e,o)},children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:ao(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[s.jsx("span",{className:"source-icon",children:s.jsx("span",{dangerouslySetInnerHTML:{__html:Os(e.source_kind)}})}),s.jsx("span",{className:"entry-title",children:dt(e.title)||dt(e.entry_uid)})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:dt(e.entity_kind)})}),s.jsx("div",{className:"col-size",children:s.jsx("span",{className:"size-total",children:cl(e.total_artifact_bytes)})}),s.jsx("div",{className:"url-cell col-url",children:dt(e.original_url)})]})}function Om({entry:e,archiveId:t,rowIndex:n,isSelected:r,isMultiSelected:l,onRowClick:i,selectedUids:a,deletedUids:o,isPublicSession:u}){const[c,y]=d.useState(!1),[g,h]=d.useState(!1),[v,x]=d.useState(null),[S,N]=d.useState(!1),f=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!c?s.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>y(!0),style:{objectFit:"contain"}}):s.jsx("span",{dangerouslySetInnerHTML:{__html:Os(e.source_kind)}}),m=r||l,w=e.child_count>0&&!u;function C(k){k.stopPropagation(),i(e,{ctrlKey:!0,metaKey:!1,shiftKey:!1,preventDefault(){}})}async function E(k){if(k.stopPropagation(),g){h(!1);return}if(h(!0),v===null&&!S){N(!0);try{const T=await Oh(t,e.entry_uid);x(T)}catch{x([])}finally{N(!1)}}}const b=["entry-row-outer",n%2===0?"entry-row-outer--light":"entry-row-outer--dark",r&&"is-selected",l&&"is-multi-selected"].filter(Boolean).join(" ");return s.jsxs("div",{className:b,"data-entry-uid":e.entry_uid,children:[s.jsxs("div",{className:"entry-row-main",tabIndex:0,onMouseDown:k=>{k.shiftKey&&k.preventDefault()},onClick:k=>i(e,k),onKeyDown:k=>{k.key==="Enter"&&i(e,k)},children:[s.jsx("div",{className:"col-check",children:s.jsx("button",{type:"button",className:`row-checkbox${m?" is-checked":""}`,"aria-pressed":m,"aria-label":m?"Deselect entry":"Select entry",onClick:C,onKeyDown:k=>k.stopPropagation()})}),s.jsx("div",{className:"col-added",children:ao(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[w&&s.jsx("button",{type:"button",className:`entry-expand-btn${g?" is-expanded":""}`,"aria-label":g?"Collapse children":`Expand ${e.child_count} items`,"aria-expanded":g,onClick:E,onKeyDown:k=>k.stopPropagation()}),s.jsx("span",{className:"source-icon",children:f}),s.jsx("span",{className:"entry-title",children:dt(e.title)||dt(e.entry_uid)}),w&&s.jsx("span",{className:"child-count-badge","aria-hidden":"true",children:e.child_count})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:dt(e.entity_kind)})}),s.jsxs("div",{className:"col-size",children:[s.jsx("span",{className:"size-total",children:cl(e.total_artifact_bytes)}),e.cached_bytes>0&&e.cacheable_bytes>0&&s.jsxs("span",{className:"size-cached-pct",title:`${cl(e.cached_bytes)} already on disk from an earlier entry`,children:[Math.round(e.cached_bytes/e.cacheable_bytes*100),"% cached"]})]}),s.jsx("div",{className:"url-cell col-url",children:dt(e.original_url)})]}),g&&s.jsxs(s.Fragment,{children:[S&&s.jsx("div",{className:"child-entries-loading",children:"Loading…"}),s.jsx("div",{className:"child-entries","aria-label":`${e.child_count} child entries`,children:v&&v.filter(k=>!(o!=null&&o.has(k.entry_uid))).map((k,T)=>s.jsx($m,{entry:k,index:T,onRowClick:i,selectedUids:a},k.entry_uid))})]})]})}function Am({entries:e,selectedUids:t,onRowClick:n,archiveId:r,pendingCaptures:l=[],deletedUids:i,isPublicSession:a}){return s.jsx("section",{id:"archive-view",className:"view is-active",children:s.jsxs("div",{className:"entry-table",children:[s.jsxs("div",{className:"entry-header-row",children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:"Added"}),s.jsx("div",{className:"col-title",children:"Title"}),s.jsx("div",{className:"col-type",children:"Type"}),s.jsx("div",{className:"col-size",children:"Size"}),s.jsx("div",{className:"col-url",children:"Original URL"})]}),s.jsxs("div",{id:"entries-body",children:[l.filter(o=>o.archiveId===r).reverse().map(o=>s.jsx(Im,{},o.id)),e.map((o,u)=>s.jsx(Om,{entry:o,rowIndex:u,archiveId:r,isSelected:t.size===1&&t.has(o.entry_uid),isMultiSelected:t.size>=2&&t.has(o.entry_uid),onRowClick:n,selectedUids:t,deletedUids:i,isPublicSession:a},o.entry_uid))]})]})})}function Mm(e){if(!e)return"—";try{return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return e}}function Fm({status:e}){const t=e==="completed"?"run-status--completed":e==="failed"?"run-status--failed":e==="in_progress"?"run-status--in-progress":"",n=e?e.replace(/_/g," "):"—";return s.jsx("span",{className:`run-status ${t}`,children:n})}function Bm({runs:e}){const[t,n]=d.useState(null);function r(l){n(i=>i===l?null:l)}return s.jsx("section",{id:"runs-view",className:"view is-active",children:s.jsxs("table",{className:"entry-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Started"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Requested"}),s.jsx("th",{children:"Completed"}),s.jsx("th",{children:"Failed"})]})}),s.jsx("tbody",{children:e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:5,style:{color:"var(--muted)",padding:"24px 16px",textAlign:"center"},children:"No runs yet."})}):e.map(l=>{const i=l.status==="failed"&&l.error_summary,a=t===l.run_uid;return[s.jsxs("tr",{className:i?"run-row run-row--failed":"run-row",onClick:i?()=>r(l.run_uid):void 0,title:i?a?"Click to hide error":"Click to view error":void 0,children:[s.jsx("td",{children:Mm(l.started_at)}),s.jsxs("td",{children:[s.jsx(Fm,{status:l.status}),i&&s.jsx("span",{className:"run-expand-hint","aria-hidden":"true",children:a?"▴":"▾"})]}),s.jsx("td",{children:l.requested_count??"—"}),s.jsx("td",{children:l.completed_count??"—"}),s.jsx("td",{children:l.failed_count??"—"})]},l.run_uid),i&&a&&s.jsx("tr",{className:"run-error-row",children:s.jsx("td",{colSpan:5,children:s.jsx("pre",{className:"run-error-detail",children:l.error_summary})})},`${l.run_uid}-detail`)]})})]})})}const Um=4;function Hm({archives:e}){const{currentUser:t}=d.useContext(As)??{},n=t&&(t.role_bits&Um)!==0,[r,l]=d.useState("users"),[i,a]=d.useState([]),[o,u]=d.useState([]),[c,y]=d.useState(!1),[g,h]=d.useState(null),[v,x]=d.useState(""),[S,N]=d.useState(""),[p,f]=d.useState(""),[m,w]=d.useState(null),[C,E]=d.useState(!1),[b,k]=d.useState(""),[T,L]=d.useState(""),[q,F]=d.useState(null),[X,Z]=d.useState(!1),ue=d.useCallback(async()=>{if(n){y(!0),h(null);try{const[P,H]=await Promise.all([im(),um()]);a(P),u(H)}catch(P){h(P.message)}finally{y(!1)}}},[n]);d.useEffect(()=>{ue()},[ue]);async function Ae(P){const H=P.status==="active"?"disabled":"active";try{await om(P.user_uid,H),a(te=>te.map(ee=>ee.user_uid===P.user_uid?{...ee,status:H}:ee))}catch(te){h(te.message)}}async function ge(P){if(P.preventDefault(),!v.trim()||!S){w("Username and password required");return}E(!0),w(null);try{await am(v.trim(),S,p.trim()||void 0),x(""),N(""),f(""),await ue()}catch(H){w(H.message)}finally{E(!1)}}async function D(P){if(P.preventDefault(),!b.trim()||!T.trim()){F("Slug and name required");return}Z(!0),F(null);try{await cm(b.trim(),T.trim()),k(""),L(""),await ue()}catch(H){F(H.message)}finally{Z(!1)}}return n?s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsxs("div",{className:"view-tabs",children:[s.jsx("button",{className:`view-tab${r==="users"?" is-active":""}`,onClick:()=>l("users"),children:"Users"}),s.jsx("button",{className:`view-tab${r==="roles"?" is-active":""}`,onClick:()=>l("roles"),children:"Roles"}),s.jsx("button",{className:`view-tab${r==="archives"?" is-active":""}`,onClick:()=>l("archives"),children:"Archives"})]}),g&&s.jsx("div",{className:"form-msg form-msg--err",children:g}),r==="users"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Users"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Username"}),s.jsx("th",{children:"Email"}),s.jsx("th",{children:"Roles"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:i.map(P=>s.jsxs("tr",{className:P.status==="disabled"?"admin-row-disabled":"",children:[s.jsx("td",{children:P.username}),s.jsx("td",{className:"muted",children:P.email||"—"}),s.jsx("td",{children:P.role_slugs.join(", ")||"—"}),s.jsx("td",{children:s.jsx("span",{className:`status-badge status-${P.status}`,children:P.status})}),s.jsx("td",{children:s.jsx("button",{className:"admin-action-btn",onClick:()=>Ae(P),children:P.status==="active"?"Ban":"Unban"})})]},P.user_uid))})]}),s.jsx("h3",{children:"Create User"}),s.jsxs("form",{className:"admin-form",onSubmit:ge,children:[s.jsx("input",{className:"admin-input",placeholder:"Username",value:v,onChange:P=>x(P.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:S,onChange:P=>N(P.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:p,onChange:P=>f(P.target.value)}),m&&s.jsx("div",{className:"form-msg form-msg--err",children:m}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:C,children:C?"Creating…":"Create User"})]})]}),r==="roles"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Roles"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Slug"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Level"}),s.jsx("th",{children:"Bit"}),s.jsx("th",{children:"Built-in"})]})}),s.jsx("tbody",{children:o.map(P=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:P.slug})}),s.jsx("td",{children:P.name}),s.jsx("td",{children:P.level}),s.jsx("td",{children:P.bit_position}),s.jsx("td",{children:P.is_builtin?"✓":""})]},P.role_uid))})]}),s.jsx("h3",{children:"Create Custom Role"}),s.jsxs("form",{className:"admin-form",onSubmit:D,children:[s.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:b,onChange:P=>k(P.target.value),required:!0}),s.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:T,onChange:P=>L(P.target.value),required:!0}),q&&s.jsx("div",{className:"form-msg form-msg--err",children:q}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:X,children:X?"Creating…":"Create Role"})]})]}),r==="archives"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(P=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:P.label}),s.jsx("div",{className:"muted",children:P.archive_path})]},P.id))})]})]}):s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsx("p",{className:"muted",children:"You need admin privileges to access this panel."}),s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(P=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:P.label}),s.jsx("div",{className:"muted",children:P.archive_path})]},P.id))})]})}function Yd({node:e,onPick:t}){var n;return s.jsxs("li",{children:[s.jsx("button",{className:"tag-picker-node-btn",title:e.tag.full_path,onClick:()=>t(e.tag),children:e.tag.slug}),((n=e.children)==null?void 0:n.length)>0&&s.jsx("div",{className:"tag-children",children:s.jsx("ul",{className:"tag-tree-list",children:e.children.map(r=>s.jsx(Yd,{node:r,onPick:t},r.tag.tag_uid))})})]})}function Tu({title:e,tagNodes:t,excludeUid:n,onPick:r,onCancel:l}){d.useEffect(()=>{function o(u){u.key==="Escape"&&(u.preventDefault(),u.stopPropagation(),l())}return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[l]);function i(o){return o.filter(u=>u.tag.tag_uid!==n).map(u=>({...u,children:i(u.children)}))}const a=n?i(t):t;return s.jsx("div",{className:"tag-picker-backdrop",onClick:o=>{o.target===o.currentTarget&&l()},children:s.jsxs("div",{className:"tag-picker-modal",role:"dialog","aria-modal":"true",children:[s.jsxs("div",{className:"tag-picker-header",children:[s.jsx("span",{className:"tag-picker-title",children:e}),s.jsx("button",{className:"tag-picker-close",onClick:l,title:"Cancel","aria-label":"Cancel",children:"×"})]}),s.jsxs("div",{className:"tag-picker-body",children:[s.jsx("button",{className:"tag-picker-root-btn",onClick:()=>r(null),title:"Place at root level (no parent)",children:"↑ Root tag (no parent)"}),a.length>0?s.jsx("ul",{className:"tag-tree-list tag-picker-tree",children:a.map(o=>s.jsx(Yd,{node:o,onPick:r},o.tag.tag_uid))}):s.jsx("p",{className:"tag-picker-empty",children:"No other tags available."})]})]})})}function Zd({parentPath:e,archiveId:t,onDone:n,onCancel:r}){const[l,i]=d.useState(""),a=d.useRef(!1);async function o(){const u=l.trim();if(!u){r();return}const c=e?`${e}/${u}`:`/${u}`;try{await Wh(t,c),n()}catch(y){alert(y.message||"Create failed"),r()}}return s.jsx("input",{className:"tag-rename-input",autoFocus:!0,placeholder:"tag name",value:l,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&u.currentTarget.blur(),u.key==="Escape"&&(a.current=!0,u.currentTarget.blur())},onBlur:()=>{a.current?(a.current=!1,r()):o()}})}function ef({node:e,archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:y,pendingCreateParentUid:g,onCreateDone:h,onCreateCancel:v}){var q;const x=n===e.tag.full_path,[S,N]=d.useState(!1),[p,f]=d.useState(""),m=d.useRef(!1);function w(){if(S)return;if(c){y(e);return}const F=x?null:e.tag.full_path;r(F),l("archive")}function C(F){F.stopPropagation(),!c&&(f(e.tag.slug),N(!0))}async function E(){const F=p.trim();if(!F||F===e.tag.slug){N(!1);return}try{const X=await Uh(t,e.tag.tag_uid,F);i(e.tag.full_path,X.full_path),o()}catch{}finally{N(!1)}}async function b(F){var Z;F.stopPropagation();const X=((Z=e.children)==null?void 0:Z.length)>0?`Delete tag "${e.tag.full_path}" and all its child tags? This cannot be undone.`:`Delete tag "${e.tag.full_path}"? This cannot be undone.`;if(window.confirm(X))try{await Hh(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const k={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:y,pendingCreateParentUid:g,onCreateDone:h,onCreateCancel:v},T=g===e.tag.tag_uid,L=((q=e.children)==null?void 0:q.length)>0;return s.jsxs("li",{children:[s.jsxs("div",{className:`tag-node-row${c?" tag-node-row--move-select":""}`,children:[S?s.jsx("input",{className:"tag-rename-input",autoFocus:!0,value:p,onChange:F=>f(F.target.value),onKeyDown:F=>{F.key==="Enter"&&F.currentTarget.blur(),F.key==="Escape"&&(m.current=!0,F.currentTarget.blur())},onBlur:()=>{m.current?(m.current=!1,N(!1)):E()}}):s.jsxs("button",{className:`tag-node-btn${x?" is-active":""}${c?" tag-node-btn--move-select":""}`,title:c?`Select "${e.tag.full_path}" to move`:e.tag.full_path,onClick:w,onDoubleClick:c?void 0:C,children:[s.jsx("span",{className:"tag-node-label",children:u?e.tag.name:e.tag.slug}),s.jsx("span",{className:"tag-node-count",children:e.children.length===0?`(${e.entry_count})`:`(${e.entry_count}) (${e.subtree_count} Total)`}),!c&&s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",title:"Rename tag",onClick:F=>{F.stopPropagation(),C(F)},children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),!S&&!c&&s.jsx("button",{className:"remove tag-node-delete",title:`Delete "${e.tag.full_path}"`,onClick:b,"aria-label":`Delete "${e.tag.full_path}"`,children:"×"})]}),(L||T)&&s.jsx("div",{className:"tag-children",children:s.jsxs("ul",{className:"tag-tree-list",children:[e.children.map(F=>s.jsx(ef,{node:F,...k},F.tag.tag_uid)),T&&s.jsx("li",{children:s.jsx(Zd,{parentPath:e.tag.full_path,archiveId:t,onDone:h,onCancel:v})})]})})]})}function Wm({archiveId:e,tagNodes:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u}){const[c,y]=d.useState(null),[g,h]=d.useState(null);function v(){y("select-source"),h(null)}function x(){y(null),h(null)}d.useEffect(()=>{if(c!=="select-source")return;function X(Z){Z.key==="Escape"&&(Z.preventDefault(),Z.stopPropagation(),x())}return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[c]);function S(X){h(X),y("select-dest")}async function N(X){const Z=g.tag.full_path,ue=g.tag.tag_uid,Ae=(X==null?void 0:X.tag_uid)??null;x();try{const ge=await Vh(e,ue,Ae);i(Z,ge.full_path),o()}catch(ge){alert(ge.message||"Move failed")}}const[p,f]=d.useState(null),[m,w]=d.useState(void 0);function C(){f("select-parent"),w(void 0)}function E(){f(null),w(void 0)}function b(X){w(X??null),f("input")}function k(){f(null),w(void 0),o()}const T=c==="select-source",L=p==="input"?m?m.tag_uid:"__root__":void 0,q={archiveId:e,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:T,onMoveSourceSelect:S,pendingCreateParentUid:L,onCreateDone:k,onCreateCancel:E},F=L==="__root__";return s.jsxs("section",{id:"tags-view",className:"view is-active",children:[s.jsxs("div",{className:"tag-tree",children:[s.jsx("div",{className:"tag-tree-header",children:T?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title tag-tree-title--move",children:"Select a tag to move"}),s.jsx("button",{className:"tag-tree-action-btn tag-tree-action-btn--cancel",onClick:x,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title",children:"Tags"}),n&&s.jsxs("span",{className:"tag-tree-active",title:n,children:["Filtering: ",n]}),s.jsxs("div",{className:"tag-tree-actions",children:[s.jsx("button",{className:"tag-tree-action-btn",onClick:C,title:"Create a new tag",disabled:!!p||!!c,children:"+ New"}),s.jsx("button",{className:"tag-tree-action-btn",onClick:v,title:"Move a tag to a different parent",disabled:!!p||!!c||t.length===0,children:"Move"})]})]})}),t.length===0&&!F?s.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):s.jsxs("ul",{className:"tag-tree-list",children:[t.map(X=>s.jsx(ef,{node:X,...q},X.tag.tag_uid)),F&&s.jsx("li",{children:s.jsx(Zd,{parentPath:null,archiveId:e,onDone:k,onCancel:E})})]})]}),p==="select-parent"&&s.jsx(Tu,{title:"Create tag under…",tagNodes:t,excludeUid:null,onPick:b,onCancel:E}),c==="select-dest"&&g&&s.jsx(Tu,{title:`Move "${g.tag.slug}" under…`,tagNodes:t,excludeUid:g.tag.tag_uid,onPick:N,onCancel:x})]})}const Or=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],Vm=e=>{var t;return((t=Or.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function Qm({archiveId:e}){const[t,n]=d.useState([]),[r,l]=d.useState(!1),[i,a]=d.useState(null),[o,u]=d.useState(null),[c,y]=d.useState(null),[g,h]=d.useState(!1),[v,x]=d.useState(null),[S,N]=d.useState(""),[p,f]=d.useState(""),[m,w]=d.useState(2),[C,E]=d.useState(!1),[b,k]=d.useState(!0),[T,L]=d.useState(null),[q,F]=d.useState(""),[X,Z]=d.useState(2),[ue,Ae]=d.useState(!1),[ge,D]=d.useState(null),[P,H]=d.useState(!1),[te,ee]=d.useState(""),Re=d.useRef(null),Y=t.find(O=>O.collection_uid===o)??null,ye=(Y==null?void 0:Y.slug)==="_default_",ce=d.useCallback(async()=>{if(e){l(!0),a(null);try{const O=await io(e);n(O)}catch(O){a(O.message)}finally{l(!1)}}},[e]),Ee=d.useCallback(async O=>{if(!O){y(null);return}h(!0),x(null);try{const K=await fm(e,O);y(K)}catch(K){x(K.message)}finally{h(!1)}},[e]);d.useEffect(()=>{ce()},[ce]),d.useEffect(()=>{Ee(o)},[o,Ee]),d.useEffect(()=>{P&&Re.current&&Re.current.focus()},[P]),d.useEffect(()=>{c!=null&&Z(c.default_visibility_bits)},[c]);async function Ye(O){O.preventDefault();const K=S.trim(),de=p.trim();if(!(!K||!de)){E(!0),L(null);try{const Be=await dm(e,K,de,m,b);N(""),f(""),w(2),k(!0),await ce(),u(Be.collection_uid)}catch(Be){L(Be.message)}finally{E(!1)}}}async function Ct(){const O=te.trim();if(!O||!Y){H(!1);return}try{await pi(e,Y.collection_uid,{name:O}),await ce(),y(K=>K&&{...K,name:O})}catch(K){a(K.message)}finally{H(!1)}}async function yt(O){if(Y)try{await pi(e,Y.collection_uid,{default_visibility_bits:O}),await ce(),y(K=>K&&{...K,default_visibility_bits:O})}catch(K){a(K.message)}}async function Ht(O){if(Y)try{await pi(e,Y.collection_uid,{requires_auth:O}),await ce(),y(K=>K&&{...K,requires_auth:O})}catch(K){a(K.message)}}async function ut(){if(Y&&window.confirm(`Delete collection "${Y.name}"? Entries will not be deleted.`))try{await mm(e,Y.collection_uid),u(null),y(null),await ce()}catch(O){a(O.message)}}async function rt(O){O.preventDefault();const K=q.trim();if(!(!K||!Y)){Ae(!0),D(null);try{await ca(e,Y.collection_uid,K,X),F(""),await Ee(Y.collection_uid)}catch(de){D(de.message)}finally{Ae(!1)}}}async function vt(O){if(Y)try{await pm(e,Y.collection_uid,O),await Ee(Y.collection_uid)}catch(K){x(K.message)}}async function Et(O,K){if(Y)try{await hm(e,Y.collection_uid,O,K),y(de=>de&&{...de,entries:de.entries.map(Be=>Be.entry_uid===O?{...Be,collection_visibility_bits:K}:Be)})}catch(de){x(de.message)}}return e?s.jsxs("div",{className:"collections-view",children:[s.jsx("h2",{className:"collections-heading",children:"Collections"}),r&&s.jsx("div",{className:"muted",children:"Loading…"}),i&&s.jsxs("div",{className:"collections-error",children:[i," ",s.jsx("button",{onClick:()=>a(null),className:"coll-dismiss",children:"×"})]}),s.jsxs("div",{className:"collections-layout",children:[s.jsxs("div",{className:"collections-sidebar",children:[t.map(O=>s.jsxs("button",{className:`coll-sidebar-row${o===O.collection_uid?" is-active":""}`,onClick:()=>u(O.collection_uid),children:[s.jsx("span",{className:"coll-row-name",children:O.name}),s.jsx("span",{className:"coll-row-meta",children:Vm(O.default_visibility_bits)})]},O.collection_uid)),t.length===0&&!r&&s.jsx("div",{className:"muted",style:{padding:"8px 12px"},children:"No collections yet."})]}),Y?s.jsxs("div",{className:"coll-detail",children:[s.jsxs("div",{className:"coll-detail-header",children:[P?s.jsx("input",{ref:Re,className:"coll-rename-input",value:te,onChange:O=>ee(O.target.value),onBlur:Ct,onKeyDown:O=>{O.key==="Enter"&&Ct(),O.key==="Escape"&&H(!1)}}):s.jsxs("h3",{className:`coll-detail-name${ye?"":" coll-detail-name--editable"}`,title:ye?void 0:"Click to rename",onClick:()=>{ye||(ee(Y.name),H(!0))},children:[(c==null?void 0:c.name)??Y.name,!ye&&s.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!ye&&s.jsx("button",{className:"coll-delete-btn",onClick:ut,title:"Delete collection",children:"Delete"})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Entries' default visibility"}),s.jsx("select",{className:"coll-vis-select",value:(c==null?void 0:c.default_visibility_bits)??Y.default_visibility_bits,onChange:O=>yt(Number(O.target.value)),children:Or.map(O=>s.jsx("option",{value:O.value,children:O.label},O.value))})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Collection access"}),s.jsxs("label",{className:"coll-auth-label",children:[s.jsx("input",{type:"checkbox",checked:!!((c==null?void 0:c.requires_auth)??Y.requires_auth),onChange:O=>Ht(O.target.checked)})," Require authentication to view"]})]}),s.jsxs("div",{className:"coll-entries-section",children:[s.jsx("div",{className:"coll-section-heading",children:"Entries"}),g&&s.jsx("div",{className:"muted",children:"Loading…"}),v&&s.jsx("div",{className:"collections-error",children:v}),!g&&c&&(c.entries.length===0?s.jsx("div",{className:"muted",children:"No entries in this collection."}):s.jsx("ul",{className:"coll-entries-list",children:c.entries.map(O=>s.jsxs("li",{className:"coll-entry-row",children:[s.jsxs("div",{className:"coll-entry-info",children:[s.jsx("span",{className:"coll-entry-title",children:O.title||O.entry_uid}),s.jsx("span",{className:"coll-entry-kind muted",children:O.source_kind})]}),s.jsxs("div",{className:"coll-entry-actions",children:[s.jsx("select",{className:"coll-entry-vis-select",value:O.collection_visibility_bits,onChange:K=>Et(O.entry_uid,Number(K.target.value)),children:Or.map(K=>s.jsx("option",{value:K.value,children:K.label},K.value))}),!ye&&s.jsx("button",{className:"coll-entry-remove",onClick:()=>vt(O.entry_uid),title:"Remove from collection",children:"×"})]})]},O.entry_uid))}))]}),!ye&&s.jsxs("form",{className:"coll-add-entry-form",onSubmit:rt,children:[s.jsx("div",{className:"coll-section-heading",children:"Add entry"}),s.jsxs("div",{className:"coll-add-entry-row",children:[s.jsx("input",{className:"coll-add-entry-input",type:"text",value:q,onChange:O=>F(O.target.value),placeholder:"entry_uid",required:!0}),s.jsx("select",{className:"coll-vis-select",value:X,onChange:O=>Z(Number(O.target.value)),children:Or.map(O=>s.jsx("option",{value:O.value,children:O.label},O.value))}),s.jsx("button",{className:"coll-add-btn",type:"submit",disabled:ue,children:ue?"…":"Add"})]}),ge&&s.jsx("div",{className:"collections-error",style:{marginTop:4},children:ge})]})]}):s.jsx("div",{className:"coll-detail coll-detail--empty",children:s.jsx("div",{className:"muted",children:"Select a collection to view details."})})]}),s.jsxs("details",{className:"coll-create-details",children:[s.jsx("summary",{children:"+ Create collection"}),s.jsxs("form",{className:"coll-create-form",onSubmit:Ye,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-name",children:"Name"}),s.jsx("input",{className:"capture-input",id:"coll-name",type:"text",value:S,onChange:O=>{N(O.target.value),p||f(O.target.value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""))},placeholder:"My Collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-slug",children:"Slug"}),s.jsx("input",{className:"capture-input",id:"coll-slug",type:"text",value:p,onChange:O=>f(O.target.value),placeholder:"my-collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-vis",children:"Entries' default visibility"}),s.jsx("select",{className:"capture-input",id:"coll-vis",style:{height:42},value:m,onChange:O=>w(Number(O.target.value)),children:Or.map(O=>s.jsx("option",{value:O.value,children:O.label},O.value))})]}),s.jsx("div",{className:"form-field",children:s.jsxs("label",{className:"form-label",children:[s.jsx("input",{type:"checkbox",checked:b,onChange:O=>k(O.target.checked)})," Require authentication to view"]})}),T&&s.jsx("div",{className:"collections-error",children:T}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:C,children:C?"Creating…":"Create collection"})]})]})]}):s.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const Km=4;function qm({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=d.useContext(As)??{},i=r&&(r.role_bits&Km)!==0,a=["profile","tokens",...i?["instance","cookies","extensions","storage"]:[]],o={profile:"Profile",tokens:"API Tokens",instance:"Instance",cookies:"Cookies",extensions:"Extensions",storage:"Storage"};return s.jsxs("section",{className:"admin-view",children:[s.jsx("h1",{children:"Settings"}),s.jsx("div",{className:"view-tabs",children:a.map(u=>s.jsx("button",{className:`view-tab${e===u?" is-active":""}`,onClick:()=>t(u),children:o[u]},u))}),e==="profile"&&s.jsx(Xm,{currentUser:r,setCurrentUser:l}),e==="tokens"&&s.jsx(Jm,{}),e==="instance"&&i&&s.jsx(Gm,{}),e==="cookies"&&i&&s.jsx(Zm,{}),e==="extensions"&&i&&s.jsx(eg,{}),e==="storage"&&i&&s.jsx(Ym,{archiveId:n})]})}function Xm({currentUser:e,setCurrentUser:t}){const[n,r]=d.useState((e==null?void 0:e.display_name)??""),[l,i]=d.useState(!1),[a,o]=d.useState(null),[u,c]=d.useState(""),[y,g]=d.useState(""),[h,v]=d.useState(""),[x,S]=d.useState(!1),[N,p]=d.useState(null);async function f(w){w.preventDefault(),i(!0),o(null);try{await em(n),t(C=>({...C,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(C){o({ok:!1,text:C.message})}finally{i(!1)}}async function m(w){if(w.preventDefault(),y!==h){p({ok:!1,text:"Passwords do not match."});return}S(!0),p(null);try{await nm(u,y),c(""),g(""),v(""),p({ok:!0,text:"Password changed."})}catch(C){p({ok:!1,text:C.message})}finally{S(!1)}}return s.jsxs("div",{style:{maxWidth:440},children:[s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Name"}),s.jsxs("form",{onSubmit:f,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"display-name",children:"Name shown in the UI"}),s.jsx("input",{className:"field-input",id:"display-name",placeholder:(e==null?void 0:e.username)??"",value:n,onChange:w=>r(w.target.value)})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:l,children:l?"Saving…":"Save"})]})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Preferences"}),s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:(e==null?void 0:e.humanize_slugs)??!1,onChange:async w=>{const C=w.target.checked;try{await tm({humanize_slugs:C}),t(E=>({...E,humanize_slugs:C}))}catch{}}}),s.jsx("span",{className:"form-label",style:{margin:0},children:"Humanize tag display"})]}),s.jsx("p",{className:"muted",style:{fontSize:13,margin:"4px 0 0"},children:'When on, tag paths show as "X / Articles" instead of "x/articles".'})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Change Password"}),s.jsxs("form",{onSubmit:m,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"cur-pw",children:"Current password"}),s.jsx("input",{className:"field-input",id:"cur-pw",type:"password",value:u,onChange:w=>c(w.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"new-pw",children:"New password"}),s.jsx("input",{className:"field-input",id:"new-pw",type:"password",value:y,onChange:w=>g(w.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"confirm-pw",children:"Confirm new password"}),s.jsx("input",{className:"field-input",id:"confirm-pw",type:"password",value:h,onChange:w=>v(w.target.value),required:!0})]}),N&&s.jsx("div",{className:`form-msg form-msg--${N.ok?"ok":"err"}`,children:N.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Changing…":"Change Password"})]})]})]})}function Jm(){const[e,t]=d.useState([]),[n,r]=d.useState(!0),[l,i]=d.useState(null),[a,o]=d.useState(""),[u,c]=d.useState(!1),[y,g]=d.useState(null),h=d.useCallback(async()=>{r(!0),i(null);try{t(await rm())}catch(S){i(S.message)}finally{r(!1)}},[]);d.useEffect(()=>{h()},[h]);async function v(S){if(S.preventDefault(),!!a.trim()){c(!0);try{const N=await lm(a.trim());g(N),o(""),h()}catch(N){i(N.message)}finally{c(!1)}}}async function x(S){try{await sm(S),t(N=>N.filter(p=>p.token_uid!==S))}catch(N){i(N.message)}}return s.jsx("div",{style:{maxWidth:600},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"API Tokens"}),y&&s.jsxs("div",{className:"token-banner",children:[s.jsx("strong",{children:"Token created."})," Copy it now — it won't be shown again.",s.jsx("code",{children:y.raw_token}),s.jsx("button",{className:"token-dismiss",onClick:()=>g(null),children:"Dismiss"})]}),s.jsxs("form",{className:"token-create-row",onSubmit:v,children:[s.jsx("input",{className:"field-input field-input--flex",placeholder:"Token name",value:a,onChange:S=>o(S.target.value),required:!0}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:u,children:u?"Creating…":"Create token"})]}),l&&s.jsx("div",{className:"form-msg form-msg--err",children:l}),n?s.jsx("div",{className:"muted",children:"Loading…"}):s.jsxs("div",{children:[e.length===0&&s.jsx("div",{className:"muted",children:"No tokens yet."}),e.map(S=>s.jsxs("div",{className:"token-row",children:[s.jsxs("div",{className:"token-row-info",children:[s.jsx("strong",{children:S.name}),s.jsxs("div",{className:"muted",children:["Created ",S.created_at.slice(0,10),S.last_used_at&&` · Last used ${S.last_used_at.slice(0,10)}`]})]}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"4px 10px"},onClick:()=>x(S.token_uid),children:"Revoke"})]},S.token_uid))]})]})})}function Gm(){const[e,t]=d.useState(null),[n,r]=d.useState(!0),[l,i]=d.useState(null),[a,o]=d.useState(!1),[u,c]=d.useState(null);d.useEffect(()=>{(async()=>{try{t(await so())}catch(g){i(g.message)}finally{r(!1)}})()},[]);async function y(g){g.preventDefault(),o(!0),c(null);try{await ql(e),c({ok:!0,text:"Saved."})}catch(h){c({ok:!1,text:h.message})}finally{o(!1)}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):e?s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Instance Settings"}),s.jsxs("form",{onSubmit:y,children:[[["public_index_enabled","Public index (unauthenticated browsing)"],["public_entry_content_enabled","Public entry content"],["open_registration_enabled","Open registration"]].map(([g,h])=>s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:!!e[g],onChange:v=>t(x=>({...x,[g]:v.target.checked}))}),h]},g)),s.jsxs("div",{className:"form-field",style:{marginTop:4},children:[s.jsx("label",{className:"form-label",children:"Default entry visibility"}),s.jsxs("select",{className:"field-input",value:e.default_entry_visibility,onChange:g=>t(h=>({...h,default_entry_visibility:Number(g.target.value)})),children:[s.jsx("option",{value:0,children:"Private"}),s.jsx("option",{value:2,children:"Unlisted"}),s.jsx("option",{value:3,children:"Public"})]})]}),u&&s.jsx("div",{className:`form-msg form-msg--${u.ok?"ok":"err"}`,children:u.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:a,children:a?"Saving…":"Save Settings"})]})]})}):null}function mi(e){if(e===0)return"0 B";const t=["B","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(1024));return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function Ym({archiveId:e}){const[t,n]=d.useState("idle"),[r,l]=d.useState(null),[i,a]=d.useState(null),[o,u]=d.useState(null);function c(){n("idle"),l(null),a(null),u(null)}async function y(){n("scanning"),u(null),l(null);try{const v=await gm(e);l(v),n("scanned")}catch(v){u(v.message),n("error")}}async function g(){n("deleting"),u(null);try{const v=await ym(e);a(v),n("done")}catch(v){u(v.message),n("error")}}const h=r&&r.deletable_files===0&&r.orphaned_blob_rows===0;return s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Orphan Cleanup"}),s.jsxs("p",{className:"muted",style:{marginBottom:16},children:["Scan for blob files and database records that are no longer referenced by any archive entry and safely delete them."," ",s.jsx("strong",{children:"Cleanup is blocked while captures are running."})]}),!e&&s.jsx("div",{className:"muted",children:"No archive selected."}),e&&t==="idle"&&s.jsx("button",{className:"btn-ghost",onClick:y,children:"Scan for orphaned blobs"}),t==="scanning"&&s.jsx("div",{className:"muted",children:"Scanning…"}),t==="scanned"&&r&&h&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"form-msg form-msg--ok",children:"Archive is clean — nothing to remove."}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Done"})]}),t==="scanned"&&r&&!h&&s.jsxs("div",{children:[s.jsxs("div",{style:{marginBottom:14,lineHeight:1.6},children:["Found ",s.jsx("strong",{children:r.deletable_files})," unreferenced file",r.deletable_files!==1?"s":""," ","and ",s.jsx("strong",{children:r.orphaned_blob_rows})," orphaned DB record",r.orphaned_blob_rows!==1?"s":""," ","— ",s.jsx("strong",{children:mi(r.total_bytes)})," recoverable."]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsxs("button",{className:"btn-danger",onClick:g,children:["Delete (",mi(r.total_bytes),")"]}),s.jsx("button",{className:"btn-ghost",onClick:c,children:"Cancel"})]})]}),t==="deleting"&&s.jsx("div",{className:"muted",children:"Deleting…"}),t==="done"&&i&&s.jsxs("div",{children:[s.jsxs("div",{className:"form-msg form-msg--ok",children:["Freed ",s.jsx("strong",{children:mi(i.freed_bytes)})," ","— removed ",i.deleted_files," file",i.deleted_files!==1?"s":""," ","and ",i.deleted_blob_rows," DB record",i.deleted_blob_rows!==1?"s":"","."]}),i.errors&&i.errors.length>0&&s.jsxs("div",{className:"form-msg form-msg--err",style:{marginTop:6},children:[i.errors.length," file",i.errors.length!==1?"s":""," could not be deleted."]}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Scan again"})]}),t==="error"&&s.jsxs("div",{children:[s.jsx("div",{className:"form-msg form-msg--err",children:o}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Try again"})]})]})})}function Zm(){const[e,t]=d.useState(null),[n,r]=d.useState(!0),[l,i]=d.useState(null),[a,o]=d.useState("global"),[u,c]=d.useState(""),[y,g]=d.useState("{}"),[h,v]=d.useState(null),[x,S]=d.useState(!1),[N,p]=d.useState({});d.useEffect(()=>{f()},[]);async function f(){r(!0),i(null);try{t(await wm())}catch(k){i(k.message)}finally{r(!1)}}async function m(k){k.preventDefault();try{JSON.parse(y)}catch{v({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}S(!0),v(null);try{await km(a==="global"?null:u.trim(),a,y),c(""),g("{}"),o("global"),v({ok:!0,text:"Rule added."}),await f()}catch(T){v({ok:!1,text:T.message})}finally{S(!1)}}async function w(k){try{await Sm(k),await f()}catch(T){i(T.message)}}function C(k){p(T=>({...T,[k.rule_uid]:{cookiesInput:k.cookies_json,saving:!1,msg:null}}))}function E(k){p(T=>{const L={...T};return delete L[k],L})}async function b(k){const T=N[k.rule_uid];try{JSON.parse(T.cookiesInput)}catch{p(L=>({...L,[k.rule_uid]:{...L[k.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}p(L=>({...L,[k.rule_uid]:{...L[k.rule_uid],saving:!0,msg:null}}));try{await jm(k.rule_uid,{cookies_json:T.cookiesInput}),E(k.rule_uid),await f()}catch(L){p(q=>({...q,[k.rule_uid]:{...q[k.rule_uid],saving:!1,msg:{ok:!1,text:L.message}}}))}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):s.jsx("div",{style:{maxWidth:560},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Cookie Rules"}),s.jsx("p",{className:"muted",style:{marginBottom:12},children:"Cookies are injected into every capture network request (yt-dlp, HTTP downloads, web-page snapshots). Global rules apply to all URLs; wildcard and regex rules apply only to matching URLs."}),e&&e.length>0?s.jsxs("table",{className:"data-table",style:{width:"100%",marginBottom:16},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Pattern"}),s.jsx("th",{children:"Cookies"}),s.jsx("th",{style:{width:100},children:"Actions"})]})}),s.jsx("tbody",{children:e.map(k=>{const T=N[k.rule_uid],L=k.url_pattern?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"muted",children:[k.pattern_kind,":"]})," ",s.jsx("code",{children:k.url_pattern})]}):s.jsx("span",{className:"muted",children:"global (all URLs)"});return s.jsxs("tr",{children:[s.jsx("td",{children:L}),s.jsx("td",{children:T?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:T.cookiesInput,onChange:q=>p(F=>({...F,[k.rule_uid]:{...F[k.rule_uid],cookiesInput:q.target.value}}))}),T.msg&&s.jsx("div",{className:`form-msg form-msg--${T.msg.ok?"ok":"err"}`,children:T.msg.text}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{className:"btn-primary",style:{fontSize:12,padding:"2px 8px"},disabled:T.saving,onClick:()=>b(k),children:T.saving?"Saving…":"Save"}),s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>E(k.rule_uid),children:"Cancel"})]})]}):s.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:k.cookies_json})}),s.jsx("td",{children:!T&&s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>C(k),children:"Edit"}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>w(k.rule_uid),children:"Del"})]})})]},k.rule_uid)})})]}):s.jsx("p",{className:"muted",style:{marginBottom:16},children:"No cookie rules defined."}),s.jsx("h3",{style:{marginBottom:8},children:"Add Rule"}),s.jsxs("form",{onSubmit:m,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Pattern type"}),s.jsxs("select",{className:"field-input",value:a,onChange:k=>o(k.target.value),children:[s.jsx("option",{value:"global",children:"Global (all URLs)"}),s.jsx("option",{value:"wildcard",children:"Wildcard (e.g. *.youtube.com)"}),s.jsx("option",{value:"regex",children:"Regex (matched against full URL)"})]})]}),a!=="global"&&s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:a==="wildcard"?"URL/hostname pattern":"Regex pattern"}),s.jsx("input",{className:"field-input",type:"text",value:u,onChange:k=>c(k.target.value),placeholder:a==="wildcard"?"*.youtube.com or https://example.com/*":".*\\.youtube\\.com.*",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Cookies (JSON object)"}),s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:13,minHeight:70},value:y,onChange:k=>g(k.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),h&&s.jsx("div",{className:`form-msg form-msg--${h.ok?"ok":"err"}`,children:h.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Adding…":"Add Rule"})]})]})})}function eg(){const[e,t]=d.useState(null),[n,r]=d.useState(!0),[l,i]=d.useState(!1),[a,o]=d.useState(null);d.useEffect(()=>{(async()=>{try{t(await so())}catch(N){o({ok:!1,text:N.message})}finally{r(!1)}})()},[]);async function u(N){i(!0),o(null);try{await ql({ublock_enabled:N}),t(p=>({...p,ublock_enabled:N})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function c(N){i(!0),o(null);try{await ql({cookie_ext_enabled:N}),t(p=>({...p,cookie_ext_enabled:N})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function y(N){i(!0),o(null);try{await ql({modal_closer_enabled:N}),t(p=>({...p,modal_closer_enabled:N})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}if(n)return s.jsx("div",{className:"muted",children:"Loading\\u2026"});const g=(e==null?void 0:e.ublock_ext_available)??!1,h=(e==null?void 0:e.ublock_enabled)??!0,v=(e==null?void 0:e.cookie_ext_available)??!1,x=(e==null?void 0:e.cookie_ext_enabled)??!0,S=(e==null?void 0:e.modal_closer_enabled)??!0;return s.jsx("div",{children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Extensions"}),s.jsx("p",{className:"form-hint",style:{marginBottom:20},children:"Extensions run inside the browser during WebPage captures and can block ads, accept cookie banners, and more. Changes take effect on the next capture."}),s.jsxs("div",{className:"ext-grid",children:[s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"ext-card-desc",children:"Blocks ads, trackers, and other page clutter during archiving via Chrome’s declarativeNetRequest API (Manifest V3)."}),!g&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_UBLOCK_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":h,className:`ext-toggle${h?" ext-toggle--on":""}`,onClick:()=>u(!h),disabled:l,"aria-label":"Toggle uBlock Origin Lite",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"I Still Don’t Care About Cookies"}),s.jsx("span",{className:"ext-card-desc",children:"Dismiss cookie consent banners during archiving."}),!v&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":x,className:`ext-toggle${x?" ext-toggle--on":""}`,onClick:()=>c(!x),disabled:l,"aria-label":"Toggle I Still Don't Care About Cookies",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"Modal & Dialog Closer"}),s.jsx("span",{className:"ext-card-desc",children:"Auto-dismiss cookie banners, consent overlays, and other modal dialogs before a WebPage capture is taken. Implemented as an injected browser script; no external extension required."})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":S,className:`ext-toggle${S?" ext-toggle--on":""}`,onClick:()=>y(!S),disabled:l,"aria-label":"Toggle Modal and Dialog Closer",children:s.jsx("span",{className:"ext-toggle-knob"})})]})})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text})]})})}const Pu={0:"Private",1:"Public",2:"Users only",3:"Public"},tg=()=>s.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M7 17 17 7M9 7h8v8"})});function ng({archiveId:e,selectedEntry:t,selectedUids:n,selectedEntries:r,detail:l,onTagFilterSet:i,tagNodes:a,onTagsRefresh:o,onEntryTitleChange:u,onEntryDeleted:c,onBulkDeleted:y,humanizeTags:g,onDetailRefresh:h,onOpenPreview:v,onPlay:x,isPublicSession:S}){var gl;const[N,p]=d.useState([]),[f,m]=d.useState(""),[w,C]=d.useState([]),[E,b]=d.useState(""),k=d.useRef(0),T=d.useRef(!1),[L,q]=d.useState(!1),[F,X]=d.useState(""),[Z,ue]=d.useState("idle"),[Ae,ge]=d.useState(""),D=d.useRef(null),[P,H]=d.useState(!1);d.useEffect(()=>{H(!1)},[(gl=l==null?void 0:l.summary)==null?void 0:gl.entry_uid]);const te=(n==null?void 0:n.size)>=2,[ee,Re]=d.useState(""),[Y,ye]=d.useState("idle"),[ce,Ee]=d.useState(""),[Ye,Ct]=d.useState([]),[yt,Ht]=d.useState(""),[ut,rt]=d.useState("idle"),[vt,Et]=d.useState(""),[O,K]=d.useState("idle"),[de,Be]=d.useState(""),[Dt,ze]=d.useState("idle"),[Fn,Nn]=d.useState("");d.useEffect(()=>{const z=++k.current;if(D.current&&(clearInterval(D.current),D.current=null),ue("idle"),ge(""),!t||!e){p([]),C([]);return}if(S){p([]),C([]);return}q(!1),X(""),T.current=!1,p([]),Promise.all([Il(e,t.entry_uid),Cu(e,t.entry_uid)]).then(([re,be])=>{z===k.current&&(p(re),C(be))}).catch(()=>{})},[t,e,S]),d.useEffect(()=>()=>{clearInterval(D.current)},[]),d.useEffect(()=>{if(!e){Ct([]);return}io(e).then(Ct).catch(()=>Ct([]))},[e]),d.useEffect(()=>{Re(""),ye("idle"),Ee(""),Ht(""),rt("idle"),Et(""),K("idle"),Be(""),ze("idle"),Nn("")},[n]);async function tn(){const z=n.size;if(!window.confirm(`Delete ${z} entr${z===1?"y":"ies"}? This cannot be undone.`))return;K("running");const re=new Set;for(const be of n)try{await _u(e,be),re.add(be)}catch{}K("idle"),y==null||y(re)}async function Ve(){const z=ee.trim();if(z){ye("running"),Ee("");try{for(const re of n)await Nu(e,re,z);Re(""),ye("done"),o==null||o(),setTimeout(()=>ye("idle"),1800)}catch(re){Ee(re.message),ye("error")}}}async function wr(){if(!yt)return;rt("running"),Et("");const z=[],re=Ye.find(be=>be.collection_uid===yt);for(const be of n)try{await ca(e,yt,be,(re==null?void 0:re.default_visibility_bits)??2)}catch{z.push(be)}z.length>0?(Et(`Failed for ${z.length} entr${z.length===1?"y":"ies"}.`),rt("error")):(rt("done"),setTimeout(()=>rt("idle"),1800))}async function Bn(){if(!de||!t)return;ze("running"),Nn("");const z=Ye.find(re=>re.collection_uid===de);try{await ca(e,de,t.entry_uid,(z==null?void 0:z.default_visibility_bits)??2),ze("done"),Be("");const re=await Cu(e,t.entry_uid);C(re),setTimeout(()=>ze("idle"),1800)}catch(re){Nn(re.message),ze("error")}}async function j(){const z=F.trim()||null;try{await Fh(e,t.entry_uid,z),u==null||u(t.entry_uid,z)}catch{}finally{q(!1)}}async function B(){const z=f.trim();if(!(!z||!t))try{await Nu(e,t.entry_uid,z),m(""),b("");const re=await Il(e,t.entry_uid);p(re),o()}catch(re){b(re.message)}}async function M(z){try{await Bh(e,t.entry_uid,z);const re=await Il(e,t.entry_uid);p(re),o()}catch{}}async function A(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await _u(e,t.entry_uid),c==null||c(t.entry_uid)}catch{}}async function W(){if(!t||!e||Z==="running")return;const z=k.current,re=t.entry_uid;ue("running"),ge("");try{const{job_uid:be}=await vm(e,re);if(k.current!==z)return;D.current=setInterval(async()=>{try{const $t=await Xd(e,be);if($t.status==="completed"){if(clearInterval(D.current),D.current=null,k.current!==z)return;ue("done");const Wt=await Il(e,re);if(k.current!==z)return;p(Wt),h==null||h()}else if($t.status==="failed"){if(clearInterval(D.current),D.current=null,k.current!==z)return;ue("error"),ge($t.error_text||"Re-archive failed.")}}catch{if(clearInterval(D.current),D.current=null,k.current!==z)return;ue("error"),ge("Network error while polling.")}},500)}catch(be){if(k.current!==z)return;ue("error"),ge(be.message||"Failed to start re-archive.")}}const V=l?[["Added",ao(l.summary.archived_at)],["Source",l.summary.source_kind],["Type",l.summary.entity_kind],["Visibility",Pu[l.summary.visibility]??l.summary.visibility],["Root",l.structured_root_relpath]]:[],pe=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),ae=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv","pdf","html","htm","jpg","jpeg","png","gif","webp","avif","svg","bmp"]),xe=l?l.artifacts.findIndex(z=>z.artifact_role==="primary_media"):-1,ie=xe>=0?l.artifacts[xe]:null,Qe=ie?ie.relpath.split(".").pop().toLowerCase():"",we=ie&&pe.has(Qe),Un=xe>=0&&t?`/api/archives/${e}/entries/${t.entry_uid}/artifacts/${xe}`:null,xt=l&&!we&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread"||ie&&ae.has(Qe));return s.jsxs("aside",{className:"context-rail",children:[s.jsx("div",{className:"rail-eyebrow",children:"Context"}),te?S?s.jsxs("p",{className:"bulk-count",children:[s.jsx("span",{className:"bulk-count-num",children:n.size})," entries selected"]}):s.jsxs("div",{className:"bulk-panel",children:[s.jsxs("p",{className:"bulk-count",children:[s.jsx("span",{className:"bulk-count-num",children:n.size})," entries selected"]}),s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Assign tag"}),ce&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:ce}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:ee,onChange:z=>Re(z.target.value),onKeyDown:z=>{z.key==="Enter"&&Ve()}}),s.jsx("button",{className:"tag-add-btn",onClick:Ve,disabled:Y==="running"||!ee.trim(),children:Y==="running"?"…":Y==="done"?"✓":"Add"})]})]}),Ye.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Add to collection"}),s.jsxs("div",{className:"bulk-coll-row",children:[s.jsxs("select",{className:"bulk-coll-select",value:yt,onChange:z=>Ht(z.target.value),children:[s.jsx("option",{value:"",children:"Pick a collection…"}),Ye.filter(z=>z.slug!=="_default_").map(z=>s.jsx("option",{value:z.collection_uid,children:z.name},z.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:wr,disabled:!yt||ut==="running",children:ut==="running"?"…":ut==="done"?"✓":ut==="error"?"!":"Add"})]}),vt&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"6px 0 0"},children:vt})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:tn,disabled:O==="running",children:O==="running"?"Deleting…":`Delete ${n.size} entr${n.size===1?"y":"ies"}`})})]}):t?l?s.jsxs(s.Fragment,{children:[S?s.jsx("h2",{className:"rail-title",children:dt(l.summary.title)||dt(l.summary.entry_uid)}):L?s.jsx("input",{className:"rail-title-input",autoFocus:!0,value:F,onChange:z=>X(z.target.value),onKeyDown:z=>{z.key==="Enter"&&z.currentTarget.blur(),z.key==="Escape"&&(T.current=!0,z.currentTarget.blur())},onBlur:()=>{T.current?q(!1):j(),T.current=!1}}):s.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{X(l.summary.title??""),q(!0)},children:[dt(l.summary.title)||dt(l.summary.entry_uid),s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),l.summary.original_url&&s.jsxs("a",{className:"url-tile",href:l.summary.original_url,target:"_blank",rel:"noopener noreferrer",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:Os(l.summary.source_kind)}}),s.jsx("span",{className:"u-text",children:l.summary.original_url}),s.jsx("span",{className:"ext",children:s.jsx(tg,{})})]}),we&&x&&s.jsx("button",{className:"rail-preview-btn",onClick:()=>x(Un,t),children:"▶ Play"}),xt&&v&&s.jsx("button",{className:"rail-preview-btn",onClick:v,children:"Preview"}),s.jsx("div",{className:"meta-list",children:V.filter(([,z])=>z!=null&&z!=="").map(([z,re])=>s.jsxs("div",{className:"meta-item",children:[s.jsx("span",{className:"meta-k",children:z}),s.jsx("span",{className:`meta-v${z==="Root"?" mono":""}`,children:dt(re)})]},z))}),l.artifacts.length>0&&(()=>{const z=l.artifacts.map((Ie,jr)=>({...Ie,_idx:jr})),re=z.filter(Ie=>Ie.artifact_role==="font"),be=z.filter(Ie=>Ie.artifact_role!=="font"),$t=re.reduce((Ie,jr)=>Ie+(jr.byte_size||0),0),Wt=l.summary.entry_uid,kr=Ie=>s.jsx("li",{children:s.jsxs("a",{href:`/api/archives/${e}/entries/${Wt}/artifacts/${Ie._idx}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[s.jsx("span",{className:"artifact-name",children:Ie.artifact_role==="font"?Ie.relpath.split("/").pop():Ie.artifact_role.replace(/_/g," ")}),s.jsx("span",{className:"artifact-size",children:Ie.byte_size!=null?cl(Ie.byte_size):"—"})]})},Ie._idx);return s.jsxs("div",{className:"rail-section",children:[s.jsxs("div",{className:"rail-section-heading",children:["Artifacts ",s.jsx("span",{className:"num",children:l.artifacts.length})]}),s.jsxs("ul",{className:"artifact-list",children:[be.map(kr),re.length>0&&s.jsxs("li",{className:"artifact-group",children:[s.jsxs("button",{type:"button",className:"artifact-group-header artifact-link","aria-expanded":P,onClick:()=>H(Ie=>!Ie),children:[s.jsxs("span",{className:"artifact-name",children:[s.jsx("span",{"aria-hidden":"true",className:`artifact-group-chevron${P?" open":""}`,children:"›"}),` fonts (${re.length})`]}),s.jsx("span",{className:"artifact-size",children:cl($t)})]}),P&&s.jsx("ul",{className:"artifact-list artifact-group-body",children:re.map(kr)})]})]})]})})()]}):s.jsx("p",{className:"tags-empty",children:"Loading\\u2026"}):s.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&!te&&!S&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Tags"}),N.length===0?s.jsx("p",{className:"tags-empty",children:"No tags yet."}):s.jsx("div",{className:"tags-wrap",children:N.map(z=>s.jsxs("span",{className:"tag-pill",title:z.full_path,children:[g?Gd(z.full_path):z.full_path,s.jsx("button",{className:"remove",title:`Remove tag ${z.full_path}`,onClick:()=>M(z.tag_uid),children:"×"})]},z.tag_uid))}),E&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:E}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:f,onChange:z=>m(z.target.value),onKeyDown:z=>{z.key==="Enter"&&B()}}),s.jsx("button",{className:"tag-add-btn",onClick:B,children:"Add"})]})]}),(w.length>0||Ye.filter(z=>z.slug!=="_default_").length>0)&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Collections"}),w.map(z=>s.jsxs("div",{className:"coll-row",children:[s.jsx("span",{className:"coll-name",children:z.name}),s.jsx("span",{className:"vis-badge",children:Pu[z.visibility_bits]??`bits:${z.visibility_bits}`})]},z.collection_uid)),Ye.filter(z=>z.slug!=="_default_").length>0&&s.jsxs("div",{className:"bulk-coll-row",style:{marginTop:8},children:[s.jsxs("select",{className:"bulk-coll-select",value:de,onChange:z=>Be(z.target.value),children:[s.jsx("option",{value:"",children:"Add to collection…"}),Ye.filter(z=>z.slug!=="_default_").map(z=>s.jsx("option",{value:z.collection_uid,children:z.name},z.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:Bn,disabled:!de||Dt==="running",children:Dt==="running"?"…":Dt==="done"?"✓":Dt==="error"?"!":"Add"})]}),Fn&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"4px 0 0"},children:Fn})]}),l&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread")&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Actions"}),s.jsx("button",{className:"rail-rearchive-btn",onClick:W,disabled:Z==="running",children:Z==="running"?"Re-archiving…":"Re-archive"}),Z==="done"&&s.jsx("p",{className:"form-msg form-msg--ok",style:{marginTop:"6px"},children:"Re-archived successfully."}),Z==="error"&&s.jsx("p",{className:"form-msg form-msg--err",style:{marginTop:"6px"},children:Ae})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:A,children:"Delete entry"})})]})]})}const rg=/\/api\/archives\/([^/]+)\/entries\/([^/]+)\/artifacts\/(\d+)/;function lg(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M5 17H3a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h18a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-2"}),s.jsx("polygon",{points:"12 15 17 21 7 21 12 15"})]})}function sg({src:e,contentType:t="video/mp4"}){const n=d.useRef(null),[r,l]=d.useState(null),[i,a]=d.useState(!1),[o,u]=d.useState(!1);d.useEffect(()=>{if(!e){l(null);return}const g=e.match(rg);if(!g){l(e);return}let h=!1;return l(null),xm(g[1],g[2],parseInt(g[3],10)).then(({url:v})=>{h||l(v)}).catch(()=>{h||l(e)}),()=>{h=!0}},[e]),d.useEffect(()=>{n.current&&n.current.load()},[r]),d.useEffect(()=>{u(typeof HTMLVideoElement<"u"&&"webkitShowPlaybackTargetPicker"in HTMLVideoElement.prototype)},[]),d.useEffect(()=>{var h;const g=v=>{if(v)try{cast.framework.CastContext.getInstance().setOptions({receiverApplicationId:chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,autoJoinPolicy:chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}),a(!0)}catch{}};if((h=window.cast)!=null&&h.framework)g(!0);else if(window.__onGCastApiAvailable=g,!document.querySelector('script[src*="cast_sender"]')){const v=document.createElement("script");v.src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1",document.head.appendChild(v)}},[]),d.useEffect(()=>{if(!i||!r)return;const g=cast.framework.CastContext.getInstance(),{CastContextEventType:h,SessionState:v}=cast.framework,x=N=>{if(!N)return;const p=new chrome.cast.media.MediaInfo(window.location.origin+r,t);N.loadMedia(new chrome.cast.media.LoadRequest(p)).catch(()=>{})};x(g.getCurrentSession());const S=N=>{(N.sessionState===v.SESSION_STARTED||N.sessionState===v.SESSION_RESUMED)&&x(g.getCurrentSession())};return g.addEventListener(h.SESSION_STATE_CHANGED,S),()=>g.removeEventListener(h.SESSION_STATE_CHANGED,S)},[i,r,t]);const c=()=>{var g,h;(h=(g=n.current)==null?void 0:g.webkitShowPlaybackTargetPicker)==null||h.call(g)},y=i||o;return s.jsx("div",{className:"preview-video-wrap",style:{position:"relative"},children:e?s.jsxs(s.Fragment,{children:[r?s.jsxs("video",{ref:n,controls:!0,autoPlay:!1,playsInline:!0,"x-webkit-airplay":"allow",style:{width:"100%",maxHeight:"100%",display:"block"},children:[s.jsx("source",{src:r}),"Your browser does not support the video element."]}):s.jsx("div",{className:"video-tv-loading","aria-label":"Loading video…"}),y&&r&&s.jsxs("div",{className:"video-tv-controls",children:[o&&s.jsx("button",{className:"video-tv-btn",title:"AirPlay to device","aria-label":"AirPlay to device",onClick:c,children:s.jsx(lg,{})}),i&&s.jsx("google-cast-launcher",{className:"video-tv-btn",title:"Cast to TV"})]})]}):s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No video available"})})}function Lu({src:e,type:t,title:n,originalUrl:r}){const l=r||e,i=n||null;return s.jsxs("div",{className:"preview-iframe-wrap",style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:[s.jsxs("div",{className:"preview-iframe-toolbar",style:{display:"flex",flexDirection:"column",gap:"2px",padding:"6px 12px",borderBottom:"1px solid var(--line-soft)",background:"var(--paper-2)",flexShrink:0},children:[i&&s.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600,color:"var(--ink)",fontFamily:"var(--sans)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",color:"var(--muted)",fontFamily:"var(--sans)"},children:l}),s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{fontSize:"0.78rem",color:"var(--accent)",textDecoration:"none",whiteSpace:"nowrap",fontFamily:"var(--sans)",flexShrink:0},children:t==="pdf"?"Open PDF ↗":"Open in new tab ↗"})]})]}),s.jsx("iframe",{src:e,sandbox:"allow-same-origin allow-popups",allow:"autoplay 'none'",referrerPolicy:"no-referrer",style:{flex:1,border:"none",width:"100%",minHeight:0},title:i||(t==="pdf"?"PDF preview":"Page preview")})]})}function ig({src:e,alt:t}){return s.jsx("div",{className:"preview-image-wrap",style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",background:"var(--paper-2)",overflow:"hidden"},children:s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{display:"contents"},children:s.jsx("img",{src:e,alt:t||"",style:{objectFit:"contain",maxHeight:"100%",maxWidth:"100%",display:"block",cursor:"pointer"}})})})}function tf(e){return e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(new Date(e*1e3)):""}function Ru(e){return!e||!e.includes("&")?e:e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}const G={card:{background:"var(--paper)",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},threadOuter:{border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},tweetRow:{display:"flex",gap:"10px",padding:"10px 12px"},tweetRowThread:{display:"flex",gap:"10px",padding:"10px 12px 0"},leftCol:{display:"flex",flexDirection:"column",alignItems:"center",flexShrink:0,width:"36px"},rightCol:{flex:1,minWidth:0,paddingBottom:"8px"},avatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},avatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},threadLine:{flex:1,width:"2px",background:"var(--line-soft, var(--line))",margin:"4px 0",minHeight:"12px",borderRadius:"1px"},authorRow:{display:"flex",alignItems:"baseline",gap:"4px",flexWrap:"wrap",marginBottom:"4px",lineHeight:"1.3"},authorName:{fontWeight:"700",fontSize:"14px",color:"var(--ink)"},authorHandle:{fontSize:"13px",color:"var(--muted)"},datePart:{fontSize:"13px",color:"var(--muted)"},tweetText:{fontSize:"14px",lineHeight:"1.5",color:"var(--ink)",whiteSpace:"pre-line",marginBottom:"8px",wordBreak:"break-word"},stats:{display:"flex",gap:"12px",fontSize:"13px",color:"var(--muted)"},link:{color:"var(--accent)",textDecoration:"none"},loading:{padding:"24px 16px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},error:{padding:"24px 16px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},mediaGrid:{marginBottom:"8px",borderRadius:"10px",overflow:"hidden",border:"1px solid var(--line)"},mediaImg:{display:"block",width:"100%",objectFit:"cover",maxHeight:"260px"},mediaVideo:{display:"block",width:"100%",maxHeight:"260px",background:"#000"},article:{maxWidth:"560px",margin:"0 auto",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"280px"},aMeta:{padding:"10px 14px 0"},aTweetTitle:{fontSize:"20px",fontWeight:"800",letterSpacing:"-0.3px",color:"var(--ink)",lineHeight:"1.3",marginBottom:"8px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},aAvatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},aAuthorName:{fontSize:"14px",fontWeight:"700",color:"var(--ink)",lineHeight:"1.3"},aAuthorSub:{fontSize:"13px",color:"var(--muted)",lineHeight:"1.3"},aDivider:{border:"none",borderTop:"1px solid var(--line)",margin:"0"},aBody:{padding:"4px 14px 16px"},bH1:{fontSize:"22px",fontWeight:"800",letterSpacing:"-0.4px",color:"var(--ink)",lineHeight:"1.25",margin:"16px 0 6px"},bH2:{fontSize:"18px",fontWeight:"700",letterSpacing:"-0.2px",color:"var(--ink)",lineHeight:"1.3",margin:"14px 0 4px"},bP:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.65",marginBottom:"12px",marginTop:"0"},bSpacer:{height:"4px",display:"block"},bQuote:{borderLeft:"3px solid var(--line)",padding:"2px 12px",margin:"12px 0",color:"var(--muted)",fontSize:"15px",lineHeight:"1.6"},bHr:{border:"none",borderTop:"1px solid var(--line)",margin:"14px 0"},bImg:{width:"100%",display:"block",borderRadius:"8px",margin:"12px 0"},bUl:{margin:"8px 0 12px",paddingLeft:"24px"},bOl:{margin:"8px 0 12px",paddingLeft:"24px"},bLi:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.6",marginBottom:"4px"},bTweet:{display:"flex",alignItems:"center",gap:"10px",border:"1px solid var(--line)",borderRadius:"10px",padding:"10px 14px",margin:"12px 0",color:"var(--muted)",fontSize:"14px",textDecoration:"none"},bMdPre:{borderRadius:"8px",margin:"10px 0",overflow:"auto",background:"var(--paper-3, var(--field))",padding:"12px 14px"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"12px",lineHeight:"1.6",color:"var(--ink)",background:"transparent",display:"block"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:"var(--paper-3, var(--field))",padding:"1px 5px",borderRadius:"4px",color:"var(--ink)"},qtBadge:{fontSize:"11px",color:"var(--muted)",display:"inline-flex",alignItems:"center",gap:"2px",marginLeft:"4px",letterSpacing:"0.03em",flexShrink:0},lightboxBackdrop:{position:"fixed",inset:0,zIndex:500,background:"rgba(0,0,0,0.92)",display:"flex",alignItems:"center",justifyContent:"center",padding:"20px"},lightboxContent:{display:"flex",flexDirection:"column",alignItems:"center",gap:"10px",maxWidth:"90vw",maxHeight:"90vh"},lightboxToolbar:{display:"flex",alignItems:"center",gap:"10px",alignSelf:"flex-end"},lightboxImg:{maxWidth:"88vw",maxHeight:"80vh",objectFit:"contain",borderRadius:"6px",display:"block"},lightboxNav:{display:"flex",gap:"12px",alignItems:"center"},lightboxNavBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"20px",cursor:"pointer",borderRadius:"50%",width:"36px",height:"36px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"16px",cursor:"pointer",borderRadius:"50%",width:"30px",height:"30px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxLink:{color:"rgba(255,255,255,0.7)",textDecoration:"none",fontSize:"14px"},lightboxCounter:{color:"rgba(255,255,255,0.6)",fontSize:"13px"}},De={bg:"#000000",border:"#2f3336",text:"#e7e9ea",dim:"#71767b",accent:"#1d9bf0",codeBg:"#16181c"},gi={article:{background:De.bg,color:De.text,minHeight:"100%",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif'},articleInner:{maxWidth:"598px",margin:"0 auto",paddingBottom:"80px"},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"420px"},aMeta:{padding:"20px 16px 0"},aTweetTitle:{fontSize:"34px",fontWeight:"800",letterSpacing:"-0.5px",color:De.text,lineHeight:"44px",marginBottom:"16px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"16px"},aAvatar:{width:"40px",height:"40px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"40px",height:"40px",borderRadius:"50%",background:De.border,flexShrink:0},aAuthorName:{fontSize:"15px",fontWeight:"700",color:De.text,lineHeight:"1.3"},aAuthorSub:{fontSize:"15px",color:De.dim,lineHeight:"1.3"},aDivider:{border:"none",borderTop:`1px solid ${De.border}`,margin:"0"},aBody:{padding:"4px 16px 0"},bH1:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:De.text,lineHeight:"36px",margin:"24px 0 10px"},bH2:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:De.text,lineHeight:"36px",margin:"24px 0 10px"},bP:{fontSize:"17px",color:De.text,lineHeight:"1.5",marginBottom:"16px",marginTop:"0"},bSpacer:{height:"6px",display:"block"},bQuote:{borderLeft:`3px solid ${De.border}`,padding:"2px 14px",margin:"14px 0",color:De.dim,fontSize:"17px",lineHeight:"1.5"},bHr:{border:"none",borderTop:`1px solid ${De.border}`,margin:"28px 0"},bImg:{width:"100%",display:"block",borderRadius:"12px",margin:"16px 0"},bUl:{margin:"10px 0 16px",paddingLeft:"28px"},bOl:{margin:"10px 0 16px",paddingLeft:"28px"},bLi:{fontSize:"17px",color:De.text,lineHeight:"1.5",marginBottom:"6px"},bTweet:{display:"flex",alignItems:"center",gap:"12px",border:`1px solid ${De.border}`,borderRadius:"12px",padding:"14px 16px",margin:"14px 0",color:De.dim,fontSize:"15px",textDecoration:"none"},bMdPre:{borderRadius:"12px",margin:"12px 0",overflow:"auto",background:"#1e2029"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"13px",lineHeight:"1.65",padding:"18px 20px",display:"block",color:De.text,background:"transparent"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:De.codeBg,padding:"2px 6px",borderRadius:"4px",color:"#e6edf3"},link:{color:De.accent,textDecoration:"none"}};function ag(e,t,n){const r={};return n&&n.forEach((l,i)=>{l.relpath&&(r[l.relpath]=`/api/archives/${e}/entries/${t}/artifacts/${i}`)}),r}function ur(e,t,n){return e&&n[e]?n[e]:t||null}function nf(){return s.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",style:{flexShrink:0,color:"var(--ink)"},children:s.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.748l7.73-8.835L1.254 2.25H8.08l4.259 5.63L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77z"})})}function oo(e,t,...n){var r;if(e.fromIndex!=null&&e.toIndex!=null)return{s:e.fromIndex,e:e.toIndex};if(((r=e.indices)==null?void 0:r.length)===2)return{s:e.indices[0],e:e.indices[1]};if(t)for(const l of n){if(!l)continue;const i=t.indexOf(l);if(i!==-1)return{s:i,e:i+l.length}}return null}function rf(e,t){const n=e.expanded_url||e.url||e.text||"",r=e.display_url||e.expanded_url||e.url||e.text||"",l=oo(e,t,e.url,e.text,e.display_url,e.expanded_url);return!l||!n?null:{...l,kind:"url",href:n,display:r}}function lf(e,t){const n=e.screen_name||e.name||e.text||"",r=n?`@${n}`:null,l=oo(e,t,r);return!l||!n?null:{...l,kind:"mention",screen_name:n}}const zu=/https?:\/\/[^\s<>"'\])]+/g,og=/[.,;:!?)()]+$/;function ws(e,t){const n=[];let r=0,l;for(zu.lastIndex=0;(l=zu.exec(e))!==null;){l.index>r&&n.push(e.slice(r,l.index));let i=l[0].replace(og,"");n.push(s.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",style:t,children:i},l.index));const a=l[0].slice(i.length);a&&n.push(a),r=l.index+l[0].length}return r===0?e:(rrf(o,e)).filter(Boolean),...(t.user_mentions||[]).map(o=>lf(o,e)).filter(Boolean)];if(r.length===0&&n.length===0)return ws(Ru(e),G.link);const l=new Set([0,e.length]);for(const o of r)o.s>=0&&o.s<=e.length&&l.add(o.s),o.e>=0&&o.e<=e.length&&l.add(o.e);for(const[o,u]of n)o>=0&&o<=e.length&&l.add(o),u>=0&&u<=e.length&&l.add(u);const i=(o,u)=>n.some(([c,y])=>c<=o&&y>=u),a=[...l].sort((o,u)=>o-u);return a.slice(0,-1).map((o,u)=>{const c=a[u+1];if(i(o,c))return null;const y=e.slice(o,c),g=r.filter(x=>x.s<=o&&x.e>=c),h=g.find(x=>x.kind==="url");if(h)return s.jsx("a",{href:h.href,target:"_blank",rel:"noopener noreferrer",style:G.link,children:h.display||y},u);const v=g.find(x=>x.kind==="mention");return v?s.jsx("a",{href:`https://x.com/${v.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:G.link,children:y},u):s.jsx("span",{children:ws(Ru(y),G.link)},u)}).filter(o=>o!==null)}function cg(e,t,n,r,l=G){if(!e)return null;t=t||[],n=n||[],r=r||[];const i=[];for(const u of t)u.length>0&&i.push({s:u.offset,e:u.offset+u.length,kind:"style",style:u.style});for(const u of n){const c=rf(u,e);c&&i.push(c)}for(const u of r){const c=lf(u,e);c&&i.push(c)}if(i.length===0)return ws(e,l.link);const a=new Set([0,e.length]);for(const u of i)u.s>=0&&u.s<=e.length&&a.add(u.s),u.e>=0&&u.e<=e.length&&a.add(u.e);const o=[...a].sort((u,c)=>u-c);return o.slice(0,-1).map((u,c)=>{const y=o[c+1],g=i.filter(N=>N.s<=u&&N.e>=y),h=e.slice(u,y);let v;if(h.includes(` -`)){const N=h.split(` -`);v=N.flatMap((p,f)=>fN.kind==="style"&&N.style==="Code")&&(v=s.jsx("code",{style:l.iCode,children:v})),g.some(N=>N.kind==="style"&&N.style==="Bold")&&(v=s.jsx("strong",{children:v})),g.some(N=>N.kind==="style"&&N.style==="Italic")&&(v=s.jsx("em",{children:v})),g.some(N=>N.kind==="style"&&N.style==="Underline")&&(v=s.jsx("u",{children:v})),g.some(N=>N.kind==="style"&&N.style==="Strikethrough")&&(v=s.jsx("s",{children:v}));const x=g.find(N=>N.kind==="url");if(x){const N=/^https?:\/\/t\.co\//i.test(v);v=s.jsx("a",{href:x.href,target:"_blank",rel:"noopener noreferrer",style:l.link,children:N?x.display:v})}const S=g.find(N=>N.kind==="mention");return S&&(v=s.jsx("a",{href:`https://x.com/${S.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:l.link,children:v})),s.jsx("span",{children:typeof v=="string"?ws(v,l.link):v},c)})}function dg(e,t,n){const r=(n==null?void 0:n.st)||G,l=e.resolved_entities||[];return l.length===0?null:l.map((i,a)=>{var o;switch(i.type){case"divider":return s.jsx("hr",{style:r.bHr},a);case"media":{const u=ur(i.local_path,i.url,t);return u?s.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:c=>{var y;!c.metaKey&&!c.ctrlKey&&(c.preventDefault(),(y=n==null?void 0:n.onImgClick)==null||y.call(n,u))},children:s.jsx("img",{src:u,style:r.bImg,loading:"lazy",alt:""})},a):null}case"tweet":return i.tweet_id?s.jsxs("a",{href:`https://x.com/i/status/${i.tweet_id}`,target:"_blank",rel:"noopener noreferrer",style:r.bTweet,children:[s.jsx(nf,{}),"View post on X"]},a):null;case"link":return i.url?s.jsx("p",{style:r.bP,children:s.jsx("a",{href:i.url,target:"_blank",rel:"noopener noreferrer",style:r.link,children:i.url})},a):null;case"markdown":{const u=i.markdown??((o=i.data)==null?void 0:o.markdown)??"";return s.jsx("pre",{style:r.bMdPre,children:s.jsx("code",{style:r.bMdCode,children:u})},a)}case"emoji":return i.url?s.jsx("img",{src:i.url,alt:"",style:{height:"1.2em",verticalAlign:"middle",margin:"0 1px"}},a):null;default:return null}})}function yi(e,t,n,r){const l=(r==null?void 0:r.st)||G,i=e.type||"",a=e.text||"",o=e.inline_style_ranges||[],u=e.data||{},c=cg(a,o,u.urls||[],u.mentions||[],l);switch(i){case"header-one":return s.jsx("h1",{style:l.bH1,children:c},t);case"header-two":{const y=a.match(/(?:x\.com|twitter\.com)\/i\/status\/(\d+)/);return y?s.jsxs("a",{href:`https://x.com/i/status/${y[1]}`,target:"_blank",rel:"noopener noreferrer",style:l.bTweet,children:[s.jsx(nf,{}),"View post on X"]},t):s.jsx("h2",{style:l.bH2,children:c},t)}case"unstyled":return a.trim()?s.jsx("p",{style:l.bP,children:c},t):s.jsx("span",{style:l.bSpacer},t);case"blockquote":return s.jsx("blockquote",{style:l.bQuote,children:c},t);case"unordered-list-item":case"ordered-list-item":return s.jsx("li",{style:l.bLi,children:c},t);case"atomic":return s.jsx("span",{children:dg(e,n,r)},t);default:return a?s.jsx("p",{style:l.bP,children:c},t):null}}function fg(e,t,n){const r=(n==null?void 0:n.st)||G,l=[];let i=0;for(;i{r&&(l==null||l(!0))},[r,l]);const o=r?gi:G,u=e.cover_media||{},c=e.author||t||{},y=e.first_published_at_secs?tf(e.first_published_at_secs):"",h=[c.screen_name?`@${c.screen_name}`:"",y].filter(Boolean).join(" · "),v=ur(u.local_path,u.url,n),x=ur(c.avatar_local_path,c.avatar_url,n),S=s.jsxs(s.Fragment,{children:[i&&s.jsx(sf,{items:[{src:i,alt:""}],startIndex:0,onClose:()=>a(null)}),v&&s.jsx("a",{href:v,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:N=>{!N.metaKey&&!N.ctrlKey&&(N.preventDefault(),a(v))},children:s.jsx("img",{src:v,style:o.aCover,alt:"Article cover"})}),s.jsxs("div",{style:o.aMeta,children:[e.title&&s.jsx("div",{style:o.aTweetTitle,children:e.title}),s.jsxs("div",{style:o.aAuthorRow,children:[x?s.jsx("img",{src:x,style:o.aAvatar,alt:c.name||""}):s.jsx("div",{style:o.aAvatarPh}),s.jsxs("div",{children:[s.jsx("div",{style:o.aAuthorName,children:c.name||c.screen_name||"Unknown"}),h&&s.jsx("div",{style:o.aAuthorSub,children:h})]})]})]}),s.jsx("hr",{style:o.aDivider}),s.jsx("div",{style:o.aBody,children:fg(e.blocks||[],n,{onImgClick:a,st:o})})]});return r?s.jsx("div",{style:gi.article,children:s.jsx("div",{style:gi.articleInner,children:S})}):s.jsx("div",{style:G.article,children:S})}function hg({photos:e,onOpen:t}){const n=e.length;if(n===0)return null;if(n===1)return s.jsx("a",{href:e[0].src,target:"_blank",rel:"noopener noreferrer",style:{display:"block"},onClick:l=>{!l.metaKey&&!l.ctrlKey&&(l.preventDefault(),t(0))},children:s.jsx("img",{src:e[0].src,alt:e[0].alt||"",style:G.mediaImg,loading:"lazy"})});const r=n<=2?"180px":"140px";return s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gridTemplateRows:n===2?r:`${r} ${r}`,gap:"2px"},children:e.map((l,i)=>s.jsx("a",{href:l.src,target:"_blank",rel:"noopener noreferrer",style:{display:"block",overflow:"hidden",gridRow:n===3&&i===0?"span 2":void 0},onClick:a=>{!a.metaKey&&!a.ctrlKey&&(a.preventDefault(),t(i))},children:s.jsx("img",{src:l.src,alt:l.alt||"",loading:"lazy",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}})},i))})}function sf({items:e,startIndex:t,onClose:n}){const[r,l]=d.useState(t);d.useEffect(()=>{const a=o=>{(o.key==="Escape"||o.key==="ArrowLeft"||o.key==="ArrowRight")&&(o.stopPropagation(),o.preventDefault()),o.key==="Escape"&&n(),o.key==="ArrowRight"&&l(u=>Math.min(u+1,e.length-1)),o.key==="ArrowLeft"&&l(u=>Math.max(u-1,0))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[n,e.length]);const i=e[r];return s.jsx("div",{style:G.lightboxBackdrop,onClick:n,children:s.jsxs("div",{style:G.lightboxContent,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{style:G.lightboxToolbar,children:[e.length>1&&s.jsxs("span",{style:G.lightboxCounter,children:[r+1," / ",e.length]}),s.jsx("a",{href:i.src,target:"_blank",rel:"noopener noreferrer",style:G.lightboxLink,title:"Open in new tab",children:"↗"}),s.jsx("button",{style:G.lightboxBtn,onClick:n,"aria-label":"Close",children:"×"})]}),s.jsx("img",{src:i.src,alt:i.alt||"",style:G.lightboxImg}),e.length>1&&s.jsxs("div",{style:G.lightboxNav,children:[s.jsx("button",{style:G.lightboxNavBtn,onClick:()=>l(a=>Math.max(a-1,0)),disabled:r===0,children:"‹"}),s.jsx("button",{style:G.lightboxNavBtn,onClick:()=>l(a=>Math.min(a+1,e.length-1)),disabled:r===e.length-1,children:"›"})]})]})})}function Iu({tweet:e,isInThread:t,isLast:n,artifactMap:r}){var f,m;const[l,i]=d.useState(null),a=e.author||{},o=e.created_at_secs?tf(e.created_at_secs):"",u=e.entities||{},c=ur(a.avatar_local_path,a.avatar_url,r),y=t&&!n,g=e.is_quote_status===!0,h=t?G.tweetRowThread:G.tweetRow,v=e.full_text||"",x=((m=(f=e.extended_entities)==null?void 0:f.media)!=null&&m.length?e.extended_entities.media:u.media)||[],S=[],N=[];for(const w of x)if(w.type==="photo"){const C=ur(w.local_path,w.media_url_https,r);C&&S.push({kind:"photo",src:C,alt:w.alt_text||""})}else if(w.type==="video"||w.type==="animated_gif"){const C=w.local_path&&r[w.local_path]||(()=>{var b,k;return(k=(((b=w.video_info)==null?void 0:b.variants)||[]).filter(T=>T.content_type==="video/mp4").sort((T,L)=>(L.bitrate||0)-(T.bitrate||0))[0])==null?void 0:k.url})();C&&N.push({kind:w.type==="animated_gif"?"gif":"video",src:C})}const p=[];for(const w of x){if(!w.url||!(w.type==="photo"?S.some(b=>b.src===ur(w.local_path,w.media_url_https,r)):N.length>0))continue;const E=oo(w,v,w.url);E&&p.push([E.s,E.e])}return s.jsxs(s.Fragment,{children:[l!==null&&s.jsx(sf,{items:S,startIndex:l,onClose:()=>i(null)}),s.jsxs("div",{style:h,children:[s.jsxs("div",{style:G.leftCol,children:[c?s.jsx("img",{src:c,style:G.avatar,alt:a.name||""}):s.jsx("div",{style:G.avatarPh}),y&&s.jsx("div",{style:G.threadLine})]}),s.jsxs("div",{style:G.rightCol,children:[s.jsxs("div",{style:G.authorRow,children:[s.jsx("span",{style:G.authorName,children:a.name||a.screen_name||"Unknown"}),a.screen_name&&s.jsxs("span",{style:G.authorHandle,children:["@",a.screen_name]}),o&&s.jsxs("span",{style:G.datePart,children:["· ",o]}),g&&s.jsx("span",{style:G.qtBadge,title:"Quote tweet",children:"↻ QT"})]}),s.jsx("div",{style:G.tweetText,children:ug(v,u,p)}),S.length>0&&s.jsx("div",{style:G.mediaGrid,children:s.jsx(hg,{photos:S,onOpen:w=>i(w)})}),N.map((w,C)=>s.jsx("div",{style:G.mediaGrid,children:s.jsx("video",{src:w.src,style:G.mediaVideo,controls:!0,loop:w.kind==="gif",muted:w.kind==="gif",autoPlay:w.kind==="gif"})},C)),(e.retweet_count>0||e.favorite_count>0)&&s.jsxs("div",{style:G.stats,children:[e.favorite_count>0&&s.jsxs("span",{children:["❤️ ",e.favorite_count.toLocaleString()]}),e.retweet_count>0&&s.jsxs("span",{children:["🔁 ",e.retweet_count.toLocaleString()]})]})]})]})]})}function mg({archiveId:e,entryUid:t,artifacts:n,entityKind:r,fullPage:l,onXArticle:i}){const[a,o]=d.useState(!0),[u,c]=d.useState(null),[y,g]=d.useState([]);if(d.useEffect(()=>{if(o(!0),c(null),g([]),!n||!e||!t){o(!1);return}const x=n.map((N,p)=>({...N,index:p})).filter(N=>N.artifact_role==="raw_tweet_json");if(x.length===0){c("No tweet data found."),o(!1);return}let S=!1;return Ah(e,t,x.map(N=>N.index)).then(async N=>{if(S)return;const p=/https?:\/\/t\.co\/[A-Za-z0-9]+/g,f=b=>{var T;const k=b.full_text||"";return(((T=b.entities)==null?void 0:T.urls)||[]).map(L=>{var q;if(L.fromIndex!=null&&L.toIndex!=null)return[L.fromIndex,L.toIndex];if(((q=L.indices)==null?void 0:q.length)===2)return[L.indices[0],L.indices[1]];if(L.url){const F=k.indexOf(L.url);if(F!==-1)return[F,F+L.url.length]}return null}).filter(Boolean)},m=(b,k,T)=>b.some(([L,q])=>L<=k&&q>=T),w=new Set;for(const b of N){const k=b.full_text||"",T=f(b);let L;for(p.lastIndex=0;(L=p.exec(k))!==null;)m(T,L.index,L.index+L[0].length)||w.add(L[0])}const C=w.size>0?await Mh([...w]).catch(()=>({})):{},E=N.map(b=>{var F;const k=b.full_text||"",T=f(b),L=[];let q;for(p.lastIndex=0;(q=p.exec(k))!==null;){const X=q[0],Z=C[X];Z&&Z!==X&&!m(T,q.index,q.index+X.length)&&L.push({url:X,expanded_url:Z,display_url:(()=>{try{const ue=new URL(Z);return ue.hostname+(ue.pathname.length>1?"/…":"")}catch{return Z}})(),fromIndex:q.index,toIndex:q.index+X.length})}return L.length===0?b:{...b,entities:{...b.entities||{},urls:[...((F=b.entities)==null?void 0:F.urls)||[],...L]}}});S||g(E)}).catch(N=>{S||c(N.message||"Failed to load tweet.")}).finally(()=>{S||o(!1)}),()=>{S=!0}},[e,t,n]),a)return s.jsx("div",{style:G.loading,children:"Loading…"});if(u)return s.jsxs("div",{style:G.error,children:["Error: ",u]});if(y.length===0)return null;const h=ag(e,t,n);if(r==="tweet_thread")return s.jsx("div",{style:G.threadOuter,children:y.map((x,S)=>s.jsx(Iu,{tweet:x,isInThread:!0,isLast:S===y.length-1,artifactMap:h},x.id||S))});const v=y[0];return v.is_article&&v.article?s.jsx(pg,{article:v.article,tweetAuthor:v.author,artifactMap:h,fullPage:l,onXArticle:i}):s.jsx("div",{style:G.card,children:s.jsx(Iu,{tweet:v,isInThread:!1,isLast:!0,artifactMap:h})})}const gg=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv"]),yg=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),vg=new Set(["jpg","jpeg","png","gif","webp","avif","svg","bmp"]),xg={mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo",m4v:"video/mp4",ogv:"video/ogg"};function af({archiveId:e,entry:t,detail:n,fullPage:r,onXArticle:l}){if(!t)return s.jsx("div",{className:"preview-panel preview-panel--empty",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Select an entry to preview"})});if(!n)return s.jsx("div",{className:"preview-panel preview-panel--loading",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Loading…"})});const{summary:i,artifacts:a}=n,o=i.entry_uid,u=i.entity_kind;if(u==="tweet"||u==="tweet_thread"){const v=s.jsx(mg,{archiveId:e,entryUid:o,artifacts:a,entityKind:u,fullPage:r,onXArticle:l});return r?v:s.jsx("div",{className:"preview-tweet-wrap",children:v})}const c=a.findIndex(v=>v.artifact_role==="primary_media");if(c===-1)return s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),a.length>0&&s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((v,x)=>s.jsxs("li",{children:[v.artifact_role,": ",v.relpath]},x))})]});const y=a[c],g=`/api/archives/${e}/entries/${o}/artifacts/${c}`,h=y.relpath.split(".").pop().toLowerCase();return gg.has(h)?s.jsx("div",{className:"preview-panel",children:s.jsx(sg,{src:g,contentType:xg[h]||"video/mp4"})}):yg.has(h)?s.jsxs("div",{className:"preview-panel preview-panel--audio",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"12px",padding:"24px",fontFamily:"var(--sans)"},children:[s.jsx("span",{style:{fontSize:"2rem"},children:"🎵"}),s.jsx("span",{style:{color:"var(--ink)",fontSize:"0.95rem",fontWeight:600},children:i.title||o}),s.jsx("audio",{src:g,controls:!0,style:{marginTop:"8px",width:"100%",maxWidth:"400px"}})]}):h==="pdf"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Lu,{src:g,type:"pdf",title:i.title,originalUrl:i.original_url})}):h==="html"||h==="htm"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Lu,{src:g,type:"page",title:i.title,originalUrl:i.original_url})}):vg.has(h)?s.jsx("div",{className:"preview-panel",style:{height:"100%"},children:s.jsx(ig,{src:g,alt:i.title||"Image"})}):s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((v,x)=>s.jsxs("li",{children:[v.artifact_role,": ",v.relpath]},x))})]})}function wg({archiveId:e,entry:t,detail:n,onClose:r}){var l,i;return d.useEffect(()=>{const a=o=>{o.key==="Escape"&&r()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[r]),s.jsx("div",{className:"preview-modal-backdrop",onClick:r,children:s.jsxs("div",{className:`preview-modal${((l=n==null?void 0:n.summary)==null?void 0:l.entity_kind)==="tweet"||((i=n==null?void 0:n.summary)==null?void 0:i.entity_kind)==="tweet_thread"?"":" preview-modal--full"}`,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{className:"preview-modal-header",children:[s.jsx("span",{className:"preview-modal-title",children:(t==null?void 0:t.title)||(t==null?void 0:t.entry_uid)||"Preview"}),s.jsx("a",{className:"preview-modal-newtab",href:`/preview/${e}/${t==null?void 0:t.entry_uid}`,target:"_blank",rel:"noopener noreferrer",title:"Open in new tab",children:"↗"}),s.jsx("button",{className:"preview-modal-close",onClick:r,"aria-label":"Close preview",children:"×"})]}),s.jsx("div",{className:"preview-modal-body",children:s.jsx(af,{archiveId:e,entry:t,detail:n})})]})})}function Du(e){if(!isFinite(e)||isNaN(e))return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`}function kg({entry:e,src:t,archiveId:n,onClose:r}){const l=d.useRef(null),[i,a]=d.useState(!1),[o,u]=d.useState(0),[c,y]=d.useState(NaN),[g,h]=d.useState(1);d.useEffect(()=>{!l.current||!t||(l.current.load(),u(0),y(NaN),a(!1))},[t]),d.useEffect(()=>{l.current&&(l.current.volume=g)},[g]);function v(){const f=l.current;f&&(i?f.pause():f.play().catch(()=>{}))}function x(f){const m=l.current;if(!m||!isFinite(c))return;const w=Number(f.target.value);m.currentTime=w,u(w)}function S(f){h(Number(f.target.value))}const N=(e==null?void 0:e.title)||(e==null?void 0:e.entry_uid)||"Unknown",p=(e==null?void 0:e.source_kind)||"other";return s.jsxs(s.Fragment,{children:[s.jsx("audio",{ref:l,src:t||void 0,preload:"auto",onPlay:()=>a(!0),onPause:()=>a(!1),onEnded:()=>a(!1),onTimeUpdate:()=>{var f;return u(((f=l.current)==null?void 0:f.currentTime)??0)},onLoadedMetadata:()=>{var f;return y(((f=l.current)==null?void 0:f.duration)??NaN)},onDurationChange:()=>{var f;return y(((f=l.current)==null?void 0:f.duration)??NaN)},style:{display:"none"}}),s.jsxs("div",{className:"audio-bar",style:{position:"fixed",bottom:0,left:0,right:0,zIndex:100,background:"var(--paper-3)",borderTop:"1px solid var(--line)",display:"flex",alignItems:"center",gap:"16px",padding:"0 16px",height:"56px",fontFamily:"var(--sans)"},children:[s.jsxs("div",{className:"audio-bar-info",style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,flex:"0 1 220px",overflow:"hidden"},children:[s.jsx("span",{className:"source-icon",style:{flexShrink:0,width:"18px",height:"18px",display:"flex",alignItems:"center"},dangerouslySetInnerHTML:{__html:Os(p)}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.85rem",color:"var(--ink)"},title:N,children:N})]}),s.jsxs("div",{className:"audio-bar-controls",style:{display:"flex",alignItems:"center",gap:"10px",flex:"1 1 0",minWidth:0},children:[s.jsx("button",{onClick:v,"aria-label":i?"Pause":"Play",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--ink)",flexShrink:0,fontSize:"1.2rem",lineHeight:1},children:i?"⏸":"▶"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:Du(o)}),s.jsx("input",{type:"range",min:0,max:isFinite(c)?c:0,step:.1,value:isFinite(o)?o:0,onChange:x,"aria-label":"Seek",style:{flex:1,minWidth:0,accentColor:"var(--accent)"}}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:Du(c)})]}),s.jsxs("div",{className:"audio-bar-right",style:{display:"flex",alignItems:"center",gap:"8px",flex:"0 1 160px"},children:[s.jsx("span",{style:{fontSize:"0.85rem",color:"var(--muted)",flexShrink:0},children:"🔊"}),s.jsx("input",{type:"range",min:0,max:1,step:.01,value:g,onChange:S,"aria-label":"Volume",style:{width:"80px",accentColor:"var(--accent)"}}),s.jsx("button",{onClick:r,"aria-label":"Close audio player",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--muted)",fontSize:"1rem",lineHeight:1,marginLeft:"4px"},children:"✕"})]})]})]})}function jg({archiveId:e,entryUid:t}){var h,v;const[n,r]=d.useState(null),[l,i]=d.useState(!0),[a,o]=d.useState(null),[u,c]=d.useState(!1);d.useEffect(()=>{if(!u)return;const x=document.documentElement,S=document.body,N=x.style.colorScheme,p=S.style.background;return x.style.colorScheme="dark",S.style.background="#000",()=>{x.style.colorScheme=N,S.style.background=p}},[u]),d.useEffect(()=>{c(!1),$r(e,t).then(x=>{r(x),i(!1)}).catch(x=>{o((x==null?void 0:x.message)||"Failed to load entry"),i(!1)})},[e,t]);const y=((h=n==null?void 0:n.summary)==null?void 0:h.title)||t,g=(v=n==null?void 0:n.summary)==null?void 0:v.original_url;return s.jsxs("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column",background:u?"#000":"var(--paper)",fontFamily:"var(--sans)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",padding:u?"8px 12px":"10px 16px",borderBottom:u?"none":"1px solid var(--line)",flexShrink:0,position:u?"sticky":"relative",top:0,zIndex:20,background:u?"rgba(0,0,0,0.82)":"var(--paper-2)",backdropFilter:u?"blur(12px)":"none",WebkitBackdropFilter:u?"blur(12px)":"none"},children:[s.jsx("a",{href:"/",style:{color:u?"#1d9bf0":"var(--accent)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"← Archive"}),s.jsx("span",{style:{flex:1,fontSize:"14px",fontWeight:600,color:u?"#e7e9ea":"var(--ink)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y}),g&&s.jsx("a",{href:g,target:"_blank",rel:"noopener noreferrer",style:{color:u?"#71767b":"var(--muted)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"Original ↗"})]}),s.jsxs("div",{style:u?{flex:1}:{flex:1,minHeight:0,overflow:"auto",display:"flex",flexDirection:"column"},children:[l&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},children:"Loading…"}),a&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},children:a}),n&&s.jsx(af,{archiveId:e,entry:n.summary,detail:n,fullPage:!0,onXArticle:c})]})]})}const Sg=7e3;function Ng({toasts:e,onDismiss:t,onIgnoreUblock:n}){return e.length?s.jsx("div",{className:"toast-stack",role:"log","aria-live":"polite","aria-label":"Notifications",children:e.map(r=>s.jsx(Cg,{toast:r,onDismiss:t,onIgnoreUblock:n},r.id))}):null}function _g(e){if(!e)return null;if(e.length<=52)return e;try{const{hostname:t,pathname:n,search:r}=new URL(e),l=n.split("/").filter(Boolean),i=(l[l.length-1]??"")+r,a=i?`${t}/…/${i}`:t;return a.length<=56?a:a.slice(0,53)+"…"}catch{return"…"+e.slice(-51)}}function Cg({toast:e,onDismiss:t,onIgnoreUblock:n}){const[r,l]=d.useState(!1),i=e.type==="warning",a=e.type==="success";d.useEffect(()=>{if(r)return;const u=setTimeout(()=>t(e.id),Sg);return()=>clearTimeout(u)},[r,e.id,t]);const o=_g(e.locator);return a?s.jsx("div",{className:"toast toast--success",role:"alert","aria-atomic":"true",children:s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✓"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsx("div",{className:"toast-btns",children:s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})})]})}):i?s.jsxs("div",{className:"toast toast--warning",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"⚠"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived with warnings"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),"aria-expanded":r,children:r?"Hide":"Details"}),e.locator&&s.jsx("button",{type:"button",className:"toast-view-btn toast-ignore-btn",onClick:()=>{n==null||n(),t(e.id)},children:"Ignore"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&s.jsx("p",{className:"toast-warning-detail",children:e.text||"The page was captured but one or more browser extensions were unavailable (ad-blocking or cookie-consent). Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config."})]}):s.jsxs("div",{className:"toast toast--error",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✕"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Capture failed"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),children:r?"Hide":"View error"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&e.text&&s.jsx("pre",{className:"toast-error-detail",children:e.text})]})}const As=d.createContext(null),Eg=["archive","tags","collections","runs","admin","settings"],bg=["profile","tokens","instance","cookies","extensions","storage"],Lr=(()=>{const e=window.location.pathname.match(/^\/preview\/([^/]+)\/([^/]+)/);return e?{archiveId:e[1],entryUid:e[2]}:null})();function At(){const e=window.location.pathname.split("/").filter(Boolean),t=Eg.includes(e[0])?e[0]:"archive",n=t==="settings"&&bg.includes(e[1])?e[1]:"profile",r=new URLSearchParams(window.location.search),l=r.get("q")??"",i=t==="archive"?r.get("tag")??null:null,a=t==="archive"?r.get("entry")??null:null,o=t==="archive"?r.get("collection")??null:null,u=o==="main"?null:o,c=r.get("archive")??null;return{view:t,settingsTab:n,q:l,tag:i,entry:a,collection:u,archive:c}}function Tg(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function Pg(){const[e,t]=d.useState("loading"),[n,r]=d.useState(null);d.useEffect(()=>{(async()=>{var $,Q,J;if(await Xh()){t("setup");return}const I=await Zh();if(!I){const{collection:le,archive:Te}=At();try{const Ke=await ju(),Ne=Te?(($=Ke.find(Ms=>Ms.id===Te))==null?void 0:$.id)??((Q=Ke[0])==null?void 0:Q.id):(J=Ke[0])==null?void 0:J.id;if(Ne){await Su(Ne,le),i(Ke),o(Ne),c(le),t("authenticated");return}}catch{}t("login");return}r(I),t("authenticated")})()},[]),d.useEffect(()=>{const _=()=>{n&&(r(null),t("login"))};return window.addEventListener("auth:expired",_),()=>window.removeEventListener("auth:expired",_)},[n]),d.useEffect(()=>{const _=()=>{const{view:I,settingsTab:$,q:Q,tag:J,entry:le,collection:Te}=At();T(I),q($),X(Q),b(J),p(le),m(null),C(le?new Set([le]):new Set),c(Te)};return window.addEventListener("popstate",_),()=>window.removeEventListener("popstate",_)},[]);const[l,i]=d.useState([]),[a,o]=d.useState(null),[u,c]=d.useState(()=>At().collection),[y,g]=d.useState([]),[h,v]=d.useState([]),[x,S]=d.useState(()=>new Set),[N,p]=d.useState(()=>At().entry),[f,m]=d.useState(null),[w,C]=d.useState(()=>{const _=At().entry;return _?new Set([_]):new Set}),[E,b]=d.useState(()=>At().tag),[k,T]=d.useState(()=>At().view),[L,q]=d.useState(()=>At().settingsTab),[F,X]=d.useState(()=>At().q),[Z,ue]=d.useState(""),[Ae,ge]=d.useState(!1),[D,P]=d.useState([]),[H,te]=d.useState([]),[ee,Re]=d.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[Y,ye]=d.useState([]),ce=d.useRef(0),[Ee,Ye]=d.useState(()=>{try{const _=JSON.parse(sessionStorage.getItem("pendingCaptures")||"[]");if(Array.isArray(_))return _}catch{}return[]});d.useEffect(()=>{sessionStorage.setItem("pendingCaptures",JSON.stringify(Ee))},[Ee]);const[Ct,yt]=d.useState(()=>sessionStorage.getItem("ublockWarningIgnored")==="true"),[Ht,ut]=d.useState(null),rt=d.useRef(0),vt=d.useRef(null),Et=d.useRef(!1),O=d.useRef(!0),K=d.useRef(null),de=d.useRef(0),Be=d.useRef(new Map),Dt=(n==null?void 0:n.humanize_slugs)??!1;d.useEffect(()=>{const _=++rt.current;ut(null),!(!f||!a)&&$r(a,f.entry_uid).then(I=>{_===rt.current&&ut(I)}).catch(()=>{})},[f,a]),d.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",ee)},[ee]);const ze=d.useCallback(async(_,I,$,Q)=>{if(_){ge(!0);try{let J;I||$?J=await $h(_,I,$,Q):J=await Su(_,Q),v(J),C(le=>{if(le.size<2)return le;const Te=new Set(J.map(Ne=>Ne.entry_uid)),Ke=new Set([...le].filter(Ne=>Te.has(Ne)));return Ke.size===le.size?le:Ke}),ue(J.length===0?"No results":`${J.length} result${J.length===1?"":"s"}`)}catch{v([]),ue("Search failed. Try again.")}finally{ge(!1)}}},[]);d.useEffect(()=>{e==="authenticated"&&(a||ju().then(_=>{if(i(_),_.length>0){const{archive:I}=At(),$=I?_.find(Q=>Q.id===I):null;o(($==null?void 0:$.id)??_[0].id)}}))},[e,a]),d.useEffect(()=>{if(!a)return;const _=!n;if(O.current){O.current=!1;const $=[];_||($.push(fi(a).then(P)),$.push(Dl(a).then(te))),$.length&&Promise.all($);return}b(null),m(null),p(null),C(new Set),c(null);const I=[ze(a,"",null,null)];_||(I.push(fi(a).then(P)),I.push(Dl(a).then(te))),Promise.all(I)},[a,n]),d.useEffect(()=>{if(a===null)return;const _=setTimeout(()=>{ze(a,F,E,u)},300);return()=>clearTimeout(_)},[F,a,u]),d.useEffect(()=>{a!==null&&(E!==null&&T("archive"),ze(a,F,E,u))},[E,a,u]);const Fn=d.useCallback(_=>{o(_),c(null);const I=new URLSearchParams(window.location.search);I.set("archive",_),I.delete("collection");const $=I.toString();history.replaceState(null,"",window.location.pathname+($?"?"+$:""))},[]);d.useEffect(()=>{if(!a){g([]);return}io(a).then(g).catch(()=>g([]))},[a]);const Nn=d.useCallback(_=>{if(!n){const Q=_?y.find(J=>J.collection_uid===_):y.find(J=>J.slug==="_default_");if(Q!=null&&Q.requires_auth){t("login");return}}c(_),m(null),p(null),C(new Set),ze(a,F,E,_);const I=new URLSearchParams(window.location.search);_?(I.set("collection",_),I.set("archive",a)):(I.delete("collection"),a&&I.set("archive",a));const $=I.toString();history.replaceState(null,"",window.location.pathname+($?"?"+$:""))},[a,F,E,n,y,ze]),tn=d.useCallback(_=>{T(_),_==="tags"&&a&&Dl(a).then(te)},[a]);d.useEffect(()=>{if(Lr)return;const _=Tg(k,L);window.location.pathname!==_&&history.pushState(null,"",_+window.location.search)},[k,L]);const Ve=d.useCallback(_=>{p(_?_.entry_uid:null),m(_)},[]),wr=d.useCallback((_,I)=>{if(Be.current.set(_.entry_uid,_),++de.current,I.shiftKey&&K.current!==null){I.preventDefault();const $=[...document.querySelectorAll("#entries-body [data-entry-uid]")],Q=$.findIndex(Ne=>Ne.dataset.entryUid===K.current),J=$.findIndex(Ne=>Ne.dataset.entryUid===_.entry_uid);if(Q===-1||J===-1){K.current=_.entry_uid,C(new Set([_.entry_uid])),Ve(_);return}const le=Math.min(Q,J),Te=Math.max(Q,J),Ke=new Set($.slice(le,Te+1).map(Ne=>Ne.dataset.entryUid));C(Ke),Ke.size===1&&Ve(_)}else if(I.ctrlKey||I.metaKey){K.current=_.entry_uid;const $=new Set(w);if($.has(_.entry_uid)?$.delete(_.entry_uid):$.add(_.entry_uid),C($),$.size===0)Ve(null);else if($.size===1){const[Q]=$,J=Be.current.get(Q)??h.find(le=>le.entry_uid===Q)??null;if(J)Ve(J);else{const le=++de.current;$r(a,Q).then(Te=>{le===de.current&&(Te!=null&&Te.summary)&&Ve(Te.summary)}).catch(()=>{})}}else Ve(null)}else K.current=_.entry_uid,C(new Set([_.entry_uid])),Ve(_)},[h,w,Ve,a]),Bn=d.useCallback(_=>{b(_)},[]),j=d.useCallback(()=>{b(null)},[]),B=d.useCallback(()=>{a&&Dl(a).then(te)},[a]),M=d.useCallback((_,I)=>{E===_?b(I):E!=null&&E.startsWith(_+"/")&&b(I+E.slice(_.length))},[E]),A=d.useCallback(_=>{(E===_||E!=null&&E.startsWith(_+"/"))&&b(null)},[E]),W=d.useCallback((_,I)=>{v($=>$.map(Q=>Q.entry_uid===_?{...Q,title:I}:Q)),m($=>$&&$.entry_uid===_?{...$,title:I}:$),ut($=>$&&$.summary.entry_uid===_?{...$,summary:{...$.summary,title:I}}:$)},[]),V=d.useCallback(()=>{if(!a||!f)return;const _=++rt.current;$r(a,f.entry_uid).then(I=>{_===rt.current&&ut(I)}).catch(()=>{})},[a,f]),pe=d.useCallback(_=>{const I=h.some($=>$.entry_uid===_);S($=>{const Q=new Set($);return Q.add(_),Q}),v($=>$.filter(Q=>Q.entry_uid!==_)),m($=>($==null?void 0:$.entry_uid)===_?null:$),p($=>$===_?null:$),C($=>{const Q=new Set($);return Q.delete(_),Q}),I||ze(a,F,E,u)},[h,a,F,E,u,ze]),ae=d.useCallback(_=>{const I=new Set(h.map(Q=>Q.entry_uid)),$=[..._].some(Q=>!I.has(Q));S(Q=>{const J=new Set(Q);return _.forEach(le=>J.add(le)),J}),v(Q=>Q.filter(J=>!_.has(J.entry_uid))),C(new Set),m(null),p(null),$&&ze(a,F,E,u)},[h,a,F,E,u,ze]);d.useEffect(()=>{if(w.size>=2)p(null),m(null);else if(w.size===1){const[_]=w;p(_)}else p(null),m(null)},[w]);const xe=d.useMemo(()=>h.filter(_=>w.has(_.entry_uid)),[h,w]);d.useEffect(()=>{if(!N||f)return;const _=h.find(I=>I.entry_uid===N);_&&m(_)},[h,N,f]),d.useEffect(()=>{if(Lr)return;const _=new URLSearchParams(window.location.search).get("archive"),I=new URLSearchParams;F&&I.set("q",F),k==="archive"&&E&&I.set("tag",E),k==="archive"&&N&&I.set("entry",N),k==="archive"&&u?(I.set("collection",u),a&&I.set("archive",a)):_&&a&&I.set("archive",a);const $=I.toString(),Q=window.location.pathname+($?"?"+$:"");window.location.pathname+window.location.search!==Q&&history.replaceState(null,"",Q)},[F,E,N,u,a,k]),d.useEffect(()=>{const _=I=>{var le,Te,Ke,Ne;const $=I.key==="/"&&!I.metaKey&&!I.ctrlKey&&!I.altKey,Q=(I.metaKey||I.ctrlKey)&&I.key==="k";if(!$&&!Q)return;const J=(le=document.activeElement)==null?void 0:le.tagName;$&&(J==="INPUT"||J==="TEXTAREA"||J==="SELECT")||$&&((Te=document.activeElement)!=null&&Te.isContentEditable)||(I.preventDefault(),k==="archive"?((Ke=vt.current)==null||Ke.focus(),(Ne=vt.current)==null||Ne.select()):(Et.current=!0,T("archive")))};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[k]),d.useEffect(()=>{const _=I=>{var co,fo;if(I.metaKey||I.ctrlKey||I.altKey||I.key!=="j"&&I.key!=="k")return;const $=(co=document.activeElement)==null?void 0:co.tagName;if($==="INPUT"||$==="TEXTAREA"||$==="SELECT"||(fo=document.activeElement)!=null&&fo.isContentEditable)return;const Q=[...document.querySelectorAll("#entries-body [data-entry-uid]")];if(Q.length===0)return;const[J]=w.size===1?w:[null],le=J?Q.findIndex(nn=>nn.dataset.entryUid===J):-1,Te=I.key==="j"?Math.min(le+1,Q.length-1):Math.max(le-1,0);if(Te===le&&le!==-1)return;const Ke=Q[Te<0?0:Te],Ne=Ke.dataset.entryUid;K.current=Ne;const Ms=++de.current;C(new Set([Ne]));const uo=Be.current.get(Ne)??h.find(nn=>nn.entry_uid===Ne)??null;uo?Ve(uo):$r(a,Ne).then(nn=>{Ms===de.current&&(nn!=null&&nn.summary)&&Ve(nn.summary)}).catch(()=>{}),Ke.scrollIntoView({block:"nearest"}),I.preventDefault()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[w,h,Ve,a]),d.useEffect(()=>{k==="archive"&&Et.current&&(Et.current=!1,requestAnimationFrame(()=>{var _,I;(_=vt.current)==null||_.focus(),(I=vt.current)==null||I.select()}))},[k]);const ie=d.useCallback(()=>{Re(!0)},[]),Qe=d.useCallback(()=>{Re(!1)},[]),we=d.useCallback(()=>{if(a)return Promise.allSettled([ze(a,F,E,u),fi(a).then(P)])},[a,F,E,u,ze]),Un=d.useCallback((_,I,$="error",Q=null)=>{if($==="warning"&&Ct&&I)return;const J=++ce.current;ye(le=>[...le,{id:J,text:_,locator:I,type:$,headline:Q}])},[Ct]),xt=d.useCallback(_=>{ye(I=>I.filter($=>$.id!==_))},[]),gl=d.useCallback(()=>{sessionStorage.setItem("ublockWarningIgnored","true"),yt(!0),ye(_=>_.filter(I=>!(I.type==="warning"&&I.locator)))},[]),z=d.useCallback(_=>{Ye(I=>[...I,_])},[]),re=d.useCallback(_=>{Ye(I=>I.filter($=>$.id!==_))},[]),[be,$t]=d.useState(null),[Wt,kr]=d.useState(null),Ie=d.useCallback(()=>{f&&$t(f.entry_uid)},[f]),jr=d.useCallback(()=>$t(null),[]),of=d.useCallback((_,I)=>{kr({src:_,entry:I})},[]),uf=d.useCallback(()=>kr(null),[]);return d.useEffect(()=>{$t(null)},[f]),d.useEffect(()=>{const _=I=>{var Q,J,le;if(I.key!=="Escape"||ee||be)return;const $=(Q=document.activeElement)==null?void 0:Q.tagName;$==="INPUT"||$==="TEXTAREA"||$==="SELECT"||w.size>0&&(I.preventDefault(),C(new Set),(le=(J=document.activeElement)==null?void 0:J.blur)==null||le.call(J))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[ee,be,w]),d.useEffect(()=>(document.body.classList.toggle("has-audio-bar",!!Wt),()=>document.body.classList.remove("has-audio-bar")),[Wt]),Lr?s.jsx(jg,{archiveId:Lr.archiveId,entryUid:Lr.entryUid}):e==="loading"?s.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?s.jsx(Em,{onComplete:()=>t("login")}):e==="login"?s.jsx(Cm,{onLogin:_=>{r(_),t("authenticated")}}):s.jsx(As.Provider,{value:{currentUser:n,setCurrentUser:r},children:s.jsxs(s.Fragment,{children:[s.jsx(bm,{archives:l,archiveId:a,onArchiveChange:Fn,view:k,onViewChange:tn,onCaptureClick:ie,collections:y,selectedCollectionUid:u,onCollectionChange:Nn,isPublicSession:!n,onSignInClick:()=>t("login")}),s.jsxs("main",{className:"app-shell",children:[s.jsxs("div",{className:"workspace",children:[k==="archive"&&s.jsxs("div",{className:"toolbar",children:[s.jsxs("div",{className:"search-field",children:[s.jsx("span",{className:"ico","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"11",cy:"11",r:"7"}),s.jsx("line",{x1:"16.5",y1:"16.5",x2:"21",y2:"21"})]})}),s.jsx("input",{ref:vt,className:"search-input",type:"search","aria-label":"Search archive","aria-busy":Ae,placeholder:"Search titles, URLs, types, tags…",value:F,onChange:_=>X(_.target.value)}),s.jsx("span",{className:"kbd",children:"⌘K"})]}),s.jsxs("span",{className:"result-count",children:[Z&&s.jsxs(s.Fragment,{children:[s.jsx("b",{children:Z.split(" ")[0]})," ",Z.split(" ").slice(1).join(" ")]}),E&&s.jsxs("button",{className:"tag-filter-badge",onClick:j,children:["× ",Dt?Gd(E):E]})]})]}),k==="archive"&&s.jsx(Am,{entries:h,selectedUids:w,onRowClick:wr,archiveId:a,pendingCaptures:Ee,deletedUids:x,isPublicSession:!n}),k==="runs"&&s.jsx(Bm,{runs:D}),k==="admin"&&s.jsx(Hm,{archives:l}),k==="tags"&&s.jsx(Wm,{archiveId:a,tagNodes:H,tagFilter:E,onTagFilterSet:Bn,onViewChange:tn,onTagRenamed:M,onTagDeleted:A,onTagsRefresh:B,humanizeTags:Dt}),k==="collections"&&s.jsx(Qm,{archiveId:a}),k==="settings"&&s.jsx(qm,{tab:L,onTabChange:q,archiveId:a})]}),s.jsx(ng,{archiveId:a,selectedEntry:f,selectedUids:w,selectedEntries:xe,detail:Ht,onTagFilterSet:Bn,tagNodes:H,onTagsRefresh:B,onEntryTitleChange:W,onEntryDeleted:pe,onBulkDeleted:ae,humanizeTags:Dt,onDetailRefresh:V,onOpenPreview:Ie,onPlay:of,isPublicSession:!n})]}),be&&f&&f.entry_uid===be&&s.jsx(wg,{archiveId:a,entry:f,detail:Ht,onClose:jr}),Wt&&s.jsx(kg,{entry:Wt.entry,src:Wt.src,archiveId:a,onClose:uf}),s.jsx(Lm,{open:ee,archiveId:a,onClose:Qe,onCaptured:we,onToast:Un,activeJobs:Ee,onJobStarted:z,onJobSettled:re}),s.jsx(Ng,{toasts:Y,onDismiss:xt,onIgnoreUblock:gl})]})})}qd(document.getElementById("root")).render(s.jsx(d.StrictMode,{children:s.jsx(Pg,{})})); diff --git a/crates/archivr-server/static/assets/index-CthL4K20.js b/crates/archivr-server/static/assets/index-CthL4K20.js new file mode 100644 index 0000000..00add7e --- /dev/null +++ b/crates/archivr-server/static/assets/index-CthL4K20.js @@ -0,0 +1,47 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(l){if(l.ep)return;l.ep=!0;const i=n(l);fetch(l.href,i)}})();var Du={exports:{}},ks={},Ou={exports:{}},ne={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var fl=Symbol.for("react.element"),cf=Symbol.for("react.portal"),df=Symbol.for("react.fragment"),ff=Symbol.for("react.strict_mode"),pf=Symbol.for("react.profiler"),hf=Symbol.for("react.provider"),mf=Symbol.for("react.context"),gf=Symbol.for("react.forward_ref"),yf=Symbol.for("react.suspense"),vf=Symbol.for("react.memo"),xf=Symbol.for("react.lazy"),po=Symbol.iterator;function wf(e){return e===null||typeof e!="object"?null:(e=po&&e[po]||e["@@iterator"],typeof e=="function"?e:null)}var Au={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Mu=Object.assign,Fu={};function yr(e,t,n){this.props=e,this.context=t,this.refs=Fu,this.updater=n||Au}yr.prototype.isReactComponent={};yr.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};yr.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Bu(){}Bu.prototype=yr.prototype;function da(e,t,n){this.props=e,this.context=t,this.refs=Fu,this.updater=n||Au}var fa=da.prototype=new Bu;fa.constructor=da;Mu(fa,yr.prototype);fa.isPureReactComponent=!0;var ho=Array.isArray,Uu=Object.prototype.hasOwnProperty,pa={current:null},Hu={key:!0,ref:!0,__self:!0,__source:!0};function Wu(e,t,n){var r,l={},i=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(i=""+t.key),t)Uu.call(t,r)&&!Hu.hasOwnProperty(r)&&(l[r]=t[r]);var o=arguments.length-2;if(o===1)l.children=n;else if(1>>1,ee=D[te];if(0>>1;tel(he,V))uel(Ee,he)?(D[te]=Ee,D[ue]=V,te=ue):(D[te]=he,D[Y]=V,te=Y);else if(uel(Ee,V))D[te]=Ee,D[ue]=V,te=ue;else break e}}return P}function l(D,P){var V=D.sortIndex-P.sortIndex;return V!==0?V:D.id-P.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var a=Date,o=a.now();e.unstable_now=function(){return a.now()-o}}var u=[],c=[],y=1,g=null,h=3,v=!1,x=!1,S=!1,N=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,f=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function m(D){for(var P=n(c);P!==null;){if(P.callback===null)r(c);else if(P.startTime<=D)r(c),P.sortIndex=P.expirationTime,t(u,P);else break;P=n(c)}}function k(D){if(S=!1,m(D),!x)if(n(u)!==null)x=!0,Ae(_);else{var P=n(c);P!==null&&ye(k,P.startTime-D)}}function _(D,P){x=!1,S&&(S=!1,p(j),j=-1),v=!0;var V=h;try{for(m(P),g=n(u);g!==null&&(!(g.expirationTime>P)||D&&!K());){var te=g.callback;if(typeof te=="function"){g.callback=null,h=g.priorityLevel;var ee=te(g.expirationTime<=P);P=e.unstable_now(),typeof ee=="function"?g.callback=ee:g===n(u)&&r(u),m(P)}else r(u);g=n(u)}if(g!==null)var Re=!0;else{var Y=n(c);Y!==null&&ye(k,Y.startTime-P),Re=!1}return Re}finally{g=null,h=V,v=!1}}var E=!1,b=null,j=-1,T=5,L=-1;function K(){return!(e.unstable_now()-LD||125te?(D.sortIndex=V,t(c,D),n(u)===null&&D===n(c)&&(S?(p(j),j=-1):S=!0,ye(k,V-te))):(D.sortIndex=ee,t(u,D),x||v||(x=!0,Ae(_))),D},e.unstable_shouldYield=K,e.unstable_wrapCallback=function(D){var P=h;return function(){var V=h;h=P;try{return D.apply(this,arguments)}finally{h=V}}}})(Xu);Ku.exports=Xu;var Lf=Ku.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Rf=d,gt=Lf;function R(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),vi=Object.prototype.hasOwnProperty,zf=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,go={},yo={};function If(e){return vi.call(yo,e)?!0:vi.call(go,e)?!1:zf.test(e)?yo[e]=!0:(go[e]=!0,!1)}function $f(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Df(e,t,n,r){if(t===null||typeof t>"u"||$f(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function nt(e,t,n,r,l,i,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=a}var Ve={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Ve[e]=new nt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Ve[t]=new nt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Ve[e]=new nt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Ve[e]=new nt(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Ve[e]=new nt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Ve[e]=new nt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Ve[e]=new nt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Ve[e]=new nt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Ve[e]=new nt(e,5,!1,e.toLowerCase(),null,!1,!1)});var ma=/[\-:]([a-z])/g;function ga(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(ma,ga);Ve[t]=new nt(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ma,ga);Ve[t]=new nt(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ma,ga);Ve[t]=new nt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Ve[e]=new nt(e,1,!1,e.toLowerCase(),null,!1,!1)});Ve.xlinkHref=new nt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Ve[e]=new nt(e,1,!1,e.toLowerCase(),null,!0,!0)});function ya(e,t,n,r){var l=Ve.hasOwnProperty(t)?Ve[t]:null;(l!==null?l.type!==0:r||!(2o||l[a]!==i[o]){var u=` +`+l[a].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=a&&0<=o);break}}}finally{Us=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Rr(e):""}function Of(e){switch(e.tag){case 5:return Rr(e.type);case 16:return Rr("Lazy");case 13:return Rr("Suspense");case 19:return Rr("SuspenseList");case 0:case 2:case 15:return e=Hs(e.type,!1),e;case 11:return e=Hs(e.type.render,!1),e;case 1:return e=Hs(e.type,!0),e;default:return""}}function ji(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Qn:return"Fragment";case Vn:return"Portal";case xi:return"Profiler";case va:return"StrictMode";case wi:return"Suspense";case ki:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Yu:return(e.displayName||"Context")+".Consumer";case Gu:return(e._context.displayName||"Context")+".Provider";case xa:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case wa:return t=e.displayName||null,t!==null?t:ji(e.type)||"Memo";case sn:t=e._payload,e=e._init;try{return ji(e(t))}catch{}}return null}function Af(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ji(t);case 8:return t===va?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function wn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function ec(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Mf(e){var t=ec(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(a){r=""+a,i.call(this,a)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function wl(e){e._valueTracker||(e._valueTracker=Mf(e))}function tc(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=ec(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Jl(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Si(e,t){var n=t.checked;return Se({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function xo(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=wn(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function nc(e,t){t=t.checked,t!=null&&ya(e,"checked",t,!1)}function Ni(e,t){nc(e,t);var n=wn(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?_i(e,t.type,n):t.hasOwnProperty("defaultValue")&&_i(e,t.type,wn(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function wo(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function _i(e,t,n){(t!=="number"||Jl(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var zr=Array.isArray;function rr(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=kl.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Kr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Ar={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Ff=["Webkit","ms","Moz","O"];Object.keys(Ar).forEach(function(e){Ff.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Ar[t]=Ar[e]})});function ic(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Ar.hasOwnProperty(e)&&Ar[e]?(""+t).trim():t+"px"}function ac(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=ic(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Bf=Se({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function bi(e,t){if(t){if(Bf[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(R(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(R(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(R(61))}if(t.style!=null&&typeof t.style!="object")throw Error(R(62))}}function Ti(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Pi=null;function ka(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Li=null,lr=null,sr=null;function So(e){if(e=ml(e)){if(typeof Li!="function")throw Error(R(280));var t=e.stateNode;t&&(t=Cs(t),Li(e.stateNode,e.type,t))}}function oc(e){lr?sr?sr.push(e):sr=[e]:lr=e}function uc(){if(lr){var e=lr,t=sr;if(sr=lr=null,So(e),t)for(e=0;e>>=0,e===0?32:31-(Yf(e)/Zf|0)|0}var jl=64,Sl=4194304;function Ir(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function es(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,a=n&268435455;if(a!==0){var o=a&~l;o!==0?r=Ir(o):(i&=a,i!==0&&(r=Ir(i)))}else a=n&~l,a!==0?r=Ir(a):i!==0&&(r=Ir(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function pl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-zt(t),e[t]=n}function rp(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Fr),Ro=" ",zo=!1;function Tc(e,t){switch(e){case"keyup":return Lp.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Pc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var qn=!1;function zp(e,t){switch(e){case"compositionend":return Pc(t);case"keypress":return t.which!==32?null:(zo=!0,Ro);case"textInput":return e=t.data,e===Ro&&zo?null:e;default:return null}}function Ip(e,t){if(qn)return e==="compositionend"||!Ta&&Tc(e,t)?(e=Ec(),Fl=Ca=cn=null,qn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Oo(n)}}function Ic(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Ic(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function $c(){for(var e=window,t=Jl();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Jl(e.document)}return t}function Pa(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Hp(e){var t=$c(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Ic(n.ownerDocument.documentElement,n)){if(r!==null&&Pa(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=Ao(n,i);var a=Ao(n,r);l&&a&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Kn=null,Oi=null,Ur=null,Ai=!1;function Mo(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ai||Kn==null||Kn!==Jl(r)||(r=Kn,"selectionStart"in r&&Pa(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ur&&el(Ur,r)||(Ur=r,r=rs(Oi,"onSelect"),0Gn||(e.current=Wi[Gn],Wi[Gn]=null,Gn--)}function pe(e,t){Gn++,Wi[Gn]=e.current,e.current=t}var kn={},Ye=Sn(kn),it=Sn(!1),In=kn;function dr(e,t){var n=e.type.contextTypes;if(!n)return kn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function at(e){return e=e.childContextTypes,e!=null}function ss(){ge(it),ge(Ye)}function Qo(e,t,n){if(Ye.current!==kn)throw Error(R(168));pe(Ye,t),pe(it,n)}function Wc(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(R(108,Af(e)||"Unknown",l));return Se({},n,r)}function is(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||kn,In=Ye.current,pe(Ye,e),pe(it,it.current),!0}function qo(e,t,n){var r=e.stateNode;if(!r)throw Error(R(169));n?(e=Wc(e,t,In),r.__reactInternalMemoizedMergedChildContext=e,ge(it),ge(Ye),pe(Ye,e)):ge(it),pe(it,n)}var qt=null,Es=!1,ri=!1;function Vc(e){qt===null?qt=[e]:qt.push(e)}function th(e){Es=!0,Vc(e)}function Nn(){if(!ri&&qt!==null){ri=!0;var e=0,t=ae;try{var n=qt;for(ae=1;e>=a,l-=a,Kt=1<<32-zt(t)+l|n<j?(T=b,b=null):T=b.sibling;var L=h(p,b,m[j],k);if(L===null){b===null&&(b=T);break}e&&b&&L.alternate===null&&t(p,b),f=i(L,f,j),E===null?_=L:E.sibling=L,E=L,b=T}if(j===m.length)return n(p,b),ve&&Cn(p,j),_;if(b===null){for(;jj?(T=b,b=null):T=b.sibling;var K=h(p,b,L.value,k);if(K===null){b===null&&(b=T);break}e&&b&&K.alternate===null&&t(p,b),f=i(K,f,j),E===null?_=K:E.sibling=K,E=K,b=T}if(L.done)return n(p,b),ve&&Cn(p,j),_;if(b===null){for(;!L.done;j++,L=m.next())L=g(p,L.value,k),L!==null&&(f=i(L,f,j),E===null?_=L:E.sibling=L,E=L);return ve&&Cn(p,j),_}for(b=r(p,b);!L.done;j++,L=m.next())L=v(b,p,j,L.value,k),L!==null&&(e&&L.alternate!==null&&b.delete(L.key===null?j:L.key),f=i(L,f,j),E===null?_=L:E.sibling=L,E=L);return e&&b.forEach(function(U){return t(p,U)}),ve&&Cn(p,j),_}function N(p,f,m,k){if(typeof m=="object"&&m!==null&&m.type===Qn&&m.key===null&&(m=m.props.children),typeof m=="object"&&m!==null){switch(m.$$typeof){case xl:e:{for(var _=m.key,E=f;E!==null;){if(E.key===_){if(_=m.type,_===Qn){if(E.tag===7){n(p,E.sibling),f=l(E,m.props.children),f.return=p,p=f;break e}}else if(E.elementType===_||typeof _=="object"&&_!==null&&_.$$typeof===sn&&Jo(_)===E.type){n(p,E.sibling),f=l(E,m.props),f.ref=br(p,E,m),f.return=p,p=f;break e}n(p,E);break}else t(p,E);E=E.sibling}m.type===Qn?(f=zn(m.props.children,p.mode,k,m.key),f.return=p,p=f):(k=Kl(m.type,m.key,m.props,null,p.mode,k),k.ref=br(p,f,m),k.return=p,p=k)}return a(p);case Vn:e:{for(E=m.key;f!==null;){if(f.key===E)if(f.tag===4&&f.stateNode.containerInfo===m.containerInfo&&f.stateNode.implementation===m.implementation){n(p,f.sibling),f=l(f,m.children||[]),f.return=p,p=f;break e}else{n(p,f);break}else t(p,f);f=f.sibling}f=di(m,p.mode,k),f.return=p,p=f}return a(p);case sn:return E=m._init,N(p,f,E(m._payload),k)}if(zr(m))return x(p,f,m,k);if(Sr(m))return S(p,f,m,k);Pl(p,m)}return typeof m=="string"&&m!==""||typeof m=="number"?(m=""+m,f!==null&&f.tag===6?(n(p,f.sibling),f=l(f,m),f.return=p,p=f):(n(p,f),f=ci(m,p.mode,k),f.return=p,p=f),a(p)):n(p,f)}return N}var pr=Xc(!0),Jc=Xc(!1),us=Sn(null),cs=null,er=null,Ia=null;function $a(){Ia=er=cs=null}function Da(e){var t=us.current;ge(us),e._currentValue=t}function qi(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function ar(e,t){cs=e,Ia=er=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(st=!0),e.firstContext=null)}function _t(e){var t=e._currentValue;if(Ia!==e)if(e={context:e,memoizedValue:t,next:null},er===null){if(cs===null)throw Error(R(308));er=e,cs.dependencies={lanes:0,firstContext:e}}else er=er.next=e;return t}var Tn=null;function Oa(e){Tn===null?Tn=[e]:Tn.push(e)}function Gc(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Oa(t)):(n.next=l.next,l.next=n),t.interleaved=n,Zt(e,r)}function Zt(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var an=!1;function Aa(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Yc(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Jt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function gn(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,ie&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,Zt(e,n)}return l=r.interleaved,l===null?(t.next=t,Oa(r)):(t.next=l.next,l.next=t),r.interleaved=t,Zt(e,n)}function Ul(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Sa(e,n)}}function Go(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=a:i=i.next=a,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function ds(e,t,n,r){var l=e.updateQueue;an=!1;var i=l.firstBaseUpdate,a=l.lastBaseUpdate,o=l.shared.pending;if(o!==null){l.shared.pending=null;var u=o,c=u.next;u.next=null,a===null?i=c:a.next=c,a=u;var y=e.alternate;y!==null&&(y=y.updateQueue,o=y.lastBaseUpdate,o!==a&&(o===null?y.firstBaseUpdate=c:o.next=c,y.lastBaseUpdate=u))}if(i!==null){var g=l.baseState;a=0,y=c=u=null,o=i;do{var h=o.lane,v=o.eventTime;if((r&h)===h){y!==null&&(y=y.next={eventTime:v,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var x=e,S=o;switch(h=t,v=n,S.tag){case 1:if(x=S.payload,typeof x=="function"){g=x.call(v,g,h);break e}g=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=S.payload,h=typeof x=="function"?x.call(v,g,h):x,h==null)break e;g=Se({},g,h);break e;case 2:an=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,h=l.effects,h===null?l.effects=[o]:h.push(o))}else v={eventTime:v,lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},y===null?(c=y=v,u=g):y=y.next=v,a|=h;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;h=o,o=h.next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}while(!0);if(y===null&&(u=g),l.baseState=u,l.firstBaseUpdate=c,l.lastBaseUpdate=y,t=l.shared.interleaved,t!==null){l=t;do a|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);On|=a,e.lanes=a,e.memoizedState=g}}function Yo(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=si.transition;si.transition={};try{e(!1),t()}finally{ae=n,si.transition=r}}function md(){return Ct().memoizedState}function sh(e,t,n){var r=vn(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},gd(e))yd(t,n);else if(n=Gc(e,t,n,r),n!==null){var l=et();It(n,e,r,l),vd(n,t,r)}}function ih(e,t,n){var r=vn(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(gd(e))yd(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var a=t.lastRenderedState,o=i(a,n);if(l.hasEagerState=!0,l.eagerState=o,$t(o,a)){var u=t.interleaved;u===null?(l.next=l,Oa(t)):(l.next=u.next,u.next=l),t.interleaved=l;return}}catch{}finally{}n=Gc(e,t,l,r),n!==null&&(l=et(),It(n,e,r,l),vd(n,t,r))}}function gd(e){var t=e.alternate;return e===je||t!==null&&t===je}function yd(e,t){Hr=ps=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function vd(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Sa(e,n)}}var hs={readContext:_t,useCallback:Xe,useContext:Xe,useEffect:Xe,useImperativeHandle:Xe,useInsertionEffect:Xe,useLayoutEffect:Xe,useMemo:Xe,useReducer:Xe,useRef:Xe,useState:Xe,useDebugValue:Xe,useDeferredValue:Xe,useTransition:Xe,useMutableSource:Xe,useSyncExternalStore:Xe,useId:Xe,unstable_isNewReconciler:!1},ah={readContext:_t,useCallback:function(e,t){return Ft().memoizedState=[e,t===void 0?null:t],e},useContext:_t,useEffect:eu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Wl(4194308,4,cd.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Wl(4194308,4,e,t)},useInsertionEffect:function(e,t){return Wl(4,2,e,t)},useMemo:function(e,t){var n=Ft();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Ft();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=sh.bind(null,je,e),[r.memoizedState,e]},useRef:function(e){var t=Ft();return e={current:e},t.memoizedState=e},useState:Zo,useDebugValue:Qa,useDeferredValue:function(e){return Ft().memoizedState=e},useTransition:function(){var e=Zo(!1),t=e[0];return e=lh.bind(null,e[1]),Ft().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=je,l=Ft();if(ve){if(n===void 0)throw Error(R(407));n=n()}else{if(n=t(),Fe===null)throw Error(R(349));Dn&30||nd(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,eu(ld.bind(null,r,i,e),[e]),r.flags|=2048,ol(9,rd.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Ft(),t=Fe.identifierPrefix;if(ve){var n=Xt,r=Kt;n=(r&~(1<<32-zt(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=il++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=a.createElement(n,{is:r.is}):(e=a.createElement(n),n==="select"&&(a=e,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):e=a.createElementNS(e,n),e[Bt]=t,e[rl]=r,bd(e,t,!1,!1),t.stateNode=e;e:{switch(a=Ti(n,r),n){case"dialog":me("cancel",e),me("close",e),l=r;break;case"iframe":case"object":case"embed":me("load",e),l=r;break;case"video":case"audio":for(l=0;l<$r.length;l++)me($r[l],e);l=r;break;case"source":me("error",e),l=r;break;case"img":case"image":case"link":me("error",e),me("load",e),l=r;break;case"details":me("toggle",e),l=r;break;case"input":xo(e,r),l=Si(e,r),me("invalid",e);break;case"option":l=r;break;case"select":e._wrapperState={wasMultiple:!!r.multiple},l=Se({},r,{value:void 0}),me("invalid",e);break;case"textarea":ko(e,r),l=Ci(e,r),me("invalid",e);break;default:l=r}bi(n,l),o=l;for(i in o)if(o.hasOwnProperty(i)){var u=o[i];i==="style"?ac(e,u):i==="dangerouslySetInnerHTML"?(u=u?u.__html:void 0,u!=null&&sc(e,u)):i==="children"?typeof u=="string"?(n!=="textarea"||u!=="")&&Kr(e,u):typeof u=="number"&&Kr(e,""+u):i!=="suppressContentEditableWarning"&&i!=="suppressHydrationWarning"&&i!=="autoFocus"&&(qr.hasOwnProperty(i)?u!=null&&i==="onScroll"&&me("scroll",e):u!=null&&ya(e,i,u,a))}switch(n){case"input":wl(e),wo(e,r,!1);break;case"textarea":wl(e),jo(e);break;case"option":r.value!=null&&e.setAttribute("value",""+wn(r.value));break;case"select":e.multiple=!!r.multiple,i=r.value,i!=null?rr(e,!!r.multiple,i,!1):r.defaultValue!=null&&rr(e,!!r.multiple,r.defaultValue,!0);break;default:typeof l.onClick=="function"&&(e.onclick=ls)}switch(n){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(t.flags|=4)}t.ref!==null&&(t.flags|=512,t.flags|=2097152)}return Je(t),null;case 6:if(e&&t.stateNode!=null)Pd(e,t,e.memoizedProps,r);else{if(typeof r!="string"&&t.stateNode===null)throw Error(R(166));if(n=Pn(sl.current),Pn(Ht.current),Tl(t)){if(r=t.stateNode,n=t.memoizedProps,r[Bt]=t,(i=r.nodeValue!==n)&&(e=mt,e!==null))switch(e.tag){case 3:bl(r.nodeValue,n,(e.mode&1)!==0);break;case 5:e.memoizedProps.suppressHydrationWarning!==!0&&bl(r.nodeValue,n,(e.mode&1)!==0)}i&&(t.flags|=4)}else r=(n.nodeType===9?n:n.ownerDocument).createTextNode(r),r[Bt]=t,t.stateNode=r}return Je(t),null;case 13:if(ge(ke),r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(ve&&ht!==null&&t.mode&1&&!(t.flags&128))Kc(),fr(),t.flags|=98560,i=!1;else if(i=Tl(t),r!==null&&r.dehydrated!==null){if(e===null){if(!i)throw Error(R(318));if(i=t.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(R(317));i[Bt]=t}else fr(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Je(t),i=!1}else Rt!==null&&(ua(Rt),Rt=null),i=!0;if(!i)return t.flags&65536?t:null}return t.flags&128?(t.lanes=n,t):(r=r!==null,r!==(e!==null&&e.memoizedState!==null)&&r&&(t.child.flags|=8192,t.mode&1&&(e===null||ke.current&1?Oe===0&&(Oe=3):Za())),t.updateQueue!==null&&(t.flags|=4),Je(t),null);case 4:return hr(),ta(e,t),e===null&&tl(t.stateNode.containerInfo),Je(t),null;case 10:return Da(t.type._context),Je(t),null;case 17:return at(t.type)&&ss(),Je(t),null;case 19:if(ge(ke),i=t.memoizedState,i===null)return Je(t),null;if(r=(t.flags&128)!==0,a=i.rendering,a===null)if(r)Tr(i,!1);else{if(Oe!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(a=fs(e),a!==null){for(t.flags|=128,Tr(i,!1),r=a.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),t.subtreeFlags=0,r=n,n=t.child;n!==null;)i=n,e=r,i.flags&=14680066,a=i.alternate,a===null?(i.childLanes=0,i.lanes=e,i.child=null,i.subtreeFlags=0,i.memoizedProps=null,i.memoizedState=null,i.updateQueue=null,i.dependencies=null,i.stateNode=null):(i.childLanes=a.childLanes,i.lanes=a.lanes,i.child=a.child,i.subtreeFlags=0,i.deletions=null,i.memoizedProps=a.memoizedProps,i.memoizedState=a.memoizedState,i.updateQueue=a.updateQueue,i.type=a.type,e=a.dependencies,i.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),n=n.sibling;return pe(ke,ke.current&1|2),t.child}e=e.sibling}i.tail!==null&&Ce()>gr&&(t.flags|=128,r=!0,Tr(i,!1),t.lanes=4194304)}else{if(!r)if(e=fs(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Tr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!ve)return Je(t),null}else 2*Ce()-i.renderingStartTime>gr&&n!==1073741824&&(t.flags|=128,r=!0,Tr(i,!1),t.lanes=4194304);i.isBackwards?(a.sibling=t.child,t.child=a):(n=i.last,n!==null?n.sibling=a:t.child=a,i.last=a)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Ce(),t.sibling=null,n=ke.current,pe(ke,r?n&1|2:n&1),t):(Je(t),null);case 22:case 23:return Ya(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?ft&1073741824&&(Je(t),t.subtreeFlags&6&&(t.flags|=8192)):Je(t),null;case 24:return null;case 25:return null}throw Error(R(156,t.tag))}function mh(e,t){switch(Ra(t),t.tag){case 1:return at(t.type)&&ss(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return hr(),ge(it),ge(Ye),Ba(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Fa(t),null;case 13:if(ge(ke),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(R(340));fr()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ge(ke),null;case 4:return hr(),null;case 10:return Da(t.type._context),null;case 22:case 23:return Ya(),null;case 24:return null;default:return null}}var Rl=!1,Ge=!1,gh=typeof WeakSet=="function"?WeakSet:Set,W=null;function tr(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){_e(e,t,r)}else n.current=null}function na(e,t,n){try{n()}catch(r){_e(e,t,r)}}var du=!1;function yh(e,t){if(Mi=ts,e=$c(),Pa(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var a=0,o=-1,u=-1,c=0,y=0,g=e,h=null;t:for(;;){for(var v;g!==n||l!==0&&g.nodeType!==3||(o=a+l),g!==i||r!==0&&g.nodeType!==3||(u=a+r),g.nodeType===3&&(a+=g.nodeValue.length),(v=g.firstChild)!==null;)h=g,g=v;for(;;){if(g===e)break t;if(h===n&&++c===l&&(o=a),h===i&&++y===r&&(u=a),(v=g.nextSibling)!==null)break;g=h,h=g.parentNode}g=v}n=o===-1||u===-1?null:{start:o,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(Fi={focusedElem:e,selectionRange:n},ts=!1,W=t;W!==null;)if(t=W,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,W=e;else for(;W!==null;){t=W;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var S=x.memoizedProps,N=x.memoizedState,p=t.stateNode,f=p.getSnapshotBeforeUpdate(t.elementType===t.type?S:Pt(t.type,S),N);p.__reactInternalSnapshotBeforeUpdate=f}break;case 3:var m=t.stateNode.containerInfo;m.nodeType===1?m.textContent="":m.nodeType===9&&m.documentElement&&m.removeChild(m.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(R(163))}}catch(k){_e(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,W=e;break}W=t.return}return x=du,du=!1,x}function Wr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&na(t,n,i)}l=l.next}while(l!==r)}}function Ps(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function ra(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Ld(e){var t=e.alternate;t!==null&&(e.alternate=null,Ld(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Bt],delete t[rl],delete t[Hi],delete t[Zp],delete t[eh])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Rd(e){return e.tag===5||e.tag===3||e.tag===4}function fu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Rd(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function la(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=ls));else if(r!==4&&(e=e.child,e!==null))for(la(e,t,n),e=e.sibling;e!==null;)la(e,t,n),e=e.sibling}function sa(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(sa(e,t,n),e=e.sibling;e!==null;)sa(e,t,n),e=e.sibling}var He=null,Lt=!1;function ln(e,t,n){for(n=n.child;n!==null;)zd(e,t,n),n=n.sibling}function zd(e,t,n){if(Ut&&typeof Ut.onCommitFiberUnmount=="function")try{Ut.onCommitFiberUnmount(js,n)}catch{}switch(n.tag){case 5:Ge||tr(n,t);case 6:var r=He,l=Lt;He=null,ln(e,t,n),He=r,Lt=l,He!==null&&(Lt?(e=He,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):He.removeChild(n.stateNode));break;case 18:He!==null&&(Lt?(e=He,n=n.stateNode,e.nodeType===8?ni(e.parentNode,n):e.nodeType===1&&ni(e,n),Yr(e)):ni(He,n.stateNode));break;case 4:r=He,l=Lt,He=n.stateNode.containerInfo,Lt=!0,ln(e,t,n),He=r,Lt=l;break;case 0:case 11:case 14:case 15:if(!Ge&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,a=i.destroy;i=i.tag,a!==void 0&&(i&2||i&4)&&na(n,t,a),l=l.next}while(l!==r)}ln(e,t,n);break;case 1:if(!Ge&&(tr(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){_e(n,t,o)}ln(e,t,n);break;case 21:ln(e,t,n);break;case 22:n.mode&1?(Ge=(r=Ge)||n.memoizedState!==null,ln(e,t,n),Ge=r):ln(e,t,n);break;default:ln(e,t,n)}}function pu(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new gh),t.forEach(function(r){var l=Ch.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Tt(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=a),r&=~i}if(r=l,r=Ce()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*xh(r/1960))-r,10e?16:e,dn===null)var r=!1;else{if(e=dn,dn=null,ys=0,ie&6)throw Error(R(331));var l=ie;for(ie|=4,W=e.current;W!==null;){var i=W,a=i.child;if(W.flags&16){var o=i.deletions;if(o!==null){for(var u=0;uCe()-Ja?Rn(e,0):Xa|=n),ot(e,t)}function Bd(e,t){t===0&&(e.mode&1?(t=Sl,Sl<<=1,!(Sl&130023424)&&(Sl=4194304)):t=1);var n=et();e=Zt(e,t),e!==null&&(pl(e,t,n),ot(e,n))}function _h(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Bd(e,n)}function Ch(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(R(314))}r!==null&&r.delete(t),Bd(e,n)}var Ud;Ud=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||it.current)st=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return st=!1,ph(e,t,n);st=!!(e.flags&131072)}else st=!1,ve&&t.flags&1048576&&Qc(t,os,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Vl(e,t),e=t.pendingProps;var l=dr(t,Ye.current);ar(t,n),l=Ha(null,t,r,e,l,n);var i=Wa();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,at(r)?(i=!0,is(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Aa(t),l.updater=Ts,t.stateNode=l,l._reactInternals=t,Xi(t,r,e,n),t=Yi(null,t,r,!0,i,n)):(t.tag=0,ve&&i&&La(t),Ze(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Vl(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=bh(r),e=Pt(r,e),l){case 0:t=Gi(null,t,r,e,n);break e;case 1:t=ou(null,t,r,e,n);break e;case 11:t=iu(null,t,r,e,n);break e;case 14:t=au(null,t,r,Pt(r.type,e),n);break e}throw Error(R(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Pt(r,l),Gi(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Pt(r,l),ou(e,t,r,l,n);case 3:e:{if(_d(t),e===null)throw Error(R(387));r=t.pendingProps,i=t.memoizedState,l=i.element,Yc(e,t),ds(t,r,null,n);var a=t.memoizedState;if(r=a.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=mr(Error(R(423)),t),t=uu(e,t,r,n,l);break e}else if(r!==l){l=mr(Error(R(424)),t),t=uu(e,t,r,n,l);break e}else for(ht=mn(t.stateNode.containerInfo.firstChild),mt=t,ve=!0,Rt=null,n=Jc(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(fr(),r===l){t=en(e,t,n);break e}Ze(e,t,r,n)}t=t.child}return t;case 5:return Zc(t),e===null&&Qi(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,a=l.children,Bi(r,l)?a=null:i!==null&&Bi(r,i)&&(t.flags|=32),Nd(e,t),Ze(e,t,a,n),t.child;case 6:return e===null&&Qi(t),null;case 13:return Cd(e,t,n);case 4:return Ma(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=pr(t,null,r,n):Ze(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Pt(r,l),iu(e,t,r,l,n);case 7:return Ze(e,t,t.pendingProps,n),t.child;case 8:return Ze(e,t,t.pendingProps.children,n),t.child;case 12:return Ze(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,a=l.value,pe(us,r._currentValue),r._currentValue=a,i!==null)if($t(i.value,a)){if(i.children===l.children&&!it.current){t=en(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){a=i.child;for(var u=o.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=Jt(-1,n&-n),u.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var y=c.pending;y===null?u.next=u:(u.next=y.next,y.next=u),c.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),qi(i.return,n,t),o.lanes|=n;break}u=u.next}}else if(i.tag===10)a=i.type===t.type?null:i.child;else if(i.tag===18){if(a=i.return,a===null)throw Error(R(341));a.lanes|=n,o=a.alternate,o!==null&&(o.lanes|=n),qi(a,n,t),a=i.sibling}else a=i.child;if(a!==null)a.return=i;else for(a=i;a!==null;){if(a===t){a=null;break}if(i=a.sibling,i!==null){i.return=a.return,a=i;break}a=a.return}i=a}Ze(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,ar(t,n),l=_t(l),r=r(l),t.flags|=1,Ze(e,t,r,n),t.child;case 14:return r=t.type,l=Pt(r,t.pendingProps),l=Pt(r.type,l),au(e,t,r,l,n);case 15:return jd(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Pt(r,l),Vl(e,t),t.tag=1,at(r)?(e=!0,is(t)):e=!1,ar(t,n),xd(t,r,l),Xi(t,r,l,n),Yi(null,t,r,!0,e,n);case 19:return Ed(e,t,n);case 22:return Sd(e,t,n)}throw Error(R(156,t.tag))};function Hd(e,t){return gc(e,t)}function Eh(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function St(e,t,n,r){return new Eh(e,t,n,r)}function eo(e){return e=e.prototype,!(!e||!e.isReactComponent)}function bh(e){if(typeof e=="function")return eo(e)?1:0;if(e!=null){if(e=e.$$typeof,e===xa)return 11;if(e===wa)return 14}return 2}function xn(e,t){var n=e.alternate;return n===null?(n=St(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Kl(e,t,n,r,l,i){var a=2;if(r=e,typeof e=="function")eo(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case Qn:return zn(n.children,l,i,t);case va:a=8,l|=8;break;case xi:return e=St(12,n,t,l|2),e.elementType=xi,e.lanes=i,e;case wi:return e=St(13,n,t,l),e.elementType=wi,e.lanes=i,e;case ki:return e=St(19,n,t,l),e.elementType=ki,e.lanes=i,e;case Zu:return Rs(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Gu:a=10;break e;case Yu:a=9;break e;case xa:a=11;break e;case wa:a=14;break e;case sn:a=16,r=null;break e}throw Error(R(130,e==null?e:typeof e,""))}return t=St(a,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function zn(e,t,n,r){return e=St(7,e,r,t),e.lanes=n,e}function Rs(e,t,n,r){return e=St(22,e,r,t),e.elementType=Zu,e.lanes=n,e.stateNode={isHidden:!1},e}function ci(e,t,n){return e=St(6,e,null,t),e.lanes=n,e}function di(e,t,n){return t=St(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Th(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Vs(0),this.expirationTimes=Vs(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Vs(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function to(e,t,n,r,l,i,a,o,u){return e=new Th(e,t,n,o,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=St(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Aa(i),e}function Ph(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(qd)}catch(e){console.error(e)}}qd(),qu.exports=yt;var $h=qu.exports,Kd,ku=$h;Kd=ku.createRoot,ku.hydrateRoot;async function Le(e){const t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return t.json()}async function ju(){return Le("/api/archives")}async function Su(e,t=null){const n=t?`/api/archives/${e}/entries?collection=${encodeURIComponent(t)}`:`/api/archives/${e}/entries`;return Le(n)}async function Dh(e,t,n,r=null){const l=new URLSearchParams;return t&&l.set("q",t),n&&l.set("tag",n),r&&l.set("collection",r),Le(`/api/archives/${e}/entries/search?${l}`)}async function Dr(e,t){return Le(`/api/archives/${e}/entries/${t}`)}async function Oh(e,t){return Le(`/api/archives/${e}/entries/${t}/children`)}function Ah(e,t,n){return Promise.all(n.map(r=>Le(`/api/archives/${e}/entries/${t}/artifacts/${r}`)))}async function Mh(e){if(!e||e.length===0)return{};const t=await fetch("/api/util/resolve-tco",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return t.ok?t.json():{}}async function Fh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:n??null})});if(!r.ok)throw new Error(await r.text())}async function $l(e,t){return Le(`/api/archives/${e}/entries/${t}/tags`)}async function Nu(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag_path:n})});if(!r.ok)throw new Error(`Failed to add tag (${r.status})`)}async function Bh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags/${n}`,{method:"DELETE"});if(!r.ok)throw new Error(`Remove failed (${r.status})`)}async function _u(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`Delete failed (${n.status})`)}async function Uh(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n})});if(!r.ok)throw new Error(await r.text());return r.json()}async function Hh(e,t){const n=await fetch(`/api/archives/${e}/tags/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(await n.text())}async function Wh(e,t){const n=await fetch(`/api/archives/${e}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok)throw new Error(await n.text());return n.json()}async function Vh(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}/move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parent_uid:n??null})});if(!r.ok)throw new Error(await r.text());return r.json()}async function fi(e){return Le(`/api/archives/${e}/runs`)}async function Dl(e){return Le(`/api/archives/${e}/tags`)}async function Qh(e,t,n=null,r=null){const l={locator:t};n&&n!=="best"&&(l.quality=n),r&&(typeof r.ublock_enabled=="boolean"&&(l.ublock_enabled=r.ublock_enabled),typeof r.reader_mode=="boolean"&&(l.reader_mode=r.reader_mode),typeof r.cookie_ext_enabled=="boolean"&&(l.cookie_ext_enabled=r.cookie_ext_enabled),typeof r.modal_closer_enabled=="boolean"&&(l.modal_closer_enabled=r.modal_closer_enabled),typeof r.via_freedium=="boolean"&&(l.via_freedium=r.via_freedium),r.per_item_quality&&typeof r.per_item_quality=="object"&&Object.keys(r.per_item_quality).length>0&&(l.per_item_quality=r.per_item_quality),r.sync===!0&&(l.sync=!0));const i=await fetch(`/api/archives/${e}/captures`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok){const a=await i.json().catch(()=>({})),o=new Error(a.error||`HTTP ${i.status}`);throw o.status=i.status,o}return i.json()}async function qh(e,{title:t,body:n,mime:r="text/markdown"}){const l={title:t,body:n};r&&r!=="text/markdown"&&(l.mime=r);const i=await fetch(`/api/archives/${e}/captures/text`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok){const a=await i.json().catch(()=>({})),o=new Error(a.error||`HTTP ${i.status}`);throw o.status=i.status,o}return i.json()}async function Kh(e,t){return Le(`/api/archives/${e}/captures/probe?locator=${encodeURIComponent(t)}`)}async function Xh(e,t){const n=await fetch(`/api/archives/${e}/captures/probe-playlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({locator:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function Xd(e,t){return Le(`/api/archives/${e}/capture_jobs/${t}`)}async function Jh(){return(await(await fetch("/api/auth/setup")).json()).setup_required===!0}async function Gh(e,t){const n=await fetch("/api/auth/setup",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Setup failed");return n.json()}async function Yh(e,t){const n=await fetch("/api/auth/login",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Login failed");return n.json()}async function Zh(){await fetch("/api/auth/logout",{method:"POST"})}async function em(){const e=await fetch("/api/auth/me");return e.status===401?null:e.json()}async function tm(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:e})});if(!t.ok)throw new Error(await t.text())}async function nm(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function rm(e,t){const n=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({current_password:e,new_password:t})});if(!n.ok){let r=await n.text();try{r=JSON.parse(r).error??r}catch{}throw new Error(r)}}async function lm(){return Le("/api/auth/tokens")}async function sm(e){const t=await fetch("/api/auth/tokens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})});if(!t.ok)throw new Error(await t.text());return t.json()}async function im(e){const t=await fetch(`/api/auth/tokens/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(await t.text())}async function so(){return Le("/api/admin/instance-settings")}async function Xl(e){const t=await fetch("/api/admin/instance-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function am(){return Le("/api/admin/users")}async function om(e,t,n){const r=await fetch("/api/admin/users",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t,email:n||void 0})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error||`HTTP ${r.status}`)}return r.json()}async function um(e,t){const n=await fetch(`/api/admin/users/${e}/status`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function cm(){return Le("/api/admin/roles")}async function dm(e,t){const n=await fetch("/api/admin/roles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:e,name:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function io(e){return Le(`/api/archives/${e}/collections`)}async function fm(e,t,n,r=2,l=!0){const i=await fetch(`/api/archives/${e}/collections`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:t,slug:n,default_visibility_bits:r,requires_auth:l})});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error||i.statusText)}return i.json()}async function pm(e,t){return Le(`/api/archives/${e}/collections/${t}`)}async function ca(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections/${t}/entries`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({entry_uid:n,visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function hm(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"DELETE"});if(!r.ok){const l=await r.json().catch(()=>({error:r.statusText}));throw new Error(l.error||r.statusText)}}async function mm(e,t,n,r){const l=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function Cu(e,t){return Le(`/api/archives/${e}/entries/${t}/collections`)}async function pi(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error??r.statusText)}}async function gm(e,t){const n=await fetch(`/api/archives/${e}/collections/${t}`,{method:"DELETE"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error??n.statusText)}}async function ym(e){return Le(`/api/archives/${e}/blob-cleanup`)}async function vm(e){const t=await fetch(`/api/archives/${e}/blob-cleanup`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error??t.statusText)}return t.json()}async function xm(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}/rearchive`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`rearchive failed: ${n.status}`)}return n.json()}async function wm(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/artifacts/${n}/media-token`,{method:"POST"});if(!r.ok)throw new Error(`media-token ${r.status}`);return r.json()}async function km(){return Le("/api/admin/cookie-rules")}async function jm(e,t,n){const r=await fetch("/api/admin/cookie-rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url_pattern:e||null,pattern_kind:t,cookies_json:n})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.message||`HTTP ${r.status}`)}return r.json()}async function Sm(e,t){const n=await fetch(`/api/admin/cookie-rules/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`HTTP ${n.status}`)}}async function Nm(e){const t=await fetch(`/api/admin/cookie-rules/${e}`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.message||`HTTP ${t.status}`)}}function _m(e,t,n){let r;return{promise:new Promise((i,a)=>{const o=new FormData;o.append("file",t),r=new XMLHttpRequest,r.open("POST",`/api/archives/${e}/uploads`),r.upload.addEventListener("progress",u=>{u.lengthComputable&&n&&n(Math.round(u.loaded/u.total*100))}),r.addEventListener("load",()=>{if(r.status>=200&&r.status<300)try{i(JSON.parse(r.responseText))}catch{a(new Error("Invalid server response"))}else{let u=`Upload failed (${r.status})`;try{u=JSON.parse(r.responseText).message||u}catch{}a(new Error(u))}}),r.addEventListener("error",()=>a(new Error("Network error during upload"))),r.addEventListener("abort",()=>a(new Error("Upload cancelled"))),r.send(o)}),abort:()=>r==null?void 0:r.abort()}}async function hi(e,t){try{await fetch(`/api/archives/${e}/uploads`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({locator:t})})}catch{}}const Cm=window.fetch;window.fetch=async(...e)=>{var n;const t=await Cm(...e);return t.status===401&&((typeof e[0]=="string"?e[0]:((n=e[0])==null?void 0:n.url)??"").includes("/api/auth/")||window.dispatchEvent(new CustomEvent("auth:expired"))),t};function Em({onLogin:e}){const[t,n]=d.useState(""),[r,l]=d.useState(""),[i,a]=d.useState(null),[o,u]=d.useState(!1);async function c(y){y.preventDefault(),a(null),u(!0);try{const g=await Yh(t,r);e(g)}catch(g){a(g.message)}finally{u(!1)}}return s.jsx("div",{className:"login-page",children:s.jsxs("div",{className:"login-card",children:[s.jsx("h1",{className:"login-brand",children:"Archivr"}),s.jsx("p",{className:"login-tagline",children:"Sign in to your archive"}),s.jsxs("form",{onSubmit:c,children:[s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-username",children:"Username"}),s.jsx("input",{className:"login-input",id:"login-username",type:"text",value:t,onChange:y=>n(y.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-password",children:"Password"}),s.jsx("input",{className:"login-input",id:"login-password",type:"password",value:r,onChange:y=>l(y.target.value),required:!0,autoComplete:"current-password"})]}),i&&s.jsx("p",{className:"login-error",children:i}),s.jsx("button",{className:"login-submit",type:"submit",disabled:o,children:o?"Signing in…":"Sign in"})]})]})})}function bm({onComplete:e}){const[t,n]=d.useState(""),[r,l]=d.useState(""),[i,a]=d.useState(""),[o,u]=d.useState(null),[c,y]=d.useState(!1);async function g(h){if(h.preventDefault(),r!==i){u("Passwords do not match");return}if(r.length<8){u("Password must be at least 8 characters");return}u(null),y(!0);try{await Gh(t,r),e()}catch(v){u(v.message)}finally{y(!1)}}return s.jsx("div",{className:"setup-page",children:s.jsxs("div",{className:"setup-card",children:[s.jsx("h1",{className:"setup-brand",children:"Archivr"}),s.jsx("p",{className:"setup-tagline",children:"Create your owner account to get started."}),s.jsxs("form",{onSubmit:g,children:[s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-username",children:"Username"}),s.jsx("input",{className:"setup-input",id:"setup-username",type:"text",value:t,onChange:h=>n(h.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-password",children:"Password"}),s.jsx("input",{className:"setup-input",id:"setup-password",type:"password",value:r,onChange:h=>l(h.target.value),required:!0,autoComplete:"new-password"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-confirm",children:"Confirm password"}),s.jsx("input",{className:"setup-input",id:"setup-confirm",type:"password",value:i,onChange:h=>a(h.target.value),required:!0,autoComplete:"new-password"})]}),o&&s.jsx("p",{className:"setup-error",children:o}),s.jsx("button",{className:"setup-submit",type:"submit",disabled:c,children:c?"Creating account…":"Create account"})]})]})})}function Tm({archives:e,archiveId:t,onArchiveChange:n,view:r,onViewChange:l,onCaptureClick:i,collections:a,selectedCollectionUid:o,onCollectionChange:u,isPublicSession:c,onSignInClick:y}){const{currentUser:g,setCurrentUser:h}=d.useContext(As)??{},[v,x]=d.useState(!1);async function S(){x(!0),await Zh(),h(null),window.location.reload()}const N=a.find(m=>m.slug==="_default_"),p=!c||!!N&&!N.requires_auth,f=a.filter(m=>m.slug!=="_default_").filter(m=>!c||!m.requires_auth);return s.jsxs("header",{className:"topbar",children:[s.jsx("div",{className:"brand",children:"Archivr"}),s.jsxs("div",{className:"switchers",children:[!c&&s.jsx("div",{className:"switcher",children:s.jsx("select",{"aria-label":"Select archive",value:t??"",onChange:m=>n(m.target.value),children:e.map(m=>s.jsx("option",{value:m.id,children:m.label},m.id))})}),f.length>0&&s.jsx("div",{className:"switcher",children:s.jsxs("select",{"aria-label":"Select collection",value:o??"",onChange:m=>u(m.target.value||null),children:[p&&s.jsx("option",{value:"",children:"All entries"}),f.map(m=>s.jsx("option",{value:m.collection_uid,children:m.name},m.collection_uid))]})})]}),c?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1}}),s.jsx("button",{className:"logout-btn",onClick:y,children:"Sign in"})]}):s.jsxs(s.Fragment,{children:[s.jsx("nav",{className:"nav","aria-label":"Primary",children:["archive","tags","collections","runs","admin","settings"].map(m=>s.jsx("button",{className:`nav-link${r===m?" is-active":""}`,onClick:()=>l(m),children:m.charAt(0).toUpperCase()+m.slice(1)},m))}),s.jsx("button",{className:"capture-button",onClick:i,children:"Capture"}),g&&s.jsxs("div",{className:"user-menu",children:[s.jsx("span",{className:"user-name",children:g.display_name||g.username}),s.jsx("button",{className:"logout-btn",onClick:S,disabled:v,children:v?"Logging out…":"Log out"})]})]})]})}let cl=1;function Jd(e){const t=e.trim(),n=t.toLowerCase();for(const r of["yt:","youtube:"])if(n.startsWith(r)){const l=n.slice(r.length);return!!(l.startsWith("video/")||l.startsWith("short/")||l.startsWith("shorts/")||/^[a-z0-9_-]{11}$/i.test(l))}if(n.startsWith("ytm:"))return!n.slice(4).startsWith("playlist/");for(const r of["x:","twitter:","tweet:"])if(n.startsWith(r))return n.slice(r.length).startsWith("media:");if(n.startsWith("spotify:"))return!1;if(n.startsWith("instagram:")||n.startsWith("facebook:")||n.startsWith("tiktok:")||n.startsWith("reddit:")||n.startsWith("snapchat:"))return!0;if(n.startsWith("http://")||n.startsWith("https://")){if(/^https?:\/\/music\.youtube\.com\/watch/.test(n)||/^https?:\/\/(?:www\.)?(?:youtu\.be\/[0-9A-Za-z_-]+|youtube\.com\/watch\?v=[0-9A-Za-z_-]+|youtube\.com\/shorts\/[0-9A-Za-z_-]+)/.test(t)||n.startsWith("https://x.com/")||n.startsWith("http://x.com/")||/^https?:\/\/(?:www\.)?instagram\.com\//.test(n)||/^https?:\/\/(?:www\.)?facebook\.com\//.test(n)||n.startsWith("https://fb.watch/")||n.startsWith("http://fb.watch/")||/^https?:\/\/(?:www\.)?tiktok\.com\//.test(n)||/^https?:\/\/(?:www\.)?reddit\.com\//.test(n)||n.startsWith("https://redd.it/")||n.startsWith("http://redd.it/")||/^https?:\/\/(?:www\.)?snapchat\.com\//.test(n))return!0;if(n.startsWith("https://open.spotify.com/")||n.startsWith("http://open.spotify.com/"))return!1}return!1}function Ln(e){const t=e.trim(),n=t.toLowerCase();for(const r of["yt:","youtube:"])if(n.startsWith(r)){const l=n.slice(r.length);return l.startsWith("playlist/")||l.startsWith("@")||l.startsWith("channel/")||l.startsWith("c/")||l.startsWith("user/")}if(n.startsWith("ytm:"))return n.slice(4).startsWith("playlist/");if(n.startsWith("spotify:")){const r=n.slice(8);return r.startsWith("album:")||r.startsWith("playlist:")}if(n.startsWith("http://")||n.startsWith("https://"))try{const r=new URL(t),l=r.hostname;if((l==="youtube.com"||l==="www.youtube.com")&&(r.pathname==="/playlist"&&r.searchParams.has("list")||r.pathname.startsWith("/@")||r.pathname.startsWith("/channel/")||r.pathname.startsWith("/c/")||r.pathname.startsWith("/user/"))||l==="music.youtube.com"&&r.pathname==="/playlist"&&r.searchParams.has("list")||l==="open.spotify.com"&&(r.pathname.startsWith("/album/")||r.pathname.startsWith("/playlist/")))return!0}catch{}return!1}function Wn(e=""){return{id:cl++,locator:e,quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,status:"idle",error:null,jobUid:null,archiveId:null,playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1,syncEnabled:!1}}function Pm(e){return{id:cl++,kind:"file",filename:e,uploadProgress:0,uploadStatus:"uploading",uploadLocator:null,uploadError:null,locator:"",quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1,syncEnabled:!1,error:null,status:"idle"}}function Lm(){return{id:cl++,kind:"text",title:"",body:"",mime:"text/markdown",locator:"",quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1,syncEnabled:!1,error:null,status:"idle"}}function Rm(e,t){return e==="best"?t.map(n=>({...n,quality:"best"})):e==="audio"?t.map(n=>n.has_audio?{...n,quality:"audio"}:n.quality!==null?n:{...n,quality:null}):t.map(n=>n.qualities.includes(e)?{...n,quality:e}:n.quality!==null?n:{...n,quality:null})}function Eu(e){return Array.isArray(e.playlistItems)&&e.playlistItems.some(t=>t.quality===null)}function zm({open:e,archiveId:t,onClose:n,onCaptured:r,onToast:l,onJobStarted:i,onJobSettled:a,activeJobs:o=[]}){const u=d.useRef(null),c=d.useRef(!0),y=d.useRef(new Map),g=d.useRef(new Map),h=d.useRef(new Map),v=d.useRef(t);d.useEffect(()=>{v.current=t},[t]);const x=d.useRef(null),[S,N]=d.useState(!1),p=d.useRef([]),f=d.useRef(!1),m=d.useRef(new Map),k=d.useRef(r),_=d.useRef(l);d.useEffect(()=>{k.current=r},[r]),d.useEffect(()=>{_.current=l},[l]);const E=d.useRef(i),b=d.useRef(a);d.useEffect(()=>{E.current=i},[i]),d.useEffect(()=>{b.current=a},[a]);const[j,T]=d.useState(()=>{try{const w=JSON.parse(sessionStorage.getItem("captureItems")||"null");if(Array.isArray(w)&&w.length>0){const B=w.filter(M=>!M.status||M.status==="idle");if(B.length>0)return B.forEach(M=>{M.id>=cl&&(cl=M.id+1)}),B.map(M=>({...Wn(M.locator),...M}))}}catch{}return[Wn()]});d.useEffect(()=>{sessionStorage.setItem("captureItems",JSON.stringify(j.filter(w=>w.kind!=="file")))},[j]),d.useEffect(()=>{p.current=j},[j]);const[L,K]=d.useState(!1),[U,X]=d.useState(null),[Z,oe]=d.useState(null),[Ae,ye]=d.useState(!0),[D,P]=d.useState(!0),[V,te]=d.useState(!0);d.useEffect(()=>{so().then(w=>{oe(w),ye(w.cookie_ext_enabled??!0),P(w.modal_closer_enabled??!0)}).catch(()=>oe({}))},[]);const ee=U!==null?U:(Z==null?void 0:Z.ublock_enabled)??!0,[Re,Y]=d.useState(!1);d.useEffect(()=>{["captureDialogLocator","captureDialogError","captureDialogBusy","captureDialogJobStatus","captureDialogJobUid"].forEach(w=>sessionStorage.removeItem(w)),o.forEach(w=>{w.jobUid&&!y.current.has(w.jobUid)&&he(w.id,w.jobUid,w.locator,w.archiveId,null)})},[]),d.useEffect(()=>{const w=u.current;if(!w)return;const B=()=>{if(g.current.forEach(M=>clearTimeout(M)),g.current.clear(),!f.current){const M=v.current;p.current.forEach(I=>{var F;I.kind==="file"&&(I.uploadStatus==="uploading"?((F=m.current.get(I.id))==null||F(),m.current.delete(I.id)):I.uploadStatus==="done"&&I.uploadLocator&&hi(M,I.uploadLocator).catch(()=>{}))})}f.current=!1,n()};return w.addEventListener("close",B),()=>w.removeEventListener("close",B)},[n]),d.useEffect(()=>{const w=u.current;w&&(e?(c.current||T([Wn()]),c.current=!1,w.open||w.showModal()):(g.current.forEach(B=>clearTimeout(B)),g.current.clear(),w.open&&w.close()))},[e]),d.useEffect(()=>()=>{y.current.forEach(w=>clearInterval(w)),g.current.forEach(w=>clearTimeout(w))},[]);function he(w,B,M,I,F=null){if(y.current.has(B))return;const H=setInterval(async()=>{var xe,fe,we,ce;try{const Ue=await Xd(I,B);if(Ue.status==="completed"){clearInterval(y.current.get(B)),y.current.delete(B),await Promise.resolve((xe=k.current)==null?void 0:xe.call(k)),(fe=b.current)==null||fe.call(b,w);try{const le=Ue.notes_json?JSON.parse(Ue.notes_json):null;if(le!=null&&le.ublock_skipped||le!=null&&le.cookie_ext_skipped){const wt=le.ublock_skipped&&le.cookie_ext_skipped?"Captured without ad-blocking or cookie-consent extension. Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config.":le.ublock_skipped?"Captured without ad-blocking. ARCHIVR_UBLOCK=true but ARCHIVR_UBLOCK_EXT is not set or the path is invalid.":"Captured without cookie-consent extension. ARCHIVR_COOKIE_EXT is not set or the path is invalid.";_.current(wt,M,"warning"),ue(F,"warning",M)}else F||_.current(null,M,"success"),ue(F,"archived")}catch{F||_.current(null,M,"success"),ue(F,"archived")}}else if(Ue.status==="failed"){clearInterval(y.current.get(B)),y.current.delete(B),(we=b.current)==null||we.call(b,w);const le=Ue.error_text||"Capture failed.";_.current(le,M),ue(F,"failed",M)}}catch(Ue){clearInterval(y.current.get(B)),y.current.delete(B),(ce=b.current)==null||ce.call(b,w);const le=Ue.message||"Network error";_.current(le,M),ue(F,"failed",M)}},500);y.current.set(B,H)}function ue(w,B,M=null){if(!w)return;const I=h.current.get(w);if(!I||(B==="archived"||B==="warning"?(I.archived++,B==="warning"&&(I.warnings++,M&&I.warningLocators.push(M))):(I.failed++,M&&I.failedLocators.push(M)),I.archived+I.failed0?`${F} archived (${H} with warnings)`:`${F} archived`;ce=xe>0?`${wt}, ${xe} failed`:wt}const Ue=F===0?"error":xe>0||H>0?"warning":"success",le=[];fe.length>0&&le.push(`Failed: +${fe.map(wt=>` ${wt}`).join(` +`)}`),we.length>0&&le.push(`With warnings: +${we.map(wt=>` ${wt}`).join(` +`)}`);const dt=le.length>0?le.join(` +`):null;_.current(dt,null,Ue,ce)}async function Ee(w,B){var we,ce,Ue;const M=v.current,I=((we=crypto.randomUUID)==null?void 0:we.call(crypto))??`job-${Date.now()}-${Math.random()}`;if(w.type==="text"){try{const le=await qh(M,{title:w.title,body:w.body,mime:w.mime}),dt=`text:${w.title}`;(ce=E.current)==null||ce.call(E,{id:I,jobUid:le.job_uid,locator:dt,archiveId:M}),he(I,le.job_uid,dt,M,B)}catch(le){const dt=le.message||"Submission failed.";_.current(dt,`text:${w.title}`),ue(B,"failed",`text:${w.title}`)}return}const F=w.locator,H=w.quality,xe=w.extraExtensions||{},fe={ublock_enabled:ee,reader_mode:Re,cookie_ext_enabled:Ae,modal_closer_enabled:D,via_freedium:V,...xe};try{const le=await Qh(M,F,H,fe);(Ue=E.current)==null||Ue.call(E,{id:I,jobUid:le.job_uid,locator:F,archiveId:M}),he(I,le.job_uid,F,M,B)}catch(le){const dt=le.message||"Submission failed.";_.current(dt,F),ue(B,"failed",F),F.startsWith("file://")&&le.status&&hi(M,F).catch(()=>{})}}function Qe(){var I,F;if(j.some(H=>H.kind==="file"&&H.uploadStatus==="uploading"))return;const w=j.filter(H=>H.kind==="file"?H.uploadStatus==="done"&&H.uploadLocator:H.kind==="text"?H.title.trim()&&H.body.trim():H.locator.trim());if(w.length===0||w.some(H=>H.kind!=="file"&&H.kind!=="text"&&Eu(H))||w.some(H=>H.kind!=="file"&&H.kind!=="text"&&(H.probeState==="probing"||Ln(H.locator)&&H.playlistProbeState!=="done"))||w.some(H=>H.kind!=="file"&&H.kind!=="text"&&Array.isArray(H.playlistItems)&&H.playlistItems.length===0))return;const B=w.length>1?((I=crypto.randomUUID)==null?void 0:I.call(crypto))??`batch-${Date.now()}`:null;B&&h.current.set(B,{total:w.length,archived:0,warnings:0,failed:0,failedLocators:[],warningLocators:[]});const M=w.map(H=>H.kind==="file"?{type:"file",locator:H.uploadLocator,quality:"best",extraExtensions:{}}:H.kind==="text"?{type:"text",title:H.title.trim(),body:H.body.trim(),mime:H.mime}:{type:"url",locator:H.locator.trim(),quality:H.playlistItems!==null?null:H.quality||"best",extraExtensions:H.playlistItems!==null?{per_item_quality:Object.fromEntries(H.playlistItems.map(xe=>[xe.id,xe.quality])),sync:H.syncEnabled}:{}});f.current=!0,T([Wn()]),(F=u.current)==null||F.close(),M.forEach(H=>Ee(H,B))}function Et(){T(w=>[...w,Wn()])}function ut(w){var M;clearTimeout(g.current.get(w)),g.current.delete(w);const B=p.current.find(I=>I.id===w);(B==null?void 0:B.kind)==="file"&&(B.uploadStatus==="uploading"?((M=m.current.get(w))==null||M(),m.current.delete(w)):B.uploadStatus==="done"&&B.uploadLocator&&hi(v.current,B.uploadLocator).catch(()=>{})),T(I=>{const F=I.filter(H=>H.id!==w);return F.length===0?[Wn()]:F})}function Wt(w,B){if(clearTimeout(g.current.get(w)),T(M=>M.map(I=>I.id===w?{...I,locator:B,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best",playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1}:I)),Jd(B)){const M=setTimeout(async()=>{g.current.delete(w),T(I=>I.map(F=>F.id===w?{...F,probeState:"probing"}:F));try{const I=await Kh(v.current,B.trim());T(F=>F.map(H=>{if(H.id!==w||H.locator!==B)return H;const xe=I.qualities??[],fe=I.has_audio??!1,we=xe.length===0&&fe?"audio":"best";return{...H,probeState:"done",probeQualities:xe,probeHasAudio:fe,quality:we}}))}catch{T(I=>I.map(F=>F.id===w?{...F,probeState:"idle",probeQualities:null}:F))}},600);g.current.set(w,M)}else if(Ln(B)){const M=setTimeout(async()=>{g.current.delete(w),T(I=>I.map(F=>F.id===w?{...F,playlistProbeState:"probing"}:F));try{const I=await Xh(v.current,B.trim());T(F=>F.map(H=>H.id!==w||H.locator!==B?H:{...H,playlistProbeState:"done",playlistInfo:I,playlistItems:I.items.map(xe=>({...xe,quality:null})),playlistQuality:null}))}catch{T(I=>I.map(F=>F.id===w?{...F,playlistProbeState:"error"}:F))}},800);g.current.set(w,M)}}function ct(w,B){T(M=>M.map(I=>I.id===w?{...I,quality:B}:I))}function rt(w,B){T(M=>M.map(I=>{if(I.id!==w)return I;const F=Rm(B,I.playlistItems);return{...I,playlistQuality:B,playlistItems:F}}))}function xt(w,B,M){T(I=>I.map(F=>F.id!==w?F:{...F,playlistItems:F.playlistItems.map(H=>H.id===B?{...H,quality:M}:H)}))}function bt(w){T(B=>B.map(M=>M.id===w?{...M,playlistExpanded:!M.playlistExpanded}:M))}function A(w,B){T(M=>M.map(I=>I.id===w?{...I,syncEnabled:B}:I))}function q(w,B){T(M=>M.map(I=>I.id!==w?I:{...I,playlistItems:I.playlistItems.filter(F=>F.id!==B)}))}function de(w){const B=Array.from(w);B.length!==0&&B.forEach(M=>{const I=Pm(M.name);T(fe=>fe.length===1&&fe[0].kind!=="file"&&!fe[0].locator.trim()?[I]:[...fe,I]);const F=v.current,{promise:H,abort:xe}=_m(F,M,fe=>{T(we=>we.map(ce=>ce.id===I.id?{...ce,uploadProgress:fe}:ce))});m.current.set(I.id,xe),H.then(fe=>{m.current.delete(I.id),T(we=>we.map(ce=>ce.id===I.id?{...ce,uploadStatus:"done",uploadLocator:fe.locator,uploadProgress:100}:ce))}).catch(fe=>{m.current.delete(I.id),fe.message!=="Upload cancelled"&&T(we=>we.map(ce=>ce.id===I.id?{...ce,uploadStatus:"error",uploadError:fe.message}:ce))})})}function Be(w){w.preventDefault(),w.stopPropagation(),w.dataTransfer.types.includes("Files")&&N(!0)}function Dt(w){w.currentTarget.contains(w.relatedTarget)||N(!1)}function ze(w){w.preventDefault(),w.stopPropagation(),N(!1),de(w.dataTransfer.files)}function Bn(w){de(w.target.files),w.target.value=""}const _n=j.some(w=>w.kind==="file"&&w.uploadStatus==="uploading"),nn=j.filter(w=>w.kind==="file"?w.uploadStatus==="done"&&w.uploadLocator:w.kind==="text"?w.title.trim()&&w.body.trim():w.locator.trim()).length,qe=j.some(w=>w.kind!=="file"&&w.kind!=="text"&&Eu(w)),wr=j.some(w=>w.kind!=="file"&&w.kind!=="text"&&Array.isArray(w.playlistItems)&&w.playlistItems.length===0),Un=j.some(w=>w.kind!=="file"&&w.kind!=="text"&&(w.probeState==="probing"||Ln(w.locator)&&w.playlistProbeState!=="done"));return s.jsx("dialog",{ref:u,className:`capture-dialog${S?" capture-dialog--dragover":""}`,onDragOver:Be,onDragLeave:Dt,onDrop:ze,children:s.jsxs("div",{className:"capture-dialog-inner",children:[s.jsxs("div",{className:"capture-dialog-header",children:[s.jsx("h2",{className:"capture-dialog-title",children:"Capture"}),s.jsx("button",{type:"button",className:"capture-dialog-close",onClick:()=>{var w;return(w=u.current)==null?void 0:w.close()},"aria-label":"Close",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),s.jsx("div",{className:"capture-rows",children:j.map((w,B)=>w.kind==="file"?s.jsx($m,{item:w,onRemove:()=>ut(w.id)},w.id):w.kind==="text"?s.jsx(Dm,{item:w,autoFocus:B===j.length-1,onTitleChange:M=>T(I=>I.map(F=>F.id===w.id?{...F,title:M}:F)),onBodyChange:M=>T(I=>I.map(F=>F.id===w.id?{...F,body:M}:F)),onMimeChange:M=>T(I=>I.map(F=>F.id===w.id?{...F,mime:M}:F)),onRemove:()=>ut(w.id),onSubmit:Qe},w.id):s.jsx(Im,{item:w,autoFocus:B===j.length-1,onLocatorChange:M=>Wt(w.id,M),onQualityChange:M=>ct(w.id,M),onRemove:()=>ut(w.id),onSubmit:Qe,onPlaylistQualityChange:M=>rt(w.id,M),onPlaylistItemQualityChange:(M,I)=>xt(w.id,M,I),onPlaylistToggle:()=>bt(w.id),onSyncChange:M=>A(w.id,M),onPlaylistItemDelete:M=>q(w.id,M)},w.id))}),s.jsx("input",{ref:x,type:"file",multiple:!0,hidden:!0,onChange:Bn,"aria-hidden":"true",tabIndex:-1}),s.jsxs("div",{className:"capture-add-row-group",children:[s.jsxs("button",{type:"button",className:"capture-add-row",onClick:Et,children:[s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"8",y1:"2",x2:"8",y2:"14"}),s.jsx("line",{x1:"2",y1:"8",x2:"14",y2:"8"})]}),"Add URL"]}),s.jsxs("button",{type:"button",className:"capture-add-row capture-add-file",onClick:()=>{var w;return(w=x.current)==null?void 0:w.click()},children:[s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"3",y:"1",width:"10",height:"14",rx:"1.5"}),s.jsx("line",{x1:"5.5",y1:"5.5",x2:"10.5",y2:"5.5"}),s.jsx("line",{x1:"5.5",y1:"8",x2:"10.5",y2:"8"}),s.jsx("line",{x1:"5.5",y1:"10.5",x2:"8.5",y2:"10.5"})]}),"Upload file"]}),s.jsxs("button",{type:"button",className:"capture-add-row capture-add-text",onClick:()=>T(w=>[...w,Lm()]),children:[s.jsx("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M2 3h12M2 7h12M2 11h8"})}),"Add text"]})]}),s.jsxs("div",{className:"capture-advanced",children:[s.jsxs("button",{type:"button",className:"capture-advanced-toggle",onClick:()=>K(w=>!w),"aria-expanded":L,children:[s.jsx("svg",{className:`capture-chevron${L?" capture-chevron--open":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("polyline",{points:"4 6 8 10 12 6"})}),"Advanced options"]}),L&&s.jsxs("div",{className:"capture-advanced-panel",children:[s.jsxs("label",{className:"capture-ext-row",children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"capture-ext-desc",children:"Block ads during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":ee,className:`ext-toggle ext-toggle--sm${ee?" ext-toggle--on":""}`,onClick:()=>X(w=>w===null?!ee:!w),"aria-label":"Toggle uBlock for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Block cookie banners"}),s.jsx("span",{className:"capture-ext-desc",children:"Dismiss cookie consent banners during this capture"}),!(Z!=null&&Z.cookie_ext_available)&&s.jsxs("span",{className:"capture-ext-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":Ae,className:`ext-toggle ext-toggle--sm${Ae?" ext-toggle--on":""}`,onClick:()=>ye(w=>!w),"aria-label":"Toggle cookie banner blocking for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Reader mode"}),s.jsx("span",{className:"capture-ext-desc",children:"Distil to article text via Readability (off by default)"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":Re,className:`ext-toggle ext-toggle--sm${Re?" ext-toggle--on":""}`,onClick:()=>Y(w=>!w),"aria-label":"Toggle reader mode for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Close modals and dialogs"}),s.jsx("span",{className:"capture-ext-desc",children:"Auto-dismiss cookie banners and overlays during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":D,className:`ext-toggle ext-toggle--sm${D?" ext-toggle--on":""}`,onClick:()=>P(w=>!w),"aria-label":"Toggle modal closer for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Freedium mirror"}),s.jsx("span",{className:"capture-ext-desc",children:"Route paywalled articles through a Freedium mirror (Medium, NYT, WaPo, etc.)"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":V,className:`ext-toggle ext-toggle--sm${V?" ext-toggle--on":""}`,onClick:()=>te(w=>!w),"aria-label":"Toggle Freedium mirror for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]})]})]}),s.jsxs("div",{className:"capture-actions",children:[s.jsx("button",{type:"button",className:"capture-submit",onClick:Qe,disabled:nn===0||qe||Un||wr||_n,children:nn>1?`Archive ${nn}`:"Archive"}),s.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var w;return(w=u.current)==null?void 0:w.close()},children:"Cancel"})]})]})})}function Im({item:e,autoFocus:t,onLocatorChange:n,onQualityChange:r,onRemove:l,onSubmit:i,onPlaylistQualityChange:a,onPlaylistItemQualityChange:o,onPlaylistToggle:u,onSyncChange:c,onPlaylistItemDelete:y}){const g=d.useRef(null);d.useEffect(()=>{var x;t&&((x=g.current)==null||x.focus())},[t]);const h=(()=>{if(Ln(e.locator)){if(e.playlistProbeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Probing playlist…",children:"…"});if(e.playlistProbeState==="done"){const x=[...new Set(e.playlistItems.flatMap(p=>p.qualities.map(f=>parseInt(f))))].sort((p,f)=>f-p),S=e.playlistItems.every(p=>p.has_audio),N=e.playlistItems.filter(p=>p.quality===null).length;return s.jsxs(s.Fragment,{children:[s.jsxs("select",{className:"capture-quality",value:e.playlistQuality??"",onChange:p=>a(p.target.value),"aria-label":"Playlist quality",children:[!e.playlistQuality&&s.jsx("option",{value:"",disabled:!0,children:"Select quality…"}),s.jsx("option",{value:"best",children:"Best quality"}),x.map(p=>s.jsxs("option",{value:`${p}p`,children:[p,"p"]},p)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]}),N>0&&s.jsxs("span",{className:"capture-conflict-badge",children:[N," need selection"]})]})}return e.playlistProbeState==="error"?s.jsx("span",{className:"capture-quality-hint capture-quality-hint--error",children:"Probe failed — edit URL to retry"}):null}if(!Jd(e.locator))return null;if(e.probeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Checking available qualities",children:"…"});if(e.probeState==="done"){const x=e.probeQualities??[],S=e.probeHasAudio??!1;return x.length===0&&!S?s.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):x.length===0&&S?s.jsx("select",{className:"capture-quality",value:"audio",onChange:N=>r(N.target.value),"aria-label":"Video quality",children:s.jsx("option",{value:"audio",children:"Audio only"})}):s.jsxs("select",{className:"capture-quality",value:e.quality||"best",onChange:N=>r(N.target.value),"aria-label":"Video quality",children:[s.jsx("option",{value:"best",children:"Best quality"}),x.map(N=>s.jsx("option",{value:N,children:N},N)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]})}return null})(),v=Ln(e.locator)&&e.playlistProbeState==="done"?s.jsxs("label",{className:"capture-sync-row",children:[s.jsx("input",{type:"checkbox",checked:e.syncEnabled,onChange:x=>c(x.target.checked)}),s.jsx("span",{children:"Sync — skip already-archived videos"})]}):null;return s.jsxs("div",{className:"capture-row",children:[s.jsxs("div",{className:"capture-row-main",children:[Ln(e.locator)&&e.playlistProbeState==="done"?s.jsx("button",{type:"button",className:"capture-playlist-toggle capture-playlist-toggle--left",onClick:u,"aria-label":e.playlistExpanded?"Collapse video list":"Expand video list","aria-expanded":e.playlistExpanded,children:e.playlistExpanded?"▲":"▼"}):null,s.jsx("input",{ref:g,className:"capture-input",type:"text",placeholder:"https://… · yt:ID · ytm:ID · tweet:ID · x:ID",value:e.locator,onChange:x=>n(x.target.value),onKeyDown:x=>{x.key==="Enter"&&i()},autoComplete:"off",spellCheck:!1}),h,s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:l,"aria-label":"Remove",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),e.error&&s.jsx("p",{className:"capture-row-error",children:e.error}),Ln(e.locator)&&e.playlistProbeState==="done"&&e.playlistExpanded?s.jsxs("div",{className:"capture-playlist-items",children:[e.playlistItems.map(x=>s.jsxs("div",{className:`capture-playlist-item${x.quality===null?" capture-playlist-item--conflict":""}`,children:[s.jsx("span",{className:"capture-playlist-item-title",children:x.title||x.url}),s.jsxs("select",{className:"capture-item-quality",value:x.quality??"",onChange:S=>o(x.id,S.target.value),"aria-label":`Quality for ${x.title||x.url}`,children:[x.quality===null&&s.jsx("option",{value:"",disabled:!0,children:"Choose…"}),s.jsx("option",{value:"best",children:"Best quality"}),x.qualities.map(S=>s.jsx("option",{value:S,children:S},S)),x.has_audio&&s.jsx("option",{value:"audio",children:"Audio only"})]}),x.quality===null&&s.jsx("span",{className:"capture-playlist-conflict-badge",children:"Choose quality"}),s.jsx("button",{type:"button",className:"capture-playlist-item-remove","aria-label":`Remove ${x.title||x.url}`,onClick:()=>y(x.id),children:"×"})]},x.id)),v]}):v]})}function $m({item:e,onRemove:t}){const n=e.uploadStatus==="uploading",r=e.uploadStatus==="done",l=e.uploadStatus==="error";return s.jsxs("div",{className:"capture-row",children:[s.jsxs("div",{className:"capture-row-main",children:[s.jsx("span",{className:"capture-file-icon","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",style:{width:14,height:14},children:[s.jsx("rect",{x:"3",y:"1",width:"10",height:"14",rx:"1.5"}),s.jsx("line",{x1:"5.5",y1:"5.5",x2:"10.5",y2:"5.5"}),s.jsx("line",{x1:"5.5",y1:"8",x2:"10.5",y2:"8"}),s.jsx("line",{x1:"5.5",y1:"10.5",x2:"8.5",y2:"10.5"})]})}),s.jsx("span",{className:`capture-file-name${l?" capture-file-name--error":""}`,children:e.filename}),n&&s.jsxs("span",{className:"capture-file-progress-wrap","aria-label":`Uploading ${e.uploadProgress}%`,children:[s.jsx("span",{className:"capture-file-progress-bar",children:s.jsx("span",{className:"capture-file-progress-fill",style:{width:`${e.uploadProgress}%`}})}),s.jsxs("span",{className:"capture-file-progress-pct",children:[e.uploadProgress,"%"]})]}),r&&s.jsx("span",{className:"capture-file-badge capture-file-badge--done","aria-label":"Upload complete",children:s.jsx("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{width:11,height:11},children:s.jsx("polyline",{points:"3 8.5 6.5 12 13 5"})})}),l&&s.jsx("span",{className:"capture-file-badge capture-file-badge--error",children:"!"}),s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:t,"aria-label":"Remove",disabled:n,children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),l&&s.jsx("p",{className:"capture-row-error",children:e.uploadError||"Upload failed"})]})}function Dm({item:e,autoFocus:t,onTitleChange:n,onBodyChange:r,onMimeChange:l,onRemove:i,onSubmit:a}){const o=d.useRef(null);return d.useEffect(()=>{var u;t&&((u=o.current)==null||u.focus())},[t]),s.jsx("div",{className:"capture-row capture-text-row",children:s.jsxs("div",{className:"capture-row-main",children:[s.jsx("span",{className:"capture-text-icon","aria-hidden":"true",children:s.jsx("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",style:{width:14,height:14},children:s.jsx("path",{d:"M2 3h12M2 7h12M2 11h8"})})}),s.jsxs("div",{className:"capture-text-inputs",children:[s.jsx("input",{ref:o,className:"capture-text-input capture-text-title",type:"text",placeholder:"Title",value:e.title,onChange:u=>n(u.target.value),maxLength:500}),s.jsx("textarea",{className:"capture-text-input capture-text-body",placeholder:"Body (markdown or plain text)",value:e.body,onChange:u=>r(u.target.value),rows:6}),s.jsx("div",{className:"capture-text-footer",children:s.jsxs("select",{className:"capture-text-mime",value:e.mime,onChange:u=>l(u.target.value),children:[s.jsx("option",{value:"text/markdown",children:"Markdown"}),s.jsx("option",{value:"text/plain",children:"Plain text"})]})})]}),s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:i,"aria-label":"Remove",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]})})}function Om(){return s.jsxs("div",{className:"skeleton-row",children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:s.jsx("span",{className:"skeleton-cell",style:{width:108,height:13}})}),s.jsxs("div",{className:"col-title",style:{gap:"0.42em",display:"flex",alignItems:"center"},children:[s.jsx("span",{className:"skeleton-cell",style:{width:14,height:14,borderRadius:"50%",flexShrink:0}}),s.jsx("span",{className:"skeleton-cell",style:{width:"58%",height:13}})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"skeleton-cell",style:{width:58,height:20,borderRadius:99}})}),s.jsx("div",{className:"col-size",children:s.jsx("span",{className:"skeleton-cell",style:{width:44,height:12}})}),s.jsx("div",{className:"col-url",children:s.jsx("span",{className:"skeleton-cell",style:{width:"65%",height:12}})})]})}function dl(e){if(!e)return"0 B";const t=["B","KB","MB","GB"];let n=e,r=0;for(;n>=1024&&r").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}function pt(e){return Am(e)??""}function ao(e){if(!e)return"";const t=new Date(e);if(isNaN(t))return e;const n=r=>String(r).padStart(2,"0");return`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())} ${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}const bu={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function Os(e){return bu[e]??bu.other}function Gd(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function Mm({entry:e,index:t,onRowClick:n,selectedUids:r}){const l=(r==null?void 0:r.size)===1&&r.has(e.entry_uid),i=(r==null?void 0:r.size)>=2&&r.has(e.entry_uid),a=["child-entry-row",t%2===0?"child-entry-row--light":"child-entry-row--dark",l&&"is-selected",i&&"is-multi-selected"].filter(Boolean).join(" ");return s.jsxs("div",{className:a,tabIndex:0,"data-entry-uid":e.entry_uid,onMouseDown:o=>{o.shiftKey&&o.preventDefault()},onClick:o=>n(e,o),onKeyDown:o=>{o.key==="Enter"&&n(e,o)},children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:ao(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[s.jsx("span",{className:"source-icon",children:s.jsx("span",{dangerouslySetInnerHTML:{__html:Os(e.source_kind)}})}),s.jsx("span",{className:"entry-title",children:pt(e.title)||pt(e.entry_uid)})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:pt(e.entity_kind)})}),s.jsx("div",{className:"col-size",children:s.jsx("span",{className:"size-total",children:dl(e.total_artifact_bytes)})}),s.jsx("div",{className:"url-cell col-url",children:pt(e.original_url)})]})}function Fm({entry:e,archiveId:t,rowIndex:n,isSelected:r,isMultiSelected:l,onRowClick:i,selectedUids:a,deletedUids:o,isPublicSession:u}){const[c,y]=d.useState(!1),[g,h]=d.useState(!1),[v,x]=d.useState(null),[S,N]=d.useState(!1),f=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!c?s.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>y(!0),style:{objectFit:"contain"}}):s.jsx("span",{dangerouslySetInnerHTML:{__html:Os(e.source_kind)}}),m=r||l,k=e.child_count>0&&!u;function _(j){j.stopPropagation(),i(e,{ctrlKey:!0,metaKey:!1,shiftKey:!1,preventDefault(){}})}async function E(j){if(j.stopPropagation(),g){h(!1);return}if(h(!0),v===null&&!S){N(!0);try{const T=await Oh(t,e.entry_uid);x(T)}catch{x([])}finally{N(!1)}}}const b=["entry-row-outer",n%2===0?"entry-row-outer--light":"entry-row-outer--dark",r&&"is-selected",l&&"is-multi-selected"].filter(Boolean).join(" ");return s.jsxs("div",{className:b,"data-entry-uid":e.entry_uid,children:[s.jsxs("div",{className:"entry-row-main",tabIndex:0,onMouseDown:j=>{j.shiftKey&&j.preventDefault()},onClick:j=>i(e,j),onKeyDown:j=>{j.key==="Enter"&&i(e,j)},children:[s.jsx("div",{className:"col-check",children:s.jsx("button",{type:"button",className:`row-checkbox${m?" is-checked":""}`,"aria-pressed":m,"aria-label":m?"Deselect entry":"Select entry",onClick:_,onKeyDown:j=>j.stopPropagation()})}),s.jsx("div",{className:"col-added",children:ao(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[k&&s.jsx("button",{type:"button",className:`entry-expand-btn${g?" is-expanded":""}`,"aria-label":g?"Collapse children":`Expand ${e.child_count} items`,"aria-expanded":g,onClick:E,onKeyDown:j=>j.stopPropagation()}),s.jsx("span",{className:"source-icon",children:f}),s.jsx("span",{className:"entry-title",children:pt(e.title)||pt(e.entry_uid)}),k&&s.jsx("span",{className:"child-count-badge","aria-hidden":"true",children:e.child_count})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:pt(e.entity_kind)})}),s.jsxs("div",{className:"col-size",children:[s.jsx("span",{className:"size-total",children:dl(e.total_artifact_bytes)}),e.cached_bytes>0&&e.cacheable_bytes>0&&s.jsxs("span",{className:"size-cached-pct",title:`${dl(e.cached_bytes)} already on disk from an earlier entry`,children:[Math.round(e.cached_bytes/e.cacheable_bytes*100),"% cached"]})]}),s.jsx("div",{className:"url-cell col-url",children:pt(e.original_url)})]}),g&&s.jsxs(s.Fragment,{children:[S&&s.jsx("div",{className:"child-entries-loading",children:"Loading…"}),s.jsx("div",{className:"child-entries","aria-label":`${e.child_count} child entries`,children:v&&v.filter(j=>!(o!=null&&o.has(j.entry_uid))).map((j,T)=>s.jsx(Mm,{entry:j,index:T,onRowClick:i,selectedUids:a},j.entry_uid))})]})]})}function Bm({entries:e,selectedUids:t,onRowClick:n,archiveId:r,pendingCaptures:l=[],deletedUids:i,isPublicSession:a}){return s.jsx("section",{id:"archive-view",className:"view is-active",children:s.jsxs("div",{className:"entry-table",children:[s.jsxs("div",{className:"entry-header-row",children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:"Added"}),s.jsx("div",{className:"col-title",children:"Title"}),s.jsx("div",{className:"col-type",children:"Type"}),s.jsx("div",{className:"col-size",children:"Size"}),s.jsx("div",{className:"col-url",children:"Original URL"})]}),s.jsxs("div",{id:"entries-body",children:[l.filter(o=>o.archiveId===r).reverse().map(o=>s.jsx(Om,{},o.id)),e.map((o,u)=>s.jsx(Fm,{entry:o,rowIndex:u,archiveId:r,isSelected:t.size===1&&t.has(o.entry_uid),isMultiSelected:t.size>=2&&t.has(o.entry_uid),onRowClick:n,selectedUids:t,deletedUids:i,isPublicSession:a},o.entry_uid))]})]})})}function Um(e){if(!e)return"—";try{return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return e}}function Hm({status:e}){const t=e==="completed"?"run-status--completed":e==="failed"?"run-status--failed":e==="in_progress"?"run-status--in-progress":"",n=e?e.replace(/_/g," "):"—";return s.jsx("span",{className:`run-status ${t}`,children:n})}function Wm({runs:e}){const[t,n]=d.useState(null);function r(l){n(i=>i===l?null:l)}return s.jsx("section",{id:"runs-view",className:"view is-active",children:s.jsxs("table",{className:"entry-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Started"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Requested"}),s.jsx("th",{children:"Completed"}),s.jsx("th",{children:"Failed"})]})}),s.jsx("tbody",{children:e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:5,style:{color:"var(--muted)",padding:"24px 16px",textAlign:"center"},children:"No runs yet."})}):e.map(l=>{const i=l.status==="failed"&&l.error_summary,a=t===l.run_uid;return[s.jsxs("tr",{className:i?"run-row run-row--failed":"run-row",onClick:i?()=>r(l.run_uid):void 0,title:i?a?"Click to hide error":"Click to view error":void 0,children:[s.jsx("td",{children:Um(l.started_at)}),s.jsxs("td",{children:[s.jsx(Hm,{status:l.status}),i&&s.jsx("span",{className:"run-expand-hint","aria-hidden":"true",children:a?"▴":"▾"})]}),s.jsx("td",{children:l.requested_count??"—"}),s.jsx("td",{children:l.completed_count??"—"}),s.jsx("td",{children:l.failed_count??"—"})]},l.run_uid),i&&a&&s.jsx("tr",{className:"run-error-row",children:s.jsx("td",{colSpan:5,children:s.jsx("pre",{className:"run-error-detail",children:l.error_summary})})},`${l.run_uid}-detail`)]})})]})})}const Vm=4;function Qm({archives:e}){const{currentUser:t}=d.useContext(As)??{},n=t&&(t.role_bits&Vm)!==0,[r,l]=d.useState("users"),[i,a]=d.useState([]),[o,u]=d.useState([]),[c,y]=d.useState(!1),[g,h]=d.useState(null),[v,x]=d.useState(""),[S,N]=d.useState(""),[p,f]=d.useState(""),[m,k]=d.useState(null),[_,E]=d.useState(!1),[b,j]=d.useState(""),[T,L]=d.useState(""),[K,U]=d.useState(null),[X,Z]=d.useState(!1),oe=d.useCallback(async()=>{if(n){y(!0),h(null);try{const[P,V]=await Promise.all([am(),cm()]);a(P),u(V)}catch(P){h(P.message)}finally{y(!1)}}},[n]);d.useEffect(()=>{oe()},[oe]);async function Ae(P){const V=P.status==="active"?"disabled":"active";try{await um(P.user_uid,V),a(te=>te.map(ee=>ee.user_uid===P.user_uid?{...ee,status:V}:ee))}catch(te){h(te.message)}}async function ye(P){if(P.preventDefault(),!v.trim()||!S){k("Username and password required");return}E(!0),k(null);try{await om(v.trim(),S,p.trim()||void 0),x(""),N(""),f(""),await oe()}catch(V){k(V.message)}finally{E(!1)}}async function D(P){if(P.preventDefault(),!b.trim()||!T.trim()){U("Slug and name required");return}Z(!0),U(null);try{await dm(b.trim(),T.trim()),j(""),L(""),await oe()}catch(V){U(V.message)}finally{Z(!1)}}return n?s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsxs("div",{className:"view-tabs",children:[s.jsx("button",{className:`view-tab${r==="users"?" is-active":""}`,onClick:()=>l("users"),children:"Users"}),s.jsx("button",{className:`view-tab${r==="roles"?" is-active":""}`,onClick:()=>l("roles"),children:"Roles"}),s.jsx("button",{className:`view-tab${r==="archives"?" is-active":""}`,onClick:()=>l("archives"),children:"Archives"})]}),g&&s.jsx("div",{className:"form-msg form-msg--err",children:g}),r==="users"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Users"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Username"}),s.jsx("th",{children:"Email"}),s.jsx("th",{children:"Roles"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:i.map(P=>s.jsxs("tr",{className:P.status==="disabled"?"admin-row-disabled":"",children:[s.jsx("td",{children:P.username}),s.jsx("td",{className:"muted",children:P.email||"—"}),s.jsx("td",{children:P.role_slugs.join(", ")||"—"}),s.jsx("td",{children:s.jsx("span",{className:`status-badge status-${P.status}`,children:P.status})}),s.jsx("td",{children:s.jsx("button",{className:"admin-action-btn",onClick:()=>Ae(P),children:P.status==="active"?"Ban":"Unban"})})]},P.user_uid))})]}),s.jsx("h3",{children:"Create User"}),s.jsxs("form",{className:"admin-form",onSubmit:ye,children:[s.jsx("input",{className:"admin-input",placeholder:"Username",value:v,onChange:P=>x(P.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:S,onChange:P=>N(P.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:p,onChange:P=>f(P.target.value)}),m&&s.jsx("div",{className:"form-msg form-msg--err",children:m}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:_,children:_?"Creating…":"Create User"})]})]}),r==="roles"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Roles"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Slug"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Level"}),s.jsx("th",{children:"Bit"}),s.jsx("th",{children:"Built-in"})]})}),s.jsx("tbody",{children:o.map(P=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:P.slug})}),s.jsx("td",{children:P.name}),s.jsx("td",{children:P.level}),s.jsx("td",{children:P.bit_position}),s.jsx("td",{children:P.is_builtin?"✓":""})]},P.role_uid))})]}),s.jsx("h3",{children:"Create Custom Role"}),s.jsxs("form",{className:"admin-form",onSubmit:D,children:[s.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:b,onChange:P=>j(P.target.value),required:!0}),s.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:T,onChange:P=>L(P.target.value),required:!0}),K&&s.jsx("div",{className:"form-msg form-msg--err",children:K}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:X,children:X?"Creating…":"Create Role"})]})]}),r==="archives"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(P=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:P.label}),s.jsx("div",{className:"muted",children:P.archive_path})]},P.id))})]})]}):s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsx("p",{className:"muted",children:"You need admin privileges to access this panel."}),s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(P=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:P.label}),s.jsx("div",{className:"muted",children:P.archive_path})]},P.id))})]})}function Yd({node:e,onPick:t}){var n;return s.jsxs("li",{children:[s.jsx("button",{className:"tag-picker-node-btn",title:e.tag.full_path,onClick:()=>t(e.tag),children:e.tag.slug}),((n=e.children)==null?void 0:n.length)>0&&s.jsx("div",{className:"tag-children",children:s.jsx("ul",{className:"tag-tree-list",children:e.children.map(r=>s.jsx(Yd,{node:r,onPick:t},r.tag.tag_uid))})})]})}function Tu({title:e,tagNodes:t,excludeUid:n,onPick:r,onCancel:l}){d.useEffect(()=>{function o(u){u.key==="Escape"&&(u.preventDefault(),u.stopPropagation(),l())}return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[l]);function i(o){return o.filter(u=>u.tag.tag_uid!==n).map(u=>({...u,children:i(u.children)}))}const a=n?i(t):t;return s.jsx("div",{className:"tag-picker-backdrop",onClick:o=>{o.target===o.currentTarget&&l()},children:s.jsxs("div",{className:"tag-picker-modal",role:"dialog","aria-modal":"true",children:[s.jsxs("div",{className:"tag-picker-header",children:[s.jsx("span",{className:"tag-picker-title",children:e}),s.jsx("button",{className:"tag-picker-close",onClick:l,title:"Cancel","aria-label":"Cancel",children:"×"})]}),s.jsxs("div",{className:"tag-picker-body",children:[s.jsx("button",{className:"tag-picker-root-btn",onClick:()=>r(null),title:"Place at root level (no parent)",children:"↑ Root tag (no parent)"}),a.length>0?s.jsx("ul",{className:"tag-tree-list tag-picker-tree",children:a.map(o=>s.jsx(Yd,{node:o,onPick:r},o.tag.tag_uid))}):s.jsx("p",{className:"tag-picker-empty",children:"No other tags available."})]})]})})}function Zd({parentPath:e,archiveId:t,onDone:n,onCancel:r}){const[l,i]=d.useState(""),a=d.useRef(!1);async function o(){const u=l.trim();if(!u){r();return}const c=e?`${e}/${u}`:`/${u}`;try{await Wh(t,c),n()}catch(y){alert(y.message||"Create failed"),r()}}return s.jsx("input",{className:"tag-rename-input",autoFocus:!0,placeholder:"tag name",value:l,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&u.currentTarget.blur(),u.key==="Escape"&&(a.current=!0,u.currentTarget.blur())},onBlur:()=>{a.current?(a.current=!1,r()):o()}})}function ef({node:e,archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:y,pendingCreateParentUid:g,onCreateDone:h,onCreateCancel:v}){var K;const x=n===e.tag.full_path,[S,N]=d.useState(!1),[p,f]=d.useState(""),m=d.useRef(!1);function k(){if(S)return;if(c){y(e);return}const U=x?null:e.tag.full_path;r(U),l("archive")}function _(U){U.stopPropagation(),!c&&(f(e.tag.slug),N(!0))}async function E(){const U=p.trim();if(!U||U===e.tag.slug){N(!1);return}try{const X=await Uh(t,e.tag.tag_uid,U);i(e.tag.full_path,X.full_path),o()}catch{}finally{N(!1)}}async function b(U){var Z;U.stopPropagation();const X=((Z=e.children)==null?void 0:Z.length)>0?`Delete tag "${e.tag.full_path}" and all its child tags? This cannot be undone.`:`Delete tag "${e.tag.full_path}"? This cannot be undone.`;if(window.confirm(X))try{await Hh(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const j={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:y,pendingCreateParentUid:g,onCreateDone:h,onCreateCancel:v},T=g===e.tag.tag_uid,L=((K=e.children)==null?void 0:K.length)>0;return s.jsxs("li",{children:[s.jsxs("div",{className:`tag-node-row${c?" tag-node-row--move-select":""}`,children:[S?s.jsx("input",{className:"tag-rename-input",autoFocus:!0,value:p,onChange:U=>f(U.target.value),onKeyDown:U=>{U.key==="Enter"&&U.currentTarget.blur(),U.key==="Escape"&&(m.current=!0,U.currentTarget.blur())},onBlur:()=>{m.current?(m.current=!1,N(!1)):E()}}):s.jsxs("button",{className:`tag-node-btn${x?" is-active":""}${c?" tag-node-btn--move-select":""}`,title:c?`Select "${e.tag.full_path}" to move`:e.tag.full_path,onClick:k,onDoubleClick:c?void 0:_,children:[s.jsx("span",{className:"tag-node-label",children:u?e.tag.name:e.tag.slug}),s.jsx("span",{className:"tag-node-count",children:e.children.length===0?`(${e.entry_count})`:`(${e.entry_count}) (${e.subtree_count} Total)`}),!c&&s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",title:"Rename tag",onClick:U=>{U.stopPropagation(),_(U)},children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),!S&&!c&&s.jsx("button",{className:"remove tag-node-delete",title:`Delete "${e.tag.full_path}"`,onClick:b,"aria-label":`Delete "${e.tag.full_path}"`,children:"×"})]}),(L||T)&&s.jsx("div",{className:"tag-children",children:s.jsxs("ul",{className:"tag-tree-list",children:[e.children.map(U=>s.jsx(ef,{node:U,...j},U.tag.tag_uid)),T&&s.jsx("li",{children:s.jsx(Zd,{parentPath:e.tag.full_path,archiveId:t,onDone:h,onCancel:v})})]})})]})}function qm({archiveId:e,tagNodes:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u}){const[c,y]=d.useState(null),[g,h]=d.useState(null);function v(){y("select-source"),h(null)}function x(){y(null),h(null)}d.useEffect(()=>{if(c!=="select-source")return;function X(Z){Z.key==="Escape"&&(Z.preventDefault(),Z.stopPropagation(),x())}return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[c]);function S(X){h(X),y("select-dest")}async function N(X){const Z=g.tag.full_path,oe=g.tag.tag_uid,Ae=(X==null?void 0:X.tag_uid)??null;x();try{const ye=await Vh(e,oe,Ae);i(Z,ye.full_path),o()}catch(ye){alert(ye.message||"Move failed")}}const[p,f]=d.useState(null),[m,k]=d.useState(void 0);function _(){f("select-parent"),k(void 0)}function E(){f(null),k(void 0)}function b(X){k(X??null),f("input")}function j(){f(null),k(void 0),o()}const T=c==="select-source",L=p==="input"?m?m.tag_uid:"__root__":void 0,K={archiveId:e,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:T,onMoveSourceSelect:S,pendingCreateParentUid:L,onCreateDone:j,onCreateCancel:E},U=L==="__root__";return s.jsxs("section",{id:"tags-view",className:"view is-active",children:[s.jsxs("div",{className:"tag-tree",children:[s.jsx("div",{className:"tag-tree-header",children:T?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title tag-tree-title--move",children:"Select a tag to move"}),s.jsx("button",{className:"tag-tree-action-btn tag-tree-action-btn--cancel",onClick:x,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title",children:"Tags"}),n&&s.jsxs("span",{className:"tag-tree-active",title:n,children:["Filtering: ",n]}),s.jsxs("div",{className:"tag-tree-actions",children:[s.jsx("button",{className:"tag-tree-action-btn",onClick:_,title:"Create a new tag",disabled:!!p||!!c,children:"+ New"}),s.jsx("button",{className:"tag-tree-action-btn",onClick:v,title:"Move a tag to a different parent",disabled:!!p||!!c||t.length===0,children:"Move"})]})]})}),t.length===0&&!U?s.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):s.jsxs("ul",{className:"tag-tree-list",children:[t.map(X=>s.jsx(ef,{node:X,...K},X.tag.tag_uid)),U&&s.jsx("li",{children:s.jsx(Zd,{parentPath:null,archiveId:e,onDone:j,onCancel:E})})]})]}),p==="select-parent"&&s.jsx(Tu,{title:"Create tag under…",tagNodes:t,excludeUid:null,onPick:b,onCancel:E}),c==="select-dest"&&g&&s.jsx(Tu,{title:`Move "${g.tag.slug}" under…`,tagNodes:t,excludeUid:g.tag.tag_uid,onPick:N,onCancel:x})]})}const Or=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],Km=e=>{var t;return((t=Or.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function Xm({archiveId:e}){const[t,n]=d.useState([]),[r,l]=d.useState(!1),[i,a]=d.useState(null),[o,u]=d.useState(null),[c,y]=d.useState(null),[g,h]=d.useState(!1),[v,x]=d.useState(null),[S,N]=d.useState(""),[p,f]=d.useState(""),[m,k]=d.useState(2),[_,E]=d.useState(!1),[b,j]=d.useState(!0),[T,L]=d.useState(null),[K,U]=d.useState(""),[X,Z]=d.useState(2),[oe,Ae]=d.useState(!1),[ye,D]=d.useState(null),[P,V]=d.useState(!1),[te,ee]=d.useState(""),Re=d.useRef(null),Y=t.find(A=>A.collection_uid===o)??null,he=(Y==null?void 0:Y.slug)==="_default_",ue=d.useCallback(async()=>{if(e){l(!0),a(null);try{const A=await io(e);n(A)}catch(A){a(A.message)}finally{l(!1)}}},[e]),Ee=d.useCallback(async A=>{if(!A){y(null);return}h(!0),x(null);try{const q=await pm(e,A);y(q)}catch(q){x(q.message)}finally{h(!1)}},[e]);d.useEffect(()=>{ue()},[ue]),d.useEffect(()=>{Ee(o)},[o,Ee]),d.useEffect(()=>{P&&Re.current&&Re.current.focus()},[P]),d.useEffect(()=>{c!=null&&Z(c.default_visibility_bits)},[c]);async function Qe(A){A.preventDefault();const q=S.trim(),de=p.trim();if(!(!q||!de)){E(!0),L(null);try{const Be=await fm(e,q,de,m,b);N(""),f(""),k(2),j(!0),await ue(),u(Be.collection_uid)}catch(Be){L(Be.message)}finally{E(!1)}}}async function Et(){const A=te.trim();if(!A||!Y){V(!1);return}try{await pi(e,Y.collection_uid,{name:A}),await ue(),y(q=>q&&{...q,name:A})}catch(q){a(q.message)}finally{V(!1)}}async function ut(A){if(Y)try{await pi(e,Y.collection_uid,{default_visibility_bits:A}),await ue(),y(q=>q&&{...q,default_visibility_bits:A})}catch(q){a(q.message)}}async function Wt(A){if(Y)try{await pi(e,Y.collection_uid,{requires_auth:A}),await ue(),y(q=>q&&{...q,requires_auth:A})}catch(q){a(q.message)}}async function ct(){if(Y&&window.confirm(`Delete collection "${Y.name}"? Entries will not be deleted.`))try{await gm(e,Y.collection_uid),u(null),y(null),await ue()}catch(A){a(A.message)}}async function rt(A){A.preventDefault();const q=K.trim();if(!(!q||!Y)){Ae(!0),D(null);try{await ca(e,Y.collection_uid,q,X),U(""),await Ee(Y.collection_uid)}catch(de){D(de.message)}finally{Ae(!1)}}}async function xt(A){if(Y)try{await hm(e,Y.collection_uid,A),await Ee(Y.collection_uid)}catch(q){x(q.message)}}async function bt(A,q){if(Y)try{await mm(e,Y.collection_uid,A,q),y(de=>de&&{...de,entries:de.entries.map(Be=>Be.entry_uid===A?{...Be,collection_visibility_bits:q}:Be)})}catch(de){x(de.message)}}return e?s.jsxs("div",{className:"collections-view",children:[s.jsx("h2",{className:"collections-heading",children:"Collections"}),r&&s.jsx("div",{className:"muted",children:"Loading…"}),i&&s.jsxs("div",{className:"collections-error",children:[i," ",s.jsx("button",{onClick:()=>a(null),className:"coll-dismiss",children:"×"})]}),s.jsxs("div",{className:"collections-layout",children:[s.jsxs("div",{className:"collections-sidebar",children:[t.map(A=>s.jsxs("button",{className:`coll-sidebar-row${o===A.collection_uid?" is-active":""}`,onClick:()=>u(A.collection_uid),children:[s.jsx("span",{className:"coll-row-name",children:A.name}),s.jsx("span",{className:"coll-row-meta",children:Km(A.default_visibility_bits)})]},A.collection_uid)),t.length===0&&!r&&s.jsx("div",{className:"muted",style:{padding:"8px 12px"},children:"No collections yet."})]}),Y?s.jsxs("div",{className:"coll-detail",children:[s.jsxs("div",{className:"coll-detail-header",children:[P?s.jsx("input",{ref:Re,className:"coll-rename-input",value:te,onChange:A=>ee(A.target.value),onBlur:Et,onKeyDown:A=>{A.key==="Enter"&&Et(),A.key==="Escape"&&V(!1)}}):s.jsxs("h3",{className:`coll-detail-name${he?"":" coll-detail-name--editable"}`,title:he?void 0:"Click to rename",onClick:()=>{he||(ee(Y.name),V(!0))},children:[(c==null?void 0:c.name)??Y.name,!he&&s.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!he&&s.jsx("button",{className:"coll-delete-btn",onClick:ct,title:"Delete collection",children:"Delete"})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Entries' default visibility"}),s.jsx("select",{className:"coll-vis-select",value:(c==null?void 0:c.default_visibility_bits)??Y.default_visibility_bits,onChange:A=>ut(Number(A.target.value)),children:Or.map(A=>s.jsx("option",{value:A.value,children:A.label},A.value))})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Collection access"}),s.jsxs("label",{className:"coll-auth-label",children:[s.jsx("input",{type:"checkbox",checked:!!((c==null?void 0:c.requires_auth)??Y.requires_auth),onChange:A=>Wt(A.target.checked)})," Require authentication to view"]})]}),s.jsxs("div",{className:"coll-entries-section",children:[s.jsx("div",{className:"coll-section-heading",children:"Entries"}),g&&s.jsx("div",{className:"muted",children:"Loading…"}),v&&s.jsx("div",{className:"collections-error",children:v}),!g&&c&&(c.entries.length===0?s.jsx("div",{className:"muted",children:"No entries in this collection."}):s.jsx("ul",{className:"coll-entries-list",children:c.entries.map(A=>s.jsxs("li",{className:"coll-entry-row",children:[s.jsxs("div",{className:"coll-entry-info",children:[s.jsx("span",{className:"coll-entry-title",children:A.title||A.entry_uid}),s.jsx("span",{className:"coll-entry-kind muted",children:A.source_kind})]}),s.jsxs("div",{className:"coll-entry-actions",children:[s.jsx("select",{className:"coll-entry-vis-select",value:A.collection_visibility_bits,onChange:q=>bt(A.entry_uid,Number(q.target.value)),children:Or.map(q=>s.jsx("option",{value:q.value,children:q.label},q.value))}),!he&&s.jsx("button",{className:"coll-entry-remove",onClick:()=>xt(A.entry_uid),title:"Remove from collection",children:"×"})]})]},A.entry_uid))}))]}),!he&&s.jsxs("form",{className:"coll-add-entry-form",onSubmit:rt,children:[s.jsx("div",{className:"coll-section-heading",children:"Add entry"}),s.jsxs("div",{className:"coll-add-entry-row",children:[s.jsx("input",{className:"coll-add-entry-input",type:"text",value:K,onChange:A=>U(A.target.value),placeholder:"entry_uid",required:!0}),s.jsx("select",{className:"coll-vis-select",value:X,onChange:A=>Z(Number(A.target.value)),children:Or.map(A=>s.jsx("option",{value:A.value,children:A.label},A.value))}),s.jsx("button",{className:"coll-add-btn",type:"submit",disabled:oe,children:oe?"…":"Add"})]}),ye&&s.jsx("div",{className:"collections-error",style:{marginTop:4},children:ye})]})]}):s.jsx("div",{className:"coll-detail coll-detail--empty",children:s.jsx("div",{className:"muted",children:"Select a collection to view details."})})]}),s.jsxs("details",{className:"coll-create-details",children:[s.jsx("summary",{children:"+ Create collection"}),s.jsxs("form",{className:"coll-create-form",onSubmit:Qe,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-name",children:"Name"}),s.jsx("input",{className:"capture-input",id:"coll-name",type:"text",value:S,onChange:A=>{N(A.target.value),p||f(A.target.value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""))},placeholder:"My Collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-slug",children:"Slug"}),s.jsx("input",{className:"capture-input",id:"coll-slug",type:"text",value:p,onChange:A=>f(A.target.value),placeholder:"my-collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-vis",children:"Entries' default visibility"}),s.jsx("select",{className:"capture-input",id:"coll-vis",style:{height:42},value:m,onChange:A=>k(Number(A.target.value)),children:Or.map(A=>s.jsx("option",{value:A.value,children:A.label},A.value))})]}),s.jsx("div",{className:"form-field",children:s.jsxs("label",{className:"form-label",children:[s.jsx("input",{type:"checkbox",checked:b,onChange:A=>j(A.target.checked)})," Require authentication to view"]})}),T&&s.jsx("div",{className:"collections-error",children:T}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:_,children:_?"Creating…":"Create collection"})]})]})]}):s.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const Jm=4;function Gm({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=d.useContext(As)??{},i=r&&(r.role_bits&Jm)!==0,a=["profile","tokens",...i?["instance","cookies","extensions","storage"]:[]],o={profile:"Profile",tokens:"API Tokens",instance:"Instance",cookies:"Cookies",extensions:"Extensions",storage:"Storage"};return s.jsxs("section",{className:"admin-view",children:[s.jsx("h1",{children:"Settings"}),s.jsx("div",{className:"view-tabs",children:a.map(u=>s.jsx("button",{className:`view-tab${e===u?" is-active":""}`,onClick:()=>t(u),children:o[u]},u))}),e==="profile"&&s.jsx(Ym,{currentUser:r,setCurrentUser:l}),e==="tokens"&&s.jsx(Zm,{}),e==="instance"&&i&&s.jsx(eg,{}),e==="cookies"&&i&&s.jsx(ng,{}),e==="extensions"&&i&&s.jsx(rg,{}),e==="storage"&&i&&s.jsx(tg,{archiveId:n})]})}function Ym({currentUser:e,setCurrentUser:t}){const[n,r]=d.useState((e==null?void 0:e.display_name)??""),[l,i]=d.useState(!1),[a,o]=d.useState(null),[u,c]=d.useState(""),[y,g]=d.useState(""),[h,v]=d.useState(""),[x,S]=d.useState(!1),[N,p]=d.useState(null);async function f(k){k.preventDefault(),i(!0),o(null);try{await tm(n),t(_=>({..._,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(_){o({ok:!1,text:_.message})}finally{i(!1)}}async function m(k){if(k.preventDefault(),y!==h){p({ok:!1,text:"Passwords do not match."});return}S(!0),p(null);try{await rm(u,y),c(""),g(""),v(""),p({ok:!0,text:"Password changed."})}catch(_){p({ok:!1,text:_.message})}finally{S(!1)}}return s.jsxs("div",{style:{maxWidth:440},children:[s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Name"}),s.jsxs("form",{onSubmit:f,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"display-name",children:"Name shown in the UI"}),s.jsx("input",{className:"field-input",id:"display-name",placeholder:(e==null?void 0:e.username)??"",value:n,onChange:k=>r(k.target.value)})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:l,children:l?"Saving…":"Save"})]})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Preferences"}),s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:(e==null?void 0:e.humanize_slugs)??!1,onChange:async k=>{const _=k.target.checked;try{await nm({humanize_slugs:_}),t(E=>({...E,humanize_slugs:_}))}catch{}}}),s.jsx("span",{className:"form-label",style:{margin:0},children:"Humanize tag display"})]}),s.jsx("p",{className:"muted",style:{fontSize:13,margin:"4px 0 0"},children:'When on, tag paths show as "X / Articles" instead of "x/articles".'})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Change Password"}),s.jsxs("form",{onSubmit:m,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"cur-pw",children:"Current password"}),s.jsx("input",{className:"field-input",id:"cur-pw",type:"password",value:u,onChange:k=>c(k.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"new-pw",children:"New password"}),s.jsx("input",{className:"field-input",id:"new-pw",type:"password",value:y,onChange:k=>g(k.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"confirm-pw",children:"Confirm new password"}),s.jsx("input",{className:"field-input",id:"confirm-pw",type:"password",value:h,onChange:k=>v(k.target.value),required:!0})]}),N&&s.jsx("div",{className:`form-msg form-msg--${N.ok?"ok":"err"}`,children:N.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Changing…":"Change Password"})]})]})]})}function Zm(){const[e,t]=d.useState([]),[n,r]=d.useState(!0),[l,i]=d.useState(null),[a,o]=d.useState(""),[u,c]=d.useState(!1),[y,g]=d.useState(null),h=d.useCallback(async()=>{r(!0),i(null);try{t(await lm())}catch(S){i(S.message)}finally{r(!1)}},[]);d.useEffect(()=>{h()},[h]);async function v(S){if(S.preventDefault(),!!a.trim()){c(!0);try{const N=await sm(a.trim());g(N),o(""),h()}catch(N){i(N.message)}finally{c(!1)}}}async function x(S){try{await im(S),t(N=>N.filter(p=>p.token_uid!==S))}catch(N){i(N.message)}}return s.jsx("div",{style:{maxWidth:600},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"API Tokens"}),y&&s.jsxs("div",{className:"token-banner",children:[s.jsx("strong",{children:"Token created."})," Copy it now — it won't be shown again.",s.jsx("code",{children:y.raw_token}),s.jsx("button",{className:"token-dismiss",onClick:()=>g(null),children:"Dismiss"})]}),s.jsxs("form",{className:"token-create-row",onSubmit:v,children:[s.jsx("input",{className:"field-input field-input--flex",placeholder:"Token name",value:a,onChange:S=>o(S.target.value),required:!0}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:u,children:u?"Creating…":"Create token"})]}),l&&s.jsx("div",{className:"form-msg form-msg--err",children:l}),n?s.jsx("div",{className:"muted",children:"Loading…"}):s.jsxs("div",{children:[e.length===0&&s.jsx("div",{className:"muted",children:"No tokens yet."}),e.map(S=>s.jsxs("div",{className:"token-row",children:[s.jsxs("div",{className:"token-row-info",children:[s.jsx("strong",{children:S.name}),s.jsxs("div",{className:"muted",children:["Created ",S.created_at.slice(0,10),S.last_used_at&&` · Last used ${S.last_used_at.slice(0,10)}`]})]}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"4px 10px"},onClick:()=>x(S.token_uid),children:"Revoke"})]},S.token_uid))]})]})})}function eg(){const[e,t]=d.useState(null),[n,r]=d.useState(!0),[l,i]=d.useState(null),[a,o]=d.useState(!1),[u,c]=d.useState(null);d.useEffect(()=>{(async()=>{try{t(await so())}catch(g){i(g.message)}finally{r(!1)}})()},[]);async function y(g){g.preventDefault(),o(!0),c(null);try{await Xl(e),c({ok:!0,text:"Saved."})}catch(h){c({ok:!1,text:h.message})}finally{o(!1)}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):e?s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Instance Settings"}),s.jsxs("form",{onSubmit:y,children:[[["public_index_enabled","Public index (unauthenticated browsing)"],["public_entry_content_enabled","Public entry content"],["open_registration_enabled","Open registration"]].map(([g,h])=>s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:!!e[g],onChange:v=>t(x=>({...x,[g]:v.target.checked}))}),h]},g)),s.jsxs("div",{className:"form-field",style:{marginTop:4},children:[s.jsx("label",{className:"form-label",children:"Default entry visibility"}),s.jsxs("select",{className:"field-input",value:e.default_entry_visibility,onChange:g=>t(h=>({...h,default_entry_visibility:Number(g.target.value)})),children:[s.jsx("option",{value:0,children:"Private"}),s.jsx("option",{value:2,children:"Unlisted"}),s.jsx("option",{value:3,children:"Public"})]})]}),u&&s.jsx("div",{className:`form-msg form-msg--${u.ok?"ok":"err"}`,children:u.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:a,children:a?"Saving…":"Save Settings"})]})]})}):null}function mi(e){if(e===0)return"0 B";const t=["B","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(1024));return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function tg({archiveId:e}){const[t,n]=d.useState("idle"),[r,l]=d.useState(null),[i,a]=d.useState(null),[o,u]=d.useState(null);function c(){n("idle"),l(null),a(null),u(null)}async function y(){n("scanning"),u(null),l(null);try{const v=await ym(e);l(v),n("scanned")}catch(v){u(v.message),n("error")}}async function g(){n("deleting"),u(null);try{const v=await vm(e);a(v),n("done")}catch(v){u(v.message),n("error")}}const h=r&&r.deletable_files===0&&r.orphaned_blob_rows===0;return s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Orphan Cleanup"}),s.jsxs("p",{className:"muted",style:{marginBottom:16},children:["Scan for blob files and database records that are no longer referenced by any archive entry and safely delete them."," ",s.jsx("strong",{children:"Cleanup is blocked while captures are running."})]}),!e&&s.jsx("div",{className:"muted",children:"No archive selected."}),e&&t==="idle"&&s.jsx("button",{className:"btn-ghost",onClick:y,children:"Scan for orphaned blobs"}),t==="scanning"&&s.jsx("div",{className:"muted",children:"Scanning…"}),t==="scanned"&&r&&h&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"form-msg form-msg--ok",children:"Archive is clean — nothing to remove."}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Done"})]}),t==="scanned"&&r&&!h&&s.jsxs("div",{children:[s.jsxs("div",{style:{marginBottom:14,lineHeight:1.6},children:["Found ",s.jsx("strong",{children:r.deletable_files})," unreferenced file",r.deletable_files!==1?"s":""," ","and ",s.jsx("strong",{children:r.orphaned_blob_rows})," orphaned DB record",r.orphaned_blob_rows!==1?"s":""," ","— ",s.jsx("strong",{children:mi(r.total_bytes)})," recoverable."]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsxs("button",{className:"btn-danger",onClick:g,children:["Delete (",mi(r.total_bytes),")"]}),s.jsx("button",{className:"btn-ghost",onClick:c,children:"Cancel"})]})]}),t==="deleting"&&s.jsx("div",{className:"muted",children:"Deleting…"}),t==="done"&&i&&s.jsxs("div",{children:[s.jsxs("div",{className:"form-msg form-msg--ok",children:["Freed ",s.jsx("strong",{children:mi(i.freed_bytes)})," ","— removed ",i.deleted_files," file",i.deleted_files!==1?"s":""," ","and ",i.deleted_blob_rows," DB record",i.deleted_blob_rows!==1?"s":"","."]}),i.errors&&i.errors.length>0&&s.jsxs("div",{className:"form-msg form-msg--err",style:{marginTop:6},children:[i.errors.length," file",i.errors.length!==1?"s":""," could not be deleted."]}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Scan again"})]}),t==="error"&&s.jsxs("div",{children:[s.jsx("div",{className:"form-msg form-msg--err",children:o}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Try again"})]})]})})}function ng(){const[e,t]=d.useState(null),[n,r]=d.useState(!0),[l,i]=d.useState(null),[a,o]=d.useState("global"),[u,c]=d.useState(""),[y,g]=d.useState("{}"),[h,v]=d.useState(null),[x,S]=d.useState(!1),[N,p]=d.useState({});d.useEffect(()=>{f()},[]);async function f(){r(!0),i(null);try{t(await km())}catch(j){i(j.message)}finally{r(!1)}}async function m(j){j.preventDefault();try{JSON.parse(y)}catch{v({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}S(!0),v(null);try{await jm(a==="global"?null:u.trim(),a,y),c(""),g("{}"),o("global"),v({ok:!0,text:"Rule added."}),await f()}catch(T){v({ok:!1,text:T.message})}finally{S(!1)}}async function k(j){try{await Nm(j),await f()}catch(T){i(T.message)}}function _(j){p(T=>({...T,[j.rule_uid]:{cookiesInput:j.cookies_json,saving:!1,msg:null}}))}function E(j){p(T=>{const L={...T};return delete L[j],L})}async function b(j){const T=N[j.rule_uid];try{JSON.parse(T.cookiesInput)}catch{p(L=>({...L,[j.rule_uid]:{...L[j.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}p(L=>({...L,[j.rule_uid]:{...L[j.rule_uid],saving:!0,msg:null}}));try{await Sm(j.rule_uid,{cookies_json:T.cookiesInput}),E(j.rule_uid),await f()}catch(L){p(K=>({...K,[j.rule_uid]:{...K[j.rule_uid],saving:!1,msg:{ok:!1,text:L.message}}}))}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):s.jsx("div",{style:{maxWidth:560},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Cookie Rules"}),s.jsx("p",{className:"muted",style:{marginBottom:12},children:"Cookies are injected into every capture network request (yt-dlp, HTTP downloads, web-page snapshots). Global rules apply to all URLs; wildcard and regex rules apply only to matching URLs."}),e&&e.length>0?s.jsxs("table",{className:"data-table",style:{width:"100%",marginBottom:16},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Pattern"}),s.jsx("th",{children:"Cookies"}),s.jsx("th",{style:{width:100},children:"Actions"})]})}),s.jsx("tbody",{children:e.map(j=>{const T=N[j.rule_uid],L=j.url_pattern?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"muted",children:[j.pattern_kind,":"]})," ",s.jsx("code",{children:j.url_pattern})]}):s.jsx("span",{className:"muted",children:"global (all URLs)"});return s.jsxs("tr",{children:[s.jsx("td",{children:L}),s.jsx("td",{children:T?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:T.cookiesInput,onChange:K=>p(U=>({...U,[j.rule_uid]:{...U[j.rule_uid],cookiesInput:K.target.value}}))}),T.msg&&s.jsx("div",{className:`form-msg form-msg--${T.msg.ok?"ok":"err"}`,children:T.msg.text}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{className:"btn-primary",style:{fontSize:12,padding:"2px 8px"},disabled:T.saving,onClick:()=>b(j),children:T.saving?"Saving…":"Save"}),s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>E(j.rule_uid),children:"Cancel"})]})]}):s.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:j.cookies_json})}),s.jsx("td",{children:!T&&s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>_(j),children:"Edit"}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>k(j.rule_uid),children:"Del"})]})})]},j.rule_uid)})})]}):s.jsx("p",{className:"muted",style:{marginBottom:16},children:"No cookie rules defined."}),s.jsx("h3",{style:{marginBottom:8},children:"Add Rule"}),s.jsxs("form",{onSubmit:m,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Pattern type"}),s.jsxs("select",{className:"field-input",value:a,onChange:j=>o(j.target.value),children:[s.jsx("option",{value:"global",children:"Global (all URLs)"}),s.jsx("option",{value:"wildcard",children:"Wildcard (e.g. *.youtube.com)"}),s.jsx("option",{value:"regex",children:"Regex (matched against full URL)"})]})]}),a!=="global"&&s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:a==="wildcard"?"URL/hostname pattern":"Regex pattern"}),s.jsx("input",{className:"field-input",type:"text",value:u,onChange:j=>c(j.target.value),placeholder:a==="wildcard"?"*.youtube.com or https://example.com/*":".*\\.youtube\\.com.*",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Cookies (JSON object)"}),s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:13,minHeight:70},value:y,onChange:j=>g(j.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),h&&s.jsx("div",{className:`form-msg form-msg--${h.ok?"ok":"err"}`,children:h.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Adding…":"Add Rule"})]})]})})}function rg(){const[e,t]=d.useState(null),[n,r]=d.useState(!0),[l,i]=d.useState(!1),[a,o]=d.useState(null);d.useEffect(()=>{(async()=>{try{t(await so())}catch(N){o({ok:!1,text:N.message})}finally{r(!1)}})()},[]);async function u(N){i(!0),o(null);try{await Xl({ublock_enabled:N}),t(p=>({...p,ublock_enabled:N})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function c(N){i(!0),o(null);try{await Xl({cookie_ext_enabled:N}),t(p=>({...p,cookie_ext_enabled:N})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function y(N){i(!0),o(null);try{await Xl({modal_closer_enabled:N}),t(p=>({...p,modal_closer_enabled:N})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}if(n)return s.jsx("div",{className:"muted",children:"Loading\\u2026"});const g=(e==null?void 0:e.ublock_ext_available)??!1,h=(e==null?void 0:e.ublock_enabled)??!0,v=(e==null?void 0:e.cookie_ext_available)??!1,x=(e==null?void 0:e.cookie_ext_enabled)??!0,S=(e==null?void 0:e.modal_closer_enabled)??!0;return s.jsx("div",{children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Extensions"}),s.jsx("p",{className:"form-hint",style:{marginBottom:20},children:"Extensions run inside the browser during WebPage captures and can block ads, accept cookie banners, and more. Changes take effect on the next capture."}),s.jsxs("div",{className:"ext-grid",children:[s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"ext-card-desc",children:"Blocks ads, trackers, and other page clutter during archiving via Chrome’s declarativeNetRequest API (Manifest V3)."}),!g&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_UBLOCK_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":h,className:`ext-toggle${h?" ext-toggle--on":""}`,onClick:()=>u(!h),disabled:l,"aria-label":"Toggle uBlock Origin Lite",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"I Still Don’t Care About Cookies"}),s.jsx("span",{className:"ext-card-desc",children:"Dismiss cookie consent banners during archiving."}),!v&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":x,className:`ext-toggle${x?" ext-toggle--on":""}`,onClick:()=>c(!x),disabled:l,"aria-label":"Toggle I Still Don't Care About Cookies",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"Modal & Dialog Closer"}),s.jsx("span",{className:"ext-card-desc",children:"Auto-dismiss cookie banners, consent overlays, and other modal dialogs before a WebPage capture is taken. Implemented as an injected browser script; no external extension required."})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":S,className:`ext-toggle${S?" ext-toggle--on":""}`,onClick:()=>y(!S),disabled:l,"aria-label":"Toggle Modal and Dialog Closer",children:s.jsx("span",{className:"ext-toggle-knob"})})]})})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text})]})})}const Pu={0:"Private",1:"Public",2:"Users only",3:"Public"},lg=()=>s.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M7 17 17 7M9 7h8v8"})});function sg({archiveId:e,selectedEntry:t,selectedUids:n,selectedEntries:r,detail:l,onTagFilterSet:i,tagNodes:a,onTagsRefresh:o,onEntryTitleChange:u,onEntryDeleted:c,onBulkDeleted:y,humanizeTags:g,onDetailRefresh:h,onOpenPreview:v,onPlay:x,isPublicSession:S}){var yl;const[N,p]=d.useState([]),[f,m]=d.useState(""),[k,_]=d.useState([]),[E,b]=d.useState(""),j=d.useRef(0),T=d.useRef(!1),[L,K]=d.useState(!1),[U,X]=d.useState(""),[Z,oe]=d.useState("idle"),[Ae,ye]=d.useState(""),D=d.useRef(null),[P,V]=d.useState(!1);d.useEffect(()=>{V(!1)},[(yl=l==null?void 0:l.summary)==null?void 0:yl.entry_uid]);const te=(n==null?void 0:n.size)>=2,[ee,Re]=d.useState(""),[Y,he]=d.useState("idle"),[ue,Ee]=d.useState(""),[Qe,Et]=d.useState([]),[ut,Wt]=d.useState(""),[ct,rt]=d.useState("idle"),[xt,bt]=d.useState(""),[A,q]=d.useState("idle"),[de,Be]=d.useState(""),[Dt,ze]=d.useState("idle"),[Bn,_n]=d.useState("");d.useEffect(()=>{const z=++j.current;if(D.current&&(clearInterval(D.current),D.current=null),oe("idle"),ye(""),!t||!e){p([]),_([]);return}if(S){p([]),_([]);return}K(!1),X(""),T.current=!1,p([]),Promise.all([$l(e,t.entry_uid),Cu(e,t.entry_uid)]).then(([re,be])=>{z===j.current&&(p(re),_(be))}).catch(()=>{})},[t,e,S]),d.useEffect(()=>()=>{clearInterval(D.current)},[]),d.useEffect(()=>{if(!e){Et([]);return}io(e).then(Et).catch(()=>Et([]))},[e]),d.useEffect(()=>{Re(""),he("idle"),Ee(""),Wt(""),rt("idle"),bt(""),q("idle"),Be(""),ze("idle"),_n("")},[n]);async function nn(){const z=n.size;if(!window.confirm(`Delete ${z} entr${z===1?"y":"ies"}? This cannot be undone.`))return;q("running");const re=new Set;for(const be of n)try{await _u(e,be),re.add(be)}catch{}q("idle"),y==null||y(re)}async function qe(){const z=ee.trim();if(z){he("running"),Ee("");try{for(const re of n)await Nu(e,re,z);Re(""),he("done"),o==null||o(),setTimeout(()=>he("idle"),1800)}catch(re){Ee(re.message),he("error")}}}async function wr(){if(!ut)return;rt("running"),bt("");const z=[],re=Qe.find(be=>be.collection_uid===ut);for(const be of n)try{await ca(e,ut,be,(re==null?void 0:re.default_visibility_bits)??2)}catch{z.push(be)}z.length>0?(bt(`Failed for ${z.length} entr${z.length===1?"y":"ies"}.`),rt("error")):(rt("done"),setTimeout(()=>rt("idle"),1800))}async function Un(){if(!de||!t)return;ze("running"),_n("");const z=Qe.find(re=>re.collection_uid===de);try{await ca(e,de,t.entry_uid,(z==null?void 0:z.default_visibility_bits)??2),ze("done"),Be("");const re=await Cu(e,t.entry_uid);_(re),setTimeout(()=>ze("idle"),1800)}catch(re){_n(re.message),ze("error")}}async function w(){const z=U.trim()||null;try{await Fh(e,t.entry_uid,z),u==null||u(t.entry_uid,z)}catch{}finally{K(!1)}}async function B(){const z=f.trim();if(!(!z||!t))try{await Nu(e,t.entry_uid,z),m(""),b("");const re=await $l(e,t.entry_uid);p(re),o()}catch(re){b(re.message)}}async function M(z){try{await Bh(e,t.entry_uid,z);const re=await $l(e,t.entry_uid);p(re),o()}catch{}}async function I(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await _u(e,t.entry_uid),c==null||c(t.entry_uid)}catch{}}async function F(){if(!t||!e||Z==="running")return;const z=j.current,re=t.entry_uid;oe("running"),ye("");try{const{job_uid:be}=await xm(e,re);if(j.current!==z)return;D.current=setInterval(async()=>{try{const Ot=await Xd(e,be);if(Ot.status==="completed"){if(clearInterval(D.current),D.current=null,j.current!==z)return;oe("done");const Vt=await $l(e,re);if(j.current!==z)return;p(Vt),h==null||h()}else if(Ot.status==="failed"){if(clearInterval(D.current),D.current=null,j.current!==z)return;oe("error"),ye(Ot.error_text||"Re-archive failed.")}}catch{if(clearInterval(D.current),D.current=null,j.current!==z)return;oe("error"),ye("Network error while polling.")}},500)}catch(be){if(j.current!==z)return;oe("error"),ye(be.message||"Failed to start re-archive.")}}const H=l?[["Added",ao(l.summary.archived_at)],["Source",l.summary.source_kind],["Type",l.summary.entity_kind],["Visibility",Pu[l.summary.visibility]??l.summary.visibility],["Root",l.structured_root_relpath]]:[],xe=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),fe=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv","pdf","html","htm","jpg","jpeg","png","gif","webp","avif","svg","bmp"]),we=l?l.artifacts.findIndex(z=>z.artifact_role==="primary_media"):-1,ce=we>=0?l.artifacts[we]:null,Ue=ce?ce.relpath.split(".").pop().toLowerCase():"",le=ce&&xe.has(Ue),dt=we>=0&&t?`/api/archives/${e}/entries/${t.entry_uid}/artifacts/${we}`:null,wt=l&&!le&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread"||ce&&fe.has(Ue));return s.jsxs("aside",{className:"context-rail",children:[s.jsx("div",{className:"rail-eyebrow",children:"Context"}),te?S?s.jsxs("p",{className:"bulk-count",children:[s.jsx("span",{className:"bulk-count-num",children:n.size})," entries selected"]}):s.jsxs("div",{className:"bulk-panel",children:[s.jsxs("p",{className:"bulk-count",children:[s.jsx("span",{className:"bulk-count-num",children:n.size})," entries selected"]}),s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Assign tag"}),ue&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:ue}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:ee,onChange:z=>Re(z.target.value),onKeyDown:z=>{z.key==="Enter"&&qe()}}),s.jsx("button",{className:"tag-add-btn",onClick:qe,disabled:Y==="running"||!ee.trim(),children:Y==="running"?"…":Y==="done"?"✓":"Add"})]})]}),Qe.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Add to collection"}),s.jsxs("div",{className:"bulk-coll-row",children:[s.jsxs("select",{className:"bulk-coll-select",value:ut,onChange:z=>Wt(z.target.value),children:[s.jsx("option",{value:"",children:"Pick a collection…"}),Qe.filter(z=>z.slug!=="_default_").map(z=>s.jsx("option",{value:z.collection_uid,children:z.name},z.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:wr,disabled:!ut||ct==="running",children:ct==="running"?"…":ct==="done"?"✓":ct==="error"?"!":"Add"})]}),xt&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"6px 0 0"},children:xt})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:nn,disabled:A==="running",children:A==="running"?"Deleting…":`Delete ${n.size} entr${n.size===1?"y":"ies"}`})})]}):t?l?s.jsxs(s.Fragment,{children:[S?s.jsx("h2",{className:"rail-title",children:pt(l.summary.title)||pt(l.summary.entry_uid)}):L?s.jsx("input",{className:"rail-title-input",autoFocus:!0,value:U,onChange:z=>X(z.target.value),onKeyDown:z=>{z.key==="Enter"&&z.currentTarget.blur(),z.key==="Escape"&&(T.current=!0,z.currentTarget.blur())},onBlur:()=>{T.current?K(!1):w(),T.current=!1}}):s.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{X(l.summary.title??""),K(!0)},children:[pt(l.summary.title)||pt(l.summary.entry_uid),s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),l.summary.original_url&&s.jsxs("a",{className:"url-tile",href:l.summary.original_url,target:"_blank",rel:"noopener noreferrer",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:Os(l.summary.source_kind)}}),s.jsx("span",{className:"u-text",children:l.summary.original_url}),s.jsx("span",{className:"ext",children:s.jsx(lg,{})})]}),le&&x&&s.jsx("button",{className:"rail-preview-btn",onClick:()=>x(dt,t),children:"▶ Play"}),wt&&v&&s.jsx("button",{className:"rail-preview-btn",onClick:v,children:"Preview"}),s.jsx("div",{className:"meta-list",children:H.filter(([,z])=>z!=null&&z!=="").map(([z,re])=>s.jsxs("div",{className:"meta-item",children:[s.jsx("span",{className:"meta-k",children:z}),s.jsx("span",{className:`meta-v${z==="Root"?" mono":""}`,children:pt(re)})]},z))}),l.artifacts.length>0&&(()=>{const z=l.artifacts.map((Ie,jr)=>({...Ie,_idx:jr})),re=z.filter(Ie=>Ie.artifact_role==="font"),be=z.filter(Ie=>Ie.artifact_role!=="font"),Ot=re.reduce((Ie,jr)=>Ie+(jr.byte_size||0),0),Vt=l.summary.entry_uid,kr=Ie=>s.jsx("li",{children:s.jsxs("a",{href:`/api/archives/${e}/entries/${Vt}/artifacts/${Ie._idx}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[s.jsx("span",{className:"artifact-name",children:Ie.artifact_role==="font"?Ie.relpath.split("/").pop():Ie.artifact_role.replace(/_/g," ")}),s.jsx("span",{className:"artifact-size",children:Ie.byte_size!=null?dl(Ie.byte_size):"—"})]})},Ie._idx);return s.jsxs("div",{className:"rail-section",children:[s.jsxs("div",{className:"rail-section-heading",children:["Artifacts ",s.jsx("span",{className:"num",children:l.artifacts.length})]}),s.jsxs("ul",{className:"artifact-list",children:[be.map(kr),re.length>0&&s.jsxs("li",{className:"artifact-group",children:[s.jsxs("button",{type:"button",className:"artifact-group-header artifact-link","aria-expanded":P,onClick:()=>V(Ie=>!Ie),children:[s.jsxs("span",{className:"artifact-name",children:[s.jsx("span",{"aria-hidden":"true",className:`artifact-group-chevron${P?" open":""}`,children:"›"}),` fonts (${re.length})`]}),s.jsx("span",{className:"artifact-size",children:dl(Ot)})]}),P&&s.jsx("ul",{className:"artifact-list artifact-group-body",children:re.map(kr)})]})]})]})})()]}):s.jsx("p",{className:"tags-empty",children:"Loading\\u2026"}):s.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&!te&&!S&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Tags"}),N.length===0?s.jsx("p",{className:"tags-empty",children:"No tags yet."}):s.jsx("div",{className:"tags-wrap",children:N.map(z=>s.jsxs("span",{className:"tag-pill",title:z.full_path,children:[g?Gd(z.full_path):z.full_path,s.jsx("button",{className:"remove",title:`Remove tag ${z.full_path}`,onClick:()=>M(z.tag_uid),children:"×"})]},z.tag_uid))}),E&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:E}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:f,onChange:z=>m(z.target.value),onKeyDown:z=>{z.key==="Enter"&&B()}}),s.jsx("button",{className:"tag-add-btn",onClick:B,children:"Add"})]})]}),(k.length>0||Qe.filter(z=>z.slug!=="_default_").length>0)&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Collections"}),k.map(z=>s.jsxs("div",{className:"coll-row",children:[s.jsx("span",{className:"coll-name",children:z.name}),s.jsx("span",{className:"vis-badge",children:Pu[z.visibility_bits]??`bits:${z.visibility_bits}`})]},z.collection_uid)),Qe.filter(z=>z.slug!=="_default_").length>0&&s.jsxs("div",{className:"bulk-coll-row",style:{marginTop:8},children:[s.jsxs("select",{className:"bulk-coll-select",value:de,onChange:z=>Be(z.target.value),children:[s.jsx("option",{value:"",children:"Add to collection…"}),Qe.filter(z=>z.slug!=="_default_").map(z=>s.jsx("option",{value:z.collection_uid,children:z.name},z.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:Un,disabled:!de||Dt==="running",children:Dt==="running"?"…":Dt==="done"?"✓":Dt==="error"?"!":"Add"})]}),Bn&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"4px 0 0"},children:Bn})]}),l&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread")&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Actions"}),s.jsx("button",{className:"rail-rearchive-btn",onClick:F,disabled:Z==="running",children:Z==="running"?"Re-archiving…":"Re-archive"}),Z==="done"&&s.jsx("p",{className:"form-msg form-msg--ok",style:{marginTop:"6px"},children:"Re-archived successfully."}),Z==="error"&&s.jsx("p",{className:"form-msg form-msg--err",style:{marginTop:"6px"},children:Ae})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:I,children:"Delete entry"})})]})]})}const ig=/\/api\/archives\/([^/]+)\/entries\/([^/]+)\/artifacts\/(\d+)/;function ag(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M5 17H3a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h18a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-2"}),s.jsx("polygon",{points:"12 15 17 21 7 21 12 15"})]})}function og({src:e,contentType:t="video/mp4"}){const n=d.useRef(null),[r,l]=d.useState(null),[i,a]=d.useState(!1),[o,u]=d.useState(!1);d.useEffect(()=>{if(!e){l(null);return}const g=e.match(ig);if(!g){l(e);return}let h=!1;return l(null),wm(g[1],g[2],parseInt(g[3],10)).then(({url:v})=>{h||l(v)}).catch(()=>{h||l(e)}),()=>{h=!0}},[e]),d.useEffect(()=>{n.current&&n.current.load()},[r]),d.useEffect(()=>{u(typeof HTMLVideoElement<"u"&&"webkitShowPlaybackTargetPicker"in HTMLVideoElement.prototype)},[]),d.useEffect(()=>{var h;const g=v=>{if(v)try{cast.framework.CastContext.getInstance().setOptions({receiverApplicationId:chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,autoJoinPolicy:chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}),a(!0)}catch{}};if((h=window.cast)!=null&&h.framework)g(!0);else if(window.__onGCastApiAvailable=g,!document.querySelector('script[src*="cast_sender"]')){const v=document.createElement("script");v.src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1",document.head.appendChild(v)}},[]),d.useEffect(()=>{if(!i||!r)return;const g=cast.framework.CastContext.getInstance(),{CastContextEventType:h,SessionState:v}=cast.framework,x=N=>{if(!N)return;const p=new chrome.cast.media.MediaInfo(window.location.origin+r,t);N.loadMedia(new chrome.cast.media.LoadRequest(p)).catch(()=>{})};x(g.getCurrentSession());const S=N=>{(N.sessionState===v.SESSION_STARTED||N.sessionState===v.SESSION_RESUMED)&&x(g.getCurrentSession())};return g.addEventListener(h.SESSION_STATE_CHANGED,S),()=>g.removeEventListener(h.SESSION_STATE_CHANGED,S)},[i,r,t]);const c=()=>{var g,h;(h=(g=n.current)==null?void 0:g.webkitShowPlaybackTargetPicker)==null||h.call(g)},y=i||o;return s.jsx("div",{className:"preview-video-wrap",style:{position:"relative"},children:e?s.jsxs(s.Fragment,{children:[r?s.jsxs("video",{ref:n,controls:!0,autoPlay:!1,playsInline:!0,"x-webkit-airplay":"allow",style:{width:"100%",maxHeight:"100%",display:"block"},children:[s.jsx("source",{src:r}),"Your browser does not support the video element."]}):s.jsx("div",{className:"video-tv-loading","aria-label":"Loading video…"}),y&&r&&s.jsxs("div",{className:"video-tv-controls",children:[o&&s.jsx("button",{className:"video-tv-btn",title:"AirPlay to device","aria-label":"AirPlay to device",onClick:c,children:s.jsx(ag,{})}),i&&s.jsx("google-cast-launcher",{className:"video-tv-btn",title:"Cast to TV"})]})]}):s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No video available"})})}function Lu({src:e,type:t,title:n,originalUrl:r}){const l=r||e,i=n||null;return s.jsxs("div",{className:"preview-iframe-wrap",style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:[s.jsxs("div",{className:"preview-iframe-toolbar",style:{display:"flex",flexDirection:"column",gap:"2px",padding:"6px 12px",borderBottom:"1px solid var(--line-soft)",background:"var(--paper-2)",flexShrink:0},children:[i&&s.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600,color:"var(--ink)",fontFamily:"var(--sans)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",color:"var(--muted)",fontFamily:"var(--sans)"},children:l}),s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{fontSize:"0.78rem",color:"var(--accent)",textDecoration:"none",whiteSpace:"nowrap",fontFamily:"var(--sans)",flexShrink:0},children:t==="pdf"?"Open PDF ↗":"Open in new tab ↗"})]})]}),s.jsx("iframe",{src:e,sandbox:"allow-same-origin allow-popups",allow:"autoplay 'none'",referrerPolicy:"no-referrer",style:{flex:1,border:"none",width:"100%",minHeight:0},title:i||(t==="pdf"?"PDF preview":"Page preview")})]})}function ug({src:e,alt:t}){return s.jsx("div",{className:"preview-image-wrap",style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",background:"var(--paper-2)",overflow:"hidden"},children:s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{display:"contents"},children:s.jsx("img",{src:e,alt:t||"",style:{objectFit:"contain",maxHeight:"100%",maxWidth:"100%",display:"block",cursor:"pointer"}})})})}function tf(e){return e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(new Date(e*1e3)):""}function Ru(e){return!e||!e.includes("&")?e:e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}const G={card:{background:"var(--paper)",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},threadOuter:{border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},tweetRow:{display:"flex",gap:"10px",padding:"10px 12px"},tweetRowThread:{display:"flex",gap:"10px",padding:"10px 12px 0"},leftCol:{display:"flex",flexDirection:"column",alignItems:"center",flexShrink:0,width:"36px"},rightCol:{flex:1,minWidth:0,paddingBottom:"8px"},avatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},avatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},threadLine:{flex:1,width:"2px",background:"var(--line-soft, var(--line))",margin:"4px 0",minHeight:"12px",borderRadius:"1px"},authorRow:{display:"flex",alignItems:"baseline",gap:"4px",flexWrap:"wrap",marginBottom:"4px",lineHeight:"1.3"},authorName:{fontWeight:"700",fontSize:"14px",color:"var(--ink)"},authorHandle:{fontSize:"13px",color:"var(--muted)"},datePart:{fontSize:"13px",color:"var(--muted)"},tweetText:{fontSize:"14px",lineHeight:"1.5",color:"var(--ink)",whiteSpace:"pre-line",marginBottom:"8px",wordBreak:"break-word"},stats:{display:"flex",gap:"12px",fontSize:"13px",color:"var(--muted)"},link:{color:"var(--accent)",textDecoration:"none"},loading:{padding:"24px 16px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},error:{padding:"24px 16px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},mediaGrid:{marginBottom:"8px",borderRadius:"10px",overflow:"hidden",border:"1px solid var(--line)"},mediaImg:{display:"block",width:"100%",objectFit:"cover",maxHeight:"260px"},mediaVideo:{display:"block",width:"100%",maxHeight:"260px",background:"#000"},article:{maxWidth:"560px",margin:"0 auto",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"280px"},aMeta:{padding:"10px 14px 0"},aTweetTitle:{fontSize:"20px",fontWeight:"800",letterSpacing:"-0.3px",color:"var(--ink)",lineHeight:"1.3",marginBottom:"8px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},aAvatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},aAuthorName:{fontSize:"14px",fontWeight:"700",color:"var(--ink)",lineHeight:"1.3"},aAuthorSub:{fontSize:"13px",color:"var(--muted)",lineHeight:"1.3"},aDivider:{border:"none",borderTop:"1px solid var(--line)",margin:"0"},aBody:{padding:"4px 14px 16px"},bH1:{fontSize:"22px",fontWeight:"800",letterSpacing:"-0.4px",color:"var(--ink)",lineHeight:"1.25",margin:"16px 0 6px"},bH2:{fontSize:"18px",fontWeight:"700",letterSpacing:"-0.2px",color:"var(--ink)",lineHeight:"1.3",margin:"14px 0 4px"},bP:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.65",marginBottom:"12px",marginTop:"0"},bSpacer:{height:"4px",display:"block"},bQuote:{borderLeft:"3px solid var(--line)",padding:"2px 12px",margin:"12px 0",color:"var(--muted)",fontSize:"15px",lineHeight:"1.6"},bHr:{border:"none",borderTop:"1px solid var(--line)",margin:"14px 0"},bImg:{width:"100%",display:"block",borderRadius:"8px",margin:"12px 0"},bUl:{margin:"8px 0 12px",paddingLeft:"24px"},bOl:{margin:"8px 0 12px",paddingLeft:"24px"},bLi:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.6",marginBottom:"4px"},bTweet:{display:"flex",alignItems:"center",gap:"10px",border:"1px solid var(--line)",borderRadius:"10px",padding:"10px 14px",margin:"12px 0",color:"var(--muted)",fontSize:"14px",textDecoration:"none"},bMdPre:{borderRadius:"8px",margin:"10px 0",overflow:"auto",background:"var(--paper-3, var(--field))",padding:"12px 14px"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"12px",lineHeight:"1.6",color:"var(--ink)",background:"transparent",display:"block"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:"var(--paper-3, var(--field))",padding:"1px 5px",borderRadius:"4px",color:"var(--ink)"},qtBadge:{fontSize:"11px",color:"var(--muted)",display:"inline-flex",alignItems:"center",gap:"2px",marginLeft:"4px",letterSpacing:"0.03em",flexShrink:0},lightboxBackdrop:{position:"fixed",inset:0,zIndex:500,background:"rgba(0,0,0,0.92)",display:"flex",alignItems:"center",justifyContent:"center",padding:"20px"},lightboxContent:{display:"flex",flexDirection:"column",alignItems:"center",gap:"10px",maxWidth:"90vw",maxHeight:"90vh"},lightboxToolbar:{display:"flex",alignItems:"center",gap:"10px",alignSelf:"flex-end"},lightboxImg:{maxWidth:"88vw",maxHeight:"80vh",objectFit:"contain",borderRadius:"6px",display:"block"},lightboxNav:{display:"flex",gap:"12px",alignItems:"center"},lightboxNavBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"20px",cursor:"pointer",borderRadius:"50%",width:"36px",height:"36px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"16px",cursor:"pointer",borderRadius:"50%",width:"30px",height:"30px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxLink:{color:"rgba(255,255,255,0.7)",textDecoration:"none",fontSize:"14px"},lightboxCounter:{color:"rgba(255,255,255,0.6)",fontSize:"13px"}},$e={bg:"#000000",border:"#2f3336",text:"#e7e9ea",dim:"#71767b",accent:"#1d9bf0",codeBg:"#16181c"},gi={article:{background:$e.bg,color:$e.text,minHeight:"100%",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif'},articleInner:{maxWidth:"598px",margin:"0 auto",paddingBottom:"80px"},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"420px"},aMeta:{padding:"20px 16px 0"},aTweetTitle:{fontSize:"34px",fontWeight:"800",letterSpacing:"-0.5px",color:$e.text,lineHeight:"44px",marginBottom:"16px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"16px"},aAvatar:{width:"40px",height:"40px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"40px",height:"40px",borderRadius:"50%",background:$e.border,flexShrink:0},aAuthorName:{fontSize:"15px",fontWeight:"700",color:$e.text,lineHeight:"1.3"},aAuthorSub:{fontSize:"15px",color:$e.dim,lineHeight:"1.3"},aDivider:{border:"none",borderTop:`1px solid ${$e.border}`,margin:"0"},aBody:{padding:"4px 16px 0"},bH1:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:$e.text,lineHeight:"36px",margin:"24px 0 10px"},bH2:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:$e.text,lineHeight:"36px",margin:"24px 0 10px"},bP:{fontSize:"17px",color:$e.text,lineHeight:"1.5",marginBottom:"16px",marginTop:"0"},bSpacer:{height:"6px",display:"block"},bQuote:{borderLeft:`3px solid ${$e.border}`,padding:"2px 14px",margin:"14px 0",color:$e.dim,fontSize:"17px",lineHeight:"1.5"},bHr:{border:"none",borderTop:`1px solid ${$e.border}`,margin:"28px 0"},bImg:{width:"100%",display:"block",borderRadius:"12px",margin:"16px 0"},bUl:{margin:"10px 0 16px",paddingLeft:"28px"},bOl:{margin:"10px 0 16px",paddingLeft:"28px"},bLi:{fontSize:"17px",color:$e.text,lineHeight:"1.5",marginBottom:"6px"},bTweet:{display:"flex",alignItems:"center",gap:"12px",border:`1px solid ${$e.border}`,borderRadius:"12px",padding:"14px 16px",margin:"14px 0",color:$e.dim,fontSize:"15px",textDecoration:"none"},bMdPre:{borderRadius:"12px",margin:"12px 0",overflow:"auto",background:"#1e2029"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"13px",lineHeight:"1.65",padding:"18px 20px",display:"block",color:$e.text,background:"transparent"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:$e.codeBg,padding:"2px 6px",borderRadius:"4px",color:"#e6edf3"},link:{color:$e.accent,textDecoration:"none"}};function cg(e,t,n){const r={};return n&&n.forEach((l,i)=>{l.relpath&&(r[l.relpath]=`/api/archives/${e}/entries/${t}/artifacts/${i}`)}),r}function ur(e,t,n){return e&&n[e]?n[e]:t||null}function nf(){return s.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",style:{flexShrink:0,color:"var(--ink)"},children:s.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.748l7.73-8.835L1.254 2.25H8.08l4.259 5.63L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77z"})})}function oo(e,t,...n){var r;if(e.fromIndex!=null&&e.toIndex!=null)return{s:e.fromIndex,e:e.toIndex};if(((r=e.indices)==null?void 0:r.length)===2)return{s:e.indices[0],e:e.indices[1]};if(t)for(const l of n){if(!l)continue;const i=t.indexOf(l);if(i!==-1)return{s:i,e:i+l.length}}return null}function rf(e,t){const n=e.expanded_url||e.url||e.text||"",r=e.display_url||e.expanded_url||e.url||e.text||"",l=oo(e,t,e.url,e.text,e.display_url,e.expanded_url);return!l||!n?null:{...l,kind:"url",href:n,display:r}}function lf(e,t){const n=e.screen_name||e.name||e.text||"",r=n?`@${n}`:null,l=oo(e,t,r);return!l||!n?null:{...l,kind:"mention",screen_name:n}}const zu=/https?:\/\/[^\s<>"'\])]+/g,dg=/[.,;:!?)()]+$/;function ws(e,t){const n=[];let r=0,l;for(zu.lastIndex=0;(l=zu.exec(e))!==null;){l.index>r&&n.push(e.slice(r,l.index));let i=l[0].replace(dg,"");n.push(s.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",style:t,children:i},l.index));const a=l[0].slice(i.length);a&&n.push(a),r=l.index+l[0].length}return r===0?e:(rrf(o,e)).filter(Boolean),...(t.user_mentions||[]).map(o=>lf(o,e)).filter(Boolean)];if(r.length===0&&n.length===0)return ws(Ru(e),G.link);const l=new Set([0,e.length]);for(const o of r)o.s>=0&&o.s<=e.length&&l.add(o.s),o.e>=0&&o.e<=e.length&&l.add(o.e);for(const[o,u]of n)o>=0&&o<=e.length&&l.add(o),u>=0&&u<=e.length&&l.add(u);const i=(o,u)=>n.some(([c,y])=>c<=o&&y>=u),a=[...l].sort((o,u)=>o-u);return a.slice(0,-1).map((o,u)=>{const c=a[u+1];if(i(o,c))return null;const y=e.slice(o,c),g=r.filter(x=>x.s<=o&&x.e>=c),h=g.find(x=>x.kind==="url");if(h)return s.jsx("a",{href:h.href,target:"_blank",rel:"noopener noreferrer",style:G.link,children:h.display||y},u);const v=g.find(x=>x.kind==="mention");return v?s.jsx("a",{href:`https://x.com/${v.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:G.link,children:y},u):s.jsx("span",{children:ws(Ru(y),G.link)},u)}).filter(o=>o!==null)}function pg(e,t,n,r,l=G){if(!e)return null;t=t||[],n=n||[],r=r||[];const i=[];for(const u of t)u.length>0&&i.push({s:u.offset,e:u.offset+u.length,kind:"style",style:u.style});for(const u of n){const c=rf(u,e);c&&i.push(c)}for(const u of r){const c=lf(u,e);c&&i.push(c)}if(i.length===0)return ws(e,l.link);const a=new Set([0,e.length]);for(const u of i)u.s>=0&&u.s<=e.length&&a.add(u.s),u.e>=0&&u.e<=e.length&&a.add(u.e);const o=[...a].sort((u,c)=>u-c);return o.slice(0,-1).map((u,c)=>{const y=o[c+1],g=i.filter(N=>N.s<=u&&N.e>=y),h=e.slice(u,y);let v;if(h.includes(` +`)){const N=h.split(` +`);v=N.flatMap((p,f)=>fN.kind==="style"&&N.style==="Code")&&(v=s.jsx("code",{style:l.iCode,children:v})),g.some(N=>N.kind==="style"&&N.style==="Bold")&&(v=s.jsx("strong",{children:v})),g.some(N=>N.kind==="style"&&N.style==="Italic")&&(v=s.jsx("em",{children:v})),g.some(N=>N.kind==="style"&&N.style==="Underline")&&(v=s.jsx("u",{children:v})),g.some(N=>N.kind==="style"&&N.style==="Strikethrough")&&(v=s.jsx("s",{children:v}));const x=g.find(N=>N.kind==="url");if(x){const N=/^https?:\/\/t\.co\//i.test(v);v=s.jsx("a",{href:x.href,target:"_blank",rel:"noopener noreferrer",style:l.link,children:N?x.display:v})}const S=g.find(N=>N.kind==="mention");return S&&(v=s.jsx("a",{href:`https://x.com/${S.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:l.link,children:v})),s.jsx("span",{children:typeof v=="string"?ws(v,l.link):v},c)})}function hg(e,t,n){const r=(n==null?void 0:n.st)||G,l=e.resolved_entities||[];return l.length===0?null:l.map((i,a)=>{var o;switch(i.type){case"divider":return s.jsx("hr",{style:r.bHr},a);case"media":{const u=ur(i.local_path,i.url,t);return u?s.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:c=>{var y;!c.metaKey&&!c.ctrlKey&&(c.preventDefault(),(y=n==null?void 0:n.onImgClick)==null||y.call(n,u))},children:s.jsx("img",{src:u,style:r.bImg,loading:"lazy",alt:""})},a):null}case"tweet":return i.tweet_id?s.jsxs("a",{href:`https://x.com/i/status/${i.tweet_id}`,target:"_blank",rel:"noopener noreferrer",style:r.bTweet,children:[s.jsx(nf,{}),"View post on X"]},a):null;case"link":return i.url?s.jsx("p",{style:r.bP,children:s.jsx("a",{href:i.url,target:"_blank",rel:"noopener noreferrer",style:r.link,children:i.url})},a):null;case"markdown":{const u=i.markdown??((o=i.data)==null?void 0:o.markdown)??"";return s.jsx("pre",{style:r.bMdPre,children:s.jsx("code",{style:r.bMdCode,children:u})},a)}case"emoji":return i.url?s.jsx("img",{src:i.url,alt:"",style:{height:"1.2em",verticalAlign:"middle",margin:"0 1px"}},a):null;default:return null}})}function yi(e,t,n,r){const l=(r==null?void 0:r.st)||G,i=e.type||"",a=e.text||"",o=e.inline_style_ranges||[],u=e.data||{},c=pg(a,o,u.urls||[],u.mentions||[],l);switch(i){case"header-one":return s.jsx("h1",{style:l.bH1,children:c},t);case"header-two":{const y=a.match(/(?:x\.com|twitter\.com)\/i\/status\/(\d+)/);return y?s.jsxs("a",{href:`https://x.com/i/status/${y[1]}`,target:"_blank",rel:"noopener noreferrer",style:l.bTweet,children:[s.jsx(nf,{}),"View post on X"]},t):s.jsx("h2",{style:l.bH2,children:c},t)}case"unstyled":return a.trim()?s.jsx("p",{style:l.bP,children:c},t):s.jsx("span",{style:l.bSpacer},t);case"blockquote":return s.jsx("blockquote",{style:l.bQuote,children:c},t);case"unordered-list-item":case"ordered-list-item":return s.jsx("li",{style:l.bLi,children:c},t);case"atomic":return s.jsx("span",{children:hg(e,n,r)},t);default:return a?s.jsx("p",{style:l.bP,children:c},t):null}}function mg(e,t,n){const r=(n==null?void 0:n.st)||G,l=[];let i=0;for(;i{r&&(l==null||l(!0))},[r,l]);const o=r?gi:G,u=e.cover_media||{},c=e.author||t||{},y=e.first_published_at_secs?tf(e.first_published_at_secs):"",h=[c.screen_name?`@${c.screen_name}`:"",y].filter(Boolean).join(" · "),v=ur(u.local_path,u.url,n),x=ur(c.avatar_local_path,c.avatar_url,n),S=s.jsxs(s.Fragment,{children:[i&&s.jsx(sf,{items:[{src:i,alt:""}],startIndex:0,onClose:()=>a(null)}),v&&s.jsx("a",{href:v,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:N=>{!N.metaKey&&!N.ctrlKey&&(N.preventDefault(),a(v))},children:s.jsx("img",{src:v,style:o.aCover,alt:"Article cover"})}),s.jsxs("div",{style:o.aMeta,children:[e.title&&s.jsx("div",{style:o.aTweetTitle,children:e.title}),s.jsxs("div",{style:o.aAuthorRow,children:[x?s.jsx("img",{src:x,style:o.aAvatar,alt:c.name||""}):s.jsx("div",{style:o.aAvatarPh}),s.jsxs("div",{children:[s.jsx("div",{style:o.aAuthorName,children:c.name||c.screen_name||"Unknown"}),h&&s.jsx("div",{style:o.aAuthorSub,children:h})]})]})]}),s.jsx("hr",{style:o.aDivider}),s.jsx("div",{style:o.aBody,children:mg(e.blocks||[],n,{onImgClick:a,st:o})})]});return r?s.jsx("div",{style:gi.article,children:s.jsx("div",{style:gi.articleInner,children:S})}):s.jsx("div",{style:G.article,children:S})}function yg({photos:e,onOpen:t}){const n=e.length;if(n===0)return null;if(n===1)return s.jsx("a",{href:e[0].src,target:"_blank",rel:"noopener noreferrer",style:{display:"block"},onClick:l=>{!l.metaKey&&!l.ctrlKey&&(l.preventDefault(),t(0))},children:s.jsx("img",{src:e[0].src,alt:e[0].alt||"",style:G.mediaImg,loading:"lazy"})});const r=n<=2?"180px":"140px";return s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gridTemplateRows:n===2?r:`${r} ${r}`,gap:"2px"},children:e.map((l,i)=>s.jsx("a",{href:l.src,target:"_blank",rel:"noopener noreferrer",style:{display:"block",overflow:"hidden",gridRow:n===3&&i===0?"span 2":void 0},onClick:a=>{!a.metaKey&&!a.ctrlKey&&(a.preventDefault(),t(i))},children:s.jsx("img",{src:l.src,alt:l.alt||"",loading:"lazy",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}})},i))})}function sf({items:e,startIndex:t,onClose:n}){const[r,l]=d.useState(t);d.useEffect(()=>{const a=o=>{(o.key==="Escape"||o.key==="ArrowLeft"||o.key==="ArrowRight")&&(o.stopPropagation(),o.preventDefault()),o.key==="Escape"&&n(),o.key==="ArrowRight"&&l(u=>Math.min(u+1,e.length-1)),o.key==="ArrowLeft"&&l(u=>Math.max(u-1,0))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[n,e.length]);const i=e[r];return s.jsx("div",{style:G.lightboxBackdrop,onClick:n,children:s.jsxs("div",{style:G.lightboxContent,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{style:G.lightboxToolbar,children:[e.length>1&&s.jsxs("span",{style:G.lightboxCounter,children:[r+1," / ",e.length]}),s.jsx("a",{href:i.src,target:"_blank",rel:"noopener noreferrer",style:G.lightboxLink,title:"Open in new tab",children:"↗"}),s.jsx("button",{style:G.lightboxBtn,onClick:n,"aria-label":"Close",children:"×"})]}),s.jsx("img",{src:i.src,alt:i.alt||"",style:G.lightboxImg}),e.length>1&&s.jsxs("div",{style:G.lightboxNav,children:[s.jsx("button",{style:G.lightboxNavBtn,onClick:()=>l(a=>Math.max(a-1,0)),disabled:r===0,children:"‹"}),s.jsx("button",{style:G.lightboxNavBtn,onClick:()=>l(a=>Math.min(a+1,e.length-1)),disabled:r===e.length-1,children:"›"})]})]})})}function Iu({tweet:e,isInThread:t,isLast:n,artifactMap:r}){var f,m;const[l,i]=d.useState(null),a=e.author||{},o=e.created_at_secs?tf(e.created_at_secs):"",u=e.entities||{},c=ur(a.avatar_local_path,a.avatar_url,r),y=t&&!n,g=e.is_quote_status===!0,h=t?G.tweetRowThread:G.tweetRow,v=e.full_text||"",x=((m=(f=e.extended_entities)==null?void 0:f.media)!=null&&m.length?e.extended_entities.media:u.media)||[],S=[],N=[];for(const k of x)if(k.type==="photo"){const _=ur(k.local_path,k.media_url_https,r);_&&S.push({kind:"photo",src:_,alt:k.alt_text||""})}else if(k.type==="video"||k.type==="animated_gif"){const _=k.local_path&&r[k.local_path]||(()=>{var b,j;return(j=(((b=k.video_info)==null?void 0:b.variants)||[]).filter(T=>T.content_type==="video/mp4").sort((T,L)=>(L.bitrate||0)-(T.bitrate||0))[0])==null?void 0:j.url})();_&&N.push({kind:k.type==="animated_gif"?"gif":"video",src:_})}const p=[];for(const k of x){if(!k.url||!(k.type==="photo"?S.some(b=>b.src===ur(k.local_path,k.media_url_https,r)):N.length>0))continue;const E=oo(k,v,k.url);E&&p.push([E.s,E.e])}return s.jsxs(s.Fragment,{children:[l!==null&&s.jsx(sf,{items:S,startIndex:l,onClose:()=>i(null)}),s.jsxs("div",{style:h,children:[s.jsxs("div",{style:G.leftCol,children:[c?s.jsx("img",{src:c,style:G.avatar,alt:a.name||""}):s.jsx("div",{style:G.avatarPh}),y&&s.jsx("div",{style:G.threadLine})]}),s.jsxs("div",{style:G.rightCol,children:[s.jsxs("div",{style:G.authorRow,children:[s.jsx("span",{style:G.authorName,children:a.name||a.screen_name||"Unknown"}),a.screen_name&&s.jsxs("span",{style:G.authorHandle,children:["@",a.screen_name]}),o&&s.jsxs("span",{style:G.datePart,children:["· ",o]}),g&&s.jsx("span",{style:G.qtBadge,title:"Quote tweet",children:"↻ QT"})]}),s.jsx("div",{style:G.tweetText,children:fg(v,u,p)}),S.length>0&&s.jsx("div",{style:G.mediaGrid,children:s.jsx(yg,{photos:S,onOpen:k=>i(k)})}),N.map((k,_)=>s.jsx("div",{style:G.mediaGrid,children:s.jsx("video",{src:k.src,style:G.mediaVideo,controls:!0,loop:k.kind==="gif",muted:k.kind==="gif",autoPlay:k.kind==="gif"})},_)),(e.retweet_count>0||e.favorite_count>0)&&s.jsxs("div",{style:G.stats,children:[e.favorite_count>0&&s.jsxs("span",{children:["❤️ ",e.favorite_count.toLocaleString()]}),e.retweet_count>0&&s.jsxs("span",{children:["🔁 ",e.retweet_count.toLocaleString()]})]})]})]})]})}function vg({archiveId:e,entryUid:t,artifacts:n,entityKind:r,fullPage:l,onXArticle:i}){const[a,o]=d.useState(!0),[u,c]=d.useState(null),[y,g]=d.useState([]);if(d.useEffect(()=>{if(o(!0),c(null),g([]),!n||!e||!t){o(!1);return}const x=n.map((N,p)=>({...N,index:p})).filter(N=>N.artifact_role==="raw_tweet_json");if(x.length===0){c("No tweet data found."),o(!1);return}let S=!1;return Ah(e,t,x.map(N=>N.index)).then(async N=>{if(S)return;const p=/https?:\/\/t\.co\/[A-Za-z0-9]+/g,f=b=>{var T;const j=b.full_text||"";return(((T=b.entities)==null?void 0:T.urls)||[]).map(L=>{var K;if(L.fromIndex!=null&&L.toIndex!=null)return[L.fromIndex,L.toIndex];if(((K=L.indices)==null?void 0:K.length)===2)return[L.indices[0],L.indices[1]];if(L.url){const U=j.indexOf(L.url);if(U!==-1)return[U,U+L.url.length]}return null}).filter(Boolean)},m=(b,j,T)=>b.some(([L,K])=>L<=j&&K>=T),k=new Set;for(const b of N){const j=b.full_text||"",T=f(b);let L;for(p.lastIndex=0;(L=p.exec(j))!==null;)m(T,L.index,L.index+L[0].length)||k.add(L[0])}const _=k.size>0?await Mh([...k]).catch(()=>({})):{},E=N.map(b=>{var U;const j=b.full_text||"",T=f(b),L=[];let K;for(p.lastIndex=0;(K=p.exec(j))!==null;){const X=K[0],Z=_[X];Z&&Z!==X&&!m(T,K.index,K.index+X.length)&&L.push({url:X,expanded_url:Z,display_url:(()=>{try{const oe=new URL(Z);return oe.hostname+(oe.pathname.length>1?"/…":"")}catch{return Z}})(),fromIndex:K.index,toIndex:K.index+X.length})}return L.length===0?b:{...b,entities:{...b.entities||{},urls:[...((U=b.entities)==null?void 0:U.urls)||[],...L]}}});S||g(E)}).catch(N=>{S||c(N.message||"Failed to load tweet.")}).finally(()=>{S||o(!1)}),()=>{S=!0}},[e,t,n]),a)return s.jsx("div",{style:G.loading,children:"Loading…"});if(u)return s.jsxs("div",{style:G.error,children:["Error: ",u]});if(y.length===0)return null;const h=cg(e,t,n);if(r==="tweet_thread")return s.jsx("div",{style:G.threadOuter,children:y.map((x,S)=>s.jsx(Iu,{tweet:x,isInThread:!0,isLast:S===y.length-1,artifactMap:h},x.id||S))});const v=y[0];return v.is_article&&v.article?s.jsx(gg,{article:v.article,tweetAuthor:v.author,artifactMap:h,fullPage:l,onXArticle:i}):s.jsx("div",{style:G.card,children:s.jsx(Iu,{tweet:v,isInThread:!1,isLast:!0,artifactMap:h})})}const xg=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv"]),wg=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),kg=new Set(["jpg","jpeg","png","gif","webp","avif","svg","bmp"]),jg={mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo",m4v:"video/mp4",ogv:"video/ogg"};function af({archiveId:e,entry:t,detail:n,fullPage:r,onXArticle:l}){if(!t)return s.jsx("div",{className:"preview-panel preview-panel--empty",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Select an entry to preview"})});if(!n)return s.jsx("div",{className:"preview-panel preview-panel--loading",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Loading…"})});const{summary:i,artifacts:a}=n,o=i.entry_uid,u=i.entity_kind;if(u==="tweet"||u==="tweet_thread"){const v=s.jsx(vg,{archiveId:e,entryUid:o,artifacts:a,entityKind:u,fullPage:r,onXArticle:l});return r?v:s.jsx("div",{className:"preview-tweet-wrap",children:v})}const c=a.findIndex(v=>v.artifact_role==="primary_media");if(c===-1)return s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),a.length>0&&s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((v,x)=>s.jsxs("li",{children:[v.artifact_role,": ",v.relpath]},x))})]});const y=a[c],g=`/api/archives/${e}/entries/${o}/artifacts/${c}`,h=y.relpath.split(".").pop().toLowerCase();return xg.has(h)?s.jsx("div",{className:"preview-panel",children:s.jsx(og,{src:g,contentType:jg[h]||"video/mp4"})}):wg.has(h)?s.jsxs("div",{className:"preview-panel preview-panel--audio",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"12px",padding:"24px",fontFamily:"var(--sans)"},children:[s.jsx("span",{style:{fontSize:"2rem"},children:"🎵"}),s.jsx("span",{style:{color:"var(--ink)",fontSize:"0.95rem",fontWeight:600},children:i.title||o}),s.jsx("audio",{src:g,controls:!0,style:{marginTop:"8px",width:"100%",maxWidth:"400px"}})]}):h==="pdf"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Lu,{src:g,type:"pdf",title:i.title,originalUrl:i.original_url})}):h==="html"||h==="htm"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Lu,{src:g,type:"page",title:i.title,originalUrl:i.original_url})}):kg.has(h)?s.jsx("div",{className:"preview-panel",style:{height:"100%"},children:s.jsx(ug,{src:g,alt:i.title||"Image"})}):s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((v,x)=>s.jsxs("li",{children:[v.artifact_role,": ",v.relpath]},x))})]})}function Sg({archiveId:e,entry:t,detail:n,onClose:r}){var l,i;return d.useEffect(()=>{const a=o=>{o.key==="Escape"&&r()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[r]),s.jsx("div",{className:"preview-modal-backdrop",onClick:r,children:s.jsxs("div",{className:`preview-modal${((l=n==null?void 0:n.summary)==null?void 0:l.entity_kind)==="tweet"||((i=n==null?void 0:n.summary)==null?void 0:i.entity_kind)==="tweet_thread"?"":" preview-modal--full"}`,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{className:"preview-modal-header",children:[s.jsx("span",{className:"preview-modal-title",children:(t==null?void 0:t.title)||(t==null?void 0:t.entry_uid)||"Preview"}),s.jsx("a",{className:"preview-modal-newtab",href:`/preview/${e}/${t==null?void 0:t.entry_uid}`,target:"_blank",rel:"noopener noreferrer",title:"Open in new tab",children:"↗"}),s.jsx("button",{className:"preview-modal-close",onClick:r,"aria-label":"Close preview",children:"×"})]}),s.jsx("div",{className:"preview-modal-body",children:s.jsx(af,{archiveId:e,entry:t,detail:n})})]})})}function $u(e){if(!isFinite(e)||isNaN(e))return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`}function Ng({entry:e,src:t,archiveId:n,onClose:r}){const l=d.useRef(null),[i,a]=d.useState(!1),[o,u]=d.useState(0),[c,y]=d.useState(NaN),[g,h]=d.useState(1);d.useEffect(()=>{!l.current||!t||(l.current.load(),u(0),y(NaN),a(!1))},[t]),d.useEffect(()=>{l.current&&(l.current.volume=g)},[g]);function v(){const f=l.current;f&&(i?f.pause():f.play().catch(()=>{}))}function x(f){const m=l.current;if(!m||!isFinite(c))return;const k=Number(f.target.value);m.currentTime=k,u(k)}function S(f){h(Number(f.target.value))}const N=(e==null?void 0:e.title)||(e==null?void 0:e.entry_uid)||"Unknown",p=(e==null?void 0:e.source_kind)||"other";return s.jsxs(s.Fragment,{children:[s.jsx("audio",{ref:l,src:t||void 0,preload:"auto",onPlay:()=>a(!0),onPause:()=>a(!1),onEnded:()=>a(!1),onTimeUpdate:()=>{var f;return u(((f=l.current)==null?void 0:f.currentTime)??0)},onLoadedMetadata:()=>{var f;return y(((f=l.current)==null?void 0:f.duration)??NaN)},onDurationChange:()=>{var f;return y(((f=l.current)==null?void 0:f.duration)??NaN)},style:{display:"none"}}),s.jsxs("div",{className:"audio-bar",style:{position:"fixed",bottom:0,left:0,right:0,zIndex:100,background:"var(--paper-3)",borderTop:"1px solid var(--line)",display:"flex",alignItems:"center",gap:"16px",padding:"0 16px",height:"56px",fontFamily:"var(--sans)"},children:[s.jsxs("div",{className:"audio-bar-info",style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,flex:"0 1 220px",overflow:"hidden"},children:[s.jsx("span",{className:"source-icon",style:{flexShrink:0,width:"18px",height:"18px",display:"flex",alignItems:"center"},dangerouslySetInnerHTML:{__html:Os(p)}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.85rem",color:"var(--ink)"},title:N,children:N})]}),s.jsxs("div",{className:"audio-bar-controls",style:{display:"flex",alignItems:"center",gap:"10px",flex:"1 1 0",minWidth:0},children:[s.jsx("button",{onClick:v,"aria-label":i?"Pause":"Play",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--ink)",flexShrink:0,fontSize:"1.2rem",lineHeight:1},children:i?"⏸":"▶"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:$u(o)}),s.jsx("input",{type:"range",min:0,max:isFinite(c)?c:0,step:.1,value:isFinite(o)?o:0,onChange:x,"aria-label":"Seek",style:{flex:1,minWidth:0,accentColor:"var(--accent)"}}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:$u(c)})]}),s.jsxs("div",{className:"audio-bar-right",style:{display:"flex",alignItems:"center",gap:"8px",flex:"0 1 160px"},children:[s.jsx("span",{style:{fontSize:"0.85rem",color:"var(--muted)",flexShrink:0},children:"🔊"}),s.jsx("input",{type:"range",min:0,max:1,step:.01,value:g,onChange:S,"aria-label":"Volume",style:{width:"80px",accentColor:"var(--accent)"}}),s.jsx("button",{onClick:r,"aria-label":"Close audio player",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--muted)",fontSize:"1rem",lineHeight:1,marginLeft:"4px"},children:"✕"})]})]})]})}function _g({archiveId:e,entryUid:t}){var h,v;const[n,r]=d.useState(null),[l,i]=d.useState(!0),[a,o]=d.useState(null),[u,c]=d.useState(!1);d.useEffect(()=>{if(!u)return;const x=document.documentElement,S=document.body,N=x.style.colorScheme,p=S.style.background;return x.style.colorScheme="dark",S.style.background="#000",()=>{x.style.colorScheme=N,S.style.background=p}},[u]),d.useEffect(()=>{c(!1),Dr(e,t).then(x=>{r(x),i(!1)}).catch(x=>{o((x==null?void 0:x.message)||"Failed to load entry"),i(!1)})},[e,t]);const y=((h=n==null?void 0:n.summary)==null?void 0:h.title)||t,g=(v=n==null?void 0:n.summary)==null?void 0:v.original_url;return s.jsxs("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column",background:u?"#000":"var(--paper)",fontFamily:"var(--sans)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",padding:u?"8px 12px":"10px 16px",borderBottom:u?"none":"1px solid var(--line)",flexShrink:0,position:u?"sticky":"relative",top:0,zIndex:20,background:u?"rgba(0,0,0,0.82)":"var(--paper-2)",backdropFilter:u?"blur(12px)":"none",WebkitBackdropFilter:u?"blur(12px)":"none"},children:[s.jsx("a",{href:"/",style:{color:u?"#1d9bf0":"var(--accent)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"← Archive"}),s.jsx("span",{style:{flex:1,fontSize:"14px",fontWeight:600,color:u?"#e7e9ea":"var(--ink)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y}),g&&s.jsx("a",{href:g,target:"_blank",rel:"noopener noreferrer",style:{color:u?"#71767b":"var(--muted)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"Original ↗"})]}),s.jsxs("div",{style:u?{flex:1}:{flex:1,minHeight:0,overflow:"auto",display:"flex",flexDirection:"column"},children:[l&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},children:"Loading…"}),a&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},children:a}),n&&s.jsx(af,{archiveId:e,entry:n.summary,detail:n,fullPage:!0,onXArticle:c})]})]})}const Cg=7e3;function Eg({toasts:e,onDismiss:t,onIgnoreUblock:n}){return e.length?s.jsx("div",{className:"toast-stack",role:"log","aria-live":"polite","aria-label":"Notifications",children:e.map(r=>s.jsx(Tg,{toast:r,onDismiss:t,onIgnoreUblock:n},r.id))}):null}function bg(e){if(!e)return null;if(e.length<=52)return e;try{const{hostname:t,pathname:n,search:r}=new URL(e),l=n.split("/").filter(Boolean),i=(l[l.length-1]??"")+r,a=i?`${t}/…/${i}`:t;return a.length<=56?a:a.slice(0,53)+"…"}catch{return"…"+e.slice(-51)}}function Tg({toast:e,onDismiss:t,onIgnoreUblock:n}){const[r,l]=d.useState(!1),i=e.type==="warning",a=e.type==="success";d.useEffect(()=>{if(r)return;const u=setTimeout(()=>t(e.id),Cg);return()=>clearTimeout(u)},[r,e.id,t]);const o=bg(e.locator);return a?s.jsx("div",{className:"toast toast--success",role:"alert","aria-atomic":"true",children:s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✓"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsx("div",{className:"toast-btns",children:s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})})]})}):i?s.jsxs("div",{className:"toast toast--warning",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"⚠"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived with warnings"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),"aria-expanded":r,children:r?"Hide":"Details"}),e.locator&&s.jsx("button",{type:"button",className:"toast-view-btn toast-ignore-btn",onClick:()=>{n==null||n(),t(e.id)},children:"Ignore"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&s.jsx("p",{className:"toast-warning-detail",children:e.text||"The page was captured but one or more browser extensions were unavailable (ad-blocking or cookie-consent). Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config."})]}):s.jsxs("div",{className:"toast toast--error",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✕"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Capture failed"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),children:r?"Hide":"View error"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&e.text&&s.jsx("pre",{className:"toast-error-detail",children:e.text})]})}const As=d.createContext(null),Pg=["archive","tags","collections","runs","admin","settings"],Lg=["profile","tokens","instance","cookies","extensions","storage"],Lr=(()=>{const e=window.location.pathname.match(/^\/preview\/([^/]+)\/([^/]+)/);return e?{archiveId:e[1],entryUid:e[2]}:null})();function Mt(){const e=window.location.pathname.split("/").filter(Boolean),t=Pg.includes(e[0])?e[0]:"archive",n=t==="settings"&&Lg.includes(e[1])?e[1]:"profile",r=new URLSearchParams(window.location.search),l=r.get("q")??"",i=t==="archive"?r.get("tag")??null:null,a=t==="archive"?r.get("entry")??null:null,o=t==="archive"?r.get("collection")??null:null,u=o==="main"?null:o,c=r.get("archive")??null;return{view:t,settingsTab:n,q:l,tag:i,entry:a,collection:u,archive:c}}function Rg(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function zg(){const[e,t]=d.useState("loading"),[n,r]=d.useState(null);d.useEffect(()=>{(async()=>{var O,Q,J;if(await Jh()){t("setup");return}const $=await em();if(!$){const{collection:se,archive:Te}=Mt();try{const Ke=await ju(),Ne=Te?((O=Ke.find(Ms=>Ms.id===Te))==null?void 0:O.id)??((Q=Ke[0])==null?void 0:Q.id):(J=Ke[0])==null?void 0:J.id;if(Ne){await Su(Ne,se),i(Ke),o(Ne),c(se),t("authenticated");return}}catch{}t("login");return}r($),t("authenticated")})()},[]),d.useEffect(()=>{const C=()=>{n&&(r(null),t("login"))};return window.addEventListener("auth:expired",C),()=>window.removeEventListener("auth:expired",C)},[n]),d.useEffect(()=>{const C=()=>{const{view:$,settingsTab:O,q:Q,tag:J,entry:se,collection:Te}=Mt();T($),K(O),X(Q),b(J),p(se),m(null),_(se?new Set([se]):new Set),c(Te)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[]);const[l,i]=d.useState([]),[a,o]=d.useState(null),[u,c]=d.useState(()=>Mt().collection),[y,g]=d.useState([]),[h,v]=d.useState([]),[x,S]=d.useState(()=>new Set),[N,p]=d.useState(()=>Mt().entry),[f,m]=d.useState(null),[k,_]=d.useState(()=>{const C=Mt().entry;return C?new Set([C]):new Set}),[E,b]=d.useState(()=>Mt().tag),[j,T]=d.useState(()=>Mt().view),[L,K]=d.useState(()=>Mt().settingsTab),[U,X]=d.useState(()=>Mt().q),[Z,oe]=d.useState(""),[Ae,ye]=d.useState(!1),[D,P]=d.useState([]),[V,te]=d.useState([]),[ee,Re]=d.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[Y,he]=d.useState([]),ue=d.useRef(0),[Ee,Qe]=d.useState(()=>{try{const C=JSON.parse(sessionStorage.getItem("pendingCaptures")||"[]");if(Array.isArray(C))return C}catch{}return[]});d.useEffect(()=>{sessionStorage.setItem("pendingCaptures",JSON.stringify(Ee))},[Ee]);const[Et,ut]=d.useState(()=>sessionStorage.getItem("ublockWarningIgnored")==="true"),[Wt,ct]=d.useState(null),rt=d.useRef(0),xt=d.useRef(null),bt=d.useRef(!1),A=d.useRef(!0),q=d.useRef(null),de=d.useRef(0),Be=d.useRef(new Map),Dt=(n==null?void 0:n.humanize_slugs)??!1;d.useEffect(()=>{const C=++rt.current;ct(null),!(!f||!a)&&Dr(a,f.entry_uid).then($=>{C===rt.current&&ct($)}).catch(()=>{})},[f,a]),d.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",ee)},[ee]);const ze=d.useCallback(async(C,$,O,Q)=>{if(C){ye(!0);try{let J;$||O?J=await Dh(C,$,O,Q):J=await Su(C,Q),v(J),_(se=>{if(se.size<2)return se;const Te=new Set(J.map(Ne=>Ne.entry_uid)),Ke=new Set([...se].filter(Ne=>Te.has(Ne)));return Ke.size===se.size?se:Ke}),oe(J.length===0?"No results":`${J.length} result${J.length===1?"":"s"}`)}catch{v([]),oe("Search failed. Try again.")}finally{ye(!1)}}},[]);d.useEffect(()=>{e==="authenticated"&&(a||ju().then(C=>{if(i(C),C.length>0){const{archive:$}=Mt(),O=$?C.find(Q=>Q.id===$):null;o((O==null?void 0:O.id)??C[0].id)}}))},[e,a]),d.useEffect(()=>{if(!a)return;const C=!n;if(A.current){A.current=!1;const O=[];C||(O.push(fi(a).then(P)),O.push(Dl(a).then(te))),O.length&&Promise.all(O);return}b(null),m(null),p(null),_(new Set),c(null);const $=[ze(a,"",null,null)];C||($.push(fi(a).then(P)),$.push(Dl(a).then(te))),Promise.all($)},[a,n]),d.useEffect(()=>{if(a===null)return;const C=setTimeout(()=>{ze(a,U,E,u)},300);return()=>clearTimeout(C)},[U,a,u]),d.useEffect(()=>{a!==null&&(E!==null&&T("archive"),ze(a,U,E,u))},[E,a,u]);const Bn=d.useCallback(C=>{o(C),c(null);const $=new URLSearchParams(window.location.search);$.set("archive",C),$.delete("collection");const O=$.toString();history.replaceState(null,"",window.location.pathname+(O?"?"+O:""))},[]);d.useEffect(()=>{if(!a){g([]);return}io(a).then(g).catch(()=>g([]))},[a]);const _n=d.useCallback(C=>{if(!n){const Q=C?y.find(J=>J.collection_uid===C):y.find(J=>J.slug==="_default_");if(Q!=null&&Q.requires_auth){t("login");return}}c(C),m(null),p(null),_(new Set),ze(a,U,E,C);const $=new URLSearchParams(window.location.search);C?($.set("collection",C),$.set("archive",a)):($.delete("collection"),a&&$.set("archive",a));const O=$.toString();history.replaceState(null,"",window.location.pathname+(O?"?"+O:""))},[a,U,E,n,y,ze]),nn=d.useCallback(C=>{T(C),C==="tags"&&a&&Dl(a).then(te)},[a]);d.useEffect(()=>{if(Lr)return;const C=Rg(j,L);window.location.pathname!==C&&history.pushState(null,"",C+window.location.search)},[j,L]);const qe=d.useCallback(C=>{p(C?C.entry_uid:null),m(C)},[]),wr=d.useCallback((C,$)=>{if(Be.current.set(C.entry_uid,C),++de.current,$.shiftKey&&q.current!==null){$.preventDefault();const O=[...document.querySelectorAll("#entries-body [data-entry-uid]")],Q=O.findIndex(Ne=>Ne.dataset.entryUid===q.current),J=O.findIndex(Ne=>Ne.dataset.entryUid===C.entry_uid);if(Q===-1||J===-1){q.current=C.entry_uid,_(new Set([C.entry_uid])),qe(C);return}const se=Math.min(Q,J),Te=Math.max(Q,J),Ke=new Set(O.slice(se,Te+1).map(Ne=>Ne.dataset.entryUid));_(Ke),Ke.size===1&&qe(C)}else if($.ctrlKey||$.metaKey){q.current=C.entry_uid;const O=new Set(k);if(O.has(C.entry_uid)?O.delete(C.entry_uid):O.add(C.entry_uid),_(O),O.size===0)qe(null);else if(O.size===1){const[Q]=O,J=Be.current.get(Q)??h.find(se=>se.entry_uid===Q)??null;if(J)qe(J);else{const se=++de.current;Dr(a,Q).then(Te=>{se===de.current&&(Te!=null&&Te.summary)&&qe(Te.summary)}).catch(()=>{})}}else qe(null)}else q.current=C.entry_uid,_(new Set([C.entry_uid])),qe(C)},[h,k,qe,a]),Un=d.useCallback(C=>{b(C)},[]),w=d.useCallback(()=>{b(null)},[]),B=d.useCallback(()=>{a&&Dl(a).then(te)},[a]),M=d.useCallback((C,$)=>{E===C?b($):E!=null&&E.startsWith(C+"/")&&b($+E.slice(C.length))},[E]),I=d.useCallback(C=>{(E===C||E!=null&&E.startsWith(C+"/"))&&b(null)},[E]),F=d.useCallback((C,$)=>{v(O=>O.map(Q=>Q.entry_uid===C?{...Q,title:$}:Q)),m(O=>O&&O.entry_uid===C?{...O,title:$}:O),ct(O=>O&&O.summary.entry_uid===C?{...O,summary:{...O.summary,title:$}}:O)},[]),H=d.useCallback(()=>{if(!a||!f)return;const C=++rt.current;Dr(a,f.entry_uid).then($=>{C===rt.current&&ct($)}).catch(()=>{})},[a,f]),xe=d.useCallback(C=>{const $=h.some(O=>O.entry_uid===C);S(O=>{const Q=new Set(O);return Q.add(C),Q}),v(O=>O.filter(Q=>Q.entry_uid!==C)),m(O=>(O==null?void 0:O.entry_uid)===C?null:O),p(O=>O===C?null:O),_(O=>{const Q=new Set(O);return Q.delete(C),Q}),$||ze(a,U,E,u)},[h,a,U,E,u,ze]),fe=d.useCallback(C=>{const $=new Set(h.map(Q=>Q.entry_uid)),O=[...C].some(Q=>!$.has(Q));S(Q=>{const J=new Set(Q);return C.forEach(se=>J.add(se)),J}),v(Q=>Q.filter(J=>!C.has(J.entry_uid))),_(new Set),m(null),p(null),O&&ze(a,U,E,u)},[h,a,U,E,u,ze]);d.useEffect(()=>{if(k.size>=2)p(null),m(null);else if(k.size===1){const[C]=k;p(C)}else p(null),m(null)},[k]);const we=d.useMemo(()=>h.filter(C=>k.has(C.entry_uid)),[h,k]);d.useEffect(()=>{if(!N||f)return;const C=h.find($=>$.entry_uid===N);C&&m(C)},[h,N,f]),d.useEffect(()=>{if(Lr)return;const C=new URLSearchParams(window.location.search).get("archive"),$=new URLSearchParams;U&&$.set("q",U),j==="archive"&&E&&$.set("tag",E),j==="archive"&&N&&$.set("entry",N),j==="archive"&&u?($.set("collection",u),a&&$.set("archive",a)):C&&a&&$.set("archive",a);const O=$.toString(),Q=window.location.pathname+(O?"?"+O:"");window.location.pathname+window.location.search!==Q&&history.replaceState(null,"",Q)},[U,E,N,u,a,j]),d.useEffect(()=>{const C=$=>{var se,Te,Ke,Ne;const O=$.key==="/"&&!$.metaKey&&!$.ctrlKey&&!$.altKey,Q=($.metaKey||$.ctrlKey)&&$.key==="k";if(!O&&!Q)return;const J=(se=document.activeElement)==null?void 0:se.tagName;O&&(J==="INPUT"||J==="TEXTAREA"||J==="SELECT")||O&&((Te=document.activeElement)!=null&&Te.isContentEditable)||($.preventDefault(),j==="archive"?((Ke=xt.current)==null||Ke.focus(),(Ne=xt.current)==null||Ne.select()):(bt.current=!0,T("archive")))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[j]),d.useEffect(()=>{const C=$=>{var co,fo;if($.metaKey||$.ctrlKey||$.altKey||$.key!=="j"&&$.key!=="k")return;const O=(co=document.activeElement)==null?void 0:co.tagName;if(O==="INPUT"||O==="TEXTAREA"||O==="SELECT"||(fo=document.activeElement)!=null&&fo.isContentEditable)return;const Q=[...document.querySelectorAll("#entries-body [data-entry-uid]")];if(Q.length===0)return;const[J]=k.size===1?k:[null],se=J?Q.findIndex(rn=>rn.dataset.entryUid===J):-1,Te=$.key==="j"?Math.min(se+1,Q.length-1):Math.max(se-1,0);if(Te===se&&se!==-1)return;const Ke=Q[Te<0?0:Te],Ne=Ke.dataset.entryUid;q.current=Ne;const Ms=++de.current;_(new Set([Ne]));const uo=Be.current.get(Ne)??h.find(rn=>rn.entry_uid===Ne)??null;uo?qe(uo):Dr(a,Ne).then(rn=>{Ms===de.current&&(rn!=null&&rn.summary)&&qe(rn.summary)}).catch(()=>{}),Ke.scrollIntoView({block:"nearest"}),$.preventDefault()};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[k,h,qe,a]),d.useEffect(()=>{j==="archive"&&bt.current&&(bt.current=!1,requestAnimationFrame(()=>{var C,$;(C=xt.current)==null||C.focus(),($=xt.current)==null||$.select()}))},[j]);const ce=d.useCallback(()=>{Re(!0)},[]),Ue=d.useCallback(()=>{Re(!1)},[]),le=d.useCallback(()=>{if(a)return Promise.allSettled([ze(a,U,E,u),fi(a).then(P)])},[a,U,E,u,ze]),dt=d.useCallback((C,$,O="error",Q=null)=>{if(O==="warning"&&Et&&$)return;const J=++ue.current;he(se=>[...se,{id:J,text:C,locator:$,type:O,headline:Q}])},[Et]),wt=d.useCallback(C=>{he($=>$.filter(O=>O.id!==C))},[]),yl=d.useCallback(()=>{sessionStorage.setItem("ublockWarningIgnored","true"),ut(!0),he(C=>C.filter($=>!($.type==="warning"&&$.locator)))},[]),z=d.useCallback(C=>{Qe($=>[...$,C])},[]),re=d.useCallback(C=>{Qe($=>$.filter(O=>O.id!==C))},[]),[be,Ot]=d.useState(null),[Vt,kr]=d.useState(null),Ie=d.useCallback(()=>{f&&Ot(f.entry_uid)},[f]),jr=d.useCallback(()=>Ot(null),[]),of=d.useCallback((C,$)=>{kr({src:C,entry:$})},[]),uf=d.useCallback(()=>kr(null),[]);return d.useEffect(()=>{Ot(null)},[f]),d.useEffect(()=>{const C=$=>{var Q,J,se;if($.key!=="Escape"||ee||be)return;const O=(Q=document.activeElement)==null?void 0:Q.tagName;O==="INPUT"||O==="TEXTAREA"||O==="SELECT"||k.size>0&&($.preventDefault(),_(new Set),(se=(J=document.activeElement)==null?void 0:J.blur)==null||se.call(J))};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[ee,be,k]),d.useEffect(()=>(document.body.classList.toggle("has-audio-bar",!!Vt),()=>document.body.classList.remove("has-audio-bar")),[Vt]),Lr?s.jsx(_g,{archiveId:Lr.archiveId,entryUid:Lr.entryUid}):e==="loading"?s.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?s.jsx(bm,{onComplete:()=>t("login")}):e==="login"?s.jsx(Em,{onLogin:C=>{r(C),t("authenticated")}}):s.jsx(As.Provider,{value:{currentUser:n,setCurrentUser:r},children:s.jsxs(s.Fragment,{children:[s.jsx(Tm,{archives:l,archiveId:a,onArchiveChange:Bn,view:j,onViewChange:nn,onCaptureClick:ce,collections:y,selectedCollectionUid:u,onCollectionChange:_n,isPublicSession:!n,onSignInClick:()=>t("login")}),s.jsxs("main",{className:"app-shell",children:[s.jsxs("div",{className:"workspace",children:[j==="archive"&&s.jsxs("div",{className:"toolbar",children:[s.jsxs("div",{className:"search-field",children:[s.jsx("span",{className:"ico","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"11",cy:"11",r:"7"}),s.jsx("line",{x1:"16.5",y1:"16.5",x2:"21",y2:"21"})]})}),s.jsx("input",{ref:xt,className:"search-input",type:"search","aria-label":"Search archive","aria-busy":Ae,placeholder:"Search titles, URLs, types, tags…",value:U,onChange:C=>X(C.target.value)}),s.jsx("span",{className:"kbd",children:"⌘K"})]}),s.jsxs("span",{className:"result-count",children:[Z&&s.jsxs(s.Fragment,{children:[s.jsx("b",{children:Z.split(" ")[0]})," ",Z.split(" ").slice(1).join(" ")]}),E&&s.jsxs("button",{className:"tag-filter-badge",onClick:w,children:["× ",Dt?Gd(E):E]})]})]}),j==="archive"&&s.jsx(Bm,{entries:h,selectedUids:k,onRowClick:wr,archiveId:a,pendingCaptures:Ee,deletedUids:x,isPublicSession:!n}),j==="runs"&&s.jsx(Wm,{runs:D}),j==="admin"&&s.jsx(Qm,{archives:l}),j==="tags"&&s.jsx(qm,{archiveId:a,tagNodes:V,tagFilter:E,onTagFilterSet:Un,onViewChange:nn,onTagRenamed:M,onTagDeleted:I,onTagsRefresh:B,humanizeTags:Dt}),j==="collections"&&s.jsx(Xm,{archiveId:a}),j==="settings"&&s.jsx(Gm,{tab:L,onTabChange:K,archiveId:a})]}),s.jsx(sg,{archiveId:a,selectedEntry:f,selectedUids:k,selectedEntries:we,detail:Wt,onTagFilterSet:Un,tagNodes:V,onTagsRefresh:B,onEntryTitleChange:F,onEntryDeleted:xe,onBulkDeleted:fe,humanizeTags:Dt,onDetailRefresh:H,onOpenPreview:Ie,onPlay:of,isPublicSession:!n})]}),be&&f&&f.entry_uid===be&&s.jsx(Sg,{archiveId:a,entry:f,detail:Wt,onClose:jr}),Vt&&s.jsx(Ng,{entry:Vt.entry,src:Vt.src,archiveId:a,onClose:uf}),s.jsx(zm,{open:ee,archiveId:a,onClose:Ue,onCaptured:le,onToast:dt,activeJobs:Ee,onJobStarted:z,onJobSettled:re}),s.jsx(Eg,{toasts:Y,onDismiss:wt,onIgnoreUblock:yl})]})})}Kd(document.getElementById("root")).render(s.jsx(d.StrictMode,{children:s.jsx(zg,{})})); diff --git a/crates/archivr-server/static/index.html b/crates/archivr-server/static/index.html index 210c92a..65494c8 100644 --- a/crates/archivr-server/static/index.html +++ b/crates/archivr-server/static/index.html @@ -6,7 +6,7 @@ Archivr - + diff --git a/frontend/src/api.js b/frontend/src/api.js index 3bbed1f..19d6d06 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -174,6 +174,24 @@ export async function submitCapture(archiveId, locator, quality = null, extensio return res.json(); // { job_uid, status: "pending" } } +export async function submitTextCapture(archiveId, {title, body, mime = 'text/markdown'}) { + const payload = { title, body }; + if (mime && mime !== 'text/markdown') payload.mime = mime; + + const res = await fetch(`/api/archives/${archiveId}/captures/text`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payload), + }); + if (!res.ok) { + const body = await res.json().catch(() => ({})); + const err = new Error(body.error || `HTTP ${res.status}`); + err.status = res.status; + throw err; + } + return res.json(); // { job_uid, status: "pending" } +} + // Returns { has_video: bool, qualities: string[] } e.g. { has_video: true, qualities: ["1080p","720p","480p"] } // Throws on network error; returns { has_video: false, qualities: [] } on non-video locators. export async function probeCapture(archiveId, locator) { diff --git a/frontend/src/components/CaptureDialog.jsx b/frontend/src/components/CaptureDialog.jsx index 937bdd3..c4d0111 100644 --- a/frontend/src/components/CaptureDialog.jsx +++ b/frontend/src/components/CaptureDialog.jsx @@ -1,5 +1,5 @@ import { useRef, useEffect, useState, useCallback } from 'react' -import { submitCapture, pollCaptureJob, probeCapture, probePlaylist, getInstanceSettings, uploadFile, deleteUpload } from '../api' +import { submitCapture, submitTextCapture, pollCaptureJob, probeCapture, probePlaylist, getInstanceSettings, uploadFile, deleteUpload } from '../api' let nextItemId = 1 @@ -157,6 +157,30 @@ function makeFileItem(filename) { } } +function makeTextItem() { + return { + id: nextItemId++, + kind: 'text', + title: '', + body: '', + mime: 'text/markdown', + // Fields present for submission-logic compatibility + locator: '', + quality: 'best', + probeState: 'idle', + probeQualities: null, + probeHasAudio: false, + playlistProbeState: 'idle', + playlistInfo: null, + playlistItems: null, + playlistQuality: null, + playlistExpanded: false, + syncEnabled: false, + error: null, + status: 'idle', + } +} + function applyPlaylistQuality(newQ, currentItems) { if (newQ === 'best') { return currentItems.map(item => ({ ...item, quality: 'best' })) @@ -430,9 +454,30 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on onToastRef.current(text, null, type, headline) } - async function submitBgJob(locator, quality, batchId, extraExtensions = {}) { + async function submitBgJob(submission, batchId) { const aid = archiveIdRef.current const id = crypto.randomUUID?.() ?? `job-${Date.now()}-${Math.random()}` + + // Text submission + if (submission.type === 'text') { + try { + const job = await submitTextCapture(aid, { title: submission.title, body: submission.body, mime: submission.mime }) + const locator = `text:${submission.title}` + // Notify App to add skeleton + persist + onJobStartedRef.current?.({ id, jobUid: job.job_uid, locator, archiveId: aid }) + startPolling(id, job.job_uid, locator, aid, batchId) + } catch (e) { + const msg = e.message || 'Submission failed.' + onToastRef.current(msg, `text:${submission.title}`) + settleBatch(batchId, 'failed', `text:${submission.title}`) + } + return + } + + // URL/file submission + const locator = submission.locator + const quality = submission.quality + const extraExtensions = submission.extraExtensions || {} // Capture session options at call time (synchronous — before first await) const extensions = { ublock_enabled: ublockEnabled, @@ -466,16 +511,18 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on // Guard against the Enter-key shortcut in CaptureRow bypassing the // disabled button — uploads must be complete before archiving starts. if (items.some(it => it.kind === 'file' && it.uploadStatus === 'uploading')) return - const toSubmit = items.filter(it => - it.kind === 'file' ? (it.uploadStatus === 'done' && it.uploadLocator) : it.locator.trim() - ) + const toSubmit = items.filter(it => { + if (it.kind === 'file') return it.uploadStatus === 'done' && it.uploadLocator + if (it.kind === 'text') return it.title.trim() && it.body.trim() + return it.locator.trim() + }) if (toSubmit.length === 0) return - if (toSubmit.some(it => it.kind !== 'file' && hasConflict(it))) return - if (toSubmit.some(it => it.kind !== 'file' && ( + if (toSubmit.some(it => it.kind !== 'file' && it.kind !== 'text' && hasConflict(it))) return + if (toSubmit.some(it => it.kind !== 'file' && it.kind !== 'text' && ( it.probeState === 'probing' || (isPlaylistSource(it.locator) && it.playlistProbeState !== 'done')))) return - if (toSubmit.some(it => it.kind !== 'file' && Array.isArray(it.playlistItems) && it.playlistItems.length === 0)) return + if (toSubmit.some(it => it.kind !== 'file' && it.kind !== 'text' && Array.isArray(it.playlistItems) && it.playlistItems.length === 0)) return const batchId = toSubmit.length > 1 ? (crypto.randomUUID?.() ?? `batch-${Date.now()}`) : null @@ -485,9 +532,13 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on // Capture all submission data before any state changes const submissions = toSubmit.map(it => { if (it.kind === 'file') { - return { locator: it.uploadLocator, quality: 'best', extraExtensions: {} } + return { type: 'file', locator: it.uploadLocator, quality: 'best', extraExtensions: {} } + } + if (it.kind === 'text') { + return { type: 'text', title: it.title.trim(), body: it.body.trim(), mime: it.mime } } return { + type: 'url', locator: it.locator.trim(), quality: it.playlistItems !== null ? null : (it.quality || 'best'), extraExtensions: it.playlistItems !== null @@ -502,8 +553,8 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on setItems([makeItem()]) dialogRef.current?.close() // Submit each in background - submissions.forEach(({ locator, quality, extraExtensions }) => - submitBgJob(locator, quality, batchId, extraExtensions) + submissions.forEach(submission => + submitBgJob(submission, batchId) ) } @@ -687,16 +738,18 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on const anyUploading = items.some(it => it.kind === 'file' && it.uploadStatus === 'uploading') - const pendingCount = items.filter(it => - it.kind === 'file' ? (it.uploadStatus === 'done' && it.uploadLocator) : it.locator.trim() - ).length - const anyConflict = items.some(it => it.kind !== 'file' && hasConflict(it)) + const pendingCount = items.filter(it => { + if (it.kind === 'file') return it.uploadStatus === 'done' && it.uploadLocator + if (it.kind === 'text') return it.title.trim() && it.body.trim() + return it.locator.trim() + }).length + const anyConflict = items.some(it => it.kind !== 'file' && it.kind !== 'text' && hasConflict(it)) // True if any playlist row has had all its videos deleted — archive would be a no-op. const anyEmptyPlaylist = items.some(it => - it.kind !== 'file' && Array.isArray(it.playlistItems) && it.playlistItems.length === 0 + it.kind !== 'file' && it.kind !== 'text' && Array.isArray(it.playlistItems) && it.playlistItems.length === 0 ) const anyProbing = items.some(it => - it.kind !== 'file' && ( + it.kind !== 'file' && it.kind !== 'text' && ( it.probeState === 'probing' || // For playlist sources block unless probe completed successfully: // idle = debounce not yet fired; probing = in flight; error = no quality data. @@ -735,6 +788,17 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on item={item} onRemove={() => removeRow(item.id)} /> + ) : item.kind === 'text' ? ( + setItems(prev => prev.map(it => it.id === item.id ? { ...it, title: val } : it))} + onBodyChange={val => setItems(prev => prev.map(it => it.id === item.id ? { ...it, body: val } : it))} + onMimeChange={val => setItems(prev => prev.map(it => it.id === item.id ? { ...it, mime: val } : it))} + onRemove={() => removeRow(item.id)} + onSubmit={handleArchive} + /> ) : ( Upload file + {/* ── Advanced options ────────────────────────────── */} @@ -1139,3 +1209,63 @@ function CaptureFileRow({ item, onRemove }) { ) } + +function CaptureTextRow({ item, autoFocus, onTitleChange, onBodyChange, onMimeChange, onRemove, onSubmit }) { + const titleInputRef = useRef(null) + + useEffect(() => { + if (autoFocus) { + titleInputRef.current?.focus() + } + }, [autoFocus]) // eslint-disable-line react-hooks/exhaustive-deps + + return ( +
+
+ +
+ onTitleChange(e.target.value)} + maxLength={500} + /> +