diff --git a/crates/archivr-core/src/archive.rs b/crates/archivr-core/src/archive.rs index a20ff6e..2a005b3 100644 --- a/crates/archivr-core/src/archive.rs +++ b/crates/archivr-core/src/archive.rs @@ -32,6 +32,8 @@ pub struct EntrySummary { pub cached_bytes: i64, /// Number of direct child entries; 0 for non-container entries. pub child_count: i64, + /// Total non-avatar artifact bytes (query-time; used as denominator for cache-hit %). + pub cacheable_bytes: i64, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] @@ -218,7 +220,8 @@ pub fn list_root_entries( NULL AS parent_entry_uid, EXISTS(SELECT 1 FROM entry_artifacts fav WHERE fav.entry_id = e.id AND fav.artifact_role = 'favicon') AS has_favicon, e.cached_bytes, - (SELECT COUNT(*) FROM archived_entries child WHERE child.parent_entry_id = e.id) AS child_count + (SELECT COUNT(*) FROM archived_entries child WHERE child.parent_entry_id = e.id) AS child_count, + COALESCE(SUM(CASE WHEN ea.artifact_role != 'avatar' THEN b.byte_size ELSE 0 END), 0) + COALESCE((SELECT SUM(b2.byte_size) FROM archived_entries c2 JOIN entry_artifacts ea2 ON ea2.entry_id = c2.id JOIN blobs b2 ON b2.id = ea2.blob_id WHERE c2.parent_entry_id = e.id), 0) AS cacheable_bytes FROM archived_entries e JOIN source_identities si ON si.id = e.source_identity_id LEFT JOIN entry_artifacts ea ON ea.entry_id = e.id @@ -252,6 +255,7 @@ pub fn list_root_entries( has_favicon: row.get::<_, i64>(10)? != 0, cached_bytes: row.get(11)?, child_count: row.get(12)?, + cacheable_bytes: row.get(13)?, }) })? .collect::>>()?; @@ -286,6 +290,7 @@ fn get_entry_summary( has_favicon: row.get::<_, i64>(10)? != 0, cached_bytes: row.get(11)?, child_count: row.get(12)?, + cacheable_bytes: row.get(13)?, }) }) .optional()?; @@ -474,6 +479,7 @@ pub fn list_entries_for_collection( has_favicon: row.get::<_, i64>(10)? != 0, cached_bytes: row.get(11)?, child_count: row.get(12)?, + cacheable_bytes: row.get(13)?, }) })? .collect::>>()?; @@ -522,6 +528,7 @@ pub fn list_child_entries( has_favicon: row.get::<_, i64>(10)? != 0, cached_bytes: row.get(11)?, child_count: row.get(12)?, + cacheable_bytes: row.get(13)?, }) }, )? @@ -693,7 +700,8 @@ const ENTRY_SELECT_COLS: &str = "SELECT e.entry_uid, e.archived_at, e.source_kin parent.entry_uid AS parent_entry_uid, \ EXISTS(SELECT 1 FROM entry_artifacts fav WHERE fav.entry_id = e.id AND fav.artifact_role = 'favicon') AS has_favicon, \ e.cached_bytes, \ - (SELECT COUNT(*) FROM archived_entries child WHERE child.parent_entry_id = e.id) AS child_count"; + (SELECT COUNT(*) FROM archived_entries child WHERE child.parent_entry_id = e.id) AS child_count, \ + COALESCE(SUM(CASE WHEN ea.artifact_role != 'avatar' THEN b.byte_size ELSE 0 END), 0) + COALESCE((SELECT SUM(b2.byte_size) FROM archived_entries c2 JOIN entry_artifacts ea2 ON ea2.entry_id = c2.id JOIN blobs b2 ON b2.id = ea2.blob_id WHERE c2.parent_entry_id = e.id), 0) AS cacheable_bytes"; const ENTRY_FROM_JOINS: &str = "FROM archived_entries e \ JOIN source_identities si ON si.id = e.source_identity_id \ @@ -802,6 +810,7 @@ pub fn search_entries( has_favicon: row.get::<_, i64>(10)? != 0, cached_bytes: row.get(11)?, child_count: row.get(12)?, + cacheable_bytes: row.get(13)?, }) })? .collect::>>()?; @@ -1010,7 +1019,8 @@ pub fn entries_for_tag( parent.entry_uid AS parent_entry_uid, EXISTS(SELECT 1 FROM entry_artifacts fav WHERE fav.entry_id = e.id AND fav.artifact_role = 'favicon') AS has_favicon, e.cached_bytes, - (SELECT COUNT(*) FROM archived_entries child WHERE child.parent_entry_id = e.id) AS child_count + (SELECT COUNT(*) FROM archived_entries child WHERE child.parent_entry_id = e.id) AS child_count, + COALESCE(SUM(CASE WHEN ea.artifact_role != 'avatar' THEN b.byte_size ELSE 0 END), 0) AS cacheable_bytes FROM archived_entries e JOIN source_identities si ON si.id = e.source_identity_id LEFT JOIN entry_artifacts ea ON ea.entry_id = e.id @@ -1037,6 +1047,7 @@ pub fn entries_for_tag( has_favicon: row.get::<_, i64>(10)? != 0, cached_bytes: row.get(11)?, child_count: row.get(12)?, + cacheable_bytes: row.get(13)?, }) })? .collect::>>()?; diff --git a/crates/archivr-core/src/database.rs b/crates/archivr-core/src/database.rs index ab5b51e..5f85ca0 100644 --- a/crates/archivr-core/src/database.rs +++ b/crates/archivr-core/src/database.rs @@ -390,6 +390,7 @@ pub fn initialize_schema(conn: &Connection) -> Result<()> { JOIN blobs b ON b.id = ea.blob_id WHERE ea.entry_id = archived_entries.id AND ea.blob_id IS NOT NULL + AND ea.artifact_role != 'avatar' AND EXISTS ( SELECT 1 FROM entry_artifacts ea2 @@ -401,6 +402,33 @@ pub fn initialize_schema(conn: &Connection) -> Result<()> { ) );", )?; + } else { + // Re-migration: strip avatar blobs from cached_bytes on entries that + // already had the column populated before this filter was introduced. + // Scoped to entries with avatar artifacts only; fast and idempotent. + conn.execute_batch( + "UPDATE archived_entries + SET cached_bytes = ( + SELECT COALESCE(SUM(b.byte_size), 0) + FROM entry_artifacts ea + JOIN blobs b ON b.id = ea.blob_id + WHERE ea.entry_id = archived_entries.id + AND ea.blob_id IS NOT NULL + AND ea.artifact_role != 'avatar' + AND EXISTS ( + SELECT 1 + FROM entry_artifacts ea2 + JOIN archived_entries e2 ON e2.id = ea2.entry_id + WHERE ea2.blob_id = ea.blob_id + AND (e2.archived_at < archived_entries.archived_at + OR (e2.archived_at = archived_entries.archived_at + AND e2.id < archived_entries.id)) + ) + ) + WHERE id IN ( + SELECT DISTINCT entry_id FROM entry_artifacts WHERE artifact_role = 'avatar' + );", + )?; } // Migration: add notes_json column to existing capture_jobs tables. @@ -1482,6 +1510,7 @@ pub fn refresh_entry_cached_bytes(conn: &Connection, entry_id: i64) -> Result<() JOIN archived_entries e ON e.id = ea.entry_id WHERE ea.entry_id = ?1 AND ea.blob_id IS NOT NULL + AND ea.artifact_role != 'avatar' AND EXISTS ( SELECT 1 FROM entry_artifacts ea2 @@ -1518,6 +1547,7 @@ pub fn cascade_cached_bytes_after_delete(conn: &Connection, entry_id: i64) -> Re JOIN blobs b ON b.id = ea.blob_id WHERE ea.entry_id = archived_entries.id AND ea.blob_id IS NOT NULL + AND ea.artifact_role != 'avatar' AND EXISTS ( SELECT 1 FROM entry_artifacts ea3 @@ -1570,6 +1600,7 @@ fn cascade_cached_bytes_after_subtree_delete(conn: &Connection, subtree_ids: &[i JOIN blobs b ON b.id = ea.blob_id WHERE ea.entry_id = archived_entries.id AND ea.blob_id IS NOT NULL + AND ea.artifact_role != 'avatar' AND EXISTS ( SELECT 1 FROM entry_artifacts ea3 diff --git a/crates/archivr-server/static/assets/index-BlDAGZHO.js b/crates/archivr-server/static/assets/index-C9dla3pB.js similarity index 76% rename from crates/archivr-server/static/assets/index-BlDAGZHO.js rename to crates/archivr-server/static/assets/index-C9dla3pB.js index 0d6a31b..861b7ba 100644 --- a/crates/archivr-server/static/assets/index-BlDAGZHO.js +++ b/crates/archivr-server/static/assets/index-C9dla3pB.js @@ -42,6 +42,6 @@ ${be.map(We=>` ${We}`).join(` `)}`),Je.length>0&&xe.push(`With warnings: ${Je.map(We=>` ${We}`).join(` `)}`);const zt=xe.length>0?xe.join(` -`):null;k.current(zt,null,Ue,He)}async function G(N,U,D,O={}){var be,Je;const V=x.current,K=((be=crypto.randomUUID)==null?void 0:be.call(crypto))??`job-${Date.now()}-${Math.random()}`,he={ublock_enabled:ce,reader_mode:te,cookie_ext_enabled:b,modal_closer_enabled:H,via_freedium:ee,...O};try{const He=await Rh(V,N,U,he);(Je=j.current)==null||Je.call(j,{id:K,jobUid:He.job_uid,locator:N,archiveId:V}),T(K,He.job_uid,N,V,D)}catch(He){const Ue=He.message||"Submission failed.";k.current(Ue,N),M(D,"failed",N)}}function W(){var O,V;const N=d.filter(K=>K.locator.trim());if(N.length===0||N.some(K=>ou(K))||N.some(K=>K.probeState==="probing"||vn(K.locator)&&K.playlistProbeState!=="done")||N.some(K=>Array.isArray(K.playlistItems)&&K.playlistItems.length===0))return;const U=N.length>1?((O=crypto.randomUUID)==null?void 0:O.call(crypto))??`batch-${Date.now()}`:null;U&&g.current.set(U,{total:N.length,archived:0,warnings:0,failed:0,failedLocators:[],warningLocators:[]});const D=N.map(K=>({locator:K.locator.trim(),quality:K.playlistItems!==null?null:K.quality||"best",extraExtensions:K.playlistItems!==null?{per_item_quality:Object.fromEntries(K.playlistItems.map(he=>[he.id,he.quality])),sync:K.syncEnabled}:{}}));m([zn()]),(V=u.current)==null||V.close(),D.forEach(({locator:K,quality:he,extraExtensions:be})=>G(K,he,U,be))}function de(){m(N=>[...N,zn()])}function ae(N){clearTimeout(h.current.get(N)),h.current.delete(N),m(U=>{const D=U.filter(O=>O.id!==N);return D.length===0?[zn()]:D})}function De(N,U){if(clearTimeout(h.current.get(N)),m(D=>D.map(O=>O.id===N?{...O,locator:U,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best",playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1}:O)),Rd(U)){const D=setTimeout(async()=>{h.current.delete(N),m(O=>O.map(V=>V.id===N?{...V,probeState:"probing"}:V));try{const O=await Ih(x.current,U.trim());m(V=>V.map(K=>{if(K.id!==N||K.locator!==U)return K;const he=O.qualities??[],be=O.has_audio??!1,Je=he.length===0&&be?"audio":"best";return{...K,probeState:"done",probeQualities:he,probeHasAudio:be,quality:Je}}))}catch{m(O=>O.map(V=>V.id===N?{...V,probeState:"idle",probeQualities:null}:V))}},600);h.current.set(N,D)}else if(vn(U)){const D=setTimeout(async()=>{h.current.delete(N),m(O=>O.map(V=>V.id===N?{...V,playlistProbeState:"probing"}:V));try{const O=await $h(x.current,U.trim());m(V=>V.map(K=>K.id!==N||K.locator!==U?K:{...K,playlistProbeState:"done",playlistInfo:O,playlistItems:O.items.map(he=>({...he,quality:null})),playlistQuality:null}))}catch{m(O=>O.map(V=>V.id===N?{...V,playlistProbeState:"error"}:V))}},800);h.current.set(N,D)}}function ze(N,U){m(D=>D.map(O=>O.id===N?{...O,quality:U}:O))}function Be(N,U){m(D=>D.map(O=>{if(O.id!==N)return O;const V=mm(U,O.playlistItems);return{...O,playlistQuality:U,playlistItems:V}}))}function ct(N,U,D){m(O=>O.map(V=>V.id!==N?V:{...V,playlistItems:V.playlistItems.map(K=>K.id===U?{...K,quality:D}:K)}))}function nt(N){m(U=>U.map(D=>D.id===N?{...D,playlistExpanded:!D.playlistExpanded}:D))}function dt(N,U){m(D=>D.map(O=>O.id===N?{...O,syncEnabled:U}:O))}function ft(N,U){m(D=>D.map(O=>O.id!==N?O:{...O,playlistItems:O.playlistItems.filter(V=>V.id!==U)}))}const Xe=d.filter(N=>N.locator.trim()).length,R=d.some(N=>ou(N)),Y=d.some(N=>Array.isArray(N.playlistItems)&&N.playlistItems.length===0),Se=d.some(N=>N.probeState==="probing"||vn(N.locator)&&N.playlistProbeState!=="done");return s.jsx("dialog",{ref:u,className:"capture-dialog",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 N;return(N=u.current)==null?void 0:N.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:d.map((N,U)=>s.jsx(ym,{item:N,autoFocus:U===d.length-1,onLocatorChange:D=>De(N.id,D),onQualityChange:D=>ze(N.id,D),onRemove:()=>ae(N.id),onSubmit:W,onPlaylistQualityChange:D=>Be(N.id,D),onPlaylistItemQualityChange:(D,O)=>ct(N.id,D,O),onPlaylistToggle:()=>nt(N.id),onSyncChange:D=>dt(N.id,D),onPlaylistItemDelete:D=>ft(N.id,D)},N.id))}),s.jsxs("button",{type:"button",className:"capture-add-row",onClick:de,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 another"]}),s.jsxs("div",{className:"capture-advanced",children:[s.jsxs("button",{type:"button",className:"capture-advanced-toggle",onClick:()=>E(N=>!N),"aria-expanded":w,children:[s.jsx("svg",{className:`capture-chevron${w?" 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"]}),w&&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":ce,className:`ext-toggle ext-toggle--sm${ce?" ext-toggle--on":""}`,onClick:()=>_(N=>N===null?!ce:!N),"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"}),!(S!=null&&S.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":b,className:`ext-toggle ext-toggle--sm${b?" ext-toggle--on":""}`,onClick:()=>Q(N=>!N),"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":te,className:`ext-toggle ext-toggle--sm${te?" ext-toggle--on":""}`,onClick:()=>z(N=>!N),"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":H,className:`ext-toggle ext-toggle--sm${H?" ext-toggle--on":""}`,onClick:()=>q(N=>!N),"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":ee,className:`ext-toggle ext-toggle--sm${ee?" ext-toggle--on":""}`,onClick:()=>pe(N=>!N),"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:W,disabled:Xe===0||R||Se||Y,children:Xe>1?`Archive ${Xe}`:"Archive"}),s.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var N;return(N=u.current)==null?void 0:N.close()},children:"Cancel"})]})]})})}function ym({item:e,autoFocus:t,onLocatorChange:n,onQualityChange:r,onRemove:l,onSubmit:i,onPlaylistQualityChange:a,onPlaylistItemQualityChange:o,onPlaylistToggle:u,onSyncChange:c,onPlaylistItemDelete:y}){const h=f.useRef(null);f.useEffect(()=>{var v;t&&((v=h.current)==null||v.focus())},[t]);const g=(()=>{if(vn(e.locator)){if(e.playlistProbeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Probing playlist…",children:"…"});if(e.playlistProbeState==="done"){const v=[...new Set(e.playlistItems.flatMap(p=>p.qualities.map(d=>parseInt(d))))].sort((p,d)=>d-p),k=e.playlistItems.every(p=>p.has_audio),j=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"}),v.map(p=>s.jsxs("option",{value:`${p}p`,children:[p,"p"]},p)),k&&s.jsx("option",{value:"audio",children:"Audio only"})]}),j>0&&s.jsxs("span",{className:"capture-conflict-badge",children:[j," 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(!Rd(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 v=e.probeQualities??[],k=e.probeHasAudio??!1;return v.length===0&&!k?s.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):v.length===0&&k?s.jsx("select",{className:"capture-quality",value:"audio",onChange:j=>r(j.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:j=>r(j.target.value),"aria-label":"Video quality",children:[s.jsx("option",{value:"best",children:"Best quality"}),v.map(j=>s.jsx("option",{value:j,children:j},j)),k&&s.jsx("option",{value:"audio",children:"Audio only"})]})}return null})(),x=vn(e.locator)&&e.playlistProbeState==="done"?s.jsxs("label",{className:"capture-sync-row",children:[s.jsx("input",{type:"checkbox",checked:e.syncEnabled,onChange:v=>c(v.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:[vn(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:h,className:"capture-input",type:"text",placeholder:"https://… · yt:ID · ytm:ID · tweet:ID · x:ID",value:e.locator,onChange:v=>n(v.target.value),onKeyDown:v=>{v.key==="Enter"&&i()},autoComplete:"off",spellCheck:!1}),g,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}),vn(e.locator)&&e.playlistProbeState==="done"&&e.playlistExpanded?s.jsxs("div",{className:"capture-playlist-items",children:[e.playlistItems.map(v=>s.jsxs("div",{className:`capture-playlist-item${v.quality===null?" capture-playlist-item--conflict":""}`,children:[s.jsx("span",{className:"capture-playlist-item-title",children:v.title||v.url}),s.jsxs("select",{className:"capture-item-quality",value:v.quality??"",onChange:k=>o(v.id,k.target.value),"aria-label":`Quality for ${v.title||v.url}`,children:[v.quality===null&&s.jsx("option",{value:"",disabled:!0,children:"Choose…"}),s.jsx("option",{value:"best",children:"Best quality"}),v.qualities.map(k=>s.jsx("option",{value:k,children:k},k)),v.has_audio&&s.jsx("option",{value:"audio",children:"Audio only"})]}),v.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 ${v.title||v.url}`,onClick:()=>y(v.id),children:"×"})]},v.id)),x]}):x]})}function vm(){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 Xr(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 St(e){return xm(e)??""}function Ka(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 uu={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function _s(e){return uu[e]??uu.other}function Id(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function wm({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:Ka(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[s.jsx("span",{className:"source-icon",children:s.jsx("span",{dangerouslySetInnerHTML:{__html:_s(e.source_kind)}})}),s.jsx("span",{className:"entry-title",children:St(e.title)||St(e.entry_uid)})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:St(e.entity_kind)})}),s.jsx("div",{className:"col-size",children:s.jsx("span",{className:"size-total",children:Xr(e.total_artifact_bytes)})}),s.jsx("div",{className:"url-cell col-url",children:St(e.original_url)})]})}function km({entry:e,archiveId:t,rowIndex:n,isSelected:r,isMultiSelected:l,onRowClick:i,selectedUids:a,deletedUids:o}){const[u,c]=f.useState(!1),[y,h]=f.useState(!1),[g,x]=f.useState(null),[v,k]=f.useState(!1),p=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!u?s.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>c(!0),style:{objectFit:"contain"}}):s.jsx("span",{dangerouslySetInnerHTML:{__html:_s(e.source_kind)}}),d=r||l,m=e.child_count>0;function w(_){_.stopPropagation(),i(e,{ctrlKey:!0,metaKey:!1,shiftKey:!1,preventDefault(){}})}async function E(_){if(_.stopPropagation(),y){h(!1);return}if(h(!0),g===null&&!v){k(!0);try{const S=await Nh(t,e.entry_uid);x(S)}catch{x([])}finally{k(!1)}}}const P=["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:P,"data-entry-uid":e.entry_uid,children:[s.jsxs("div",{className:"entry-row-main",tabIndex:0,onMouseDown:_=>{_.shiftKey&&_.preventDefault()},onClick:_=>i(e,_),onKeyDown:_=>{_.key==="Enter"&&i(e,_)},children:[s.jsx("div",{className:"col-check",children:s.jsx("button",{type:"button",className:`row-checkbox${d?" is-checked":""}`,"aria-pressed":d,"aria-label":d?"Deselect entry":"Select entry",onClick:w,onKeyDown:_=>_.stopPropagation()})}),s.jsx("div",{className:"col-added",children:Ka(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[m&&s.jsx("button",{type:"button",className:`entry-expand-btn${y?" is-expanded":""}`,"aria-label":y?"Collapse children":`Expand ${e.child_count} items`,"aria-expanded":y,onClick:E,onKeyDown:_=>_.stopPropagation()}),s.jsx("span",{className:"source-icon",children:p}),s.jsx("span",{className:"entry-title",children:St(e.title)||St(e.entry_uid)}),m&&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:St(e.entity_kind)})}),s.jsxs("div",{className:"col-size",children:[s.jsx("span",{className:"size-total",children:Xr(e.total_artifact_bytes)}),e.cached_bytes>0&&e.total_artifact_bytes>0&&s.jsxs("span",{className:"size-cached-pct",title:`${Xr(e.cached_bytes)} already on disk from an earlier entry`,children:[Math.round(e.cached_bytes/e.total_artifact_bytes*100),"% cached"]})]}),s.jsx("div",{className:"url-cell col-url",children:St(e.original_url)})]}),y&&s.jsxs(s.Fragment,{children:[v&&s.jsx("div",{className:"child-entries-loading",children:"Loading…"}),s.jsx("div",{className:"child-entries","aria-label":`${e.child_count} child entries`,children:g&&g.filter(_=>!(o!=null&&o.has(_.entry_uid))).map((_,S)=>s.jsx(wm,{entry:_,index:S,onRowClick:i,selectedUids:a},_.entry_uid))})]})]})}function jm({entries:e,selectedUids:t,onRowClick:n,archiveId:r,pendingCaptures:l=[],deletedUids:i}){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(a=>a.archiveId===r).reverse().map(a=>s.jsx(vm,{},a.id)),e.map((a,o)=>s.jsx(km,{entry:a,rowIndex:o,archiveId:r,isSelected:t.size===1&&t.has(a.entry_uid),isMultiSelected:t.size>=2&&t.has(a.entry_uid),onRowClick:n,selectedUids:t,deletedUids:i},a.entry_uid))]})]})})}function Sm(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 Nm({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 _m({runs:e}){const[t,n]=f.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:Sm(l.started_at)}),s.jsxs("td",{children:[s.jsx(Nm,{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 Cm=4;function Em({archives:e}){const{currentUser:t}=f.useContext(Cs)??{},n=t&&(t.role_bits&Cm)!==0,[r,l]=f.useState("users"),[i,a]=f.useState([]),[o,u]=f.useState([]),[c,y]=f.useState(!1),[h,g]=f.useState(null),[x,v]=f.useState(""),[k,j]=f.useState(""),[p,d]=f.useState(""),[m,w]=f.useState(null),[E,P]=f.useState(!1),[_,S]=f.useState(""),[I,b]=f.useState(""),[Q,H]=f.useState(null),[q,ee]=f.useState(!1),pe=f.useCallback(async()=>{if(n){y(!0),g(null);try{const[T,M]=await Promise.all([Kh(),Jh()]);a(T),u(M)}catch(T){g(T.message)}finally{y(!1)}}},[n]);f.useEffect(()=>{pe()},[pe]);async function ce(T){const M=T.status==="active"?"disabled":"active";try{await Xh(T.user_uid,M),a(G=>G.map(W=>W.user_uid===T.user_uid?{...W,status:M}:W))}catch(G){g(G.message)}}async function te(T){if(T.preventDefault(),!x.trim()||!k){w("Username and password required");return}P(!0),w(null);try{await qh(x.trim(),k,p.trim()||void 0),v(""),j(""),d(""),await pe()}catch(M){w(M.message)}finally{P(!1)}}async function z(T){if(T.preventDefault(),!_.trim()||!I.trim()){H("Slug and name required");return}ee(!0),H(null);try{await Yh(_.trim(),I.trim()),S(""),b(""),await pe()}catch(M){H(M.message)}finally{ee(!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"})]}),h&&s.jsx("div",{className:"form-msg form-msg--err",children:h}),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(T=>s.jsxs("tr",{className:T.status==="disabled"?"admin-row-disabled":"",children:[s.jsx("td",{children:T.username}),s.jsx("td",{className:"muted",children:T.email||"—"}),s.jsx("td",{children:T.role_slugs.join(", ")||"—"}),s.jsx("td",{children:s.jsx("span",{className:`status-badge status-${T.status}`,children:T.status})}),s.jsx("td",{children:s.jsx("button",{className:"admin-action-btn",onClick:()=>ce(T),children:T.status==="active"?"Ban":"Unban"})})]},T.user_uid))})]}),s.jsx("h3",{children:"Create User"}),s.jsxs("form",{className:"admin-form",onSubmit:te,children:[s.jsx("input",{className:"admin-input",placeholder:"Username",value:x,onChange:T=>v(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:k,onChange:T=>j(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:p,onChange:T=>d(T.target.value)}),m&&s.jsx("div",{className:"form-msg form-msg--err",children:m}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:E,children:E?"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(T=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:T.slug})}),s.jsx("td",{children:T.name}),s.jsx("td",{children:T.level}),s.jsx("td",{children:T.bit_position}),s.jsx("td",{children:T.is_builtin?"✓":""})]},T.role_uid))})]}),s.jsx("h3",{children:"Create Custom Role"}),s.jsxs("form",{className:"admin-form",onSubmit:z,children:[s.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:_,onChange:T=>S(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:I,onChange:T=>b(T.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:q,children:q?"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(T=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:T.label}),s.jsx("div",{className:"muted",children:T.archive_path})]},T.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(T=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:T.label}),s.jsx("div",{className:"muted",children:T.archive_path})]},T.id))})]})}function $d({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($d,{node:r,onPick:t},r.tag.tag_uid))})})]})}function cu({title:e,tagNodes:t,excludeUid:n,onPick:r,onCancel:l}){f.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($d,{node:o,onPick:r},o.tag.tag_uid))}):s.jsx("p",{className:"tag-picker-empty",children:"No other tags available."})]})]})})}function Dd({parentPath:e,archiveId:t,onDone:n,onCancel:r}){const[l,i]=f.useState(""),a=f.useRef(!1);async function o(){const u=l.trim();if(!u){r();return}const c=e?`${e}/${u}`:`/${u}`;try{await Lh(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 Od({node:e,archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:y,pendingCreateParentUid:h,onCreateDone:g,onCreateCancel:x}){var Q;const v=n===e.tag.full_path,[k,j]=f.useState(!1),[p,d]=f.useState(""),m=f.useRef(!1);function w(){if(k)return;if(c){y(e);return}const H=v?null:e.tag.full_path;r(H),l("archive")}function E(H){H.stopPropagation(),!c&&(d(e.tag.slug),j(!0))}async function P(){const H=p.trim();if(!H||H===e.tag.slug){j(!1);return}try{const q=await bh(t,e.tag.tag_uid,H);i(e.tag.full_path,q.full_path),o()}catch{}finally{j(!1)}}async function _(H){var ee;H.stopPropagation();const q=((ee=e.children)==null?void 0:ee.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(q))try{await Ph(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const S={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:y,pendingCreateParentUid:h,onCreateDone:g,onCreateCancel:x},I=h===e.tag.tag_uid,b=((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:[k?s.jsx("input",{className:"tag-rename-input",autoFocus:!0,value:p,onChange:H=>d(H.target.value),onKeyDown:H=>{H.key==="Enter"&&H.currentTarget.blur(),H.key==="Escape"&&(m.current=!0,H.currentTarget.blur())},onBlur:()=>{m.current?(m.current=!1,j(!1)):P()}}):s.jsxs("button",{className:`tag-node-btn${v?" 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:E,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:H=>{H.stopPropagation(),E(H)},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"})})]}),!k&&!c&&s.jsx("button",{className:"remove tag-node-delete",title:`Delete "${e.tag.full_path}"`,onClick:_,"aria-label":`Delete "${e.tag.full_path}"`,children:"×"})]}),(b||I)&&s.jsx("div",{className:"tag-children",children:s.jsxs("ul",{className:"tag-tree-list",children:[e.children.map(H=>s.jsx(Od,{node:H,...S},H.tag.tag_uid)),I&&s.jsx("li",{children:s.jsx(Dd,{parentPath:e.tag.full_path,archiveId:t,onDone:g,onCancel:x})})]})})]})}function Tm({archiveId:e,tagNodes:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u}){const[c,y]=f.useState(null),[h,g]=f.useState(null);function x(){y("select-source"),g(null)}function v(){y(null),g(null)}f.useEffect(()=>{if(c!=="select-source")return;function q(ee){ee.key==="Escape"&&(ee.preventDefault(),ee.stopPropagation(),v())}return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[c]);function k(q){g(q),y("select-dest")}async function j(q){const ee=h.tag.full_path,pe=h.tag.tag_uid,ce=(q==null?void 0:q.tag_uid)??null;v();try{const te=await zh(e,pe,ce);i(ee,te.full_path),o()}catch(te){alert(te.message||"Move failed")}}const[p,d]=f.useState(null),[m,w]=f.useState(void 0);function E(){d("select-parent"),w(void 0)}function P(){d(null),w(void 0)}function _(q){w(q??null),d("input")}function S(){d(null),w(void 0),o()}const I=c==="select-source",b=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:I,onMoveSourceSelect:k,pendingCreateParentUid:b,onCreateDone:S,onCreateCancel:P},H=b==="__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:I?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:v,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:E,title:"Create a new tag",disabled:!!p||!!c,children:"+ New"}),s.jsx("button",{className:"tag-tree-action-btn",onClick:x,title:"Move a tag to a different parent",disabled:!!p||!!c||t.length===0,children:"Move"})]})]})}),t.length===0&&!H?s.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):s.jsxs("ul",{className:"tag-tree-list",children:[t.map(q=>s.jsx(Od,{node:q,...Q},q.tag.tag_uid)),H&&s.jsx("li",{children:s.jsx(Dd,{parentPath:null,archiveId:e,onDone:S,onCancel:P})})]})]}),p==="select-parent"&&s.jsx(cu,{title:"Create tag under…",tagNodes:t,excludeUid:null,onPick:_,onCancel:P}),c==="select-dest"&&h&&s.jsx(cu,{title:`Move "${h.tag.slug}" under…`,tagNodes:t,excludeUid:h.tag.tag_uid,onPick:j,onCancel:v})]})}const jr=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],bm=e=>{var t;return((t=jr.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function Pm({archiveId:e}){const[t,n]=f.useState([]),[r,l]=f.useState(!1),[i,a]=f.useState(null),[o,u]=f.useState(null),[c,y]=f.useState(null),[h,g]=f.useState(!1),[x,v]=f.useState(null),[k,j]=f.useState(""),[p,d]=f.useState(""),[m,w]=f.useState(2),[E,P]=f.useState(!1),[_,S]=f.useState(null),[I,b]=f.useState(""),[Q,H]=f.useState(2),[q,ee]=f.useState(!1),[pe,ce]=f.useState(null),[te,z]=f.useState(!1),[T,M]=f.useState(""),G=f.useRef(null),W=t.find(R=>R.collection_uid===o)??null,de=(W==null?void 0:W.slug)==="_default_",ae=f.useCallback(async()=>{if(e){l(!0),a(null);try{const R=await Ld(e);n(R)}catch(R){a(R.message)}finally{l(!1)}}},[e]),De=f.useCallback(async R=>{if(!R){y(null);return}g(!0),v(null);try{const Y=await Zh(e,R);y(Y)}catch(Y){v(Y.message)}finally{g(!1)}},[e]);f.useEffect(()=>{ae()},[ae]),f.useEffect(()=>{De(o)},[o,De]),f.useEffect(()=>{te&&G.current&&G.current.focus()},[te]);async function ze(R){R.preventDefault();const Y=k.trim(),Se=p.trim();if(!(!Y||!Se)){P(!0),S(null);try{const N=await Gh(e,Y,Se,m);j(""),d(""),w(2),await ae(),u(N.collection_uid)}catch(N){S(N.message)}finally{P(!1)}}}async function Be(){const R=T.trim();if(!R||!W){z(!1);return}try{await au(e,W.collection_uid,{name:R}),await ae(),y(Y=>Y&&{...Y,name:R})}catch(Y){a(Y.message)}finally{z(!1)}}async function ct(R){if(W)try{await au(e,W.collection_uid,{default_visibility_bits:R}),await ae(),y(Y=>Y&&{...Y,default_visibility_bits:R})}catch(Y){a(Y.message)}}async function nt(){if(W&&window.confirm(`Delete collection "${W.name}"? Entries will not be deleted.`))try{await rm(e,W.collection_uid),u(null),y(null),await ae()}catch(R){a(R.message)}}async function dt(R){R.preventDefault();const Y=I.trim();if(!(!Y||!W)){ee(!0),ce(null);try{await zd(e,W.collection_uid,Y,Q),b(""),await De(W.collection_uid)}catch(Se){ce(Se.message)}finally{ee(!1)}}}async function ft(R){if(W)try{await em(e,W.collection_uid,R),await De(W.collection_uid)}catch(Y){v(Y.message)}}async function Xe(R,Y){if(W)try{await tm(e,W.collection_uid,R,Y),y(Se=>Se&&{...Se,entries:Se.entries.map(N=>N.entry_uid===R?{...N,collection_visibility_bits:Y}:N)})}catch(Se){v(Se.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(R=>s.jsxs("button",{className:`coll-sidebar-row${o===R.collection_uid?" is-active":""}`,onClick:()=>u(R.collection_uid),children:[s.jsx("span",{className:"coll-row-name",children:R.name}),s.jsx("span",{className:"coll-row-meta",children:bm(R.default_visibility_bits)})]},R.collection_uid)),t.length===0&&!r&&s.jsx("div",{className:"muted",style:{padding:"8px 12px"},children:"No collections yet."})]}),W?s.jsxs("div",{className:"coll-detail",children:[s.jsxs("div",{className:"coll-detail-header",children:[te?s.jsx("input",{ref:G,className:"coll-rename-input",value:T,onChange:R=>M(R.target.value),onBlur:Be,onKeyDown:R=>{R.key==="Enter"&&Be(),R.key==="Escape"&&z(!1)}}):s.jsxs("h3",{className:`coll-detail-name${de?"":" coll-detail-name--editable"}`,title:de?void 0:"Click to rename",onClick:()=>{de||(M(W.name),z(!0))},children:[(c==null?void 0:c.name)??W.name,!de&&s.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!de&&s.jsx("button",{className:"coll-delete-btn",onClick:nt,title:"Delete collection",children:"Delete"})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Default visibility"}),s.jsx("select",{className:"coll-vis-select",value:(c==null?void 0:c.default_visibility_bits)??W.default_visibility_bits,onChange:R=>ct(Number(R.target.value)),disabled:de,children:jr.map(R=>s.jsx("option",{value:R.value,children:R.label},R.value))})]}),s.jsxs("div",{className:"coll-entries-section",children:[s.jsx("div",{className:"coll-section-heading",children:"Entries"}),h&&s.jsx("div",{className:"muted",children:"Loading…"}),x&&s.jsx("div",{className:"collections-error",children:x}),!h&&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(R=>s.jsxs("li",{className:"coll-entry-row",children:[s.jsxs("div",{className:"coll-entry-info",children:[s.jsx("span",{className:"coll-entry-title",children:R.title||R.entry_uid}),s.jsx("span",{className:"coll-entry-kind muted",children:R.source_kind})]}),s.jsxs("div",{className:"coll-entry-actions",children:[s.jsx("select",{className:"coll-entry-vis-select",value:R.collection_visibility_bits,onChange:Y=>Xe(R.entry_uid,Number(Y.target.value)),children:jr.map(Y=>s.jsx("option",{value:Y.value,children:Y.label},Y.value))}),!de&&s.jsx("button",{className:"coll-entry-remove",onClick:()=>ft(R.entry_uid),title:"Remove from collection",children:"×"})]})]},R.entry_uid))}))]}),!de&&s.jsxs("form",{className:"coll-add-entry-form",onSubmit:dt,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:I,onChange:R=>b(R.target.value),placeholder:"entry_uid",required:!0}),s.jsx("select",{className:"coll-vis-select",value:Q,onChange:R=>H(Number(R.target.value)),children:jr.map(R=>s.jsx("option",{value:R.value,children:R.label},R.value))}),s.jsx("button",{className:"coll-add-btn",type:"submit",disabled:q,children:q?"…":"Add"})]}),pe&&s.jsx("div",{className:"collections-error",style:{marginTop:4},children:pe})]})]}):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:ze,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:k,onChange:R=>{j(R.target.value),p||d(R.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:R=>d(R.target.value),placeholder:"my-collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-vis",children:"Default visibility"}),s.jsx("select",{className:"capture-input",id:"coll-vis",style:{height:42},value:m,onChange:R=>w(Number(R.target.value)),children:jr.map(R=>s.jsx("option",{value:R.value,children:R.label},R.value))})]}),_&&s.jsx("div",{className:"collections-error",children:_}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:E,children:E?"Creating…":"Create collection"})]})]})]}):s.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const Lm=4;function zm({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=f.useContext(Cs)??{},i=r&&(r.role_bits&Lm)!==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(Rm,{currentUser:r,setCurrentUser:l}),e==="tokens"&&s.jsx(Im,{}),e==="instance"&&i&&s.jsx($m,{}),e==="cookies"&&i&&s.jsx(Om,{}),e==="extensions"&&i&&s.jsx(Am,{}),e==="storage"&&i&&s.jsx(Dm,{archiveId:n})]})}function Rm({currentUser:e,setCurrentUser:t}){const[n,r]=f.useState((e==null?void 0:e.display_name)??""),[l,i]=f.useState(!1),[a,o]=f.useState(null),[u,c]=f.useState(""),[y,h]=f.useState(""),[g,x]=f.useState(""),[v,k]=f.useState(!1),[j,p]=f.useState(null);async function d(w){w.preventDefault(),i(!0),o(null);try{await Bh(n),t(E=>({...E,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(E){o({ok:!1,text:E.message})}finally{i(!1)}}async function m(w){if(w.preventDefault(),y!==g){p({ok:!1,text:"Passwords do not match."});return}k(!0),p(null);try{await Uh(u,y),c(""),h(""),x(""),p({ok:!0,text:"Password changed."})}catch(E){p({ok:!1,text:E.message})}finally{k(!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:d,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 E=w.target.checked;try{await Hh({humanize_slugs:E}),t(P=>({...P,humanize_slugs:E}))}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=>h(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:g,onChange:w=>x(w.target.value),required:!0})]}),j&&s.jsx("div",{className:`form-msg form-msg--${j.ok?"ok":"err"}`,children:j.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:v,children:v?"Changing…":"Change Password"})]})]})]})}function Im(){const[e,t]=f.useState([]),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState(""),[u,c]=f.useState(!1),[y,h]=f.useState(null),g=f.useCallback(async()=>{r(!0),i(null);try{t(await Wh())}catch(k){i(k.message)}finally{r(!1)}},[]);f.useEffect(()=>{g()},[g]);async function x(k){if(k.preventDefault(),!!a.trim()){c(!0);try{const j=await Vh(a.trim());h(j),o(""),g()}catch(j){i(j.message)}finally{c(!1)}}}async function v(k){try{await Qh(k),t(j=>j.filter(p=>p.token_uid!==k))}catch(j){i(j.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:()=>h(null),children:"Dismiss"})]}),s.jsxs("form",{className:"token-create-row",onSubmit:x,children:[s.jsx("input",{className:"field-input field-input--flex",placeholder:"Token name",value:a,onChange:k=>o(k.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(k=>s.jsxs("div",{className:"token-row",children:[s.jsxs("div",{className:"token-row-info",children:[s.jsx("strong",{children:k.name}),s.jsxs("div",{className:"muted",children:["Created ",k.created_at.slice(0,10),k.last_used_at&&` · Last used ${k.last_used_at.slice(0,10)}`]})]}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"4px 10px"},onClick:()=>v(k.token_uid),children:"Revoke"})]},k.token_uid))]})]})})}function $m(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState(!1),[u,c]=f.useState(null);f.useEffect(()=>{(async()=>{try{t(await Qa())}catch(h){i(h.message)}finally{r(!1)}})()},[]);async function y(h){h.preventDefault(),o(!0),c(null);try{await Ol(e),c({ok:!0,text:"Saved."})}catch(g){c({ok:!1,text:g.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(([h,g])=>s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:!!e[h],onChange:x=>t(v=>({...v,[h]:x.target.checked}))}),g]},h)),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:h=>t(g=>({...g,default_entry_visibility:Number(h.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 ni(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 Dm({archiveId:e}){const[t,n]=f.useState("idle"),[r,l]=f.useState(null),[i,a]=f.useState(null),[o,u]=f.useState(null);function c(){n("idle"),l(null),a(null),u(null)}async function y(){n("scanning"),u(null),l(null);try{const x=await lm(e);l(x),n("scanned")}catch(x){u(x.message),n("error")}}async function h(){n("deleting"),u(null);try{const x=await sm(e);a(x),n("done")}catch(x){u(x.message),n("error")}}const g=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&&g&&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&&!g&&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:ni(r.total_bytes)})," recoverable."]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsxs("button",{className:"btn-danger",onClick:h,children:["Delete (",ni(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:ni(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 Om(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState("global"),[u,c]=f.useState(""),[y,h]=f.useState("{}"),[g,x]=f.useState(null),[v,k]=f.useState(!1),[j,p]=f.useState({});f.useEffect(()=>{d()},[]);async function d(){r(!0),i(null);try{t(await am())}catch(S){i(S.message)}finally{r(!1)}}async function m(S){S.preventDefault();try{JSON.parse(y)}catch{x({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}k(!0),x(null);try{await om(a==="global"?null:u.trim(),a,y),c(""),h("{}"),o("global"),x({ok:!0,text:"Rule added."}),await d()}catch(I){x({ok:!1,text:I.message})}finally{k(!1)}}async function w(S){try{await cm(S),await d()}catch(I){i(I.message)}}function E(S){p(I=>({...I,[S.rule_uid]:{cookiesInput:S.cookies_json,saving:!1,msg:null}}))}function P(S){p(I=>{const b={...I};return delete b[S],b})}async function _(S){const I=j[S.rule_uid];try{JSON.parse(I.cookiesInput)}catch{p(b=>({...b,[S.rule_uid]:{...b[S.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}p(b=>({...b,[S.rule_uid]:{...b[S.rule_uid],saving:!0,msg:null}}));try{await um(S.rule_uid,{cookies_json:I.cookiesInput}),P(S.rule_uid),await d()}catch(b){p(Q=>({...Q,[S.rule_uid]:{...Q[S.rule_uid],saving:!1,msg:{ok:!1,text:b.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(S=>{const I=j[S.rule_uid],b=S.url_pattern?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"muted",children:[S.pattern_kind,":"]})," ",s.jsx("code",{children:S.url_pattern})]}):s.jsx("span",{className:"muted",children:"global (all URLs)"});return s.jsxs("tr",{children:[s.jsx("td",{children:b}),s.jsx("td",{children:I?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:I.cookiesInput,onChange:Q=>p(H=>({...H,[S.rule_uid]:{...H[S.rule_uid],cookiesInput:Q.target.value}}))}),I.msg&&s.jsx("div",{className:`form-msg form-msg--${I.msg.ok?"ok":"err"}`,children:I.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:I.saving,onClick:()=>_(S),children:I.saving?"Saving…":"Save"}),s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>P(S.rule_uid),children:"Cancel"})]})]}):s.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:S.cookies_json})}),s.jsx("td",{children:!I&&s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>E(S),children:"Edit"}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>w(S.rule_uid),children:"Del"})]})})]},S.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:S=>o(S.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:S=>c(S.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:S=>h(S.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),g&&s.jsx("div",{className:`form-msg form-msg--${g.ok?"ok":"err"}`,children:g.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:v,children:v?"Adding…":"Add Rule"})]})]})})}function Am(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(!1),[a,o]=f.useState(null);f.useEffect(()=>{(async()=>{try{t(await Qa())}catch(j){o({ok:!1,text:j.message})}finally{r(!1)}})()},[]);async function u(j){i(!0),o(null);try{await Ol({ublock_enabled:j}),t(p=>({...p,ublock_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function c(j){i(!0),o(null);try{await Ol({cookie_ext_enabled:j}),t(p=>({...p,cookie_ext_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function y(j){i(!0),o(null);try{await Ol({modal_closer_enabled:j}),t(p=>({...p,modal_closer_enabled:j})),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 h=(e==null?void 0:e.ublock_ext_available)??!1,g=(e==null?void 0:e.ublock_enabled)??!0,x=(e==null?void 0:e.cookie_ext_available)??!1,v=(e==null?void 0:e.cookie_ext_enabled)??!0,k=(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)."}),!h&&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":g,className:`ext-toggle${g?" ext-toggle--on":""}`,onClick:()=>u(!g),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."}),!x&&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":v,className:`ext-toggle${v?" ext-toggle--on":""}`,onClick:()=>c(!v),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":k,className:`ext-toggle${k?" ext-toggle--on":""}`,onClick:()=>y(!k),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 du={0:"Private",1:"Public",2:"Users only",3:"Public"},Mm=()=>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 Fm({archiveId:e,selectedEntry:t,selectedUids:n,selectedEntries:r,detail:l,onTagFilterSet:i,tagNodes:a,onTagsRefresh:o,onEntryTitleChange:u,onEntryDeleted:c,onBulkDeleted:y,humanizeTags:h,onDetailRefresh:g,onOpenPreview:x,onPlay:v}){var rl;const[k,j]=f.useState([]),[p,d]=f.useState(""),[m,w]=f.useState([]),[E,P]=f.useState(""),_=f.useRef(0),S=f.useRef(!1),[I,b]=f.useState(!1),[Q,H]=f.useState(""),[q,ee]=f.useState("idle"),[pe,ce]=f.useState(""),te=f.useRef(null),[z,T]=f.useState(!1);f.useEffect(()=>{T(!1)},[(rl=l==null?void 0:l.summary)==null?void 0:rl.entry_uid]);const M=(n==null?void 0:n.size)>=2,[G,W]=f.useState(""),[de,ae]=f.useState("idle"),[De,ze]=f.useState(""),[Be,ct]=f.useState([]),[nt,dt]=f.useState(""),[ft,Xe]=f.useState("idle"),[R,Y]=f.useState(""),[Se,N]=f.useState("idle");f.useEffect(()=>{const $=++_.current;if(te.current&&(clearInterval(te.current),te.current=null),ee("idle"),ce(""),!t||!e){j([]),w([]);return}b(!1),H(""),S.current=!1,j([]),Promise.all([jl(e,t.entry_uid),nm(e,t.entry_uid)]).then(([re,rt])=>{$===_.current&&(j(re),w(rt))}).catch(()=>{})},[t,e]),f.useEffect(()=>()=>{clearInterval(te.current)},[]),f.useEffect(()=>{if(!M||!e){ct([]);return}Ld(e).then(ct).catch(()=>ct([]))},[M,e]),f.useEffect(()=>{W(""),ae("idle"),ze(""),dt(""),Xe("idle"),Y(""),N("idle")},[n]);async function U(){const $=n.size;if(!window.confirm(`Delete ${$} entr${$===1?"y":"ies"}? This cannot be undone.`))return;N("running");const re=new Set;for(const rt of n)try{await iu(e,rt),re.add(rt)}catch{}N("idle"),y==null||y(re)}async function D(){const $=G.trim();if($){ae("running"),ze("");try{for(const re of n)await su(e,re,$);W(""),ae("done"),o==null||o(),setTimeout(()=>ae("idle"),1800)}catch(re){ze(re.message),ae("error")}}}async function O(){if(!nt)return;Xe("running"),Y("");const $=[];for(const re of n)try{await zd(e,nt,re)}catch{$.push(re)}$.length>0?(Y(`Failed for ${$.length} entr${$.length===1?"y":"ies"}.`),Xe("error")):(Xe("done"),setTimeout(()=>Xe("idle"),1800))}async function V(){const $=Q.trim()||null;try{await Eh(e,t.entry_uid,$),u==null||u(t.entry_uid,$)}catch{}finally{b(!1)}}async function K(){const $=p.trim();if(!(!$||!t))try{await su(e,t.entry_uid,$),d(""),P("");const re=await jl(e,t.entry_uid);j(re),o()}catch(re){P(re.message)}}async function he($){try{await Th(e,t.entry_uid,$);const re=await jl(e,t.entry_uid);j(re),o()}catch{}}async function be(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await iu(e,t.entry_uid),c==null||c(t.entry_uid)}catch{}}async function Je(){if(!t||!e||q==="running")return;const $=_.current,re=t.entry_uid;ee("running"),ce("");try{const{job_uid:rt}=await im(e,re);if(_.current!==$)return;te.current=setInterval(async()=>{try{const dn=await Pd(e,rt);if(dn.status==="completed"){if(clearInterval(te.current),te.current=null,_.current!==$)return;ee("done");const Ut=await jl(e,re);if(_.current!==$)return;j(Ut),g==null||g()}else if(dn.status==="failed"){if(clearInterval(te.current),te.current=null,_.current!==$)return;ee("error"),ce(dn.error_text||"Re-archive failed.")}}catch{if(clearInterval(te.current),te.current=null,_.current!==$)return;ee("error"),ce("Network error while polling.")}},500)}catch(rt){if(_.current!==$)return;ee("error"),ce(rt.message||"Failed to start re-archive.")}}const He=l?[["Added",Ka(l.summary.archived_at)],["Source",l.summary.source_kind],["Type",l.summary.entity_kind],["Visibility",du[l.summary.visibility]??l.summary.visibility],["Root",l.structured_root_relpath]]:[],Ue=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),xe=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv","pdf","html","htm","jpg","jpeg","png","gif","webp","avif","svg","bmp"]),zt=l?l.artifacts.findIndex($=>$.artifact_role==="primary_media"):-1,We=zt>=0?l.artifacts[zt]:null,tl=We?We.relpath.split(".").pop().toLowerCase():"",nl=We&&Ue.has(tl),Es=zt>=0&&t?`/api/archives/${e}/entries/${t.entry_uid}/artifacts/${zt}`:null,Ts=l&&!nl&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread"||We&&xe.has(tl));return s.jsxs("aside",{className:"context-rail",children:[s.jsx("div",{className:"rail-eyebrow",children:"Context"}),M?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"}),De&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:De}),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:G,onChange:$=>W($.target.value),onKeyDown:$=>{$.key==="Enter"&&D()}}),s.jsx("button",{className:"tag-add-btn",onClick:D,disabled:de==="running"||!G.trim(),children:de==="running"?"…":de==="done"?"✓":"Add"})]})]}),Be.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:nt,onChange:$=>dt($.target.value),children:[s.jsx("option",{value:"",children:"Pick a collection…"}),Be.map($=>s.jsx("option",{value:$.collection_uid,children:$.name},$.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:O,disabled:!nt||ft==="running",children:ft==="running"?"…":ft==="done"?"✓":ft==="error"?"!":"Add"})]}),R&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"6px 0 0"},children:R})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:U,disabled:Se==="running",children:Se==="running"?"Deleting…":`Delete ${n.size} entr${n.size===1?"y":"ies"}`})})]}):t?l?s.jsxs(s.Fragment,{children:[I?s.jsx("input",{className:"rail-title-input",autoFocus:!0,value:Q,onChange:$=>H($.target.value),onKeyDown:$=>{$.key==="Enter"&&$.currentTarget.blur(),$.key==="Escape"&&(S.current=!0,$.currentTarget.blur())},onBlur:()=>{S.current?b(!1):V(),S.current=!1}}):s.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{H(l.summary.title??""),b(!0)},children:[St(l.summary.title)||St(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:_s(l.summary.source_kind)}}),s.jsx("span",{className:"u-text",children:l.summary.original_url}),s.jsx("span",{className:"ext",children:s.jsx(Mm,{})})]}),nl&&v&&s.jsx("button",{className:"rail-preview-btn",onClick:()=>v(Es,t),children:"▶ Play"}),Ts&&x&&s.jsx("button",{className:"rail-preview-btn",onClick:x,children:"Preview"}),s.jsx("div",{className:"meta-list",children:He.filter(([,$])=>$!=null&&$!=="").map(([$,re])=>s.jsxs("div",{className:"meta-item",children:[s.jsx("span",{className:"meta-k",children:$}),s.jsx("span",{className:`meta-v${$==="Root"?" mono":""}`,children:St(re)})]},$))}),l.artifacts.length>0&&(()=>{const $=l.artifacts.map((me,bn)=>({...me,_idx:bn})),re=$.filter(me=>me.artifact_role==="font"),rt=$.filter(me=>me.artifact_role!=="font"),dn=re.reduce((me,bn)=>me+(bn.byte_size||0),0),Ut=l.summary.entry_uid,Tn=me=>s.jsx("li",{children:s.jsxs("a",{href:`/api/archives/${e}/entries/${Ut}/artifacts/${me._idx}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[s.jsx("span",{className:"artifact-name",children:me.artifact_role==="font"?me.relpath.split("/").pop():me.artifact_role.replace(/_/g," ")}),s.jsx("span",{className:"artifact-size",children:me.byte_size!=null?Xr(me.byte_size):"—"})]})},me._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:[rt.map(Tn),re.length>0&&s.jsxs("li",{className:"artifact-group",children:[s.jsxs("button",{type:"button",className:"artifact-group-header artifact-link","aria-expanded":z,onClick:()=>T(me=>!me),children:[s.jsxs("span",{className:"artifact-name",children:[s.jsx("span",{"aria-hidden":"true",className:`artifact-group-chevron${z?" open":""}`,children:"›"}),` fonts (${re.length})`]}),s.jsx("span",{className:"artifact-size",children:Xr(dn)})]}),z&&s.jsx("ul",{className:"artifact-list artifact-group-body",children:re.map(Tn)})]})]})]})})()]}):s.jsx("p",{className:"tags-empty",children:"Loading\\u2026"}):s.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&!M&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Tags"}),k.length===0?s.jsx("p",{className:"tags-empty",children:"No tags yet."}):s.jsx("div",{className:"tags-wrap",children:k.map($=>s.jsxs("span",{className:"tag-pill",title:$.full_path,children:[h?Id($.full_path):$.full_path,s.jsx("button",{className:"remove",title:`Remove tag ${$.full_path}`,onClick:()=>he($.tag_uid),children:"×"})]},$.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:p,onChange:$=>d($.target.value),onKeyDown:$=>{$.key==="Enter"&&K()}}),s.jsx("button",{className:"tag-add-btn",onClick:K,children:"Add"})]})]}),m.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Collections"}),m.map($=>s.jsxs("div",{className:"coll-row",children:[s.jsx("span",{className:"coll-name",children:$.collection_uid}),s.jsx("span",{className:"vis-badge",children:du[$.visibility_bits]??`bits:${$.visibility_bits}`})]},$.collection_uid))]}),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:Je,disabled:q==="running",children:q==="running"?"Re-archiving…":"Re-archive"}),q==="done"&&s.jsx("p",{className:"form-msg form-msg--ok",style:{marginTop:"6px"},children:"Re-archived successfully."}),q==="error"&&s.jsx("p",{className:"form-msg form-msg--err",style:{marginTop:"6px"},children:pe})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:be,children:"Delete entry"})})]})]})}function Bm({src:e}){const t=f.useRef(null);return f.useEffect(()=>{t.current&&t.current.load()},[e]),s.jsx("div",{className:"preview-video-wrap",style:{background:"#111",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",minHeight:"240px"},children:e?s.jsxs("video",{ref:t,controls:!0,autoPlay:!1,style:{width:"100%",maxHeight:"100%",display:"block"},children:[s.jsx("source",{src:e}),"Your browser does not support the video element."]}):s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No video available"})})}function fu({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 Hm({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 Ad(e){return e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(new Date(e*1e3)):""}function pu(e){return!e||!e.includes("&")?e:e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}const J={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"}},Ce={bg:"#000000",border:"#2f3336",text:"#e7e9ea",dim:"#71767b",accent:"#1d9bf0",codeBg:"#16181c"},ri={article:{background:Ce.bg,color:Ce.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:Ce.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:Ce.border,flexShrink:0},aAuthorName:{fontSize:"15px",fontWeight:"700",color:Ce.text,lineHeight:"1.3"},aAuthorSub:{fontSize:"15px",color:Ce.dim,lineHeight:"1.3"},aDivider:{border:"none",borderTop:`1px solid ${Ce.border}`,margin:"0"},aBody:{padding:"4px 16px 0"},bH1:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:Ce.text,lineHeight:"36px",margin:"24px 0 10px"},bH2:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:Ce.text,lineHeight:"36px",margin:"24px 0 10px"},bP:{fontSize:"17px",color:Ce.text,lineHeight:"1.5",marginBottom:"16px",marginTop:"0"},bSpacer:{height:"6px",display:"block"},bQuote:{borderLeft:`3px solid ${Ce.border}`,padding:"2px 14px",margin:"14px 0",color:Ce.dim,fontSize:"17px",lineHeight:"1.5"},bHr:{border:"none",borderTop:`1px solid ${Ce.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:Ce.text,lineHeight:"1.5",marginBottom:"6px"},bTweet:{display:"flex",alignItems:"center",gap:"12px",border:`1px solid ${Ce.border}`,borderRadius:"12px",padding:"14px 16px",margin:"14px 0",color:Ce.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:Ce.text,background:"transparent"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:Ce.codeBg,padding:"2px 6px",borderRadius:"4px",color:"#e6edf3"},link:{color:Ce.accent,textDecoration:"none"}};function Um(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 Yn(e,t,n){return e&&n[e]?n[e]:t||null}function Md(){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 qa(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 Fd(e,t){const n=e.expanded_url||e.url||e.text||"",r=e.display_url||e.expanded_url||e.url||e.text||"",l=qa(e,t,e.url,e.text,e.display_url,e.expanded_url);return!l||!n?null:{...l,kind:"url",href:n,display:r}}function Bd(e,t){const n=e.screen_name||e.name||e.text||"",r=n?`@${n}`:null,l=qa(e,t,r);return!l||!n?null:{...l,kind:"mention",screen_name:n}}const hu=/https?:\/\/[^\s<>"'\])]+/g,Wm=/[.,;:!?)()]+$/;function os(e,t){const n=[];let r=0,l;for(hu.lastIndex=0;(l=hu.exec(e))!==null;){l.index>r&&n.push(e.slice(r,l.index));let i=l[0].replace(Wm,"");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:(rFd(o,e)).filter(Boolean),...(t.user_mentions||[]).map(o=>Bd(o,e)).filter(Boolean)];if(r.length===0&&n.length===0)return os(pu(e),J.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),h=r.filter(v=>v.s<=o&&v.e>=c),g=h.find(v=>v.kind==="url");if(g)return s.jsx("a",{href:g.href,target:"_blank",rel:"noopener noreferrer",style:J.link,children:g.display||y},u);const x=h.find(v=>v.kind==="mention");return x?s.jsx("a",{href:`https://x.com/${x.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:J.link,children:y},u):s.jsx("span",{children:os(pu(y),J.link)},u)}).filter(o=>o!==null)}function Qm(e,t,n,r,l=J){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=Fd(u,e);c&&i.push(c)}for(const u of r){const c=Bd(u,e);c&&i.push(c)}if(i.length===0)return os(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],h=i.filter(j=>j.s<=u&&j.e>=y),g=e.slice(u,y);let x;if(g.includes(` +`):null;k.current(zt,null,Ue,He)}async function G(N,U,D,O={}){var be,Je;const V=x.current,K=((be=crypto.randomUUID)==null?void 0:be.call(crypto))??`job-${Date.now()}-${Math.random()}`,he={ublock_enabled:ce,reader_mode:te,cookie_ext_enabled:b,modal_closer_enabled:H,via_freedium:ee,...O};try{const He=await Rh(V,N,U,he);(Je=j.current)==null||Je.call(j,{id:K,jobUid:He.job_uid,locator:N,archiveId:V}),T(K,He.job_uid,N,V,D)}catch(He){const Ue=He.message||"Submission failed.";k.current(Ue,N),M(D,"failed",N)}}function W(){var O,V;const N=d.filter(K=>K.locator.trim());if(N.length===0||N.some(K=>ou(K))||N.some(K=>K.probeState==="probing"||vn(K.locator)&&K.playlistProbeState!=="done")||N.some(K=>Array.isArray(K.playlistItems)&&K.playlistItems.length===0))return;const U=N.length>1?((O=crypto.randomUUID)==null?void 0:O.call(crypto))??`batch-${Date.now()}`:null;U&&g.current.set(U,{total:N.length,archived:0,warnings:0,failed:0,failedLocators:[],warningLocators:[]});const D=N.map(K=>({locator:K.locator.trim(),quality:K.playlistItems!==null?null:K.quality||"best",extraExtensions:K.playlistItems!==null?{per_item_quality:Object.fromEntries(K.playlistItems.map(he=>[he.id,he.quality])),sync:K.syncEnabled}:{}}));m([zn()]),(V=u.current)==null||V.close(),D.forEach(({locator:K,quality:he,extraExtensions:be})=>G(K,he,U,be))}function de(){m(N=>[...N,zn()])}function ae(N){clearTimeout(h.current.get(N)),h.current.delete(N),m(U=>{const D=U.filter(O=>O.id!==N);return D.length===0?[zn()]:D})}function De(N,U){if(clearTimeout(h.current.get(N)),m(D=>D.map(O=>O.id===N?{...O,locator:U,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best",playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1}:O)),Rd(U)){const D=setTimeout(async()=>{h.current.delete(N),m(O=>O.map(V=>V.id===N?{...V,probeState:"probing"}:V));try{const O=await Ih(x.current,U.trim());m(V=>V.map(K=>{if(K.id!==N||K.locator!==U)return K;const he=O.qualities??[],be=O.has_audio??!1,Je=he.length===0&&be?"audio":"best";return{...K,probeState:"done",probeQualities:he,probeHasAudio:be,quality:Je}}))}catch{m(O=>O.map(V=>V.id===N?{...V,probeState:"idle",probeQualities:null}:V))}},600);h.current.set(N,D)}else if(vn(U)){const D=setTimeout(async()=>{h.current.delete(N),m(O=>O.map(V=>V.id===N?{...V,playlistProbeState:"probing"}:V));try{const O=await $h(x.current,U.trim());m(V=>V.map(K=>K.id!==N||K.locator!==U?K:{...K,playlistProbeState:"done",playlistInfo:O,playlistItems:O.items.map(he=>({...he,quality:null})),playlistQuality:null}))}catch{m(O=>O.map(V=>V.id===N?{...V,playlistProbeState:"error"}:V))}},800);h.current.set(N,D)}}function ze(N,U){m(D=>D.map(O=>O.id===N?{...O,quality:U}:O))}function Be(N,U){m(D=>D.map(O=>{if(O.id!==N)return O;const V=mm(U,O.playlistItems);return{...O,playlistQuality:U,playlistItems:V}}))}function ct(N,U,D){m(O=>O.map(V=>V.id!==N?V:{...V,playlistItems:V.playlistItems.map(K=>K.id===U?{...K,quality:D}:K)}))}function nt(N){m(U=>U.map(D=>D.id===N?{...D,playlistExpanded:!D.playlistExpanded}:D))}function dt(N,U){m(D=>D.map(O=>O.id===N?{...O,syncEnabled:U}:O))}function ft(N,U){m(D=>D.map(O=>O.id!==N?O:{...O,playlistItems:O.playlistItems.filter(V=>V.id!==U)}))}const Xe=d.filter(N=>N.locator.trim()).length,R=d.some(N=>ou(N)),Y=d.some(N=>Array.isArray(N.playlistItems)&&N.playlistItems.length===0),Se=d.some(N=>N.probeState==="probing"||vn(N.locator)&&N.playlistProbeState!=="done");return s.jsx("dialog",{ref:u,className:"capture-dialog",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 N;return(N=u.current)==null?void 0:N.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:d.map((N,U)=>s.jsx(ym,{item:N,autoFocus:U===d.length-1,onLocatorChange:D=>De(N.id,D),onQualityChange:D=>ze(N.id,D),onRemove:()=>ae(N.id),onSubmit:W,onPlaylistQualityChange:D=>Be(N.id,D),onPlaylistItemQualityChange:(D,O)=>ct(N.id,D,O),onPlaylistToggle:()=>nt(N.id),onSyncChange:D=>dt(N.id,D),onPlaylistItemDelete:D=>ft(N.id,D)},N.id))}),s.jsxs("button",{type:"button",className:"capture-add-row",onClick:de,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 another"]}),s.jsxs("div",{className:"capture-advanced",children:[s.jsxs("button",{type:"button",className:"capture-advanced-toggle",onClick:()=>E(N=>!N),"aria-expanded":w,children:[s.jsx("svg",{className:`capture-chevron${w?" 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"]}),w&&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":ce,className:`ext-toggle ext-toggle--sm${ce?" ext-toggle--on":""}`,onClick:()=>_(N=>N===null?!ce:!N),"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"}),!(S!=null&&S.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":b,className:`ext-toggle ext-toggle--sm${b?" ext-toggle--on":""}`,onClick:()=>Q(N=>!N),"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":te,className:`ext-toggle ext-toggle--sm${te?" ext-toggle--on":""}`,onClick:()=>z(N=>!N),"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":H,className:`ext-toggle ext-toggle--sm${H?" ext-toggle--on":""}`,onClick:()=>q(N=>!N),"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":ee,className:`ext-toggle ext-toggle--sm${ee?" ext-toggle--on":""}`,onClick:()=>pe(N=>!N),"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:W,disabled:Xe===0||R||Se||Y,children:Xe>1?`Archive ${Xe}`:"Archive"}),s.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var N;return(N=u.current)==null?void 0:N.close()},children:"Cancel"})]})]})})}function ym({item:e,autoFocus:t,onLocatorChange:n,onQualityChange:r,onRemove:l,onSubmit:i,onPlaylistQualityChange:a,onPlaylistItemQualityChange:o,onPlaylistToggle:u,onSyncChange:c,onPlaylistItemDelete:y}){const h=f.useRef(null);f.useEffect(()=>{var v;t&&((v=h.current)==null||v.focus())},[t]);const g=(()=>{if(vn(e.locator)){if(e.playlistProbeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Probing playlist…",children:"…"});if(e.playlistProbeState==="done"){const v=[...new Set(e.playlistItems.flatMap(p=>p.qualities.map(d=>parseInt(d))))].sort((p,d)=>d-p),k=e.playlistItems.every(p=>p.has_audio),j=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"}),v.map(p=>s.jsxs("option",{value:`${p}p`,children:[p,"p"]},p)),k&&s.jsx("option",{value:"audio",children:"Audio only"})]}),j>0&&s.jsxs("span",{className:"capture-conflict-badge",children:[j," 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(!Rd(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 v=e.probeQualities??[],k=e.probeHasAudio??!1;return v.length===0&&!k?s.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):v.length===0&&k?s.jsx("select",{className:"capture-quality",value:"audio",onChange:j=>r(j.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:j=>r(j.target.value),"aria-label":"Video quality",children:[s.jsx("option",{value:"best",children:"Best quality"}),v.map(j=>s.jsx("option",{value:j,children:j},j)),k&&s.jsx("option",{value:"audio",children:"Audio only"})]})}return null})(),x=vn(e.locator)&&e.playlistProbeState==="done"?s.jsxs("label",{className:"capture-sync-row",children:[s.jsx("input",{type:"checkbox",checked:e.syncEnabled,onChange:v=>c(v.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:[vn(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:h,className:"capture-input",type:"text",placeholder:"https://… · yt:ID · ytm:ID · tweet:ID · x:ID",value:e.locator,onChange:v=>n(v.target.value),onKeyDown:v=>{v.key==="Enter"&&i()},autoComplete:"off",spellCheck:!1}),g,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}),vn(e.locator)&&e.playlistProbeState==="done"&&e.playlistExpanded?s.jsxs("div",{className:"capture-playlist-items",children:[e.playlistItems.map(v=>s.jsxs("div",{className:`capture-playlist-item${v.quality===null?" capture-playlist-item--conflict":""}`,children:[s.jsx("span",{className:"capture-playlist-item-title",children:v.title||v.url}),s.jsxs("select",{className:"capture-item-quality",value:v.quality??"",onChange:k=>o(v.id,k.target.value),"aria-label":`Quality for ${v.title||v.url}`,children:[v.quality===null&&s.jsx("option",{value:"",disabled:!0,children:"Choose…"}),s.jsx("option",{value:"best",children:"Best quality"}),v.qualities.map(k=>s.jsx("option",{value:k,children:k},k)),v.has_audio&&s.jsx("option",{value:"audio",children:"Audio only"})]}),v.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 ${v.title||v.url}`,onClick:()=>y(v.id),children:"×"})]},v.id)),x]}):x]})}function vm(){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 Xr(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 St(e){return xm(e)??""}function Ka(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 uu={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function _s(e){return uu[e]??uu.other}function Id(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function wm({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:Ka(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[s.jsx("span",{className:"source-icon",children:s.jsx("span",{dangerouslySetInnerHTML:{__html:_s(e.source_kind)}})}),s.jsx("span",{className:"entry-title",children:St(e.title)||St(e.entry_uid)})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:St(e.entity_kind)})}),s.jsx("div",{className:"col-size",children:s.jsx("span",{className:"size-total",children:Xr(e.total_artifact_bytes)})}),s.jsx("div",{className:"url-cell col-url",children:St(e.original_url)})]})}function km({entry:e,archiveId:t,rowIndex:n,isSelected:r,isMultiSelected:l,onRowClick:i,selectedUids:a,deletedUids:o}){const[u,c]=f.useState(!1),[y,h]=f.useState(!1),[g,x]=f.useState(null),[v,k]=f.useState(!1),p=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!u?s.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>c(!0),style:{objectFit:"contain"}}):s.jsx("span",{dangerouslySetInnerHTML:{__html:_s(e.source_kind)}}),d=r||l,m=e.child_count>0;function w(_){_.stopPropagation(),i(e,{ctrlKey:!0,metaKey:!1,shiftKey:!1,preventDefault(){}})}async function E(_){if(_.stopPropagation(),y){h(!1);return}if(h(!0),g===null&&!v){k(!0);try{const S=await Nh(t,e.entry_uid);x(S)}catch{x([])}finally{k(!1)}}}const P=["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:P,"data-entry-uid":e.entry_uid,children:[s.jsxs("div",{className:"entry-row-main",tabIndex:0,onMouseDown:_=>{_.shiftKey&&_.preventDefault()},onClick:_=>i(e,_),onKeyDown:_=>{_.key==="Enter"&&i(e,_)},children:[s.jsx("div",{className:"col-check",children:s.jsx("button",{type:"button",className:`row-checkbox${d?" is-checked":""}`,"aria-pressed":d,"aria-label":d?"Deselect entry":"Select entry",onClick:w,onKeyDown:_=>_.stopPropagation()})}),s.jsx("div",{className:"col-added",children:Ka(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[m&&s.jsx("button",{type:"button",className:`entry-expand-btn${y?" is-expanded":""}`,"aria-label":y?"Collapse children":`Expand ${e.child_count} items`,"aria-expanded":y,onClick:E,onKeyDown:_=>_.stopPropagation()}),s.jsx("span",{className:"source-icon",children:p}),s.jsx("span",{className:"entry-title",children:St(e.title)||St(e.entry_uid)}),m&&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:St(e.entity_kind)})}),s.jsxs("div",{className:"col-size",children:[s.jsx("span",{className:"size-total",children:Xr(e.total_artifact_bytes)}),e.cached_bytes>0&&e.cacheable_bytes>0&&s.jsxs("span",{className:"size-cached-pct",title:`${Xr(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:St(e.original_url)})]}),y&&s.jsxs(s.Fragment,{children:[v&&s.jsx("div",{className:"child-entries-loading",children:"Loading…"}),s.jsx("div",{className:"child-entries","aria-label":`${e.child_count} child entries`,children:g&&g.filter(_=>!(o!=null&&o.has(_.entry_uid))).map((_,S)=>s.jsx(wm,{entry:_,index:S,onRowClick:i,selectedUids:a},_.entry_uid))})]})]})}function jm({entries:e,selectedUids:t,onRowClick:n,archiveId:r,pendingCaptures:l=[],deletedUids:i}){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(a=>a.archiveId===r).reverse().map(a=>s.jsx(vm,{},a.id)),e.map((a,o)=>s.jsx(km,{entry:a,rowIndex:o,archiveId:r,isSelected:t.size===1&&t.has(a.entry_uid),isMultiSelected:t.size>=2&&t.has(a.entry_uid),onRowClick:n,selectedUids:t,deletedUids:i},a.entry_uid))]})]})})}function Sm(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 Nm({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 _m({runs:e}){const[t,n]=f.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:Sm(l.started_at)}),s.jsxs("td",{children:[s.jsx(Nm,{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 Cm=4;function Em({archives:e}){const{currentUser:t}=f.useContext(Cs)??{},n=t&&(t.role_bits&Cm)!==0,[r,l]=f.useState("users"),[i,a]=f.useState([]),[o,u]=f.useState([]),[c,y]=f.useState(!1),[h,g]=f.useState(null),[x,v]=f.useState(""),[k,j]=f.useState(""),[p,d]=f.useState(""),[m,w]=f.useState(null),[E,P]=f.useState(!1),[_,S]=f.useState(""),[I,b]=f.useState(""),[Q,H]=f.useState(null),[q,ee]=f.useState(!1),pe=f.useCallback(async()=>{if(n){y(!0),g(null);try{const[T,M]=await Promise.all([Kh(),Jh()]);a(T),u(M)}catch(T){g(T.message)}finally{y(!1)}}},[n]);f.useEffect(()=>{pe()},[pe]);async function ce(T){const M=T.status==="active"?"disabled":"active";try{await Xh(T.user_uid,M),a(G=>G.map(W=>W.user_uid===T.user_uid?{...W,status:M}:W))}catch(G){g(G.message)}}async function te(T){if(T.preventDefault(),!x.trim()||!k){w("Username and password required");return}P(!0),w(null);try{await qh(x.trim(),k,p.trim()||void 0),v(""),j(""),d(""),await pe()}catch(M){w(M.message)}finally{P(!1)}}async function z(T){if(T.preventDefault(),!_.trim()||!I.trim()){H("Slug and name required");return}ee(!0),H(null);try{await Yh(_.trim(),I.trim()),S(""),b(""),await pe()}catch(M){H(M.message)}finally{ee(!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"})]}),h&&s.jsx("div",{className:"form-msg form-msg--err",children:h}),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(T=>s.jsxs("tr",{className:T.status==="disabled"?"admin-row-disabled":"",children:[s.jsx("td",{children:T.username}),s.jsx("td",{className:"muted",children:T.email||"—"}),s.jsx("td",{children:T.role_slugs.join(", ")||"—"}),s.jsx("td",{children:s.jsx("span",{className:`status-badge status-${T.status}`,children:T.status})}),s.jsx("td",{children:s.jsx("button",{className:"admin-action-btn",onClick:()=>ce(T),children:T.status==="active"?"Ban":"Unban"})})]},T.user_uid))})]}),s.jsx("h3",{children:"Create User"}),s.jsxs("form",{className:"admin-form",onSubmit:te,children:[s.jsx("input",{className:"admin-input",placeholder:"Username",value:x,onChange:T=>v(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:k,onChange:T=>j(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:p,onChange:T=>d(T.target.value)}),m&&s.jsx("div",{className:"form-msg form-msg--err",children:m}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:E,children:E?"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(T=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:T.slug})}),s.jsx("td",{children:T.name}),s.jsx("td",{children:T.level}),s.jsx("td",{children:T.bit_position}),s.jsx("td",{children:T.is_builtin?"✓":""})]},T.role_uid))})]}),s.jsx("h3",{children:"Create Custom Role"}),s.jsxs("form",{className:"admin-form",onSubmit:z,children:[s.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:_,onChange:T=>S(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:I,onChange:T=>b(T.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:q,children:q?"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(T=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:T.label}),s.jsx("div",{className:"muted",children:T.archive_path})]},T.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(T=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:T.label}),s.jsx("div",{className:"muted",children:T.archive_path})]},T.id))})]})}function $d({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($d,{node:r,onPick:t},r.tag.tag_uid))})})]})}function cu({title:e,tagNodes:t,excludeUid:n,onPick:r,onCancel:l}){f.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($d,{node:o,onPick:r},o.tag.tag_uid))}):s.jsx("p",{className:"tag-picker-empty",children:"No other tags available."})]})]})})}function Dd({parentPath:e,archiveId:t,onDone:n,onCancel:r}){const[l,i]=f.useState(""),a=f.useRef(!1);async function o(){const u=l.trim();if(!u){r();return}const c=e?`${e}/${u}`:`/${u}`;try{await Lh(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 Od({node:e,archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:y,pendingCreateParentUid:h,onCreateDone:g,onCreateCancel:x}){var Q;const v=n===e.tag.full_path,[k,j]=f.useState(!1),[p,d]=f.useState(""),m=f.useRef(!1);function w(){if(k)return;if(c){y(e);return}const H=v?null:e.tag.full_path;r(H),l("archive")}function E(H){H.stopPropagation(),!c&&(d(e.tag.slug),j(!0))}async function P(){const H=p.trim();if(!H||H===e.tag.slug){j(!1);return}try{const q=await bh(t,e.tag.tag_uid,H);i(e.tag.full_path,q.full_path),o()}catch{}finally{j(!1)}}async function _(H){var ee;H.stopPropagation();const q=((ee=e.children)==null?void 0:ee.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(q))try{await Ph(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const S={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:y,pendingCreateParentUid:h,onCreateDone:g,onCreateCancel:x},I=h===e.tag.tag_uid,b=((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:[k?s.jsx("input",{className:"tag-rename-input",autoFocus:!0,value:p,onChange:H=>d(H.target.value),onKeyDown:H=>{H.key==="Enter"&&H.currentTarget.blur(),H.key==="Escape"&&(m.current=!0,H.currentTarget.blur())},onBlur:()=>{m.current?(m.current=!1,j(!1)):P()}}):s.jsxs("button",{className:`tag-node-btn${v?" 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:E,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:H=>{H.stopPropagation(),E(H)},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"})})]}),!k&&!c&&s.jsx("button",{className:"remove tag-node-delete",title:`Delete "${e.tag.full_path}"`,onClick:_,"aria-label":`Delete "${e.tag.full_path}"`,children:"×"})]}),(b||I)&&s.jsx("div",{className:"tag-children",children:s.jsxs("ul",{className:"tag-tree-list",children:[e.children.map(H=>s.jsx(Od,{node:H,...S},H.tag.tag_uid)),I&&s.jsx("li",{children:s.jsx(Dd,{parentPath:e.tag.full_path,archiveId:t,onDone:g,onCancel:x})})]})})]})}function Tm({archiveId:e,tagNodes:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u}){const[c,y]=f.useState(null),[h,g]=f.useState(null);function x(){y("select-source"),g(null)}function v(){y(null),g(null)}f.useEffect(()=>{if(c!=="select-source")return;function q(ee){ee.key==="Escape"&&(ee.preventDefault(),ee.stopPropagation(),v())}return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[c]);function k(q){g(q),y("select-dest")}async function j(q){const ee=h.tag.full_path,pe=h.tag.tag_uid,ce=(q==null?void 0:q.tag_uid)??null;v();try{const te=await zh(e,pe,ce);i(ee,te.full_path),o()}catch(te){alert(te.message||"Move failed")}}const[p,d]=f.useState(null),[m,w]=f.useState(void 0);function E(){d("select-parent"),w(void 0)}function P(){d(null),w(void 0)}function _(q){w(q??null),d("input")}function S(){d(null),w(void 0),o()}const I=c==="select-source",b=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:I,onMoveSourceSelect:k,pendingCreateParentUid:b,onCreateDone:S,onCreateCancel:P},H=b==="__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:I?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:v,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:E,title:"Create a new tag",disabled:!!p||!!c,children:"+ New"}),s.jsx("button",{className:"tag-tree-action-btn",onClick:x,title:"Move a tag to a different parent",disabled:!!p||!!c||t.length===0,children:"Move"})]})]})}),t.length===0&&!H?s.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):s.jsxs("ul",{className:"tag-tree-list",children:[t.map(q=>s.jsx(Od,{node:q,...Q},q.tag.tag_uid)),H&&s.jsx("li",{children:s.jsx(Dd,{parentPath:null,archiveId:e,onDone:S,onCancel:P})})]})]}),p==="select-parent"&&s.jsx(cu,{title:"Create tag under…",tagNodes:t,excludeUid:null,onPick:_,onCancel:P}),c==="select-dest"&&h&&s.jsx(cu,{title:`Move "${h.tag.slug}" under…`,tagNodes:t,excludeUid:h.tag.tag_uid,onPick:j,onCancel:v})]})}const jr=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],bm=e=>{var t;return((t=jr.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function Pm({archiveId:e}){const[t,n]=f.useState([]),[r,l]=f.useState(!1),[i,a]=f.useState(null),[o,u]=f.useState(null),[c,y]=f.useState(null),[h,g]=f.useState(!1),[x,v]=f.useState(null),[k,j]=f.useState(""),[p,d]=f.useState(""),[m,w]=f.useState(2),[E,P]=f.useState(!1),[_,S]=f.useState(null),[I,b]=f.useState(""),[Q,H]=f.useState(2),[q,ee]=f.useState(!1),[pe,ce]=f.useState(null),[te,z]=f.useState(!1),[T,M]=f.useState(""),G=f.useRef(null),W=t.find(R=>R.collection_uid===o)??null,de=(W==null?void 0:W.slug)==="_default_",ae=f.useCallback(async()=>{if(e){l(!0),a(null);try{const R=await Ld(e);n(R)}catch(R){a(R.message)}finally{l(!1)}}},[e]),De=f.useCallback(async R=>{if(!R){y(null);return}g(!0),v(null);try{const Y=await Zh(e,R);y(Y)}catch(Y){v(Y.message)}finally{g(!1)}},[e]);f.useEffect(()=>{ae()},[ae]),f.useEffect(()=>{De(o)},[o,De]),f.useEffect(()=>{te&&G.current&&G.current.focus()},[te]);async function ze(R){R.preventDefault();const Y=k.trim(),Se=p.trim();if(!(!Y||!Se)){P(!0),S(null);try{const N=await Gh(e,Y,Se,m);j(""),d(""),w(2),await ae(),u(N.collection_uid)}catch(N){S(N.message)}finally{P(!1)}}}async function Be(){const R=T.trim();if(!R||!W){z(!1);return}try{await au(e,W.collection_uid,{name:R}),await ae(),y(Y=>Y&&{...Y,name:R})}catch(Y){a(Y.message)}finally{z(!1)}}async function ct(R){if(W)try{await au(e,W.collection_uid,{default_visibility_bits:R}),await ae(),y(Y=>Y&&{...Y,default_visibility_bits:R})}catch(Y){a(Y.message)}}async function nt(){if(W&&window.confirm(`Delete collection "${W.name}"? Entries will not be deleted.`))try{await rm(e,W.collection_uid),u(null),y(null),await ae()}catch(R){a(R.message)}}async function dt(R){R.preventDefault();const Y=I.trim();if(!(!Y||!W)){ee(!0),ce(null);try{await zd(e,W.collection_uid,Y,Q),b(""),await De(W.collection_uid)}catch(Se){ce(Se.message)}finally{ee(!1)}}}async function ft(R){if(W)try{await em(e,W.collection_uid,R),await De(W.collection_uid)}catch(Y){v(Y.message)}}async function Xe(R,Y){if(W)try{await tm(e,W.collection_uid,R,Y),y(Se=>Se&&{...Se,entries:Se.entries.map(N=>N.entry_uid===R?{...N,collection_visibility_bits:Y}:N)})}catch(Se){v(Se.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(R=>s.jsxs("button",{className:`coll-sidebar-row${o===R.collection_uid?" is-active":""}`,onClick:()=>u(R.collection_uid),children:[s.jsx("span",{className:"coll-row-name",children:R.name}),s.jsx("span",{className:"coll-row-meta",children:bm(R.default_visibility_bits)})]},R.collection_uid)),t.length===0&&!r&&s.jsx("div",{className:"muted",style:{padding:"8px 12px"},children:"No collections yet."})]}),W?s.jsxs("div",{className:"coll-detail",children:[s.jsxs("div",{className:"coll-detail-header",children:[te?s.jsx("input",{ref:G,className:"coll-rename-input",value:T,onChange:R=>M(R.target.value),onBlur:Be,onKeyDown:R=>{R.key==="Enter"&&Be(),R.key==="Escape"&&z(!1)}}):s.jsxs("h3",{className:`coll-detail-name${de?"":" coll-detail-name--editable"}`,title:de?void 0:"Click to rename",onClick:()=>{de||(M(W.name),z(!0))},children:[(c==null?void 0:c.name)??W.name,!de&&s.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!de&&s.jsx("button",{className:"coll-delete-btn",onClick:nt,title:"Delete collection",children:"Delete"})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Default visibility"}),s.jsx("select",{className:"coll-vis-select",value:(c==null?void 0:c.default_visibility_bits)??W.default_visibility_bits,onChange:R=>ct(Number(R.target.value)),disabled:de,children:jr.map(R=>s.jsx("option",{value:R.value,children:R.label},R.value))})]}),s.jsxs("div",{className:"coll-entries-section",children:[s.jsx("div",{className:"coll-section-heading",children:"Entries"}),h&&s.jsx("div",{className:"muted",children:"Loading…"}),x&&s.jsx("div",{className:"collections-error",children:x}),!h&&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(R=>s.jsxs("li",{className:"coll-entry-row",children:[s.jsxs("div",{className:"coll-entry-info",children:[s.jsx("span",{className:"coll-entry-title",children:R.title||R.entry_uid}),s.jsx("span",{className:"coll-entry-kind muted",children:R.source_kind})]}),s.jsxs("div",{className:"coll-entry-actions",children:[s.jsx("select",{className:"coll-entry-vis-select",value:R.collection_visibility_bits,onChange:Y=>Xe(R.entry_uid,Number(Y.target.value)),children:jr.map(Y=>s.jsx("option",{value:Y.value,children:Y.label},Y.value))}),!de&&s.jsx("button",{className:"coll-entry-remove",onClick:()=>ft(R.entry_uid),title:"Remove from collection",children:"×"})]})]},R.entry_uid))}))]}),!de&&s.jsxs("form",{className:"coll-add-entry-form",onSubmit:dt,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:I,onChange:R=>b(R.target.value),placeholder:"entry_uid",required:!0}),s.jsx("select",{className:"coll-vis-select",value:Q,onChange:R=>H(Number(R.target.value)),children:jr.map(R=>s.jsx("option",{value:R.value,children:R.label},R.value))}),s.jsx("button",{className:"coll-add-btn",type:"submit",disabled:q,children:q?"…":"Add"})]}),pe&&s.jsx("div",{className:"collections-error",style:{marginTop:4},children:pe})]})]}):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:ze,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:k,onChange:R=>{j(R.target.value),p||d(R.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:R=>d(R.target.value),placeholder:"my-collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-vis",children:"Default visibility"}),s.jsx("select",{className:"capture-input",id:"coll-vis",style:{height:42},value:m,onChange:R=>w(Number(R.target.value)),children:jr.map(R=>s.jsx("option",{value:R.value,children:R.label},R.value))})]}),_&&s.jsx("div",{className:"collections-error",children:_}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:E,children:E?"Creating…":"Create collection"})]})]})]}):s.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const Lm=4;function zm({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=f.useContext(Cs)??{},i=r&&(r.role_bits&Lm)!==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(Rm,{currentUser:r,setCurrentUser:l}),e==="tokens"&&s.jsx(Im,{}),e==="instance"&&i&&s.jsx($m,{}),e==="cookies"&&i&&s.jsx(Om,{}),e==="extensions"&&i&&s.jsx(Am,{}),e==="storage"&&i&&s.jsx(Dm,{archiveId:n})]})}function Rm({currentUser:e,setCurrentUser:t}){const[n,r]=f.useState((e==null?void 0:e.display_name)??""),[l,i]=f.useState(!1),[a,o]=f.useState(null),[u,c]=f.useState(""),[y,h]=f.useState(""),[g,x]=f.useState(""),[v,k]=f.useState(!1),[j,p]=f.useState(null);async function d(w){w.preventDefault(),i(!0),o(null);try{await Bh(n),t(E=>({...E,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(E){o({ok:!1,text:E.message})}finally{i(!1)}}async function m(w){if(w.preventDefault(),y!==g){p({ok:!1,text:"Passwords do not match."});return}k(!0),p(null);try{await Uh(u,y),c(""),h(""),x(""),p({ok:!0,text:"Password changed."})}catch(E){p({ok:!1,text:E.message})}finally{k(!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:d,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 E=w.target.checked;try{await Hh({humanize_slugs:E}),t(P=>({...P,humanize_slugs:E}))}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=>h(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:g,onChange:w=>x(w.target.value),required:!0})]}),j&&s.jsx("div",{className:`form-msg form-msg--${j.ok?"ok":"err"}`,children:j.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:v,children:v?"Changing…":"Change Password"})]})]})]})}function Im(){const[e,t]=f.useState([]),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState(""),[u,c]=f.useState(!1),[y,h]=f.useState(null),g=f.useCallback(async()=>{r(!0),i(null);try{t(await Wh())}catch(k){i(k.message)}finally{r(!1)}},[]);f.useEffect(()=>{g()},[g]);async function x(k){if(k.preventDefault(),!!a.trim()){c(!0);try{const j=await Vh(a.trim());h(j),o(""),g()}catch(j){i(j.message)}finally{c(!1)}}}async function v(k){try{await Qh(k),t(j=>j.filter(p=>p.token_uid!==k))}catch(j){i(j.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:()=>h(null),children:"Dismiss"})]}),s.jsxs("form",{className:"token-create-row",onSubmit:x,children:[s.jsx("input",{className:"field-input field-input--flex",placeholder:"Token name",value:a,onChange:k=>o(k.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(k=>s.jsxs("div",{className:"token-row",children:[s.jsxs("div",{className:"token-row-info",children:[s.jsx("strong",{children:k.name}),s.jsxs("div",{className:"muted",children:["Created ",k.created_at.slice(0,10),k.last_used_at&&` · Last used ${k.last_used_at.slice(0,10)}`]})]}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"4px 10px"},onClick:()=>v(k.token_uid),children:"Revoke"})]},k.token_uid))]})]})})}function $m(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState(!1),[u,c]=f.useState(null);f.useEffect(()=>{(async()=>{try{t(await Qa())}catch(h){i(h.message)}finally{r(!1)}})()},[]);async function y(h){h.preventDefault(),o(!0),c(null);try{await Ol(e),c({ok:!0,text:"Saved."})}catch(g){c({ok:!1,text:g.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(([h,g])=>s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:!!e[h],onChange:x=>t(v=>({...v,[h]:x.target.checked}))}),g]},h)),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:h=>t(g=>({...g,default_entry_visibility:Number(h.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 ni(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 Dm({archiveId:e}){const[t,n]=f.useState("idle"),[r,l]=f.useState(null),[i,a]=f.useState(null),[o,u]=f.useState(null);function c(){n("idle"),l(null),a(null),u(null)}async function y(){n("scanning"),u(null),l(null);try{const x=await lm(e);l(x),n("scanned")}catch(x){u(x.message),n("error")}}async function h(){n("deleting"),u(null);try{const x=await sm(e);a(x),n("done")}catch(x){u(x.message),n("error")}}const g=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&&g&&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&&!g&&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:ni(r.total_bytes)})," recoverable."]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsxs("button",{className:"btn-danger",onClick:h,children:["Delete (",ni(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:ni(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 Om(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState("global"),[u,c]=f.useState(""),[y,h]=f.useState("{}"),[g,x]=f.useState(null),[v,k]=f.useState(!1),[j,p]=f.useState({});f.useEffect(()=>{d()},[]);async function d(){r(!0),i(null);try{t(await am())}catch(S){i(S.message)}finally{r(!1)}}async function m(S){S.preventDefault();try{JSON.parse(y)}catch{x({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}k(!0),x(null);try{await om(a==="global"?null:u.trim(),a,y),c(""),h("{}"),o("global"),x({ok:!0,text:"Rule added."}),await d()}catch(I){x({ok:!1,text:I.message})}finally{k(!1)}}async function w(S){try{await cm(S),await d()}catch(I){i(I.message)}}function E(S){p(I=>({...I,[S.rule_uid]:{cookiesInput:S.cookies_json,saving:!1,msg:null}}))}function P(S){p(I=>{const b={...I};return delete b[S],b})}async function _(S){const I=j[S.rule_uid];try{JSON.parse(I.cookiesInput)}catch{p(b=>({...b,[S.rule_uid]:{...b[S.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}p(b=>({...b,[S.rule_uid]:{...b[S.rule_uid],saving:!0,msg:null}}));try{await um(S.rule_uid,{cookies_json:I.cookiesInput}),P(S.rule_uid),await d()}catch(b){p(Q=>({...Q,[S.rule_uid]:{...Q[S.rule_uid],saving:!1,msg:{ok:!1,text:b.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(S=>{const I=j[S.rule_uid],b=S.url_pattern?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"muted",children:[S.pattern_kind,":"]})," ",s.jsx("code",{children:S.url_pattern})]}):s.jsx("span",{className:"muted",children:"global (all URLs)"});return s.jsxs("tr",{children:[s.jsx("td",{children:b}),s.jsx("td",{children:I?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:I.cookiesInput,onChange:Q=>p(H=>({...H,[S.rule_uid]:{...H[S.rule_uid],cookiesInput:Q.target.value}}))}),I.msg&&s.jsx("div",{className:`form-msg form-msg--${I.msg.ok?"ok":"err"}`,children:I.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:I.saving,onClick:()=>_(S),children:I.saving?"Saving…":"Save"}),s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>P(S.rule_uid),children:"Cancel"})]})]}):s.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:S.cookies_json})}),s.jsx("td",{children:!I&&s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>E(S),children:"Edit"}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>w(S.rule_uid),children:"Del"})]})})]},S.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:S=>o(S.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:S=>c(S.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:S=>h(S.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),g&&s.jsx("div",{className:`form-msg form-msg--${g.ok?"ok":"err"}`,children:g.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:v,children:v?"Adding…":"Add Rule"})]})]})})}function Am(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(!1),[a,o]=f.useState(null);f.useEffect(()=>{(async()=>{try{t(await Qa())}catch(j){o({ok:!1,text:j.message})}finally{r(!1)}})()},[]);async function u(j){i(!0),o(null);try{await Ol({ublock_enabled:j}),t(p=>({...p,ublock_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function c(j){i(!0),o(null);try{await Ol({cookie_ext_enabled:j}),t(p=>({...p,cookie_ext_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function y(j){i(!0),o(null);try{await Ol({modal_closer_enabled:j}),t(p=>({...p,modal_closer_enabled:j})),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 h=(e==null?void 0:e.ublock_ext_available)??!1,g=(e==null?void 0:e.ublock_enabled)??!0,x=(e==null?void 0:e.cookie_ext_available)??!1,v=(e==null?void 0:e.cookie_ext_enabled)??!0,k=(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)."}),!h&&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":g,className:`ext-toggle${g?" ext-toggle--on":""}`,onClick:()=>u(!g),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."}),!x&&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":v,className:`ext-toggle${v?" ext-toggle--on":""}`,onClick:()=>c(!v),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":k,className:`ext-toggle${k?" ext-toggle--on":""}`,onClick:()=>y(!k),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 du={0:"Private",1:"Public",2:"Users only",3:"Public"},Mm=()=>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 Fm({archiveId:e,selectedEntry:t,selectedUids:n,selectedEntries:r,detail:l,onTagFilterSet:i,tagNodes:a,onTagsRefresh:o,onEntryTitleChange:u,onEntryDeleted:c,onBulkDeleted:y,humanizeTags:h,onDetailRefresh:g,onOpenPreview:x,onPlay:v}){var rl;const[k,j]=f.useState([]),[p,d]=f.useState(""),[m,w]=f.useState([]),[E,P]=f.useState(""),_=f.useRef(0),S=f.useRef(!1),[I,b]=f.useState(!1),[Q,H]=f.useState(""),[q,ee]=f.useState("idle"),[pe,ce]=f.useState(""),te=f.useRef(null),[z,T]=f.useState(!1);f.useEffect(()=>{T(!1)},[(rl=l==null?void 0:l.summary)==null?void 0:rl.entry_uid]);const M=(n==null?void 0:n.size)>=2,[G,W]=f.useState(""),[de,ae]=f.useState("idle"),[De,ze]=f.useState(""),[Be,ct]=f.useState([]),[nt,dt]=f.useState(""),[ft,Xe]=f.useState("idle"),[R,Y]=f.useState(""),[Se,N]=f.useState("idle");f.useEffect(()=>{const $=++_.current;if(te.current&&(clearInterval(te.current),te.current=null),ee("idle"),ce(""),!t||!e){j([]),w([]);return}b(!1),H(""),S.current=!1,j([]),Promise.all([jl(e,t.entry_uid),nm(e,t.entry_uid)]).then(([re,rt])=>{$===_.current&&(j(re),w(rt))}).catch(()=>{})},[t,e]),f.useEffect(()=>()=>{clearInterval(te.current)},[]),f.useEffect(()=>{if(!M||!e){ct([]);return}Ld(e).then(ct).catch(()=>ct([]))},[M,e]),f.useEffect(()=>{W(""),ae("idle"),ze(""),dt(""),Xe("idle"),Y(""),N("idle")},[n]);async function U(){const $=n.size;if(!window.confirm(`Delete ${$} entr${$===1?"y":"ies"}? This cannot be undone.`))return;N("running");const re=new Set;for(const rt of n)try{await iu(e,rt),re.add(rt)}catch{}N("idle"),y==null||y(re)}async function D(){const $=G.trim();if($){ae("running"),ze("");try{for(const re of n)await su(e,re,$);W(""),ae("done"),o==null||o(),setTimeout(()=>ae("idle"),1800)}catch(re){ze(re.message),ae("error")}}}async function O(){if(!nt)return;Xe("running"),Y("");const $=[];for(const re of n)try{await zd(e,nt,re)}catch{$.push(re)}$.length>0?(Y(`Failed for ${$.length} entr${$.length===1?"y":"ies"}.`),Xe("error")):(Xe("done"),setTimeout(()=>Xe("idle"),1800))}async function V(){const $=Q.trim()||null;try{await Eh(e,t.entry_uid,$),u==null||u(t.entry_uid,$)}catch{}finally{b(!1)}}async function K(){const $=p.trim();if(!(!$||!t))try{await su(e,t.entry_uid,$),d(""),P("");const re=await jl(e,t.entry_uid);j(re),o()}catch(re){P(re.message)}}async function he($){try{await Th(e,t.entry_uid,$);const re=await jl(e,t.entry_uid);j(re),o()}catch{}}async function be(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await iu(e,t.entry_uid),c==null||c(t.entry_uid)}catch{}}async function Je(){if(!t||!e||q==="running")return;const $=_.current,re=t.entry_uid;ee("running"),ce("");try{const{job_uid:rt}=await im(e,re);if(_.current!==$)return;te.current=setInterval(async()=>{try{const dn=await Pd(e,rt);if(dn.status==="completed"){if(clearInterval(te.current),te.current=null,_.current!==$)return;ee("done");const Ut=await jl(e,re);if(_.current!==$)return;j(Ut),g==null||g()}else if(dn.status==="failed"){if(clearInterval(te.current),te.current=null,_.current!==$)return;ee("error"),ce(dn.error_text||"Re-archive failed.")}}catch{if(clearInterval(te.current),te.current=null,_.current!==$)return;ee("error"),ce("Network error while polling.")}},500)}catch(rt){if(_.current!==$)return;ee("error"),ce(rt.message||"Failed to start re-archive.")}}const He=l?[["Added",Ka(l.summary.archived_at)],["Source",l.summary.source_kind],["Type",l.summary.entity_kind],["Visibility",du[l.summary.visibility]??l.summary.visibility],["Root",l.structured_root_relpath]]:[],Ue=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),xe=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv","pdf","html","htm","jpg","jpeg","png","gif","webp","avif","svg","bmp"]),zt=l?l.artifacts.findIndex($=>$.artifact_role==="primary_media"):-1,We=zt>=0?l.artifacts[zt]:null,tl=We?We.relpath.split(".").pop().toLowerCase():"",nl=We&&Ue.has(tl),Es=zt>=0&&t?`/api/archives/${e}/entries/${t.entry_uid}/artifacts/${zt}`:null,Ts=l&&!nl&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread"||We&&xe.has(tl));return s.jsxs("aside",{className:"context-rail",children:[s.jsx("div",{className:"rail-eyebrow",children:"Context"}),M?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"}),De&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:De}),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:G,onChange:$=>W($.target.value),onKeyDown:$=>{$.key==="Enter"&&D()}}),s.jsx("button",{className:"tag-add-btn",onClick:D,disabled:de==="running"||!G.trim(),children:de==="running"?"…":de==="done"?"✓":"Add"})]})]}),Be.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:nt,onChange:$=>dt($.target.value),children:[s.jsx("option",{value:"",children:"Pick a collection…"}),Be.map($=>s.jsx("option",{value:$.collection_uid,children:$.name},$.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:O,disabled:!nt||ft==="running",children:ft==="running"?"…":ft==="done"?"✓":ft==="error"?"!":"Add"})]}),R&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"6px 0 0"},children:R})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:U,disabled:Se==="running",children:Se==="running"?"Deleting…":`Delete ${n.size} entr${n.size===1?"y":"ies"}`})})]}):t?l?s.jsxs(s.Fragment,{children:[I?s.jsx("input",{className:"rail-title-input",autoFocus:!0,value:Q,onChange:$=>H($.target.value),onKeyDown:$=>{$.key==="Enter"&&$.currentTarget.blur(),$.key==="Escape"&&(S.current=!0,$.currentTarget.blur())},onBlur:()=>{S.current?b(!1):V(),S.current=!1}}):s.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{H(l.summary.title??""),b(!0)},children:[St(l.summary.title)||St(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:_s(l.summary.source_kind)}}),s.jsx("span",{className:"u-text",children:l.summary.original_url}),s.jsx("span",{className:"ext",children:s.jsx(Mm,{})})]}),nl&&v&&s.jsx("button",{className:"rail-preview-btn",onClick:()=>v(Es,t),children:"▶ Play"}),Ts&&x&&s.jsx("button",{className:"rail-preview-btn",onClick:x,children:"Preview"}),s.jsx("div",{className:"meta-list",children:He.filter(([,$])=>$!=null&&$!=="").map(([$,re])=>s.jsxs("div",{className:"meta-item",children:[s.jsx("span",{className:"meta-k",children:$}),s.jsx("span",{className:`meta-v${$==="Root"?" mono":""}`,children:St(re)})]},$))}),l.artifacts.length>0&&(()=>{const $=l.artifacts.map((me,bn)=>({...me,_idx:bn})),re=$.filter(me=>me.artifact_role==="font"),rt=$.filter(me=>me.artifact_role!=="font"),dn=re.reduce((me,bn)=>me+(bn.byte_size||0),0),Ut=l.summary.entry_uid,Tn=me=>s.jsx("li",{children:s.jsxs("a",{href:`/api/archives/${e}/entries/${Ut}/artifacts/${me._idx}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[s.jsx("span",{className:"artifact-name",children:me.artifact_role==="font"?me.relpath.split("/").pop():me.artifact_role.replace(/_/g," ")}),s.jsx("span",{className:"artifact-size",children:me.byte_size!=null?Xr(me.byte_size):"—"})]})},me._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:[rt.map(Tn),re.length>0&&s.jsxs("li",{className:"artifact-group",children:[s.jsxs("button",{type:"button",className:"artifact-group-header artifact-link","aria-expanded":z,onClick:()=>T(me=>!me),children:[s.jsxs("span",{className:"artifact-name",children:[s.jsx("span",{"aria-hidden":"true",className:`artifact-group-chevron${z?" open":""}`,children:"›"}),` fonts (${re.length})`]}),s.jsx("span",{className:"artifact-size",children:Xr(dn)})]}),z&&s.jsx("ul",{className:"artifact-list artifact-group-body",children:re.map(Tn)})]})]})]})})()]}):s.jsx("p",{className:"tags-empty",children:"Loading\\u2026"}):s.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&!M&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Tags"}),k.length===0?s.jsx("p",{className:"tags-empty",children:"No tags yet."}):s.jsx("div",{className:"tags-wrap",children:k.map($=>s.jsxs("span",{className:"tag-pill",title:$.full_path,children:[h?Id($.full_path):$.full_path,s.jsx("button",{className:"remove",title:`Remove tag ${$.full_path}`,onClick:()=>he($.tag_uid),children:"×"})]},$.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:p,onChange:$=>d($.target.value),onKeyDown:$=>{$.key==="Enter"&&K()}}),s.jsx("button",{className:"tag-add-btn",onClick:K,children:"Add"})]})]}),m.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Collections"}),m.map($=>s.jsxs("div",{className:"coll-row",children:[s.jsx("span",{className:"coll-name",children:$.collection_uid}),s.jsx("span",{className:"vis-badge",children:du[$.visibility_bits]??`bits:${$.visibility_bits}`})]},$.collection_uid))]}),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:Je,disabled:q==="running",children:q==="running"?"Re-archiving…":"Re-archive"}),q==="done"&&s.jsx("p",{className:"form-msg form-msg--ok",style:{marginTop:"6px"},children:"Re-archived successfully."}),q==="error"&&s.jsx("p",{className:"form-msg form-msg--err",style:{marginTop:"6px"},children:pe})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:be,children:"Delete entry"})})]})]})}function Bm({src:e}){const t=f.useRef(null);return f.useEffect(()=>{t.current&&t.current.load()},[e]),s.jsx("div",{className:"preview-video-wrap",style:{background:"#111",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",minHeight:"240px"},children:e?s.jsxs("video",{ref:t,controls:!0,autoPlay:!1,style:{width:"100%",maxHeight:"100%",display:"block"},children:[s.jsx("source",{src:e}),"Your browser does not support the video element."]}):s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No video available"})})}function fu({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 Hm({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 Ad(e){return e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(new Date(e*1e3)):""}function pu(e){return!e||!e.includes("&")?e:e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}const J={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"}},Ce={bg:"#000000",border:"#2f3336",text:"#e7e9ea",dim:"#71767b",accent:"#1d9bf0",codeBg:"#16181c"},ri={article:{background:Ce.bg,color:Ce.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:Ce.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:Ce.border,flexShrink:0},aAuthorName:{fontSize:"15px",fontWeight:"700",color:Ce.text,lineHeight:"1.3"},aAuthorSub:{fontSize:"15px",color:Ce.dim,lineHeight:"1.3"},aDivider:{border:"none",borderTop:`1px solid ${Ce.border}`,margin:"0"},aBody:{padding:"4px 16px 0"},bH1:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:Ce.text,lineHeight:"36px",margin:"24px 0 10px"},bH2:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:Ce.text,lineHeight:"36px",margin:"24px 0 10px"},bP:{fontSize:"17px",color:Ce.text,lineHeight:"1.5",marginBottom:"16px",marginTop:"0"},bSpacer:{height:"6px",display:"block"},bQuote:{borderLeft:`3px solid ${Ce.border}`,padding:"2px 14px",margin:"14px 0",color:Ce.dim,fontSize:"17px",lineHeight:"1.5"},bHr:{border:"none",borderTop:`1px solid ${Ce.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:Ce.text,lineHeight:"1.5",marginBottom:"6px"},bTweet:{display:"flex",alignItems:"center",gap:"12px",border:`1px solid ${Ce.border}`,borderRadius:"12px",padding:"14px 16px",margin:"14px 0",color:Ce.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:Ce.text,background:"transparent"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:Ce.codeBg,padding:"2px 6px",borderRadius:"4px",color:"#e6edf3"},link:{color:Ce.accent,textDecoration:"none"}};function Um(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 Yn(e,t,n){return e&&n[e]?n[e]:t||null}function Md(){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 qa(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 Fd(e,t){const n=e.expanded_url||e.url||e.text||"",r=e.display_url||e.expanded_url||e.url||e.text||"",l=qa(e,t,e.url,e.text,e.display_url,e.expanded_url);return!l||!n?null:{...l,kind:"url",href:n,display:r}}function Bd(e,t){const n=e.screen_name||e.name||e.text||"",r=n?`@${n}`:null,l=qa(e,t,r);return!l||!n?null:{...l,kind:"mention",screen_name:n}}const hu=/https?:\/\/[^\s<>"'\])]+/g,Wm=/[.,;:!?)()]+$/;function os(e,t){const n=[];let r=0,l;for(hu.lastIndex=0;(l=hu.exec(e))!==null;){l.index>r&&n.push(e.slice(r,l.index));let i=l[0].replace(Wm,"");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:(rFd(o,e)).filter(Boolean),...(t.user_mentions||[]).map(o=>Bd(o,e)).filter(Boolean)];if(r.length===0&&n.length===0)return os(pu(e),J.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),h=r.filter(v=>v.s<=o&&v.e>=c),g=h.find(v=>v.kind==="url");if(g)return s.jsx("a",{href:g.href,target:"_blank",rel:"noopener noreferrer",style:J.link,children:g.display||y},u);const x=h.find(v=>v.kind==="mention");return x?s.jsx("a",{href:`https://x.com/${x.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:J.link,children:y},u):s.jsx("span",{children:os(pu(y),J.link)},u)}).filter(o=>o!==null)}function Qm(e,t,n,r,l=J){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=Fd(u,e);c&&i.push(c)}for(const u of r){const c=Bd(u,e);c&&i.push(c)}if(i.length===0)return os(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],h=i.filter(j=>j.s<=u&&j.e>=y),g=e.slice(u,y);let x;if(g.includes(` `)){const j=g.split(` `);x=j.flatMap((p,d)=>dj.kind==="style"&&j.style==="Code")&&(x=s.jsx("code",{style:l.iCode,children:x})),h.some(j=>j.kind==="style"&&j.style==="Bold")&&(x=s.jsx("strong",{children:x})),h.some(j=>j.kind==="style"&&j.style==="Italic")&&(x=s.jsx("em",{children:x})),h.some(j=>j.kind==="style"&&j.style==="Underline")&&(x=s.jsx("u",{children:x})),h.some(j=>j.kind==="style"&&j.style==="Strikethrough")&&(x=s.jsx("s",{children:x}));const v=h.find(j=>j.kind==="url");if(v){const j=/^https?:\/\/t\.co\//i.test(x);x=s.jsx("a",{href:v.href,target:"_blank",rel:"noopener noreferrer",style:l.link,children:j?v.display:x})}const k=h.find(j=>j.kind==="mention");return k&&(x=s.jsx("a",{href:`https://x.com/${k.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:l.link,children:x})),s.jsx("span",{children:typeof x=="string"?os(x,l.link):x},c)})}function Km(e,t,n){const r=(n==null?void 0:n.st)||J,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=Yn(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(Md,{}),"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 li(e,t,n,r){const l=(r==null?void 0:r.st)||J,i=e.type||"",a=e.text||"",o=e.inline_style_ranges||[],u=e.data||{},c=Qm(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(Md,{}),"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:Km(e,n,r)},t);default:return a?s.jsx("p",{style:l.bP,children:c},t):null}}function qm(e,t,n){const r=(n==null?void 0:n.st)||J,l=[];let i=0;for(;i{r&&(l==null||l(!0))},[r,l]);const o=r?ri:J,u=e.cover_media||{},c=e.author||t||{},y=e.first_published_at_secs?Ad(e.first_published_at_secs):"",g=[c.screen_name?`@${c.screen_name}`:"",y].filter(Boolean).join(" · "),x=Yn(u.local_path,u.url,n),v=Yn(c.avatar_local_path,c.avatar_url,n),k=s.jsxs(s.Fragment,{children:[i&&s.jsx(Hd,{items:[{src:i,alt:""}],startIndex:0,onClose:()=>a(null)}),x&&s.jsx("a",{href:x,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:j=>{!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),a(x))},children:s.jsx("img",{src:x,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:[v?s.jsx("img",{src:v,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"}),g&&s.jsx("div",{style:o.aAuthorSub,children:g})]})]})]}),s.jsx("hr",{style:o.aDivider}),s.jsx("div",{style:o.aBody,children:qm(e.blocks||[],n,{onImgClick:a,st:o})})]});return r?s.jsx("div",{style:ri.article,children:s.jsx("div",{style:ri.articleInner,children:k})}):s.jsx("div",{style:J.article,children:k})}function Jm({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:J.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 Hd({items:e,startIndex:t,onClose:n}){const[r,l]=f.useState(t);f.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:J.lightboxBackdrop,onClick:n,children:s.jsxs("div",{style:J.lightboxContent,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{style:J.lightboxToolbar,children:[e.length>1&&s.jsxs("span",{style:J.lightboxCounter,children:[r+1," / ",e.length]}),s.jsx("a",{href:i.src,target:"_blank",rel:"noopener noreferrer",style:J.lightboxLink,title:"Open in new tab",children:"↗"}),s.jsx("button",{style:J.lightboxBtn,onClick:n,"aria-label":"Close",children:"×"})]}),s.jsx("img",{src:i.src,alt:i.alt||"",style:J.lightboxImg}),e.length>1&&s.jsxs("div",{style:J.lightboxNav,children:[s.jsx("button",{style:J.lightboxNavBtn,onClick:()=>l(a=>Math.max(a-1,0)),disabled:r===0,children:"‹"}),s.jsx("button",{style:J.lightboxNavBtn,onClick:()=>l(a=>Math.min(a+1,e.length-1)),disabled:r===e.length-1,children:"›"})]})]})})}function mu({tweet:e,isInThread:t,isLast:n,artifactMap:r}){var d,m;const[l,i]=f.useState(null),a=e.author||{},o=e.created_at_secs?Ad(e.created_at_secs):"",u=e.entities||{},c=Yn(a.avatar_local_path,a.avatar_url,r),y=t&&!n,h=e.is_quote_status===!0,g=t?J.tweetRowThread:J.tweetRow,x=e.full_text||"",v=((m=(d=e.extended_entities)==null?void 0:d.media)!=null&&m.length?e.extended_entities.media:u.media)||[],k=[],j=[];for(const w of v)if(w.type==="photo"){const E=Yn(w.local_path,w.media_url_https,r);E&&k.push({kind:"photo",src:E,alt:w.alt_text||""})}else if(w.type==="video"||w.type==="animated_gif"){const E=w.local_path&&r[w.local_path]||(()=>{var _,S;return(S=(((_=w.video_info)==null?void 0:_.variants)||[]).filter(I=>I.content_type==="video/mp4").sort((I,b)=>(b.bitrate||0)-(I.bitrate||0))[0])==null?void 0:S.url})();E&&j.push({kind:w.type==="animated_gif"?"gif":"video",src:E})}const p=[];for(const w of v){if(!w.url||!(w.type==="photo"?k.some(_=>_.src===Yn(w.local_path,w.media_url_https,r)):j.length>0))continue;const P=qa(w,x,w.url);P&&p.push([P.s,P.e])}return s.jsxs(s.Fragment,{children:[l!==null&&s.jsx(Hd,{items:k,startIndex:l,onClose:()=>i(null)}),s.jsxs("div",{style:g,children:[s.jsxs("div",{style:J.leftCol,children:[c?s.jsx("img",{src:c,style:J.avatar,alt:a.name||""}):s.jsx("div",{style:J.avatarPh}),y&&s.jsx("div",{style:J.threadLine})]}),s.jsxs("div",{style:J.rightCol,children:[s.jsxs("div",{style:J.authorRow,children:[s.jsx("span",{style:J.authorName,children:a.name||a.screen_name||"Unknown"}),a.screen_name&&s.jsxs("span",{style:J.authorHandle,children:["@",a.screen_name]}),o&&s.jsxs("span",{style:J.datePart,children:["· ",o]}),h&&s.jsx("span",{style:J.qtBadge,title:"Quote tweet",children:"↻ QT"})]}),s.jsx("div",{style:J.tweetText,children:Vm(x,u,p)}),k.length>0&&s.jsx("div",{style:J.mediaGrid,children:s.jsx(Jm,{photos:k,onOpen:w=>i(w)})}),j.map((w,E)=>s.jsx("div",{style:J.mediaGrid,children:s.jsx("video",{src:w.src,style:J.mediaVideo,controls:!0,loop:w.kind==="gif",muted:w.kind==="gif",autoPlay:w.kind==="gif"})},E)),(e.retweet_count>0||e.favorite_count>0)&&s.jsxs("div",{style:J.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 Ym({archiveId:e,entryUid:t,artifacts:n,entityKind:r,fullPage:l,onXArticle:i}){const[a,o]=f.useState(!0),[u,c]=f.useState(null),[y,h]=f.useState([]);if(f.useEffect(()=>{if(o(!0),c(null),h([]),!n||!e||!t){o(!1);return}const v=n.map((j,p)=>({...j,index:p})).filter(j=>j.artifact_role==="raw_tweet_json");if(v.length===0){c("No tweet data found."),o(!1);return}let k=!1;return _h(e,t,v.map(j=>j.index)).then(async j=>{if(k)return;const p=/https?:\/\/t\.co\/[A-Za-z0-9]+/g,d=_=>{var I;const S=_.full_text||"";return(((I=_.entities)==null?void 0:I.urls)||[]).map(b=>{var Q;if(b.fromIndex!=null&&b.toIndex!=null)return[b.fromIndex,b.toIndex];if(((Q=b.indices)==null?void 0:Q.length)===2)return[b.indices[0],b.indices[1]];if(b.url){const H=S.indexOf(b.url);if(H!==-1)return[H,H+b.url.length]}return null}).filter(Boolean)},m=(_,S,I)=>_.some(([b,Q])=>b<=S&&Q>=I),w=new Set;for(const _ of j){const S=_.full_text||"",I=d(_);let b;for(p.lastIndex=0;(b=p.exec(S))!==null;)m(I,b.index,b.index+b[0].length)||w.add(b[0])}const E=w.size>0?await Ch([...w]).catch(()=>({})):{},P=j.map(_=>{var H;const S=_.full_text||"",I=d(_),b=[];let Q;for(p.lastIndex=0;(Q=p.exec(S))!==null;){const q=Q[0],ee=E[q];ee&&ee!==q&&!m(I,Q.index,Q.index+q.length)&&b.push({url:q,expanded_url:ee,display_url:(()=>{try{const pe=new URL(ee);return pe.hostname+(pe.pathname.length>1?"/…":"")}catch{return ee}})(),fromIndex:Q.index,toIndex:Q.index+q.length})}return b.length===0?_:{..._,entities:{..._.entities||{},urls:[...((H=_.entities)==null?void 0:H.urls)||[],...b]}}});k||h(P)}).catch(j=>{k||c(j.message||"Failed to load tweet.")}).finally(()=>{k||o(!1)}),()=>{k=!0}},[e,t,n]),a)return s.jsx("div",{style:J.loading,children:"Loading…"});if(u)return s.jsxs("div",{style:J.error,children:["Error: ",u]});if(y.length===0)return null;const g=Um(e,t,n);if(r==="tweet_thread")return s.jsx("div",{style:J.threadOuter,children:y.map((v,k)=>s.jsx(mu,{tweet:v,isInThread:!0,isLast:k===y.length-1,artifactMap:g},v.id||k))});const x=y[0];return x.is_article&&x.article?s.jsx(Xm,{article:x.article,tweetAuthor:x.author,artifactMap:g,fullPage:l,onXArticle:i}):s.jsx("div",{style:J.card,children:s.jsx(mu,{tweet:x,isInThread:!1,isLast:!0,artifactMap:g})})}const Gm=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv"]),Zm=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),eg=new Set(["jpg","jpeg","png","gif","webp","avif","svg","bmp"]);function Ud({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 x=s.jsx(Ym,{archiveId:e,entryUid:o,artifacts:a,entityKind:u,fullPage:r,onXArticle:l});return r?x:s.jsx("div",{className:"preview-tweet-wrap",children:x})}const c=a.findIndex(x=>x.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((x,v)=>s.jsxs("li",{children:[x.artifact_role,": ",x.relpath]},v))})]});const y=a[c],h=`/api/archives/${e}/entries/${o}/artifacts/${c}`,g=y.relpath.split(".").pop().toLowerCase();return Gm.has(g)?s.jsx("div",{className:"preview-panel",children:s.jsx(Bm,{src:h})}):Zm.has(g)?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:h,controls:!0,style:{marginTop:"8px",width:"100%",maxWidth:"400px"}})]}):g==="pdf"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(fu,{src:h,type:"pdf",title:i.title,originalUrl:i.original_url})}):g==="html"||g==="htm"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(fu,{src:h,type:"page",title:i.title,originalUrl:i.original_url})}):eg.has(g)?s.jsx("div",{className:"preview-panel",style:{height:"100%"},children:s.jsx(Hm,{src:h,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((x,v)=>s.jsxs("li",{children:[x.artifact_role,": ",x.relpath]},v))})]})}function tg({archiveId:e,entry:t,detail:n,onClose:r}){var l,i;return f.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(Ud,{archiveId:e,entry:t,detail:n})})]})})}function gu(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=f.useRef(null),[i,a]=f.useState(!1),[o,u]=f.useState(0),[c,y]=f.useState(NaN),[h,g]=f.useState(1);f.useEffect(()=>{!l.current||!t||(l.current.load(),u(0),y(NaN),a(!1))},[t]),f.useEffect(()=>{l.current&&(l.current.volume=h)},[h]);function x(){const d=l.current;d&&(i?d.pause():d.play().catch(()=>{}))}function v(d){const m=l.current;if(!m||!isFinite(c))return;const w=Number(d.target.value);m.currentTime=w,u(w)}function k(d){g(Number(d.target.value))}const j=(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 d;return u(((d=l.current)==null?void 0:d.currentTime)??0)},onLoadedMetadata:()=>{var d;return y(((d=l.current)==null?void 0:d.duration)??NaN)},onDurationChange:()=>{var d;return y(((d=l.current)==null?void 0:d.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:_s(p)}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.85rem",color:"var(--ink)"},title:j,children:j})]}),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:x,"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:gu(o)}),s.jsx("input",{type:"range",min:0,max:isFinite(c)?c:0,step:.1,value:isFinite(o)?o:0,onChange:v,"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:gu(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:h,onChange:k,"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 rg({archiveId:e,entryUid:t}){var g,x;const[n,r]=f.useState(null),[l,i]=f.useState(!0),[a,o]=f.useState(null),[u,c]=f.useState(!1);f.useEffect(()=>{if(!u)return;const v=document.documentElement,k=document.body,j=v.style.colorScheme,p=k.style.background;return v.style.colorScheme="dark",k.style.background="#000",()=>{v.style.colorScheme=j,k.style.background=p}},[u]),f.useEffect(()=>{c(!1),Dl(e,t).then(v=>{r(v),i(!1)}).catch(v=>{o((v==null?void 0:v.message)||"Failed to load entry"),i(!1)})},[e,t]);const y=((g=n==null?void 0:n.summary)==null?void 0:g.title)||t,h=(x=n==null?void 0:n.summary)==null?void 0:x.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}),h&&s.jsx("a",{href:h,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(Ud,{archiveId:e,entry:n.summary,detail:n,fullPage:!0,onXArticle:c})]})]})}const lg=7e3;function sg({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(ag,{toast:r,onDismiss:t,onIgnoreUblock:n},r.id))}):null}function ig(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 ag({toast:e,onDismiss:t,onIgnoreUblock:n}){const[r,l]=f.useState(!1),i=e.type==="warning",a=e.type==="success";f.useEffect(()=>{if(r)return;const u=setTimeout(()=>t(e.id),lg);return()=>clearTimeout(u)},[r,e.id,t]);const o=ig(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 Cs=f.createContext(null),yr=(()=>{const e=window.location.pathname.match(/^\/preview\/([^/]+)\/([^/]+)/);return e?{archiveId:e[1],entryUid:e[2]}:null})(),og=["archive","tags","collections","runs","admin","settings"],ug=["profile","tokens","instance","cookies","extensions","storage"];function fn(){const e=window.location.pathname.split("/").filter(Boolean),t=og.includes(e[0])?e[0]:"archive",n=t==="settings"&&ug.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;return{view:t,settingsTab:n,q:l,tag:i,entry:a}}function cg(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function dg(){const[e,t]=f.useState("loading"),[n,r]=f.useState(null);f.useEffect(()=>{(async()=>{if(await Dh()){t("setup");return}const B=await Fh();if(!B){t("login");return}r(B),t("authenticated")})()},[]),f.useEffect(()=>{const C=()=>{r(null),t("login")};return window.addEventListener("auth:expired",C),()=>window.removeEventListener("auth:expired",C)},[]),f.useEffect(()=>{const C=()=>{const{view:B,settingsTab:F,q:X,tag:se,entry:ke}=fn();E(B),_(F),I(X),m(se),x(ke),k(null),p(ke?new Set([ke]):new Set)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[]);const[l,i]=f.useState([]),[a,o]=f.useState(null),[u,c]=f.useState([]),[y,h]=f.useState(()=>new Set),[g,x]=f.useState(()=>fn().entry),[v,k]=f.useState(null),[j,p]=f.useState(()=>{const C=fn().entry;return C?new Set([C]):new Set}),[d,m]=f.useState(()=>fn().tag),[w,E]=f.useState(()=>fn().view),[P,_]=f.useState(()=>fn().settingsTab),[S,I]=f.useState(()=>fn().q),[b,Q]=f.useState(""),[H,q]=f.useState(!1),[ee,pe]=f.useState([]),[ce,te]=f.useState([]),[z,T]=f.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[M,G]=f.useState([]),W=f.useRef(0),[de,ae]=f.useState(()=>{try{const C=JSON.parse(sessionStorage.getItem("pendingCaptures")||"[]");if(Array.isArray(C))return C}catch{}return[]});f.useEffect(()=>{sessionStorage.setItem("pendingCaptures",JSON.stringify(de))},[de]);const[De,ze]=f.useState(()=>sessionStorage.getItem("ublockWarningIgnored")==="true"),[Be,ct]=f.useState(null),nt=f.useRef(0),dt=f.useRef(null),ft=f.useRef(!1),Xe=f.useRef(!0),R=f.useRef(null),Y=f.useRef(new Map),Se=(n==null?void 0:n.humanize_slugs)??!1;f.useEffect(()=>{const C=++nt.current;ct(null),!(!v||!a)&&Dl(a,v.entry_uid).then(B=>{C===nt.current&&ct(B)}).catch(()=>{})},[v,a]),f.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",z)},[z]);const N=f.useCallback(async(C,B,F)=>{if(C){q(!0);try{let X;B||F?X=await Sh(C,B,F):X=await jh(C),c(X),p(se=>{if(se.size<2)return se;const ke=new Set(X.map(Pn=>Pn.entry_uid)),ll=new Set([...se].filter(Pn=>ke.has(Pn)));return ll.size===se.size?se:ll}),Q(X.length===0?"No results":`${X.length} result${X.length===1?"":"s"}`)}catch{c([]),Q("Search failed. Try again.")}finally{q(!1)}}},[]);f.useEffect(()=>{e==="authenticated"&&kh().then(C=>{if(i(C),C.length>0){const B=C[0].id;o(B)}})},[e]),f.useEffect(()=>{if(a){if(Xe.current){Xe.current=!1,Promise.all([ti(a).then(pe),Sl(a).then(te)]);return}m(null),k(null),x(null),p(new Set),Promise.all([N(a,"",null),ti(a).then(pe),Sl(a).then(te)])}},[a]),f.useEffect(()=>{if(a===null)return;const C=setTimeout(()=>{N(a,S,d)},300);return()=>clearTimeout(C)},[S,a]),f.useEffect(()=>{a!==null&&(d!==null&&E("archive"),N(a,S,d))},[d,a]);const U=f.useCallback(C=>{o(C)},[]),D=f.useCallback(C=>{E(C),C==="tags"&&a&&Sl(a).then(te)},[a]);f.useEffect(()=>{if(yr)return;const C=cg(w,P);window.location.pathname!==C&&history.pushState(null,"",C+window.location.search)},[w,P]);const O=f.useCallback(C=>{x(C?C.entry_uid:null),k(C)},[]),V=f.useCallback((C,B)=>{if(Y.current.set(C.entry_uid,C),B.shiftKey&&R.current!==null){B.preventDefault();const F=[...document.querySelectorAll("#entries-body [data-entry-uid]")],X=F.findIndex(or=>or.dataset.entryUid===R.current),se=F.findIndex(or=>or.dataset.entryUid===C.entry_uid);if(X===-1||se===-1){R.current=C.entry_uid,p(new Set([C.entry_uid])),O(C);return}const ke=Math.min(X,se),ll=Math.max(X,se),Pn=new Set(F.slice(ke,ll+1).map(or=>or.dataset.entryUid));p(Pn),Pn.size===1&&O(C)}else if(B.ctrlKey||B.metaKey){R.current=C.entry_uid;const F=new Set(j);if(F.has(C.entry_uid)?F.delete(C.entry_uid):F.add(C.entry_uid),p(F),F.size===0)O(null);else if(F.size===1){const[X]=F,se=Y.current.get(X)??u.find(ke=>ke.entry_uid===X)??null;se?O(se):Dl(a,X).then(ke=>{ke!=null&&ke.summary&&O(ke.summary)}).catch(()=>{})}else O(null)}else R.current=C.entry_uid,p(new Set([C.entry_uid])),O(C)},[u,j,O,a]),K=f.useCallback(C=>{m(C)},[]),he=f.useCallback(()=>{m(null)},[]),be=f.useCallback(()=>{a&&Sl(a).then(te)},[a]),Je=f.useCallback((C,B)=>{d===C?m(B):d!=null&&d.startsWith(C+"/")&&m(B+d.slice(C.length))},[d]),He=f.useCallback(C=>{(d===C||d!=null&&d.startsWith(C+"/"))&&m(null)},[d]),Ue=f.useCallback((C,B)=>{c(F=>F.map(X=>X.entry_uid===C?{...X,title:B}:X)),k(F=>F&&F.entry_uid===C?{...F,title:B}:F),ct(F=>F&&F.summary.entry_uid===C?{...F,summary:{...F.summary,title:B}}:F)},[]),xe=f.useCallback(()=>{if(!a||!v)return;const C=++nt.current;Dl(a,v.entry_uid).then(B=>{C===nt.current&&ct(B)}).catch(()=>{})},[a,v]),zt=f.useCallback(C=>{const B=u.some(F=>F.entry_uid===C);h(F=>{const X=new Set(F);return X.add(C),X}),c(F=>F.filter(X=>X.entry_uid!==C)),k(F=>(F==null?void 0:F.entry_uid)===C?null:F),x(F=>F===C?null:F),p(F=>{const X=new Set(F);return X.delete(C),X}),B||N(a,S,d)},[u,a,S,d,N]),We=f.useCallback(C=>{const B=new Set(u.map(X=>X.entry_uid)),F=[...C].some(X=>!B.has(X));h(X=>{const se=new Set(X);return C.forEach(ke=>se.add(ke)),se}),c(X=>X.filter(se=>!C.has(se.entry_uid))),p(new Set),k(null),x(null),F&&N(a,S,d)},[u,a,S,d,N]);f.useEffect(()=>{if(j.size>=2)x(null),k(null);else if(j.size===1){const[C]=j;x(C)}else x(null),k(null)},[j]);const tl=f.useMemo(()=>u.filter(C=>j.has(C.entry_uid)),[u,j]);f.useEffect(()=>{if(!g||v)return;const C=u.find(B=>B.entry_uid===g);C&&k(C)},[u,g,v]),f.useEffect(()=>{if(yr)return;const C=new URLSearchParams;S&&C.set("q",S),w==="archive"&&d&&C.set("tag",d),w==="archive"&&g&&C.set("entry",g);const B=C.toString(),F=window.location.pathname+(B?"?"+B:"");window.location.pathname+window.location.search!==F&&history.replaceState(null,"",F)},[S,d,g,w]),f.useEffect(()=>{const C=B=>{var F,X;(B.metaKey||B.ctrlKey)&&B.key==="k"&&(B.preventDefault(),w==="archive"?((F=dt.current)==null||F.focus(),(X=dt.current)==null||X.select()):(ft.current=!0,E("archive")))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[w]),f.useEffect(()=>{w==="archive"&&ft.current&&(ft.current=!1,requestAnimationFrame(()=>{var C,B;(C=dt.current)==null||C.focus(),(B=dt.current)==null||B.select()}))},[w]);const nl=f.useCallback(()=>{T(!0)},[]),Es=f.useCallback(()=>{T(!1)},[]),Ts=f.useCallback(()=>{if(a)return Promise.allSettled([N(a,S,d),ti(a).then(pe)])},[a,S,d,N]),rl=f.useCallback((C,B,F="error",X=null)=>{if(F==="warning"&&De&&B)return;const se=++W.current;G(ke=>[...ke,{id:se,text:C,locator:B,type:F,headline:X}])},[De]),$=f.useCallback(C=>{G(B=>B.filter(F=>F.id!==C))},[]),re=f.useCallback(()=>{sessionStorage.setItem("ublockWarningIgnored","true"),ze(!0),G(C=>C.filter(B=>!(B.type==="warning"&&B.locator)))},[]),rt=f.useCallback(C=>{ae(B=>[...B,C])},[]),dn=f.useCallback(C=>{ae(B=>B.filter(F=>F.id!==C))},[]),[Ut,Tn]=f.useState(null),[me,bn]=f.useState(null),Wd=f.useCallback(()=>{v&&Tn(v.entry_uid)},[v]),Vd=f.useCallback(()=>Tn(null),[]),Qd=f.useCallback((C,B)=>{bn({src:C,entry:B})},[]),Kd=f.useCallback(()=>bn(null),[]);return f.useEffect(()=>{Tn(null)},[v]),f.useEffect(()=>{const C=B=>{var X,se,ke;if(B.key!=="Escape"||z||Ut)return;const F=(X=document.activeElement)==null?void 0:X.tagName;F==="INPUT"||F==="TEXTAREA"||F==="SELECT"||j.size>0&&(B.preventDefault(),p(new Set),(ke=(se=document.activeElement)==null?void 0:se.blur)==null||ke.call(se))};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[z,Ut,j]),f.useEffect(()=>(document.body.classList.toggle("has-audio-bar",!!me),()=>document.body.classList.remove("has-audio-bar")),[me]),e==="loading"?s.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?s.jsx(pm,{onComplete:()=>t("login")}):e==="login"?s.jsx(fm,{onLogin:C=>{r(C),t("authenticated")}}):yr?s.jsx(rg,{archiveId:yr.archiveId,entryUid:yr.entryUid}):s.jsx(Cs.Provider,{value:{currentUser:n,setCurrentUser:r},children:s.jsxs(s.Fragment,{children:[s.jsx(hm,{archives:l,archiveId:a,onArchiveChange:U,view:w,onViewChange:D,onCaptureClick:nl}),s.jsxs("main",{className:"app-shell",children:[s.jsxs("div",{className:"workspace",children:[w==="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:dt,className:"search-input",type:"search","aria-label":"Search archive","aria-busy":H,placeholder:"Search titles, URLs, types, tags…",value:S,onChange:C=>I(C.target.value)}),s.jsx("span",{className:"kbd",children:"⌘K"})]}),s.jsxs("span",{className:"result-count",children:[b&&s.jsxs(s.Fragment,{children:[s.jsx("b",{children:b.split(" ")[0]})," ",b.split(" ").slice(1).join(" ")]}),d&&s.jsxs("button",{className:"tag-filter-badge",onClick:he,children:["× ",Se?Id(d):d]})]})]}),w==="archive"&&s.jsx(jm,{entries:u,selectedUids:j,onRowClick:V,archiveId:a,pendingCaptures:de,deletedUids:y}),w==="runs"&&s.jsx(_m,{runs:ee}),w==="admin"&&s.jsx(Em,{archives:l}),w==="tags"&&s.jsx(Tm,{archiveId:a,tagNodes:ce,tagFilter:d,onTagFilterSet:K,onViewChange:D,onTagRenamed:Je,onTagDeleted:He,onTagsRefresh:be,humanizeTags:Se}),w==="collections"&&s.jsx(Pm,{archiveId:a}),w==="settings"&&s.jsx(zm,{tab:P,onTabChange:_,archiveId:a})]}),s.jsx(Fm,{archiveId:a,selectedEntry:v,selectedUids:j,selectedEntries:tl,detail:Be,onTagFilterSet:K,tagNodes:ce,onTagsRefresh:be,onEntryTitleChange:Ue,onEntryDeleted:zt,onBulkDeleted:We,humanizeTags:Se,onDetailRefresh:xe,onOpenPreview:Wd,onPlay:Qd})]}),Ut&&v&&v.entry_uid===Ut&&s.jsx(tg,{archiveId:a,entry:v,detail:Be,onClose:Vd}),me&&s.jsx(ng,{entry:me.entry,src:me.src,archiveId:a,onClose:Kd}),s.jsx(gm,{open:z,archiveId:a,onClose:Es,onCaptured:Ts,onToast:rl,activeJobs:de,onJobStarted:rt,onJobSettled:dn}),s.jsx(sg,{toasts:M,onDismiss:$,onIgnoreUblock:re})]})})}bd(document.getElementById("root")).render(s.jsx(f.StrictMode,{children:s.jsx(dg,{})})); diff --git a/crates/archivr-server/static/index.html b/crates/archivr-server/static/index.html index 45c1ec5..2d8a6fc 100644 --- a/crates/archivr-server/static/index.html +++ b/crates/archivr-server/static/index.html @@ -4,7 +4,7 @@ Archivr - + diff --git a/frontend/src/components/EntryRow.jsx b/frontend/src/components/EntryRow.jsx index f07d4ce..2aef582 100644 --- a/frontend/src/components/EntryRow.jsx +++ b/frontend/src/components/EntryRow.jsx @@ -143,9 +143,9 @@ export default function EntryRow({ entry, archiveId, rowIndex, isSelected, isMul
{formatBytes(entry.total_artifact_bytes)} - {entry.cached_bytes > 0 && entry.total_artifact_bytes > 0 && ( + {entry.cached_bytes > 0 && entry.cacheable_bytes > 0 && ( - {Math.round(entry.cached_bytes / entry.total_artifact_bytes * 100)}% cached + {Math.round(entry.cached_bytes / entry.cacheable_bytes * 100)}% cached )}