@codingfactory/mediables-vue 2.19.0 → 2.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/{PixiFrameExporter-CL1sPbnw.js → PixiFrameExporter-CRe8z6ua.js} +2 -2
  2. package/dist/{PixiFrameExporter-CL1sPbnw.js.map → PixiFrameExporter-CRe8z6ua.js.map} +1 -1
  3. package/dist/{PixiFrameExporter-nFehBjPQ.cjs → PixiFrameExporter-R6iQjzVw.cjs} +2 -2
  4. package/dist/{PixiFrameExporter-nFehBjPQ.cjs.map → PixiFrameExporter-R6iQjzVw.cjs.map} +1 -1
  5. package/dist/components/MediaFilterChips.vue.d.ts +10 -0
  6. package/dist/components/MediaInspectorPanel.vue.d.ts +13 -0
  7. package/dist/components/MediaLibraryShell.vue.d.ts +21 -0
  8. package/dist/components/MediaManagementView.vue.d.ts +1 -0
  9. package/dist/components/MediaTrashWorkspace.vue.d.ts +5 -0
  10. package/dist/composables/useMediaDeletion.d.ts +20 -0
  11. package/dist/composables/useMediaLibraryVisibility.d.ts +37 -0
  12. package/dist/composables/useMediaMetadata.d.ts +24 -0
  13. package/dist/editor-BQ_nY4P6.js +4302 -0
  14. package/dist/editor-BQ_nY4P6.js.map +1 -0
  15. package/dist/editor-CUV1pIsV.cjs +2 -0
  16. package/dist/editor-CUV1pIsV.cjs.map +1 -0
  17. package/dist/imageEditorState-BNQEZoCF.js +81 -0
  18. package/dist/imageEditorState-BNQEZoCF.js.map +1 -0
  19. package/dist/imageEditorState-PrcqbsfM.cjs +2 -0
  20. package/dist/imageEditorState-PrcqbsfM.cjs.map +1 -0
  21. package/dist/{index-BR0szJau.js → index-B8LxZ37n.js} +16860 -15559
  22. package/dist/index-B8LxZ37n.js.map +1 -0
  23. package/dist/index-Dae8SHT7.js +6557 -0
  24. package/dist/index-Dae8SHT7.js.map +1 -0
  25. package/dist/index-DutUeSES.cjs +357 -0
  26. package/dist/index-DutUeSES.cjs.map +1 -0
  27. package/dist/index-QOKC8XA_.cjs +2 -0
  28. package/dist/index-QOKC8XA_.cjs.map +1 -0
  29. package/dist/index.d.ts +5 -1
  30. package/dist/mediables-primitives.cjs +2 -0
  31. package/dist/mediables-primitives.cjs.map +1 -0
  32. package/dist/mediables-primitives.mjs +21 -0
  33. package/dist/mediables-primitives.mjs.map +1 -0
  34. package/dist/mediables-vanilla.cjs +1 -1
  35. package/dist/mediables-vanilla.mjs +8 -7
  36. package/dist/mediables-vanilla.mjs.map +1 -1
  37. package/dist/mediables-vue.cjs +1 -1
  38. package/dist/mediables-vue.mjs +74 -70
  39. package/dist/mediables-vue.mjs.map +1 -1
  40. package/dist/primitives-exports.d.ts +37 -0
  41. package/dist/style.css +1 -1
  42. package/dist/types/media.d.ts +2 -0
  43. package/dist/types/mediaLibraryPicker.d.ts +5 -0
  44. package/dist/utils/focus.d.ts +4 -0
  45. package/dist/vanilla-editor/core/EventEmitter.d.ts +8 -8
  46. package/dist/vanilla-editor/core/State.d.ts +441 -95
  47. package/package.json +8 -2
  48. package/dist/editor-D85y_zTO.cjs +0 -2
  49. package/dist/editor-D85y_zTO.cjs.map +0 -1
  50. package/dist/editor-DAJxTvzM.js +0 -10873
  51. package/dist/editor-DAJxTvzM.js.map +0 -1
  52. package/dist/index-BR0szJau.js.map +0 -1
  53. package/dist/index-CKYVSPfs.cjs +0 -357
  54. package/dist/index-CKYVSPfs.cjs.map +0 -1
@@ -0,0 +1,357 @@
1
+ "use strict";var Eh=Object.defineProperty;var Sh=(o,a,t)=>a in o?Eh(o,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[a]=t;var ie=(o,a,t)=>Sh(o,typeof a!="symbol"?a+"":a,t);const ml=require("pinia"),e=require("vue"),Ch=require("./imageEditorState-PrcqbsfM.cjs"),jt=require("pixi.js"),de=require("./editor-CUV1pIsV.cjs"),la=require("./index-QOKC8XA_.cjs"),G=require("@ionic/vue"),xh=require("pixi-filters");function Nh(o){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(a,t,n.get?n:{enumerable:!0,get:()=>o[t]})}}return a.default=o,Object.freeze(a)}const na=Nh(jt);let Ia={apiBaseUrl:"/api/v1",isAdmin:!1};function vc(o){return typeof o=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(o)}function ai(o){Ia={...Ia,...o}}function im(){return{...Ia}}function rm(o){Ia={...o}}function lm(o){const a=im();return ai(o),()=>{rm(a)}}function Vh(o){const a=o.trim().replace(/\/+$/,"");return a===""?"/api/v1":a.startsWith("/")?a:`/${a}`}function Th(o,a){const t=Vh(a),n=(i,r="")=>{const l=`/api${t}`;return!t.startsWith("/api/")&&i.startsWith(`${l}/`)?`${i.slice(4)}${r}`:!t.startsWith("/api/")&&i===l?`${t}${r}`:`${i}${r}`};if(/^https?:\/\//i.test(o))try{const i=typeof window<"u"?window.location.origin:"http://localhost",r=new URL(o,i);if(r.origin===i)return n(r.pathname,`${r.search}${r.hash}`)}catch{return o}return n(o)}const Bh=async(o,a={})=>{var s;const t=(s=document.querySelector('meta[name="csrf-token"]'))==null?void 0:s.getAttribute("content"),n={Accept:"application/json",...a.headers};t&&(n["X-CSRF-TOKEN"]=t),a.body instanceof FormData||(n["Content-Type"]="application/json");const r={method:a.method||"GET",headers:n,credentials:"include"};a.body instanceof FormData?r.body=a.body:a.body!==void 0&&(r.body=JSON.stringify(a.body));const l=await fetch(o,r);if(!l.ok){const d=await l.json().catch(()=>({message:"Request failed"}));throw new Error(d.message||`HTTP ${l.status}`)}if(l.status!==204)return await l.json()},ja=ml.defineStore("media",()=>{const o=e.ref([]),a=e.ref([]),t=e.ref(!1),n=e.ref(null),i=e.ref(1),r=e.ref(1),l=e.ref(24),s=e.ref({type:null,uuid:null}),d=e.ref([]),c=e.ref(!1),u=e.ref(null),m=e.ref(new Map),p=e.ref(new Map),f=e.ref(new Set),h=e.ref(new Map),v=e.ref({}),y=5*60*1e3,w=e.computed(()=>{if(Ia.apiScope)return Ia.apiScope;if(Ia.isAdmin)return"admin"}),_=e.computed(()=>w.value==="admin");function b(){return Ia.httpClient||Bh}function g(be){const _e=Ia.apiBaseUrl||"/api/v1",ye=w.value?`/${w.value}`:"";return`${_e}${ye}${be}`}function I(be){return`${Ia.apiBaseUrl||"/api/v1"}${be}`}function T(be,_e){return`${w.value??"default"}-${be}-${JSON.stringify(_e)}`}function $(be){return Date.now()-be<y}function N(){h.value.clear(),v.value={}}function B(be){if(!be||!be.data)return;const _e={};be.data.forEach(ye=>{const Ne=`${ye.file_name}-${ye.collection_name||"default"}`,Se=_e[Ne];(!Se||Object.keys(ye.generated_conversions||{}).length>Object.keys(Se.generated_conversions||{}).length)&&(_e[Ne]=ye)}),o.value=Object.values(_e),be.meta&&(i.value=be.meta.current_page,r.value=Math.ceil(be.meta.total/be.meta.per_page))}async function P(be=1,_e={}){const ye=T(be,_e),Ne=h.value.get(ye);if(Ne&&$(Ne.timestamp)){const Se=Ne.data;return B(Se),Se}t.value=!0,n.value=null;try{const Se=new URLSearchParams;Se.append("page",be.toString()),Se.append("per_page",l.value.toString()),_.value&&Se.append("linked","1");for(const it in _e)if(Object.prototype.hasOwnProperty.call(_e,it)){const rt=_e[it];rt!=null&&rt!==""&&Se.append(it,String(rt))}const Oe=await b()(g(`/media?${Se}`));return h.value.set(ye,{data:Oe,timestamp:Date.now()}),B(Oe),Oe}catch(Se){throw n.value=Se instanceof Error?Se.message:"Failed to fetch media",o.value=[],new Error(n.value)}finally{t.value=!1}}async function x(be,_e){t.value=!0,n.value=null;const ye=`${be.name}-${Date.now()}`,Ne={file:be,progress:0,status:"uploading"};m.value.set(ye,Ne);try{const Se=new FormData;Se.append("file",be),Se.append("collection",_e.collection),_e.ownerUuid&&(Se.append("owner_uuid",_e.ownerUuid),Se.append("owner_type",_e.ownerType||"")),_e.usageUuid&&(Se.append("usage_uuid",_e.usageUuid),Se.append("usage_type",_e.usageType||""),Se.append("usage_purpose",_e.usagePurpose||"")),_e.customProperties&&Se.append("custom_properties",JSON.stringify(_e.customProperties));const Oe=await b()(g("/media"),{method:"POST",body:Se});return Ne.status="completed",Ne.progress=100,Ne.media=Oe==null?void 0:Oe.data,i.value===1&&(Oe!=null&&Oe.data)&&(o.value=[Oe.data,...o.value]),N(),(Oe==null?void 0:Oe.data)||null}catch(Se){throw Ne.status="error",Ne.error=Se instanceof Error?Se.message:"Upload failed",n.value=Ne.error,new Error(n.value)}finally{t.value=!1,setTimeout(()=>{m.value.delete(ye)},5e3)}}async function M(be){t.value=!0,n.value=null;const _e=o.value.findIndex(Ne=>Ne.uuid===be);let ye;_e!==-1&&(ye=o.value.splice(_e,1)[0]);try{return await b()(g(`/media/${be}`),{method:"DELETE"}),f.value.delete(be),N(),!0}catch(Ne){throw ye&&_e!==-1&&o.value.splice(_e,0,ye),n.value=Ne instanceof Error?Ne.message:"Failed to delete media",new Error(n.value)}finally{t.value=!1}}async function E(be,_e){t.value=!0,n.value=null;try{const Ne=await b()(g(`/media/${be}`),{method:"PATCH",body:_e,data:_e});if(Ne!=null&&Ne.data){const Se=o.value.findIndex(Re=>Re.uuid===be);return Se!==-1&&(o.value[Se]={...o.value[Se],...Ne.data}),N(),Ne.data}return null}catch(ye){throw n.value=ye instanceof Error?ye.message:"Failed to update media",new Error(n.value)}finally{t.value=!1}}async function D(){t.value=!0,n.value=null;try{const _e=await b()(g("/media/collections"));return a.value=(_e==null?void 0:_e.data)||[],a.value}catch(be){throw n.value=be instanceof Error?be.message:"Failed to fetch collections",a.value=[],new Error(n.value)}finally{t.value=!1}}async function j(be,_e,ye="images",Ne){c.value=!0,u.value=null;try{const Se=new URLSearchParams;Se.append("collection",ye),Ne&&Se.append("search",Ne);const Oe=await b()(g(`/media/model/${be}/${_e}?${Se}`));return Oe!=null&&Oe.data?(d.value=Oe.data,Oe.data):[]}catch(Se){throw u.value=Se instanceof Error?Se.message:"Failed to fetch model media",d.value=[],new Error(u.value)}finally{c.value=!1}}async function L(be,_e,ye,Ne="images"){c.value=!0,u.value=null;const Se=[...d.value];try{const Oe=await b()(g(`/media/model/${be}/${_e}/attach`),{method:"POST",body:{media_uuids:ye,collection:Ne}});return await j(be,_e,Ne),(Oe==null?void 0:Oe.data)||[]}catch(Re){throw d.value=Se,u.value=Re instanceof Error?Re.message:"Failed to attach media",new Error(u.value)}finally{c.value=!1}}async function z(be,_e,ye,Ne="images"){c.value=!0,u.value=null;const Se=[...d.value];d.value=d.value.filter(Re=>Re.uuid!==ye);try{return await b()(g(`/media/model/${be}/${_e}/detach`),{method:"POST",body:{media_uuid:ye,collection:Ne}}),!0}catch(Re){throw d.value=Se,u.value=Re instanceof Error?Re.message:"Failed to detach media",new Error(u.value)}finally{c.value=!1}}async function C(be,_e,ye,Ne="images"){c.value=!0,u.value=null;const Se=[...d.value],Re=new Map(d.value.map(Oe=>[Oe.uuid,Oe]));d.value=ye.map(Oe=>Re.get(Oe)).filter(Oe=>Oe!==void 0);try{return await b()(g(`/media/model/${be}/${_e}/reorder`),{method:"POST",body:{media_uuids:ye,collection:Ne}}),!0}catch(Oe){throw d.value=Se,u.value=Oe instanceof Error?Oe.message:"Failed to reorder media",new Error(u.value)}finally{c.value=!1}}async function A(be,_e,ye={}){var pt,Nt;const Ne=b(),Se=Ia.apiBaseUrl||"/api/v1";let Re=vc(_e.documentId)?_e.documentId:vc((pt=_e.document)==null?void 0:pt.id)?_e.document.id:null,Oe=_e.documentRevisionId??null,it=typeof _e.documentRevisionNumber=="number"?_e.documentRevisionNumber:typeof((Nt=_e.document)==null?void 0:Nt.revision)=="number"?_e.document.revision:null;if(_e.document){const Ce=await Ne(`${Se}/media/${be}/editor-documents/materialize`,{method:"POST",body:{document_id:Re,base_document_revision:it,document:_e.document}});Re=Ce.document_id,Oe=Ce.document_revision_id,it=Ce.document_revision_number}if(_e.document&&Re&&Oe&&typeof it=="number"){const Ce=new FormData,Le=(_e.mimeType||_e.blob.type||"image/png")==="image/jpeg"?"jpg":"png";Ce.append("flattened_file",_e.blob,`edited.${Le}`),Ce.append("document_id",Re),Ce.append("document_revision_id",Oe),Ce.append("expected_document_revision",String(it)),Ce.append("output_mode",ye.asVariant?"save-as-variant":"save-as-new");const nt=await Ne(`${Se}/media/${be}/editor-documents/save`,{method:"POST",body:Ce});if(nt.media)return nt.media;throw new Error("Unexpected response from layered editor save endpoint")}const rt=new FormData,bt=(_e.mimeType||_e.blob.type||"image/png")==="image/jpeg"?"jpg":"png";rt.append("image_file",_e.blob,`edited.${bt}`);const Ct=Ch.serializeEditorState(_e.state);Ct&&rt.append("editor_state",Ct),rt.append("save_as_new","true"),ye.asVariant&&rt.append("as_variant","true"),ye.name!==void 0&&rt.append("name",ye.name);const mt=await Ne(`${Se}/editor/${be}/save`,{method:"POST",body:rt});if("media"in mt&&mt.media)return mt.media;if("status_url"in mt&&mt.status_url)return O(Ne,Th(mt.status_url,Se),ye.pollTimeout??6e4);throw new Error("Unexpected response from editor save endpoint")}async function O(be,_e,ye){const Ne=Date.now(),Se=2e3;for(;Date.now()-Ne<ye;){await new Promise(Oe=>setTimeout(Oe,Se));const Re=await be(_e);if(Re.status==="completed"&&Re.media)return Re.media;if(Re.status==="failed")throw new Error(Re.error??"Image processing failed")}throw new Error("Image processing timed out")}function K(be,_e,ye){s.value=ye!==void 0?{type:be,uuid:_e,collection:ye}:{type:be,uuid:_e},v.value[`${be}-${_e}`]={timestamp:Date.now()}}function se(){s.value={type:null,uuid:null},d.value=[],u.value=null}async function xe(){if(!s.value.type||!s.value.uuid)return;const be=await j(s.value.type,s.value.uuid,s.value.collection||"images");d.value=be||[]}function ue(){o.value.forEach(be=>f.value.add(be.uuid))}function le(){f.value.clear()}function Z(be){f.value.has(be)?f.value.delete(be):f.value.add(be)}function k(be){return f.value.has(be)}function F(){return Array.from(m.value.values()).some(be=>be.status==="uploading")}function W(be){return m.value.get(be)||p.value.get(be)}function J(){return[...Array.from(m.value.values()),...Array.from(p.value.values())]}async function ce(){const be=Array.from(f.value);let _e=0;for(const ye of be)try{await M(ye),_e++}catch{}return le(),_e}function Ue(be,_e){var ye;return _e&&((ye=be.conversion_urls)!=null&&ye[_e])?be.conversion_urls[_e]||"":be.original_url||be.url||""}return{items:o,collections:a,loading:t,error:n,currentPage:i,totalPages:r,itemsPerPage:l,isAdmin:_,modelContext:s,modelMedia:d,isLoadingModelMedia:c,modelMediaError:u,selectedItems:f,uploadProgress:m,uploadQueue:p,cachedResponses:v,fetchMedia:P,uploadFile:x,deleteMedia:M,updateMedia:E,clearCache:N,fetchCollections:D,fetchModelMedia:j,attachMedia:L,detachMedia:z,reorderMedia:C,saveEditedImage:A,setModelContext:K,clearModelContext:se,refreshModelMedia:xe,selectAllItems:ue,clearSelection:le,toggleSelection:Z,isSelected:k,deleteSelectedItems:ce,getHttpClient:b,getApiUrl:g,getEditorApiUrl:I,hasActiveUploads:F,getUploadProgress:W,getAllUploadProgress:J,getMediaUrl:Ue}}),sm=()=>((Ia.apiScope!=="admin"||Ia.isAdmin!==!0)&&ai({...Ia,apiScope:"admin",isAdmin:!0}),ja());class dm{constructor(a,t){this.state=a,this.editor=t,this.element=null,this._tabs=new Map,this._unsubscribers=[],this._onSelect=null}render({onSelect:a}={}){return this._onSelect=a,this.element=de.el("div",{className:"panel-tabs",role:"tablist","aria-label":"Filter categories","data-testid":"v2-category-tabs"}),de.EDITOR_CATEGORIES.forEach(t=>{const n=de.el("button",{type:"button",className:`panel-tab ${this._isSelected(t.id)?"active":""}`,role:"tab","aria-selected":this._isSelected(t.id)?"true":"false","data-category":t.id,"data-testid":`v2-category-${t.id}`,onClick:()=>this._selectCategory(t.id)});if(t.icon){const i=de.el("span",{className:"panel-tab-icon","aria-hidden":"true"});i.innerHTML=t.icon,n.appendChild(i)}n.appendChild(de.el("span",{className:"panel-tab-label"},t.name)),this._tabs.set(t.id,n),this.element.appendChild(n)}),this._unsubscribers.push(this.state.on("change:selectedCategory",()=>this._refreshActive())),this.element}_isSelected(a){const t=this.state.get("selectedCategory");return a==="crop"?this.state.get("mode")==="crop":t===a&&this.state.get("mode")!=="crop"}_selectCategory(a){var n;this.state.set("selectedCategory",a);const t=this.state.get("mode");a==="crop"?t!=="crop"&&this.editor.setMode("crop"):t!=="filters"&&this.editor.setMode("filters"),this._refreshActive(),(n=this._onSelect)==null||n.call(this,a)}_refreshActive(){this._tabs.forEach((a,t)=>{const n=this._isSelected(t);a.classList.toggle("active",n),a.setAttribute("aria-selected",n?"true":"false")})}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],this._tabs.clear(),(a=this.element)==null||a.remove(),this.element=null}}class cm{constructor(a,t){this.state=a,this.filterManager=t,this.element=null,this._unsubscribers=[],this._onToggle=null,this._onSelect=null}render({onToggle:a,onSelect:t}={}){return this._onToggle=a,this._onSelect=t,this.element=de.el("div",{className:"filter-list",role:"listbox","aria-label":"Filters","data-testid":"v2-filter-list"}),this._renderRows(),this._unsubscribers.push(this.state.on("change:selectedCategory",()=>this._renderRows()),this.state.on("change:activeFilters",()=>this._renderRows()),this.state.on("change:selectedFilter",()=>this._renderRows()),this.state.on("change:filterValues",()=>this._refreshSummaries())),this.element}_renderRows(){this.element.innerHTML="";const a=this.state.get("selectedCategory");if(!a||a==="crop")return;const t=this.filterManager.getFiltersByCategory(a),n=this.state.get("activeFilters"),i=this.state.get("selectedFilter"),r=typeof this.state.getActiveFilterLayerId=="function"?this.state.getActiveFilterLayerId():this.state.get("activeLayerId");t.forEach(l=>{var c;const s=((c=n==null?void 0:n.has)==null?void 0:c.call(n,l.id))??!1,d=i===l.id;this.element.appendChild(this._renderRow(l,s,d,r))})}_renderRow(a,t,n,i=null){const r=de.el("button",{type:"button",className:`filter-row ${n?"selected":""}`,role:"option","aria-selected":n?"true":"false","data-filter":a.id,"data-testid":`v2-filter-${a.id}`,onClick:()=>{var u;return(u=this._onSelect)==null?void 0:u.call(this,a.id,i)}}),l=de.el("button",{type:"button",className:`filter-row-toggle ${t?"active":""}`,"aria-label":`${t?"Disable":"Enable"} ${a.name}`,"aria-pressed":t?"true":"false","data-testid":`v2-filter-toggle-${a.id}`,onClick:u=>{var p,f,h,v;u.stopPropagation();const m=!((f=(p=this.state.get("activeFilters"))==null?void 0:p.has)!=null&&f.call(p,a.id));(h=this._onToggle)==null||h.call(this,a.id,m,i),m&&((v=this._onSelect)==null||v.call(this,a.id,i))}});t&&(l.innerHTML=de.checkmark),r.appendChild(l);const s=de.el("div",{className:"filter-row-body"});s.appendChild(de.el("span",{className:"filter-row-name"},a.name));const d=this._buildSummary(a,t);d&&s.appendChild(de.el("span",{className:"filter-row-summary"},d)),r.appendChild(s);const c=de.el("span",{className:"filter-row-chevron","aria-hidden":"true"});return c.innerHTML=de.chevronRight,r.appendChild(c),r}_buildSummary(a,t){if(!t)return a.description||"";const n=this.state.getFilterValues(a.id);if(!n||Object.keys(n).length===0)return a.description||"Active";const i=[];for(const r of(a.controls||[]).slice(0,4)){const l=n[r.id];if(!(l===void 0||l===r.default)&&(i.push(this._formatControlValue(r,l)),i.length>=2))break}return i.length===0?"Active":i.join(" · ")}_formatControlValue(a,t){return a.type==="toggle"?a.label:typeof t=="number"?(a.max??1)<=1&&(a.min??0)>=0?`${a.label} ${Math.round(t*100)}%`:Number.isInteger(t)?`${a.label} ${t}`:`${a.label} ${t.toFixed(2)}`:typeof t=="string"?`${a.label}`:a.label}_refreshSummaries(){var i;const a=this.state.get("selectedCategory");if(!a||a==="crop")return;const t=this.filterManager.getFiltersByCategory(a),n=this.state.get("activeFilters");for(const r of t){const l=this.element.querySelector(`[data-filter="${r.id}"]`);if(!l)continue;const s=((i=n==null?void 0:n.has)==null?void 0:i.call(n,r.id))??!1,d=this._buildSummary(r,s),c=l.querySelector(".filter-row-summary");if(d&&c)c.textContent=d;else if(d&&!c){const u=l.querySelector(".filter-row-body");u==null||u.appendChild(de.el("span",{className:"filter-row-summary"},d))}else!d&&c&&c.remove()}}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(a=this.element)==null||a.remove(),this.element=null}}class um{constructor(a,t){this.state=a,this.filterManager=t,this.element=null,this._unsubscribers=[],this._onChange=null,this._onReset=null,this._onAction=null}render({onChange:a,onReset:t,onAction:n}={}){return this._onChange=a,this._onReset=t,this._onAction=n,this.element=de.el("div",{className:"controls-section","data-testid":"v2-controls-section"}),this._renderControls(),this._unsubscribers.push(this.state.on("change:selectedFilter",()=>this._renderControls()),this.state.on("change:activeFilters",()=>this._renderControls())),this.element}_renderControls(){this.element.innerHTML="";const a=this.state.get("selectedFilter");if(!a){this.element.appendChild(de.el("div",{className:"no-filter-selected"},"Select a filter to adjust"));return}const t=typeof this.state.getActiveFilterLayerId=="function"?this.state.getActiveFilterLayerId():this.state.get("activeLayerId"),n=this.filterManager.getFilterDef(a);if(!n){this.element.appendChild(de.el("div",{className:"no-filter-selected"},"Filter not found"));return}const i=de.el("div",{className:"controls-header"});i.appendChild(de.el("span",{className:"controls-title"},n.name)),i.appendChild(de.createButton({label:"Reset",className:"btn-text",onClick:()=>this._handleReset(a,t)})),this.element.appendChild(i);const r=de.el("div",{className:"controls-grid"}),l=this.state.getFilterValues(a);(n.controls||[]).forEach(d=>{if(d.hidden)return;const c=this._createControl(a,d,l[d.id]??d.default,t);c&&r.appendChild(c)});const s=this.filterManager.getInstance(a);if(s&&typeof s.getDynamicControls=="function"){let d=[];try{d=s.getDynamicControls()||[]}catch{}d.forEach(c=>{const u=c.property||c.id,m=l[u]??c.default,p=this._createControl(a,c,m,t);p&&r.appendChild(p)})}this.element.appendChild(r)}_createControl(a,t,n,i=null){if(t.hidden)return null;const r=t.label||t.id,l=this._normalizeControlType(t.type),s=t.property||t.id;switch(l){case"slider":return de.createSlider({id:`v2-${a}-${t.id}`,label:r,min:t.min??0,max:t.max??1,step:t.step??.01,value:typeof n=="number"?n:t.default??0,onChange:d=>{var c;return(c=this._onChange)==null?void 0:c.call(this,a,s,d,i)}});case"toggle":return de.createToggle({id:`v2-${a}-${t.id}`,label:r,checked:!!n,onChange:d=>{var c;return(c=this._onChange)==null?void 0:c.call(this,a,s,d,i)}});case"color":return de.createColorPicker({id:`v2-${a}-${t.id}`,label:r,value:typeof n=="string"&&n.startsWith("#")?n:t.default||"#000000",onChange:d=>{var c;return(c=this._onChange)==null?void 0:c.call(this,a,s,d,i)}});case"select":{const d=(t.options||[]).map(c=>typeof c=="object"&&c.value!==void 0?{value:c.value,label:c.label||String(c.value)}:{value:c,label:String(c)});return de.createSelect({id:`v2-${a}-${t.id}`,label:r,options:d,value:n??t.default,onChange:c=>{var u;return(u=this._onChange)==null?void 0:u.call(this,a,s,c,i)}})}case"text":return de.createTextInput({id:`v2-${a}-${t.id}`,label:r,value:typeof n=="string"?n:t.default??"",placeholder:t.placeholder||"",onCommit:d=>{var c;return(c=this._onChange)==null?void 0:c.call(this,a,s,d,i)}});case"button":{const d=de.el("div",{className:"button-control"});return d.appendChild(de.createButton({label:r,className:"btn-secondary",onClick:()=>{var c;(c=this._onAction)==null||c.call(this,a,t.action||t.id,i),this._renderControls()}})),d}default:return null}}_normalizeControlType(a){return{slider:"slider",range:"slider",toggle:"toggle",checkbox:"toggle",color:"color",select:"select",dropdown:"select",button:"button",text:"text"}[a]||a}_handleReset(a,t=null){var n;(n=this._onReset)==null||n.call(this,a,t),this._renderControls()}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(a=this.element)==null||a.remove(),this.element=null}}class Mh{constructor(a,t){this.state=a,this.filterManager=t,this.element=null,this._unsubscribers=[],this._onRemove=null,this._onSelect=null,this._onClearAll=null}render({onRemove:a,onSelect:t,onClearAll:n}={}){return this._onRemove=a,this._onSelect=t,this._onClearAll=n,this.element=de.el("div",{className:"panel-section","data-testid":"v2-active-stack"}),this._renderContents(),this._unsubscribers.push(this.state.on("change:activeFilters",()=>this._renderContents()),this.state.on("change:selectedFilter",()=>this._refreshSelection())),this.element}_renderContents(){this.element.innerHTML="";const a=this.state.get("activeFilters"),t=(a==null?void 0:a.size)??0,n=this._activeFilterLayerId(),i=de.el("div",{className:"panel-section-title"});if(i.appendChild(de.el("span",{},`Active (${t})`)),t>0&&this._onClearAll&&i.appendChild(de.el("button",{type:"button",className:"btn btn-text",style:{padding:"2px 8px",fontSize:"11px"},"data-testid":"v2-clear-all",onClick:()=>{var s;return(s=this._onClearAll)==null?void 0:s.call(this,n)}},"Clear all")),this.element.appendChild(i),t===0){this.element.appendChild(de.el("div",{className:"active-empty"},"No filters applied"));return}const r=de.el("div",{className:"active-stack"}),l=this.state.get("selectedFilter");for(const s of a){const d=this.filterManager.getFilterDef(s);d&&r.appendChild(this._renderChip(d,s===l,n))}this.element.appendChild(r)}_renderChip(a,t,n=null){const i=de.el("div",{className:`active-chip ${t?"selected":""}`,"data-filter":a.id,"data-testid":`v2-active-${a.id}`});i.appendChild(de.el("button",{type:"button",className:"active-chip-name","aria-label":`Select ${a.name}`,onClick:()=>{var l;return(l=this._onSelect)==null?void 0:l.call(this,a.id,n)}},a.name));const r=de.el("button",{type:"button",className:"active-chip-remove","aria-label":`Remove ${a.name}`,"data-testid":`v2-active-remove-${a.id}`,onClick:()=>{var l;return(l=this._onRemove)==null?void 0:l.call(this,a.id,n)}});return r.innerHTML=de.close,i.appendChild(r),i}_activeFilterLayerId(){return typeof this.state.getActiveFilterLayerId=="function"?this.state.getActiveFilterLayerId():this.state.get("activeLayerId")}_refreshSelection(){var n;const a=this.state.get("selectedFilter"),t=(n=this.element)==null?void 0:n.querySelectorAll(".active-chip");t&&t.forEach(i=>{const r=i.getAttribute("data-filter");i.classList.toggle("selected",r===a)})}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(a=this.element)==null||a.remove(),this.element=null}}const Zo=["collapsed","half","full"];class Ih{constructor(a={}){this._onSnapChange=a.onSnapChange||null,this._ariaLabel=a.ariaLabel||"Filter controls drawer",this.element=null,this._handle=null,this._body=null,this._headerSlot=null,this._snap="half",this._dragging=!1,this._dragStartY=0,this._dragStartHeight=0,this._dragPointerId=null,this._containerHeight=0}build({header:a,body:t}={}){this.element=de.el("div",{className:"editor-v2-drawer",role:"dialog","aria-label":this._ariaLabel,"data-testid":"v2-bottom-drawer","data-snap":this._snap}),this._handle=de.el("button",{type:"button",className:"drawer-handle","aria-label":"Drag to resize filters drawer","aria-expanded":this._snap==="full"?"true":"false","data-testid":"v2-drawer-handle"});const n=de.el("span",{className:"drawer-handle-grip","aria-hidden":"true"});return this._handle.appendChild(n),this._handle.addEventListener("click",i=>{if(this._wasDragging){this._wasDragging=!1,i.preventDefault();return}this._cycleSnap()}),this._handle.addEventListener("pointerdown",i=>this._onPointerDown(i)),this._handle.addEventListener("pointermove",i=>this._onPointerMove(i)),this._handle.addEventListener("pointerup",i=>this._onPointerEnd(i)),this._handle.addEventListener("pointercancel",i=>this._onPointerEnd(i)),this.element.appendChild(this._handle),this._headerSlot=de.el("div",{className:"drawer-header"}),a&&this._headerSlot.appendChild(a),this.element.appendChild(this._headerSlot),this._body=de.el("div",{className:"drawer-body"}),t&&this._body.appendChild(t),this.element.appendChild(this._body),this.element}updateContainerHeight(a){this._containerHeight=Math.max(0,Number(a)||0),this._applySnap(this._snap,{animate:!1})}snapTo(a,t={}){Zo.includes(a)&&this._applySnap(a,{animate:t.animate!==!1})}get snap(){return this._snap}setBodyContent(a){this._body&&(this._body.innerHTML="",a&&this._body.appendChild(a))}setHeaderContent(a){this._headerSlot&&(this._headerSlot.innerHTML="",a&&this._headerSlot.appendChild(a))}_onPointerDown(a){var t,n,i;if(!(a.button!==void 0&&a.button!==0)){this._dragging=!0,this._wasDragging=!1,this._dragPointerId=a.pointerId,this._dragStartY=a.clientY,this._dragStartHeight=((t=this.element)==null?void 0:t.offsetHeight)||0;try{(i=(n=this._handle)==null?void 0:n.setPointerCapture)==null||i.call(n,a.pointerId)}catch{}this.element&&(this.element.style.transition="none")}}_onPointerMove(a){if(!this._dragging||a.pointerId!==this._dragPointerId)return;const t=a.clientY-this._dragStartY,n=this._dragStartHeight-t;this._containerHeight||window.innerHeight;const i=this._heightForSnap("collapsed"),r=this._heightForSnap("full"),l=Math.max(i,Math.min(r,n));this.element&&(this.element.style.height=`${l}px`),Math.abs(t)>4&&(this._wasDragging=!0),a.preventDefault()}_onPointerEnd(a){var i,r,l;if(!this._dragging)return;this._dragging=!1;try{(r=(i=this._handle)==null?void 0:i.releasePointerCapture)==null||r.call(i,a.pointerId)}catch{}this._dragPointerId=null;const t=((l=this.element)==null?void 0:l.offsetHeight)||0,n=this._nearestSnap(t);this._applySnap(n,{animate:!0})}_cycleSnap(){const a=Zo.indexOf(this._snap),t=Zo[(a+1)%Zo.length];this._applySnap(t,{animate:!0})}_heightForSnap(a){const t=this._containerHeight||window.innerHeight||600;switch(a){case"collapsed":return 80;case"half":return Math.round(t*.45);case"full":return Math.round(t*.85);default:return Math.round(t*.45)}}_nearestSnap(a){let t=Zo[0],n=1/0;for(const i of Zo){const r=this._heightForSnap(i),l=Math.abs(r-a);l<n&&(n=l,t=i)}return t}_applySnap(a,{animate:t}){var r,l;if(!this.element)return;const n=this._snap;this._snap=a;const i=typeof window<"u"&&((r=window.matchMedia)==null?void 0:r.call(window,"(prefers-reduced-motion: reduce)").matches);t&&!i?this.element.style.transition="height 0.25s cubic-bezier(0.33, 1, 0.68, 1)":this.element.style.transition="none",this.element.style.height=`${this._heightForSnap(a)}px`,this.element.dataset.snap=a,this._handle&&this._handle.setAttribute("aria-expanded",a==="full"?"true":"false"),a!==n&&((l=this._onSnapChange)==null||l.call(this,a,n))}destroy(){var a;(a=this.element)==null||a.remove(),this.element=null,this._handle=null,this._body=null,this._headerSlot=null}}const $h=[{id:"warm",label:"Warm",ariaLabel:"Apply warm gradient background",style:"linear-gradient(135deg, #101820 0%, #f2aa4c 100%)",fill:{gradientType:"linear",angle:135,stops:[{offset:0,color:"#101820"},{offset:1,color:"#f2aa4c"}]}},{id:"cool",label:"Cool",ariaLabel:"Apply cool gradient background",style:"linear-gradient(135deg, #0f766e 0%, #38bdf8 100%)",fill:{gradientType:"linear",angle:135,stops:[{offset:0,color:"#0f766e"},{offset:1,color:"#38bdf8"}]}},{id:"neutral",label:"Neutral",ariaLabel:"Apply neutral gradient background",style:"linear-gradient(135deg, #27272a 0%, #d4d4d8 100%)",fill:{gradientType:"linear",angle:135,stops:[{offset:0,color:"#27272a"},{offset:1,color:"#d4d4d8"}]}}];class mm{constructor(a,t){this.state=a,this.editor=t,this.element=null,this._errorMessage=null,this._unsubscribers=[]}render(){return this.element=de.el("div",{className:"background-panel","data-testid":"v2-background-panel"}),this._render(),this._unsubscribers.push(this.state.on("change:layers",()=>this._render())),this.element}_render(){var f,h,v;if(!this.element)return;this.element.innerHTML="";const a=this._backgroundLayer(),t=a!=null&&a.fill&&typeof a.fill=="object"?a.fill:{kind:"transparent"},n=typeof t.fit=="string"?t.fit:"cover",i=this._backgroundBlur(a),r=(a==null?void 0:a.locked)===!0,l=t.kind==="color"&&typeof t.value=="string"?t.value:"#ffffff";this.element.appendChild(de.el("div",{className:"panel-section-title"},de.el("span",{},"Background"))),this._errorMessage&&this.element.appendChild(de.el("p",{className:"background-panel-error",role:"alert","data-testid":"v2-background-error"},this._errorMessage));const s=de.el("input",{type:"color",className:"color-input",value:l,disabled:r?"disabled":void 0,"aria-label":"Background color","data-testid":"v2-background-color",onInput:y=>{this._runAction(this.editor.setBackgroundColor(y.target.value))}});this.element.appendChild(this._field("Color",s));const d=de.el("div",{className:"background-gradient-grid"});for(const y of $h){const w=de.el("button",{type:"button",className:"background-gradient-swatch",style:{background:y.style},"aria-label":y.ariaLabel,disabled:r?"disabled":void 0,"data-testid":`v2-background-gradient-${y.id}`,onClick:()=>{this._runAction(this.editor.setBackgroundGradient(y.fill))}},de.el("span",{className:"background-gradient-label"},y.label));d.appendChild(w)}this.element.appendChild(this._field("Gradient",d));const c=de.el("input",{type:"file",accept:"image/*",className:"background-upload-input",disabled:r?"disabled":void 0,"aria-label":"Upload background image","data-testid":"v2-background-upload",onChange:y=>{var _;const w=(_=y.target.files)==null?void 0:_[0];w&&this._runAction(this.editor.setBackgroundImageFromFile(w,{fit:n})),y.target.value=""}});this.element.appendChild(this._field("Upload",c));const u=(v=(h=(f=this.editor)==null?void 0:f._options)==null?void 0:h.backgroundReplacement)==null?void 0:v.mediaChoices;if(Array.isArray(u)&&u.length>0){const y=de.el("div",{className:"background-media-grid"});for(const w of u)w!=null&&w.source&&y.appendChild(de.el("button",{type:"button",className:"background-media-choice","aria-label":`Use ${w.label||"media"} as background`,disabled:r?"disabled":void 0,"data-testid":`v2-background-media-${w.id||w.source.mediaUuid||"choice"}`,onClick:()=>{this._runAction(this.editor.setBackgroundMediaSource(w.source,{fit:w.fit||n}))}},w.label||"Media"));this.element.appendChild(this._field("Media",y))}const m=de.el("select",{className:"select-input",disabled:r?"disabled":void 0,"aria-label":"Background image fit","data-testid":"v2-background-fit",onChange:y=>{this._runAction(this.editor.setBackgroundFit(y.target.value))}},this._option("cover","Cover",n),this._option("contain","Contain",n),this._option("stretch","Stretch",n),this._option("tile","Tile",n));this.element.appendChild(this._field("Fit",m));const p=de.el("input",{type:"range",min:"0",max:"40",step:"1",value:String(i),className:"range-input",disabled:r?"disabled":void 0,"aria-label":"Background blur","data-testid":"v2-background-blur",onInput:y=>{this._runAction(this.editor.setBackgroundBlur(Number(y.target.value)))}});this.element.appendChild(this._field("Blur",p)),this.element.appendChild(de.el("button",{type:"button",className:"btn btn-secondary background-remove-btn","aria-label":"Remove background layer",disabled:r?"disabled":void 0,"data-testid":"v2-background-remove",onClick:()=>{this._runAction(this.editor.removeBackgroundLayer())}},"Remove"))}_runAction(a){this._errorMessage=null,Promise.resolve(a).catch(t=>{var i,r;const n=t instanceof Error?t:new Error(String(t));this._errorMessage=n.message||"Background update failed",(r=(i=this.editor)==null?void 0:i.emit)==null||r.call(i,"error",n),this._render()})}_field(a,t){return de.el("label",{className:"background-field"},de.el("span",{className:"background-field-label"},a),t)}_option(a,t,n){return de.el("option",{value:a,selected:n===a?"selected":void 0},t)}_backgroundLayer(){const a=this.state.get("layers");return Array.isArray(a)?a.find(t=>(t==null?void 0:t.type)==="background"||(t==null?void 0:t.role)==="background")??null:null}_backgroundBlur(a){var r;const n=(Array.isArray(a==null?void 0:a.effects)?a.effects:[]).find(l=>(l==null?void 0:l.id)==="background-blur"),i=Number((r=n==null?void 0:n.params)==null?void 0:r.amount);return Number.isFinite(i)?i:0}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(a=this.element)==null||a.remove(),this.element=null}}class pm{constructor(a,t){this.state=a,this.editor=t,this.element=null,this._listEl=null,this._unsubscribers=[]}render(){return this.element=de.el("section",{className:"layer-stack-panel",role:"region","aria-label":"Layers","data-order":"bottom-to-top","data-testid":"v2-layer-stack-panel"}),this.element.appendChild(de.el("div",{className:"layer-stack-header"},de.el("span",{className:"layer-stack-title"},"Layers"),de.el("span",{className:"layer-stack-order"},"Bottom to top"))),this._listEl=de.el("div",{className:"layer-stack-list",role:"listbox","aria-label":"Layer order, bottom to top"}),this.element.appendChild(this._listEl),this._renderRows(),this._unsubscribers.push(this.state.on("change:layers",()=>this._renderRows()),this.state.on("change:activeLayerId",()=>this._renderRows())),this.element}_layers(){const a=this.state.get("layers");return Array.isArray(a)?a:[]}_renderRows(){if(!this._listEl)return;this._listEl.innerHTML="";const a=this._layers();if(!a.length){this._listEl.appendChild(de.el("div",{className:"layer-stack-empty",role:"status"},"No layers"));return}a.forEach((t,n)=>{this._listEl.appendChild(this._row(t,n,a.length))})}_row(a,t,n){const i=String((a==null?void 0:a.id)??""),r=this._layerName(a),l=(a==null?void 0:a.visible)!==!1,s=(a==null?void 0:a.locked)===!0,d=this.state.get("activeLayerId")===i,c=[d?"active":null,l?"visible":"hidden",s?"locked":"unlocked"].filter(Boolean).join(", "),u=de.el("div",{className:`layer-row${d?" active":""}${l?"":" hidden"}${s?" locked":""}`,role:"option","aria-selected":d?"true":"false","aria-label":`${r}, ${this._layerTypeLabel(a)}, ${c}`,"data-layer-id":i,"data-testid":`v2-layer-row-${i}`});u.appendChild(this._button({testId:`v2-layer-select-${i}`,label:`Select ${r}`,className:"layer-row-select",onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).selectLayer)==null?void 0:f.call(p,i)})},this._thumbnail(a))),u.appendChild(de.el("div",{className:"layer-row-main"},de.el("span",{className:"layer-row-name"},r),de.el("span",{className:"layer-row-meta"},this._layerTypeLabel(a))));const m=de.el("div",{className:"layer-row-actions"});return m.appendChild(this._iconButton({testId:`v2-layer-${l?"hide":"show"}-${i}`,label:`${l?"Hide":"Show"} ${r}`,icon:l?de.eye:de.eyeOff,disabled:s,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).setLayerVisibility)==null?void 0:f.call(p,i,!l)})})),m.appendChild(this._iconButton({testId:`v2-layer-${s?"unlock":"lock"}-${i}`,label:`${s?"Unlock":"Lock"} ${r}`,icon:s?de.lockClosed:de.lockOpen,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).setLayerLocked)==null?void 0:f.call(p,i,!s)})})),m.appendChild(this._iconButton({testId:`v2-layer-move-up-${i}`,label:`Move ${r} up`,icon:de.chevronRight,disabled:s,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).moveLayer)==null?void 0:f.call(p,i,"up")})})),m.appendChild(this._iconButton({testId:`v2-layer-move-down-${i}`,label:`Move ${r} down`,icon:de.chevronLeft,disabled:s,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).moveLayer)==null?void 0:f.call(p,i,"down")})})),m.appendChild(this._iconButton({testId:`v2-layer-bring-front-${i}`,label:`Bring ${r} to front`,icon:de.chevronRight,disabled:s,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).moveLayer)==null?void 0:f.call(p,i,"front")})})),m.appendChild(this._iconButton({testId:`v2-layer-send-back-${i}`,label:`Send ${r} to back`,icon:de.chevronLeft,disabled:s,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).moveLayer)==null?void 0:f.call(p,i,"back")})})),m.appendChild(this._iconButton({testId:`v2-layer-rename-${i}`,label:`Rename ${r}`,icon:de.pencil,disabled:s,onClick:()=>this._renameLayer(i,r)})),m.appendChild(this._iconButton({testId:`v2-layer-duplicate-${i}`,label:`Duplicate ${r}`,icon:de.duplicate,disabled:s,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).duplicateLayer)==null?void 0:f.call(p,i)})})),m.appendChild(this._iconButton({testId:`v2-layer-delete-${i}`,label:`Delete ${r}`,icon:de.trash,disabled:s||n<=1,onClick:()=>this._runAction(()=>{var p,f;return(f=(p=this.editor).deleteLayer)==null?void 0:f.call(p,i)})})),u.appendChild(m),u}_thumbnail(a){const t=de.el("span",{className:"layer-thumb","aria-hidden":"true"}),n=a==null?void 0:a.fill;if((n==null?void 0:n.kind)==="color")t.style.background=n.value||n.color||"#ffffff";else if((n==null?void 0:n.kind)==="gradient"&&Array.isArray(n.stops)){const i=n.stops.map(r=>`${r.color} ${Math.round(Number(r.offset||0)*100)}%`).join(", ");t.style.background=`linear-gradient(${Number(n.angle||135)}deg, ${i})`}else t.innerHTML=(a==null?void 0:a.type)==="background"?de.layers:de.move;return t}_button({testId:a,label:t,...n},i){const r=de.el("button",{type:"button","aria-label":t,"data-testid":a,...n});return i&&r.appendChild(i),r}_iconButton({testId:a,label:t,icon:n,disabled:i=!1,onClick:r}){const l=de.el("button",{type:"button",className:"layer-action-btn","aria-label":t,title:t,disabled:i?"disabled":void 0,"data-testid":a,onClick:r});return l.innerHTML=n,l}_renameLayer(a,t){var i;const n=(i=window.prompt)==null?void 0:i.call(window,"Layer name",t);typeof n=="string"&&this._runAction(()=>{var r,l;return(l=(r=this.editor).renameLayer)==null?void 0:l.call(r,a,n)})}_runAction(a){var t,n;try{Promise.resolve(a()).catch(i=>{var r,l;return(l=(r=this.editor).emit)==null?void 0:l.call(r,"error",{error:i,context:"layer-stack"})})}catch(i){(n=(t=this.editor).emit)==null||n.call(t,"error",{error:i,context:"layer-stack"})}}_layerName(a){return(typeof(a==null?void 0:a.name)=="string"?a.name.trim():"")||"Layer"}_layerTypeLabel(a){return(a==null?void 0:a.type)==="background"||(a==null?void 0:a.role)==="background"?"Background":(a==null?void 0:a.role)==="subject"?"Subject":(a==null?void 0:a.type)==="text"?"Text":"Image"}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(a=this.element)==null||a.remove(),this.element=null,this._listEl=null}}const Fh=[{value:"400",label:"Regular"},{value:"500",label:"Medium"},{value:"600",label:"Semibold"},{value:"700",label:"Bold"},{value:"800",label:"Heavy"}],Dh=[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}],Ah=[{value:"normal",label:"Normal"},{value:"multiply",label:"Multiply"},{value:"screen",label:"Screen"},{value:"overlay",label:"Overlay"}],vr={stroke:{enabled:!1,color:"#000000",width:0},shadow:{enabled:!1,color:"#000000",alpha:.5,blur:0,distance:0,angle:45},glow:{enabled:!1,color:"#ffffff",alpha:.5,blur:0},backdrop:{enabled:!1,color:"#000000",opacity:.5,padding:0,radius:0,blur:0}};class fm{constructor(a,t){this.state=a,this.editor=t,this.element=null,this._errorMessage=null,this._unsubscribers=[]}render(){return this.element=de.el("div",{className:"text-panel","data-testid":"v2-text-panel"}),this._render(),this._unsubscribers.push(this.state.on("change:layers",()=>this._render()),this.state.on("change:activeLayerId",()=>this._render())),this.element}_render(){if(!this.element)return;this.element.innerHTML="";const a=this._activeTextLayer(),t=(a==null?void 0:a.locked)===!0;if(this.element.appendChild(de.el("div",{className:"text-panel-header"},de.el("div",{className:"panel-section-title"},de.el("span",{},"Text")),de.el("button",{type:"button",className:"btn btn-secondary","data-testid":"v2-text-add",onClick:()=>{var d,c;return this._runAction((c=(d=this.editor).addTextLayer)==null?void 0:c.call(d))}},"Add text"))),this._errorMessage&&this.element.appendChild(de.el("p",{className:"text-panel-error",role:"alert","data-testid":"v2-text-error"},this._errorMessage)),!a){this.element.appendChild(de.el("p",{className:"text-panel-empty"},"Select or add a text layer."));return}const n=a.text&&typeof a.text=="object"?a.text:{},i=n.style&&typeof n.style=="object"?n.style:{},r=n.box&&typeof n.box=="object"?n.box:{},l=a.transform&&typeof a.transform=="object"?a.transform:{},s=this._textEffects(n.effects);this.element.appendChild(this._contentControl(a.id,n.content??"",t)),this.element.appendChild(this._controlGrid([this._numberField({label:"Opacity",testId:"v2-text-opacity",value:a.opacity??1,min:0,max:1,step:.05,disabled:t,onInput:d=>{var c,u;return this._runAction((u=(c=this.editor).updateTextLayer)==null?void 0:u.call(c,a.id,{opacity:d}))}}),this._selectField({label:"Blend",testId:"v2-text-blend-mode",value:a.blendMode||"normal",options:Ah,disabled:t,onChange:d=>{var c,u;return this._runAction((u=(c=this.editor).updateTextLayer)==null?void 0:u.call(c,a.id,{blendMode:d}))}})])),this.element.appendChild(this._selectField({label:"Font",testId:"v2-text-font-family",value:i.fontFamily||"Inter",options:la.TEXT_LAYER_FONT_FAMILIES.map(d=>({value:d,label:d})),disabled:t,onChange:d=>this._updateStyle(a.id,{fontFamily:d})})),this.element.appendChild(this._controlGrid([this._numberField({label:"Size",testId:"v2-text-font-size",value:i.fontSize??64,min:8,max:400,step:1,disabled:t,onInput:d=>this._updateStyle(a.id,{fontSize:d})}),this._selectField({label:"Weight",testId:"v2-text-font-weight",value:String(i.fontWeight??700),options:Fh,disabled:t,onChange:d=>this._updateStyle(a.id,{fontWeight:Number(d)})}),this._selectField({label:"Style",testId:"v2-text-font-style",value:i.fontStyle||"normal",options:[{value:"normal",label:"Normal"},{value:"italic",label:"Italic"}],disabled:t,onChange:d=>this._updateStyle(a.id,{fontStyle:d})}),this._selectField({label:"Align",testId:"v2-text-align",value:i.align||"center",options:Dh,disabled:t,onChange:d=>this._updateStyle(a.id,{align:d})})])),this.element.appendChild(this._controlGrid([this._colorField({label:"Fill",testId:"v2-text-fill",value:i.fill||"#ffffff",disabled:t,onInput:d=>this._updateStyle(a.id,{fill:d})}),this._numberField({label:"Line",testId:"v2-text-line-height",value:i.lineHeight??1.2,min:.8,max:3,step:.05,disabled:t,onInput:d=>this._updateStyle(a.id,{lineHeight:d})}),this._numberField({label:"Track",testId:"v2-text-letter-spacing",value:i.letterSpacing??0,min:-100,max:100,step:.5,disabled:t,onInput:d=>this._updateStyle(a.id,{letterSpacing:d})})])),this.element.appendChild(this._controlGrid([this._numberField({label:"X",testId:"v2-text-box-x",value:r.x??.2,min:0,max:1,step:.01,disabled:t,onInput:d=>this._updateBox(a.id,{x:d})}),this._numberField({label:"Y",testId:"v2-text-box-y",value:r.y??.2,min:0,max:1,step:.01,disabled:t,onInput:d=>this._updateBox(a.id,{y:d})}),this._numberField({label:"W",testId:"v2-text-box-width",value:r.width??.6,min:.05,max:1,step:.01,disabled:t,onInput:d=>this._updateBox(a.id,{width:d})}),this._numberField({label:"H",testId:"v2-text-box-height",value:r.height??.18,min:.05,max:1,step:.01,disabled:t,onInput:d=>this._updateBox(a.id,{height:d})}),this._numberField({label:"Rotate",testId:"v2-text-rotation",value:l.rotation??0,min:0,max:360,step:1,disabled:t,onInput:d=>{var c,u;return this._runAction((u=(c=this.editor).updateTextLayer)==null?void 0:u.call(c,a.id,{transform:{rotation:d}}))}})])),this.element.appendChild(this._effectSection("Stroke",[this._checkboxField({label:"Stroke",testId:"v2-text-stroke-enabled",checked:s.stroke.enabled,disabled:t,onChange:d=>this._updateEffects(a.id,{stroke:{enabled:d}})}),this._colorField({label:"Stroke Color",testId:"v2-text-stroke-color",value:s.stroke.color,disabled:t,onInput:d=>this._updateEffects(a.id,{stroke:{color:d}})}),this._numberField({label:"Stroke Width",testId:"v2-text-stroke-width",value:s.stroke.width,min:0,max:80,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{stroke:{width:d}})})])),this.element.appendChild(this._effectSection("Shadow",[this._checkboxField({label:"Shadow",testId:"v2-text-shadow-enabled",checked:s.shadow.enabled,disabled:t,onChange:d=>this._updateEffects(a.id,{shadow:{enabled:d}})}),this._colorField({label:"Shadow Color",testId:"v2-text-shadow-color",value:s.shadow.color,disabled:t,onInput:d=>this._updateEffects(a.id,{shadow:{color:d}})}),this._numberField({label:"Shadow Alpha",testId:"v2-text-shadow-alpha",value:s.shadow.alpha,min:0,max:1,step:.05,disabled:t,onInput:d=>this._updateEffects(a.id,{shadow:{alpha:d}})}),this._numberField({label:"Shadow Blur",testId:"v2-text-shadow-blur",value:s.shadow.blur,min:0,max:120,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{shadow:{blur:d}})}),this._numberField({label:"Shadow Distance",testId:"v2-text-shadow-distance",value:s.shadow.distance,min:0,max:200,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{shadow:{distance:d}})}),this._numberField({label:"Shadow Angle",testId:"v2-text-shadow-angle",value:s.shadow.angle,min:0,max:360,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{shadow:{angle:d}})})])),this.element.appendChild(this._effectSection("Glow",[this._checkboxField({label:"Glow",testId:"v2-text-glow-enabled",checked:s.glow.enabled,disabled:t,onChange:d=>this._updateEffects(a.id,{glow:{enabled:d}})}),this._colorField({label:"Glow Color",testId:"v2-text-glow-color",value:s.glow.color,disabled:t,onInput:d=>this._updateEffects(a.id,{glow:{color:d}})}),this._numberField({label:"Glow Alpha",testId:"v2-text-glow-alpha",value:s.glow.alpha,min:0,max:1,step:.05,disabled:t,onInput:d=>this._updateEffects(a.id,{glow:{alpha:d}})}),this._numberField({label:"Glow Blur",testId:"v2-text-glow-blur",value:s.glow.blur,min:0,max:120,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{glow:{blur:d}})})])),this.element.appendChild(this._effectSection("Backdrop",[this._checkboxField({label:"Backdrop",testId:"v2-text-backdrop-enabled",checked:s.backdrop.enabled,disabled:t,onChange:d=>this._updateEffects(a.id,{backdrop:{enabled:d}})}),this._colorField({label:"Backdrop Color",testId:"v2-text-backdrop-color",value:s.backdrop.color,disabled:t,onInput:d=>this._updateEffects(a.id,{backdrop:{color:d}})}),this._numberField({label:"Backdrop Opacity",testId:"v2-text-backdrop-opacity",value:s.backdrop.opacity,min:0,max:1,step:.05,disabled:t,onInput:d=>this._updateEffects(a.id,{backdrop:{opacity:d}})}),this._numberField({label:"Backdrop Padding",testId:"v2-text-backdrop-padding",value:s.backdrop.padding,min:0,max:200,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{backdrop:{padding:d}})}),this._numberField({label:"Backdrop Radius",testId:"v2-text-backdrop-radius",value:s.backdrop.radius,min:0,max:200,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{backdrop:{radius:d}})}),this._numberField({label:"Backdrop Blur",testId:"v2-text-backdrop-blur",value:s.backdrop.blur,min:0,max:80,step:1,disabled:t,onInput:d=>this._updateEffects(a.id,{backdrop:{blur:d}})})]))}_contentControl(a,t,n){const i=de.el("div",{className:"text-field text-content-field"});i.appendChild(de.el("label",{className:"text-field-label",for:"v2-text-content"},"Content"));let r=t==null?"":String(t);const l=de.el("textarea",{id:"v2-text-content",className:"text-area-input",rows:"4",disabled:n?"disabled":void 0,"data-testid":"v2-text-content",onInput:d=>{r=d.target.value},onBlur:()=>{var d,c;r!==t&&this._runAction((c=(d=this.editor).updateTextLayer)==null?void 0:c.call(d,a,{content:r}))},onKeyDown:d=>{var c,u;if(d.key==="Escape"){d.preventDefault(),r=t==null?"":String(t),l.value=r,l.blur();return}d.key==="Enter"&&(d.metaKey||d.ctrlKey)&&(d.preventDefault(),this._runAction((u=(c=this.editor).updateTextLayer)==null?void 0:u.call(c,a,{content:r})),l.blur())}});l.value=r,i.appendChild(l);const s=de.el("div",{className:"text-content-actions"});return s.appendChild(de.el("button",{type:"button",className:"btn btn-text",disabled:n?"disabled":void 0,"data-testid":"v2-text-cancel",onClick:()=>{r=t==null?"":String(t),l.value=r}},"Cancel")),s.appendChild(de.el("button",{type:"button",className:"btn btn-secondary",disabled:n?"disabled":void 0,"data-testid":"v2-text-commit",onClick:()=>{var d,c;return this._runAction((c=(d=this.editor).updateTextLayer)==null?void 0:c.call(d,a,{content:r}))}},"Commit")),i.appendChild(s),i}_controlGrid(a){const t=de.el("div",{className:"text-control-grid"});for(const n of a)t.appendChild(n);return t}_effectSection(a,t){return de.el("div",{className:"text-effect-section"},de.el("div",{className:"text-effect-title"},a),this._controlGrid(t))}_selectField({label:a,testId:t,value:n,options:i,disabled:r,onChange:l}){const s=de.el("select",{className:"select-input",disabled:r?"disabled":void 0,"data-testid":t,onChange:d=>l(d.target.value)});for(const d of i)s.appendChild(de.el("option",{value:d.value,selected:String(n)===String(d.value)?"selected":void 0},d.label));return this._field(a,s)}_numberField({label:a,testId:t,value:n,min:i,max:r,step:l,disabled:s,onInput:d}){const c=de.el("input",{type:"number",className:"text-number-input",min:String(i),max:String(r),step:String(l),value:String(n),disabled:s?"disabled":void 0,"data-testid":t,onInput:u=>d(Number(u.target.value))});return this._field(a,c)}_colorField({label:a,testId:t,value:n,disabled:i,onInput:r}){const l=de.el("input",{type:"color",className:"color-input",value:n,disabled:i?"disabled":void 0,"data-testid":t,onInput:s=>r(s.target.value)});return this._field(a,l)}_checkboxField({label:a,testId:t,checked:n,disabled:i,onChange:r}){const l=de.el("input",{type:"checkbox",className:"text-checkbox-input",checked:n?"checked":void 0,disabled:i?"disabled":void 0,"data-testid":t,onChange:s=>r(s.target.checked===!0)});return de.el("label",{className:"text-field text-checkbox-field"},de.el("span",{className:"text-field-label"},a),l)}_field(a,t){return de.el("label",{className:"text-field"},de.el("span",{className:"text-field-label"},a),t)}_updateStyle(a,t){var n,i;this._runAction((i=(n=this.editor).updateTextLayer)==null?void 0:i.call(n,a,{style:t}))}_updateBox(a,t){var n,i;this._runAction((i=(n=this.editor).updateTextLayer)==null?void 0:i.call(n,a,{box:t}))}_updateEffects(a,t){var n,i;this._runAction((i=(n=this.editor).updateTextLayer)==null?void 0:i.call(n,a,{effects:t}))}_textEffects(a){const t=a&&typeof a=="object"?a:{};return{stroke:{...vr.stroke,...t.stroke&&typeof t.stroke=="object"?t.stroke:{}},shadow:{...vr.shadow,...t.shadow&&typeof t.shadow=="object"?t.shadow:{}},glow:{...vr.glow,...t.glow&&typeof t.glow=="object"?t.glow:{}},backdrop:{...vr.backdrop,...t.backdrop&&typeof t.backdrop=="object"?t.backdrop:{}}}}_runAction(a){this._errorMessage=null,Promise.resolve(a).catch(t=>{var i,r;const n=t instanceof Error?t:new Error(String(t));this._errorMessage=n.message||"Text update failed",(r=(i=this.editor)==null?void 0:i.emit)==null||r.call(i,"error",n),this._render()})}_activeTextLayer(){const a=this.state.get("activeLayerId"),t=this.state.get("layers");return!a||!Array.isArray(t)?null:t.find(n=>(n==null?void 0:n.id)===a&&(n.type==="text"||n.role==="text"))??null}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(a=this.element)==null||a.remove(),this.element=null}}class Rh{constructor(a,t,n){this.state=a,this.filterManager=t,this.editor=n,this.element=null,this._headerEl=null,this._bodyEl=null,this._view="categories",this._onNavigate=null,this._callbacks=null,this._unsubscribers=[],this._categoryTabs=null,this._filterListView=null,this._filterControlsView=null,this._backgroundPanel=null,this._layerStackPanel=null,this._textPanel=null}build(a){return this._callbacks=a,this._onNavigate=a.onViewChange||null,this.element=de.el("div",{className:"drawer-nav","data-testid":"v2-mobile-nav"}),this._headerEl=de.el("div",{className:"drawer-nav-header"}),this.element.appendChild(this._headerEl),this._bodyEl=de.el("div",{className:"drawer-nav-body"}),this.element.appendChild(this._bodyEl),this._buildViews(),this._unsubscribers.push(this.state.on("change:selectedFilter",({value:t})=>{t&&this._view!=="controls"&&this.navigateTo("controls")}),this.state.on("change:selectedCategory",()=>{}),this.state.on("change:mode",({value:t})=>{t==="filters"&&this._view!=="categories"&&!this.state.get("selectedFilter")&&this.navigateTo("categories")})),this.navigateTo("categories"),this.element}_buildViews(){this._categoryTabs=new dm(this.state,this.editor),this._categoryTabsEl=this._categoryTabs.render({onSelect:a=>{if(a==="background"||a==="layers"||a==="text"){this.navigateTo(a);return}this.navigateTo("filters")}}),this._filterListView=new cm(this.state,this.filterManager),this._filterListEl=this._filterListView.render({onToggle:(a,t,n)=>this._callbacks.onFilterToggle(a,t,n),onSelect:(a,t)=>{this._callbacks.onFilterSelect(a,t),this.navigateTo("controls")}}),this._filterControlsView=new um(this.state,this.filterManager),this._filterControlsEl=this._filterControlsView.render({onChange:(a,t,n,i)=>this._callbacks.onFilterChange(a,t,n,i),onReset:(a,t)=>this._callbacks.onFilterReset(a,t),onAction:(a,t,n)=>this._callbacks.onFilterAction(a,t,n)}),this._backgroundPanel=new mm(this.state,this.editor),this._backgroundPanelEl=this._backgroundPanel.render(),this._layerStackPanel=new pm(this.state,this.editor),this._layerStackPanelEl=this._layerStackPanel.render(),this._textPanel=new fm(this.state,this.editor),this._textPanelEl=this._textPanel.render()}navigateTo(a){var n;if(!this.element)return;this._view=a,this._renderHeader(),this._bodyEl.innerHTML="";let t=null;switch(a){case"categories":t=this._categoryTabsEl;break;case"filters":t=this._filterListEl;break;case"controls":t=this._filterControlsEl;break;case"background":t=this._backgroundPanelEl;break;case"layers":t=this._layerStackPanelEl;break;case"text":t=this._textPanelEl;break;default:t=this._categoryTabsEl}t&&this._bodyEl.appendChild(t),(n=this._onNavigate)==null||n.call(this,a)}_renderHeader(){if(!this._headerEl)return;if(this._headerEl.innerHTML="",this._view!=="categories"){const n=de.el("button",{type:"button",className:"drawer-back-btn","aria-label":"Go back","data-testid":"v2-drawer-back",onClick:()=>this._goBack()});n.innerHTML=de.chevronLeft,this._headerEl.appendChild(n)}const t=this._titleForView(this._view);if(this._headerEl.appendChild(de.el("h2",{className:"drawer-nav-title"},t)),this._view==="controls"){const n=this.state.get("selectedFilter");if(n){const i=this._activeFilterLayerId();this._headerEl.appendChild(de.createButton({label:"Reset",className:"btn-text",onClick:()=>this._callbacks.onFilterReset(n,i)}))}}}_activeFilterLayerId(){return typeof this.state.getActiveFilterLayerId=="function"?this.state.getActiveFilterLayerId():this.state.get("activeLayerId")}_titleForView(a){switch(a){case"categories":return"Filters";case"filters":{const t=this.state.get("selectedCategory");return this._categoryLabel(t)||"Filters"}case"background":return"Background";case"layers":return"Layers";case"text":return"Text";case"controls":{const t=this.state.get("selectedFilter"),n=t?this.filterManager.getFilterDef(t):null;return(n==null?void 0:n.name)||"Filter"}default:return""}}_categoryLabel(a){var t;return a&&((t=de.EDITOR_CATEGORIES.find(n=>n.id===a))==null?void 0:t.name)||null}_goBack(){this._view==="controls"?(this.state.set("selectedFilter",null),this.navigateTo("filters")):(this._view==="filters"||this._view==="background"||this._view==="layers"||this._view==="text")&&this.navigateTo("categories")}get currentView(){return this._view}destroy(){var a,t,n,i,r,l,s;this._unsubscribers.forEach(d=>d()),this._unsubscribers=[],(a=this._categoryTabs)==null||a.destroy(),(t=this._filterListView)==null||t.destroy(),(n=this._filterControlsView)==null||n.destroy(),(i=this._backgroundPanel)==null||i.destroy(),(r=this._layerStackPanel)==null||r.destroy(),(l=this._textPanel)==null||l.destroy(),(s=this.element)==null||s.remove(),this.element=null}}class Lh{constructor(a,t){this.state=a,this.filterManager=t,this.element=null,this._onSelect=null,this._onRemove=null,this._unsubscribers=[]}render({onSelect:a,onRemove:t}={}){return this._onSelect=a,this._onRemove=t,this.element=de.el("div",{className:"mobile-active-chips",role:"region","aria-label":"Active filters","data-testid":"v2-mobile-active-chips"}),this._renderChips(),this._unsubscribers.push(this.state.on("change:activeFilters",()=>this._renderChips()),this.state.on("change:selectedFilter",()=>this._refreshSelection())),this.element}_renderChips(){this.element.innerHTML="";const a=this.state.get("activeFilters");if(((a==null?void 0:a.size)??0)===0){this.element.style.display="none";return}this.element.style.display="";const n=de.el("div",{className:"mobile-active-track"}),i=this.state.get("selectedFilter"),r=this._activeFilterLayerId();for(const l of a){const s=this.filterManager.getFilterDef(l);s&&n.appendChild(this._renderChip(s,l===i,r))}this.element.appendChild(n)}_renderChip(a,t,n=null){const i=de.el("div",{className:`mobile-active-chip ${t?"selected":""}`,"data-filter":a.id,"data-testid":`v2-mobile-chip-${a.id}`});i.appendChild(de.el("button",{type:"button",className:"mobile-active-chip-name","aria-label":`Edit ${a.name}`,onClick:()=>{var l;return(l=this._onSelect)==null?void 0:l.call(this,a.id,n)}},a.name));const r=de.el("button",{type:"button",className:"mobile-active-chip-remove","aria-label":`Remove ${a.name}`,"data-testid":`v2-mobile-chip-remove-${a.id}`,onClick:l=>{var s;l.stopPropagation(),(s=this._onRemove)==null||s.call(this,a.id,n)}});return r.innerHTML=de.close,i.appendChild(r),i}_activeFilterLayerId(){return typeof this.state.getActiveFilterLayerId=="function"?this.state.getActiveFilterLayerId():this.state.get("activeLayerId")}_refreshSelection(){var n;const a=this.state.get("selectedFilter"),t=(n=this.element)==null?void 0:n.querySelectorAll(".mobile-active-chip");t==null||t.forEach(i=>{const r=i.getAttribute("data-filter");i.classList.toggle("selected",r===a)})}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],(a=this.element)==null||a.remove(),this.element=null}}const gc="(max-width: 900px)";let Ph=class{constructor(a,t,n){this.state=a,this.filterManager=t,this.editor=n,this.root=null,this.canvasSection=null,this.canvasContainer=null,this.cropOverlay=null,this._callbacks=null,this._isMobile=!1,this._panel=null,this._categoryTabs=null,this._filterListView=null,this._filterControlsView=null,this._activeStack=null,this._backgroundPanel=null,this._layerStackPanel=null,this._textPanel=null,this._desktopBackgroundSection=null,this._desktopLayerSection=null,this._desktopTextSection=null,this._desktopFilterListSection=null,this._desktopCropWrapper=null,this._mobileChips=null,this._mobileDrawer=null,this._mobileNav=null,this._mobileCropWrapper=null,this._cropControlsEl=null,this._unsubscribers=[],this._mql=null,this._mqlHandler=null,this._resizeObserver=null}build(a){var t;return this._callbacks=a,this.root=de.el("div",{className:"editor-v2-body"}),this.canvasSection=de.el("div",{className:"editor-v2-canvas"}),this.canvasContainer=de.el("div",{className:"canvas-container"}),this.cropOverlay=de.el("canvas",{className:"crop-overlay","aria-hidden":"true"}),this.canvasSection.appendChild(this.canvasContainer),this.canvasSection.appendChild(this.cropOverlay),this._zoomOverlay=this._buildCanvasZoomOverlay(),this.canvasSection.appendChild(this._zoomOverlay),this.root.appendChild(this.canvasSection),this._isMobile=typeof window<"u"&&((t=window.matchMedia)==null?void 0:t.call(window,gc).matches)===!0,this._isMobile?this._buildMobileShell():this._buildDesktopShell(),typeof window<"u"&&window.matchMedia&&(this._mql=window.matchMedia(gc),this._mqlHandler=n=>this._handleBreakpointChange(n.matches),this._mql.addEventListener?this._mql.addEventListener("change",this._mqlHandler):this._mql.addListener&&this._mql.addListener(this._mqlHandler)),this._unsubscribers.push(this.state.on("change:mode",({value:n})=>this._applyMode(n)),this.state.on("change:selectedCategory",()=>this._applyMode(this.state.get("mode")))),{root:this.root,canvasContainer:this.canvasContainer,cropOverlay:this.cropOverlay}}mountCropControls(a){this._cropControlsEl=a,this._mountCropControlsInActiveShell()}_buildDesktopShell(){this._panel=de.el("div",{className:"editor-v2-panel","data-testid":"v2-inspector-panel"}),this._categoryTabs=new dm(this.state,this.editor),this._panel.appendChild(this._categoryTabs.render({onSelect:()=>this._handleDesktopCategoryChange()}));const a=de.el("div",{className:"panel-body"});this._desktopFilterListSection=de.el("div",{className:"panel-section"}),this._desktopFilterListSection.appendChild(de.el("div",{className:"panel-section-title"},de.el("span",{},"Filters"))),this._filterListView=new cm(this.state,this.filterManager),this._desktopFilterListSection.appendChild(this._filterListView.render({onToggle:(t,n,i)=>this._callbacks.onFilterToggle(t,n,i),onSelect:(t,n)=>this._callbacks.onFilterSelect(t,n)})),a.appendChild(this._desktopFilterListSection),this._filterControlsView=new um(this.state,this.filterManager),a.appendChild(this._filterControlsView.render({onChange:(t,n,i,r)=>this._callbacks.onFilterChange(t,n,i,r),onReset:(t,n)=>this._callbacks.onFilterReset(t,n),onAction:(t,n,i)=>this._callbacks.onFilterAction(t,n,i)})),this._desktopCropWrapper=de.el("div",{className:"crop-controls-wrapper",style:{display:"none"}}),a.appendChild(this._desktopCropWrapper),this._activeStack=new Mh(this.state,this.filterManager),a.appendChild(this._activeStack.render({onRemove:(t,n)=>this._callbacks.onFilterToggle(t,!1,n),onSelect:(t,n)=>this._callbacks.onFilterSelect(t,n),onClearAll:t=>{var n,i;return(i=(n=this._callbacks).onClearAll)==null?void 0:i.call(n,t)}})),this._desktopBackgroundSection=de.el("div",{className:"panel-section",style:{display:"none"}}),this._backgroundPanel=new mm(this.state,this.editor),this._desktopBackgroundSection.appendChild(this._backgroundPanel.render()),a.appendChild(this._desktopBackgroundSection),this._desktopLayerSection=de.el("div",{className:"panel-section",style:{display:"none"}}),this._layerStackPanel=new pm(this.state,this.editor),this._desktopLayerSection.appendChild(this._layerStackPanel.render()),a.appendChild(this._desktopLayerSection),this._desktopTextSection=de.el("div",{className:"panel-section",style:{display:"none"}}),this._textPanel=new fm(this.state,this.editor),this._desktopTextSection.appendChild(this._textPanel.render()),a.appendChild(this._desktopTextSection),this._panel.appendChild(a),this.root.appendChild(this._panel),this._mountCropControlsInActiveShell(),this._applyMode(this.state.get("mode"))}_buildMobileShell(){this._mobileChips=new Lh(this.state,this.filterManager);const a=this._mobileChips.render({onSelect:(r,l)=>{var s,d;this._callbacks.onFilterSelect(r,l),(s=this._mobileDrawer)==null||s.snapTo("full"),(d=this._mobileNav)==null||d.navigateTo("controls")},onRemove:(r,l)=>this._callbacks.onFilterToggle(r,!1,l)});this.root.appendChild(a),this._mobileDrawer=new Ih({onSnapChange:r=>{this.canvasContainer&&window.dispatchEvent(new Event("resize"))}}),this._mobileNav=new Rh(this.state,this.filterManager,this.editor);const t=this._mobileNav.build({onFilterToggle:this._callbacks.onFilterToggle,onFilterSelect:this._callbacks.onFilterSelect,onFilterChange:this._callbacks.onFilterChange,onFilterReset:this._callbacks.onFilterReset,onFilterAction:this._callbacks.onFilterAction,onViewChange:r=>{var l;r==="controls"&&((l=this._mobileDrawer)==null?void 0:l.snap)==="collapsed"&&this._mobileDrawer.snapTo("half")}});this._mobileCropWrapper=de.el("div",{className:"crop-controls-wrapper",style:{display:"none"}});const n=de.el("div",{className:"drawer-content"});n.appendChild(t),n.appendChild(this._mobileCropWrapper);const i=this._mobileDrawer.build({body:n});this.root.appendChild(i),this._wireDrawerSizing(),this._mountCropControlsInActiveShell(),this._applyMode(this.state.get("mode"))}_wireDrawerSizing(){if(!this.root||!this._mobileDrawer)return;const a=()=>{const t=this.root.getBoundingClientRect().height;this._mobileDrawer.updateContainerHeight(t)};a(),this._resizeObserver=new ResizeObserver(()=>a()),this._resizeObserver.observe(this.root)}_destroyDesktopShell(){var a,t,n,i,r,l,s,d,c,u;(a=this._categoryTabs)==null||a.destroy(),this._categoryTabs=null,(t=this._filterListView)==null||t.destroy(),this._filterListView=null,(n=this._filterControlsView)==null||n.destroy(),this._filterControlsView=null,(i=this._activeStack)==null||i.destroy(),this._activeStack=null,(r=this._backgroundPanel)==null||r.destroy(),this._backgroundPanel=null,(l=this._layerStackPanel)==null||l.destroy(),this._layerStackPanel=null,(s=this._textPanel)==null||s.destroy(),this._textPanel=null,this._desktopBackgroundSection=null,this._desktopLayerSection=null,this._desktopTextSection=null,this._desktopFilterListSection=null,(d=this._desktopCropWrapper)!=null&&d.parentElement&&((c=this._cropControlsEl)==null?void 0:c.parentElement)===this._desktopCropWrapper&&this._desktopCropWrapper.removeChild(this._cropControlsEl),this._desktopCropWrapper=null,(u=this._panel)==null||u.remove(),this._panel=null}_destroyMobileShell(){var a,t,n,i,r;(a=this._resizeObserver)==null||a.disconnect(),this._resizeObserver=null,(t=this._mobileNav)==null||t.destroy(),this._mobileNav=null,(n=this._mobileChips)==null||n.destroy(),this._mobileChips=null,this._mobileCropWrapper&&((i=this._cropControlsEl)==null?void 0:i.parentElement)===this._mobileCropWrapper&&this._mobileCropWrapper.removeChild(this._cropControlsEl),this._mobileCropWrapper=null,(r=this._mobileDrawer)==null||r.destroy(),this._mobileDrawer=null}_handleBreakpointChange(a){a!==this._isMobile&&(this._isMobile=a,a?(this._destroyDesktopShell(),this._buildMobileShell()):(this._destroyMobileShell(),this._buildDesktopShell()))}_mountCropControlsInActiveShell(){if(!this._cropControlsEl)return;this._cropControlsEl.remove();const a=this._isMobile?this._mobileCropWrapper:this._desktopCropWrapper;a==null||a.appendChild(this._cropControlsEl)}_handleDesktopCategoryChange(){if(this.state.get("mode")==="crop"||["background","layers","text"].includes(this.state.get("selectedCategory")))return;const t=this.state.get("selectedFilter");if(!t)return;this.filterManager.getFiltersByCategory(this.state.get("selectedCategory")).some(i=>i.id===t)||this.state.set("selectedFilter",null)}_applyMode(a){var s,d,c;const t=a==="crop",n=!t&&this.state.get("selectedCategory")==="background",i=!t&&this.state.get("selectedCategory")==="layers",r=!t&&this.state.get("selectedCategory")==="text",l=n||i||r;this._desktopFilterListSection&&(this._desktopFilterListSection.style.display=t||l?"none":""),(s=this._filterControlsView)!=null&&s.element&&(this._filterControlsView.element.style.display=t||l?"none":""),(d=this._activeStack)!=null&&d.element&&(this._activeStack.element.style.display=t||l?"none":""),this._desktopBackgroundSection&&(this._desktopBackgroundSection.style.display=n?"":"none"),this._desktopLayerSection&&(this._desktopLayerSection.style.display=i?"":"none"),this._desktopTextSection&&(this._desktopTextSection.style.display=r?"":"none"),this._desktopCropWrapper&&(this._desktopCropWrapper.style.display=t?"":"none"),(c=this._mobileNav)!=null&&c.element&&(this._mobileNav.element.style.display=t?"none":""),this._mobileCropWrapper&&(this._mobileCropWrapper.style.display=t?"":"none"),t&&this._mobileDrawer&&this._mobileDrawer.snapTo("half")}_buildCanvasZoomOverlay(){const a=de.el("div",{className:"canvas-zoom-overlay",role:"group","aria-label":"Zoom controls"}),t=de.createIconButton({icon:de.zoomOut,title:"Zoom Out",className:"canvas-zoom-btn",testId:"btn-zoom-out",ariaLabel:"Zoom out",onClick:()=>{const l=this.state.get("zoom");this.editor.setZoom(l-.25)}}),n=de.el("span",{className:"canvas-zoom-label","aria-live":"polite","aria-atomic":"true",role:"status"},`${Math.round((this.state.get("zoom")??1)*100)}%`),i=de.createIconButton({icon:de.zoomIn,title:"Zoom In",className:"canvas-zoom-btn",testId:"btn-zoom-in",ariaLabel:"Zoom in",onClick:()=>{const l=this.state.get("zoom");this.editor.setZoom(l+.25)}}),r=de.createIconButton({icon:de.expand,title:"Fit to Screen",className:"canvas-zoom-btn",testId:"btn-fit-screen",ariaLabel:"Fit to screen",onClick:()=>this.editor.fitToScreen()});return a.appendChild(t),a.appendChild(n),a.appendChild(i),a.appendChild(r),this._unsubscribers.push(this.state.on("change:zoom",({value:l})=>{n.textContent=`${Math.round(l*100)}%`})),a}destroy(){var a;this._unsubscribers.forEach(t=>t()),this._unsubscribers=[],this._mql&&this._mqlHandler&&(this._mql.removeEventListener?this._mql.removeEventListener("change",this._mqlHandler):this._mql.removeListener&&this._mql.removeListener(this._mqlHandler),this._mql=null,this._mqlHandler=null),this._destroyDesktopShell(),this._destroyMobileShell(),(a=this.root)==null||a.remove(),this.root=null,this.canvasSection=null,this.canvasContainer=null,this.cropOverlay=null}};function qo(o){if(!Number.isFinite(Number(o)))return 0;const a=Number(o)%360;return a<0?a+360:a}function Uh(o,a){const t=qo(o);return(qo(a)-t+540)%360-180}function Oh(){return new Date().toISOString()}function gr(o){return typeof o=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(o)}class zh extends la.EventEmitter{constructor(a,t={}){var r,l,s,d,c;if(super(),!a)throw new Error("VanillaImageEditorV2: container element is required");this._container=a,this._destroyed=!1,this._loadVersion=0,this._objectUrls=new Set,this._activeObjectUrl=null;const n=t.preset?de.getPreset(t.preset):null,i=n?{initialMode:n.initialMode==="crop"?"crop":"adjust",cropShape:n.cropShape,initialAspectRatio:n.aspectRatio}:{};this._options={theme:"auto",initialImage:null,initialMode:"adjust",cropShape:"free",initialAspectRatio:"free",layout:"split-panel",backgroundRemoval:{enabled:!0,endpoint:"/api/v1/media/background-removal/preview",optionsEndpoint:"/api/v1/media/background-removal/options",savedEndpoint:"/api/v1/media/{media}/background-removal",fallbackEndpoint:null},backgroundReplacement:{assetEndpoint:null,materializeEndpoint:null,targetMediaUuid:null,mediaChoices:[]},...i,...t},this._preset=n,this._state=la.createState(),this._state.set("theme",this._options.theme),this._state.set("crop.shape",this._options.cropShape),this._state.set("crop.aspect",this._options.initialAspectRatio),this._preset&&(this._state.set("lockCropShape",!!this._preset.lockCropShape),this._state.set("lockAspectRatio",!!this._preset.lockAspectRatio),this._state.set("showFilters",this._preset.showFilters!==!1),this._state.set("showCropControls",this._preset.showCropControls!==!1),this._state.set("autoZoomOnCropOverflow",!!this._preset.autoZoomOnCropOverflow)),this._renderer=new de.PixiRenderer,this._filterManager=new de.FilterManager(this._state,this._renderer),this._cropManager=new de.CropManager(this._state,this._renderer),this._removeBgManager=null,this._backgroundRemovalAvailable=!1,((r=this._options.backgroundRemoval)==null?void 0:r.enabled)!==!1&&(this._removeBgManager=new de.RemoveBgManager({endpoint:(l=this._options.backgroundRemoval)==null?void 0:l.endpoint,optionsEndpoint:(s=this._options.backgroundRemoval)==null?void 0:s.optionsEndpoint,savedEndpoint:(d=this._options.backgroundRemoval)==null?void 0:d.savedEndpoint,fallbackEndpoint:(c=this._options.backgroundRemoval)==null?void 0:c.fallbackEndpoint})),this._loadingOverlay=null,this._toolbar=null,this._layout=null,this._cropControls=null,this._editorEl=null,this._toolbarContainer=null,this._canvasContainer=null,this._cropOverlay=null,this._fileInput=null,this._mobileSaveBar=null,this._mobileSaveBtn=null,this._mobileSaveUnsub=null,this._resizeObserver=null,this._initPromise=Promise.resolve(this._init()).catch(u=>{this._destroyed||this.emit("error",u instanceof Error?u:new Error(String(u)))})}async _init(){this._state.detectTheme(),this._buildDOM(),!(!await this._renderer.mount(this._canvasContainer,0,{backgroundAlpha:0})||this._destroyed)&&(this._cropManager.setOverlayCanvas(this._cropOverlay),this._initUI(),this._setupResizeObserver(),this._setupWindowResize(),this._subscribeToState(),this._refreshBackgroundRemovalAvailability(),this._options.initialImage&&await this.loadImage(this._options.initialImage),this.emit("ready"))}_buildDOM(){this._container.innerHTML="",this._editorEl=de.el("div",{className:`vanilla-image-editor-v2 ${this._state.get("isDarkMode")?"dark":"light"}`}),this._toolbarContainer=de.el("div",{className:"editor-v2-toolbar"}),this._editorEl.appendChild(this._toolbarContainer),this._layout=new Ph(this._state,this._filterManager,this);const{root:a,canvasContainer:t,cropOverlay:n}=this._layout.build({onFilterToggle:(i,r,l)=>this._handleFilterToggle(i,r,l),onFilterSelect:(i,r)=>this._handleFilterSelect(i,r),onFilterChange:(i,r,l,s)=>this._handleFilterChange(i,r,l,s),onFilterReset:(i,r)=>this._handleFilterReset(i,r),onFilterAction:(i,r,l)=>this._handleFilterAction(i,r,l),onClearAll:i=>this.resetAll(i)});this._canvasContainer=t,this._cropOverlay=n,this._editorEl.appendChild(a),this._buildMobileSaveBar(),this._mobileSaveBar&&this._editorEl.appendChild(this._mobileSaveBar),this._fileInput=de.el("input",{type:"file",accept:"image/*",className:"hidden-file-input",style:{display:"none"},"aria-label":"Choose image file to edit",onChange:i=>this._handleFileSelect(i)}),this._editorEl.appendChild(this._fileInput),this._container.appendChild(this._editorEl)}_initUI(){this._toolbar=new de.Toolbar(this._state,this),this._toolbarContainer.appendChild(this._toolbar.render()),this._cropControls=new de.CropControls(this._state,this._cropManager,this);const a=this._cropControls.render();this._layout.mountCropControls(a)}_setupResizeObserver(){if(!this._canvasContainer)return;let a=null;this._resizeObserver=new ResizeObserver(()=>{clearTimeout(a),a=setTimeout(()=>{var t,n;this._destroyed||!this._canvasContainer||(this._renderer.resizeTo(this._canvasContainer),this._state.get("mode")==="crop"&&((n=(t=this._cropManager).drawOverlay)==null||n.call(t)))},50)}),this._resizeObserver.observe(this._canvasContainer)}_setupWindowResize(){this._handleWindowResize=()=>{},window.addEventListener("resize",this._handleWindowResize)}_subscribeToState(){this._state.on("change:isDarkMode",({value:a})=>{var t,n;(t=this._editorEl)==null||t.classList.toggle("dark",a),(n=this._editorEl)==null||n.classList.toggle("light",!a)})}async _handleFileSelect(a){var n;const t=(n=a.target.files)==null?void 0:n[0];t&&await this.loadImage(t),this._fileInput.value=""}_matchesExpectedFilterLayer(a){if(a===void 0)return!0;if(a===null)return typeof this._state.getActiveFilterLayerId=="function"?this._state.getActiveFilterLayerId()===null:this._state.get("activeLayerId")===null;const t=typeof a=="string"?a.trim():"";return t===""?!1:typeof this._state.getActiveFilterLayerId=="function"?this._state.getActiveFilterLayerId()===t:this._state.get("activeLayerId")===t}_handleFilterToggle(a,t,n=void 0){this._filterManager.toggle(a,t,n)!==!1&&(t?this._state.set("selectedFilter",a):this._state.get("selectedFilter")===a&&this._state.set("selectedFilter",null))}_handleFilterSelect(a,t=void 0){var r;if(!this._matchesExpectedFilterLayer(t))return;const n=this._state.get("activeFilters");if(!((r=n==null?void 0:n.has)!=null&&r.call(n,a))&&this._filterManager.toggle(a,!0,t)===!1)return;this._state.set("selectedFilter",a);const i=this._filterManager.getFilterDef(a);if(typeof(i==null?void 0:i.category)=="string"){const l=de.REGISTRY_TO_UI[i.category]||i.category;this._state.get("selectedCategory")!==l&&this._state.set("selectedCategory",l)}}_handleFilterChange(a,t,n,i=void 0){this._filterManager.updateValue(a,t,n,i)||this._filterManager.applyFilters(),this._renderer.render()}_handleFilterReset(a,t=void 0){var n,i;this._filterManager.resetValues(a,t),(i=(n=this._filterManager)==null?void 0:n.applyFilters)==null||i.call(n)}_handleFilterAction(a,t,n=void 0){this._filterManager.performFilterAction(a,t,n)}_revokeObjectUrl(a){!a||!this._objectUrls.has(a)||(URL.revokeObjectURL(a),this._objectUrls.delete(a),this._activeObjectUrl===a&&(this._activeObjectUrl=null))}_replaceActiveObjectUrl(a){const t=this._activeObjectUrl;this._activeObjectUrl=a,this._objectUrls.add(a),t&&t!==a&&this._revokeObjectUrl(t)}_clearActiveObjectUrl(){this._activeObjectUrl&&this._revokeObjectUrl(this._activeObjectUrl)}async _renderCurrentDocument(){var a,t;return(t=(a=this._renderer).renderLayerDocument)==null?void 0:t.call(a,this._state.getSerializableDocument(),{fallbackImageUrl:this._state.get("imageUrl")??null})}async setBackgroundFill(a){var n;const t=this._state.setBackgroundFill(a);return await this._renderCurrentDocument(),this.emit("background-changed",{layerId:t,fill:((n=this._state.getLayer(t))==null?void 0:n.fill)??null}),t}async setBackgroundColor(a){return this.setBackgroundFill({kind:"color",value:typeof a=="string"&&a.trim()!==""?a:"#ffffff"})}async setBackgroundGradient(a={}){return this.setBackgroundFill({kind:"gradient",gradientType:a.gradientType||"linear",angle:Number.isFinite(Number(a.angle))?Number(a.angle):135,stops:Array.isArray(a.stops)?a.stops:[{offset:0,color:"#111827"},{offset:1,color:"#f59e0b"}],fit:a.fit||"cover"})}async setBackgroundMediaSource(a,t={}){if(!a||typeof a!="object")throw new Error("Background source is required");return this.setBackgroundFill({kind:"media",source:a,fit:t.fit||"cover"})}async setBackgroundImageFromFile(a,t={}){var i,r;if(!(a instanceof Blob))throw new Error("Background image file is required");const n=URL.createObjectURL(a);this._objectUrls.add(n);try{if(((r=(i=this._state).isBackgroundLayerLocked)==null?void 0:r.call(i))===!0)throw new Error("Background layer is locked");const l=this._captureEditorDocumentContext(),s=await this._probeImageDimensions(n);if(!this._isCurrentEditorDocumentContext(l))return URL.revokeObjectURL(n),this._objectUrls.delete(n),null;const d=this._state.ensureBackgroundLayer();if(!d)throw new Error("Background layer is locked");let c=null,u=this._captureEditorDocumentContext(d);if(this._canUploadBackgroundAsset()){if(!await this._materializeBackgroundLayerForUpload(d))return URL.revokeObjectURL(n),this._objectUrls.delete(n),null;if(u=this._captureEditorDocumentContext(d),c=await this._uploadBackgroundAsset(a,d,n),!this._isCurrentEditorDocumentContext(u))return URL.revokeObjectURL(n),this._objectUrls.delete(n),null}return c||(c={kind:"runtime",runtimeRef:`background-${Date.now()}`,originalWidth:s.width,originalHeight:s.height,sourceHash:null,previewUrl:n}),this._isCurrentEditorDocumentContext(u)?this.setBackgroundMediaSource(c,{fit:t.fit||"cover"}):(URL.revokeObjectURL(n),this._objectUrls.delete(n),null)}catch(l){throw URL.revokeObjectURL(n),this._objectUrls.delete(n),l}}async setBackgroundFit(a){if(!this._state.setBackgroundFit(a))return!1;const n=this._backgroundLayerId();await this._renderCurrentDocument();const i=n?this._state.getLayer(n):null;return i&&this.emit("background-changed",{layerId:n,fill:i.fill??null}),!0}async setBackgroundBlur(a){if(!this._state.setBackgroundBlur(a))return!1;const n=this._backgroundLayerId();await this._renderCurrentDocument();const i=n?this._state.getLayer(n):null;return i&&this.emit("background-changed",{layerId:n,effects:i.effects??[]}),!0}_backgroundLayerId(){const a=this._state.getSerializableDocument(),t=Array.isArray(a==null?void 0:a.layers)?a.layers.find(n=>(n==null?void 0:n.type)==="background"||(n==null?void 0:n.role)==="background"):null;return typeof(t==null?void 0:t.id)=="string"?t.id:null}async removeBackgroundLayer(){return this._state.removeBackgroundLayer()?(await this._renderCurrentDocument(),this.emit("background-changed",{layerId:null,fill:null}),!0):!1}async selectLayer(a){var n,i;return this._state.setActiveLayer(a)?((i=(n=this._filterManager)==null?void 0:n.applyFilters)==null||i.call(n),this.emit("layer-changed",{action:"select",layerId:a}),!0):!1}async renameLayer(a,t){var i;return this._state.renameLayer(a,t)?(this.emit("layer-changed",{action:"rename",layerId:a,name:((i=this._state.getLayer(a))==null?void 0:i.name)??null}),!0):!1}async duplicateLayer(a){const t=this._state.duplicateLayer(a);return t?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"duplicate",layerId:a,duplicateLayerId:t}),t):null}async deleteLayer(a){return this._state.deleteLayer(a)?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"delete",layerId:a,activeLayerId:this._state.get("activeLayerId")}),!0):!1}async moveLayer(a,t){return this._state.moveLayer(a,t)?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"move",layerId:a,direction:t}),!0):!1}async setLayerVisibility(a,t){return this._state.setLayerVisibility(a,t)?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"visibility",layerId:a,visible:!!t}),!0):!1}async setLayerLocked(a,t){return this._state.setLayerLocked(a,t)?(this.emit("layer-changed",{action:"lock",layerId:a,locked:!!t}),!0):!1}async addTextLayer(a={}){const t=this._state.addTextLayer(a);return t?(this._state.set("selectedCategory","text"),await this._renderCurrentDocument(),this.emit("layer-changed",{action:"text-add",layerId:t}),t):null}async updateTextLayer(a,t={}){return this._state.updateTextLayer(a,t)?(await this._renderCurrentDocument(),this.emit("layer-changed",{action:"text-update",layerId:a,patch:t}),!0):!1}_canUploadBackgroundAsset(){var r,l;const a=(l=(r=this._options)==null?void 0:r.backgroundReplacement)==null?void 0:l.assetEndpoint,t=this._state.getEditorDocumentBinding(),n=this._state.getSerializableDocument(),i=this._backgroundTargetMediaUuid(n);return typeof a=="string"&&a.trim()!==""&&!!(t!=null&&t.documentId)&&!!n&&typeof i=="string"&&i.trim()!==""}async _materializeBackgroundLayerForUpload(a){return this._materializeCurrentDocument("Background layer materialization failed",a)}_documentMaterializationSignature(a){try{return JSON.stringify(a??null)}catch{return null}}_captureDocumentMaterializationContext(a,t,n=null){return{loadVersion:this._loadVersion,documentId:(t==null?void 0:t.documentId)??null,documentRevisionId:(t==null?void 0:t.documentRevisionId)??null,documentRevisionNumber:(t==null?void 0:t.documentRevisionNumber)??null,documentSignature:this._documentMaterializationSignature(a),requiredLayerId:n}}_captureEditorDocumentContext(a=null){return{loadVersion:this._loadVersion,documentSignature:this._documentMaterializationSignature(this._state.getSerializableDocument()),requiredLayerId:a}}_isCurrentEditorDocumentContext(a){return!(!a||this._destroyed||this._loadVersion!==a.loadVersion||this._documentMaterializationSignature(this._state.getSerializableDocument())!==a.documentSignature||a.requiredLayerId&&!this._state.getLayer(a.requiredLayerId))}_isCurrentDocumentMaterializationContext(a){if(!a||this._destroyed||this._loadVersion!==a.loadVersion)return!1;const t=this._state.getEditorDocumentBinding();if(!t||(t.documentId??null)!==a.documentId||(t.documentRevisionId??null)!==a.documentRevisionId||(t.documentRevisionNumber??null)!==a.documentRevisionNumber)return!1;const n=this._state.getSerializableDocument();return!(this._documentMaterializationSignature(n)!==a.documentSignature||a.requiredLayerId&&!this._state.getLayer(a.requiredLayerId))}async _materializeCurrentDocument(a="Editor document materialization failed",t=null){const n=this._backgroundMaterializeEndpoint(),i=this._state.getEditorDocumentBinding(),r=this._state.getSerializableDocument();if(!n||!(i!=null&&i.documentId)||!r||t!==null&&!t)return!1;const l=this._resolveBackgroundEndpoint(n,r);if(!l)return!1;const s=this._captureDocumentMaterializationContext(r,i,t),d=gr(i.documentId)?i.documentId:null,c=await fetch(l,{method:"POST",credentials:"include",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({document_id:d,base_document_revision:d===null?null:i.documentRevisionNumber,document:r})});let u=null;try{u=await c.json()}catch{u=null}if(!c.ok){const m=(u==null?void 0:u.message)||a;throw new Error(m)}return this._isCurrentDocumentMaterializationContext(s)?(u!=null&&u.document&&this._state.setEditorDocument(u.document,{documentId:u.document_id??i.documentId,documentRevisionId:u.document_revision_id??i.documentRevisionId,documentRevisionNumber:typeof u.document_revision_number=="number"?u.document_revision_number:i.documentRevisionNumber}),!0):!1}async _uploadBackgroundAsset(a,t,n){var f,h,v;const i=(h=(f=this._options)==null?void 0:f.backgroundReplacement)==null?void 0:h.assetEndpoint,r=this._state.getEditorDocumentBinding(),l=this._state.getSerializableDocument();if(!i||!(r!=null&&r.documentId)||!l)return null;const s=this._resolveBackgroundEndpoint(i,l);if(!s)return null;const d=await this._sha256File(a),c=new FormData;c.append("asset_file",a,a instanceof File&&a.name?a.name:"background.png"),c.append("asset_kind","background-upload"),c.append("document_id",r.documentId),c.append("layer_id",t),c.append("client_hash",d);const u=await fetch(s,{method:"POST",credentials:"include",headers:{Accept:"application/json"},body:c});if(!u.ok)throw new Error("Background upload failed");const m=await u.json(),p=(v=m==null?void 0:m.asset)==null?void 0:v.source;if(!p||typeof p!="object")throw new Error("Background upload did not return a usable layer source");return{...p,previewUrl:n}}_backgroundMaterializeEndpoint(){var i,r,l,s,d,c;const a=(r=(i=this._options)==null?void 0:i.backgroundReplacement)==null?void 0:r.materializeEndpoint;if(typeof a=="string"&&a.trim()!=="")return a;const t=(s=(l=this._options)==null?void 0:l.backgroundReplacement)==null?void 0:s.assetEndpoint;if(typeof t=="string"&&t.trim()!=="")return t.replace(/\/editor-assets\/?$/,"/editor-documents/materialize");const n=(c=(d=this._options)==null?void 0:d.backgroundRemoval)==null?void 0:c.savedEndpoint;return typeof n=="string"&&n.trim()!==""?n.replace(/\/background-removal\/?$/,"/editor-documents/materialize"):null}_resolveBackgroundEndpoint(a,t){if(typeof a!="string"||a.trim()==="")return null;const n=this._backgroundTargetMediaUuid(t);return a.includes("{media}")?typeof n!="string"||n.trim()===""?null:a.replace("{media}",encodeURIComponent(n)):a}_backgroundTargetMediaUuid(a){var n,i;const t=(i=(n=this._options)==null?void 0:n.backgroundReplacement)==null?void 0:i.targetMediaUuid;return typeof t=="string"&&t.trim()!==""?t:typeof(a==null?void 0:a.sourceMediaUuid)=="string"&&a.sourceMediaUuid.trim()!==""?a.sourceMediaUuid:null}async _sha256File(a){var i,r,l;const t=await a.arrayBuffer(),n=await((l=(r=(i=globalThis.crypto)==null?void 0:i.subtle)==null?void 0:r.digest)==null?void 0:l.call(r,"SHA-256",t));if(!n)throw new Error("Background upload hashing is unavailable");return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}_probeImageDimensions(a){return new Promise(t=>{const n=new Image;n.onload=()=>t({width:Math.max(1,Math.round(n.naturalWidth||n.width||1)),height:Math.max(1,Math.round(n.naturalHeight||n.height||1))}),n.onerror=()=>t({width:1,height:1}),n.src=a})}setFilterRegistry(a){this._filterManager.setRegistry(a)}async loadImage(a,t={}){var s,d,c,u;if(this._destroyed)return;(d=(s=this._removeBgManager)==null?void 0:s.cancelActiveRequests)==null||d.call(s,"image-load");const n=++this._loadVersion;let i=a,r=null;this._resetEditorState(),this._state.set("hasImage",!1),this._state.set("imageUrl",null),a instanceof Blob&&(i=URL.createObjectURL(a),r=i,this._objectUrls.add(i));const l=await this._renderer.loadTexture(i,{isCurrent:()=>!this._destroyed&&this._loadVersion===n});if(this._destroyed||this._loadVersion!==n){this._revokeObjectUrl(r);return}if(!l){this._revokeObjectUrl(r),this.emit("error",new Error("Failed to load image"));return}r?this._replaceActiveObjectUrl(r):this._clearActiveObjectUrl(),this._state.set("hasImage",!0),this._state.set("imageUrl",i),t.document?await this._hydrateDocument(t.document,{documentId:t.documentId??(gr((c=t.document)==null?void 0:c.id)?t.document.id:null),documentRevisionId:t.documentRevisionId??null,documentRevisionNumber:t.documentRevisionNumber??((u=t.document)==null?void 0:u.revision)??null,fallbackImageUrl:i}):this._initializeDefaultDocument(i),t.state&&this._hydrateState(t.state),this._options.initialMode==="crop"&&this.setMode("crop"),this.emit("imageLoaded",{url:i})}_resetEditorState(){this._filterManager.resetAll(),this._state.set("crop.rect",null),this._state.set("crop.appliedRect",null),this._state.set("crop.appliedShape",null),this._state.set("crop.appliedAspect",null),this._state.set("crop.dirty",!1),this._state.set("crop.shape",this._options.cropShape||"free"),this._state.set("crop.aspect",this._options.initialAspectRatio||"free"),this._state.set("transform.rotation",0),this._state.clearEditorDocument(),this._state.get("mode")==="crop"&&(this._cropManager.disable(),this._state.set("mode","filters"))}_initializeDefaultDocument(a){var c,u,m,p;const t=this._renderer.originalTexture,n=Math.max(1,Math.round((t==null?void 0:t.width)||1)),i=Math.max(1,Math.round((t==null?void 0:t.height)||1)),r=Oh(),l=typeof((u=(c=this._options)==null?void 0:c.backgroundReplacement)==null?void 0:u.targetMediaUuid)=="string"&&this._options.backgroundReplacement.targetMediaUuid.trim()!==""?this._options.backgroundReplacement.targetMediaUuid.trim():null,s=l?{kind:"media",mediaUuid:l,originalWidth:n,originalHeight:i,sourceHash:null}:{kind:"runtime",runtimeRef:"source-image",originalWidth:n,originalHeight:i,sourceHash:null,previewUrl:typeof a=="string"?a:null},d={version:2,id:`client-doc-${Date.now()}`,sourceMediaUuid:l,canvas:{width:n,height:i,backgroundPreviewColor:null},revision:0,layers:[{id:"subject-layer",type:"image",role:"subject",name:"Subject",visible:!0,locked:!1,opacity:1,blendMode:"normal",transform:{x:0,y:0,scaleX:1,scaleY:1,rotation:0},effects:[],metadata:{},source:s,crop:null,filters:[]}],activeLayerId:"subject-layer",export:{mimeType:"image/png",quality:null,preserveTransparency:!0,matteColor:null,trimTransparentBounds:!1},createdAt:r,updatedAt:r};this._state.setEditorDocument(d,{documentId:null,documentRevisionId:null,documentRevisionNumber:0}),(p=(m=this._renderer).renderLayerDocument)==null||p.call(m,d,{fallbackImageUrl:typeof a=="string"?a:null})}async _hydrateDocument(a,t={}){var n,i;!a||a.version!==2||(this._state.setEditorDocument(a,{documentId:t.documentId??(gr(a.id)?a.id:null),documentRevisionId:t.documentRevisionId??null,documentRevisionNumber:t.documentRevisionNumber??a.revision??null}),await((i=(n=this._renderer).renderLayerDocument)==null?void 0:i.call(n,this._state.getSerializableDocument(),{fallbackImageUrl:t.fallbackImageUrl??this._state.get("imageUrl")??null})))}_hydrateState(a){var n;if(!a||a.version!==1)return;const t=qo(((n=a.transform)==null?void 0:n.rotation)??0);if(t!==0&&this._renderer.rotateBy(t)&&this._state.set("transform.rotation",t),a.crop){const i=a.crop.shape||"free",r=a.crop.aspectRatio||"free";a.crop.rect&&(this._cropManager.applyFromPixelRect(a.crop.rect,i),this._state.set("crop.appliedRect",{...a.crop.rect}),this._state.set("crop.appliedShape",i),this._state.set("crop.appliedAspect",r)),this._state.set("crop.shape",i),this._state.set("crop.aspect",r)}if(Array.isArray(a.filters)){let i=null;for(const r of a.filters)if(r.enabled&&(i===null&&(i=r.id),this._state.toggleFilter(r.id,!0),this._filterManager.initializeValues(r.id),r.values))for(const[l,s]of Object.entries(r.values))this._state.setFilterValue(r.id,l,s);if(i!==null){this._state.set("selectedFilter",i);const r=this._filterManager.getFilterDef(i);if(typeof(r==null?void 0:r.category)=="string"){const l=de.REGISTRY_TO_UI[r.category]??r.category;this._state.set("selectedCategory",l)}}this._filterManager.applyFilters()}}openFilePicker(){var a;(a=this._fileInput)==null||a.click()}exportImage(a="png",t=.92,n={}){return!this._state.get("hasImage")||!this._applyPendingCropBeforeExport("VanillaImageEditorV2.exportImage")?null:this._renderer.exportImage(a,t,n.maxEdge??0,n.dontUpscale!==!1,n.maxPixels??0)}async exportBlob(a="png",t=.92,n={}){return!this._state.get("hasImage")||!this._applyPendingCropBeforeExport("VanillaImageEditorV2.exportBlob")?null:this._renderer.exportBlob(a,t,n)}_applyPendingCropBeforeExport(a){return!(this._state.get("crop.rect")&&!this._cropManager.apply())}async save(){if(!this._state.get("hasImage"))return;this._state.set("isSaving",!0);let a=null;try{const t=await this.exportBlob("png",.92);if(!t)throw new Error("Failed to export image");const n=i.createElement("a");a=URL.createObjectURL(t.blob),n.href=a,n.download=`edited-image-${Date.now()}.png`,i.body.appendChild(n),n.click(),i.body.removeChild(n);const i=this.getSerializableDocument(),r=this.getEditorDocumentBinding();this.emit("save",{blob:t.blob,mimeType:t.blob.type||"image/png",dimensions:{width:t.width,height:t.height},state:this.getSerializableState(),document:i,documentId:(r==null?void 0:r.documentId)??(gr(i==null?void 0:i.id)?i.id:null),documentRevisionId:(r==null?void 0:r.documentRevisionId)??null,documentRevisionNumber:(r==null?void 0:r.documentRevisionNumber)??(i==null?void 0:i.revision)??null})}catch(t){this.emit("error",{error:t})}finally{a&&URL.revokeObjectURL(a),this._state.set("isSaving",!1)}}getSerializableState(){const a=this._state.get("activeFilters"),t=[];if(a)for(const l of a){const s=this._state.getFilterValues(l);t.push({id:l,enabled:!0,values:{...s}})}const n=this._state.get("crop.appliedRect"),i=this._state.get("crop.rect"),r=n||i;return{version:1,crop:{rect:r?{...r}:null,aspectRatio:this._state.get("crop.appliedAspect")||this._state.get("crop.aspect")||"free",shape:this._state.get("crop.appliedShape")||this._state.get("crop.shape")||"free"},transform:{rotation:qo(this._state.get("transform.rotation")??0)},filters:t}}getSerializableDocument(){return this._state.getSerializableDocument()}getEditorDocumentBinding(){return this._state.getEditorDocumentBinding()}close(){this.emit("cancel")}setZoom(a){this._renderer.setZoom(a)}fitToScreen(){this._renderer.fitToScreen()}resetAll(a=void 0){this._filterManager.resetAll(a)}rotateBy(a){const t=this._state.get("transform.rotation")??0;return this.setRotationAngle(Number(t)+Number(a))}setRotationAngle(a){if(!this._state.get("hasImage"))return!1;const t=qo(this._state.get("transform.rotation")??0),n=qo(a),i=Uh(t,n),r=this._state.get("mode")==="crop";if(Math.abs(i)>.001){if(r&&this._cropManager.disable(),!this._renderer.rotateBy(i))return r&&this._cropManager.enable(),!1;this._filterManager.applyFilters(),this._state.set("crop.rect",null),this._state.set("crop.dirty",!1),r&&this._cropManager.enable()}return this._state.set("transform.rotation",n),this.emit("transformChanged",{rotation:n}),!0}resetRotation(){return this.setRotationAngle(0)}toggleTheme(){const a=this._state.get("isDarkMode");this._state.set("isDarkMode",!a)}setTheme(a){this._state.set("theme",a),this._state.detectTheme()}setMode(a){a==="crop"?this._cropManager.enable():this._cropManager.disable(),this._state.set("mode",a)}getState(){return this._state.getAll()}async removeBackground(a={}){var t,n,i,r,l,s,d,c,u,m;if(!this._removeBgManager)throw new Error("Background removal is not enabled");if(!this._state.get("hasImage"))throw new Error("No image loaded");if(!this.canRemoveBackground())throw new Error("Background removal is not available for the current editor state");this._state.set("isProcessing",!0),this._showLoadingOverlay("Removing background...");try{const p=this._activeBackgroundRemovalLayer();if(this._hasSavedEditorDocumentBinding()&&p!==null&&this._backgroundMaterializeEndpoint()&&!await this._materializeCurrentDocument("Background removal materialization failed"))return this.emit("background-removal-stale",{operationId:a.operationId??null,targetLayerId:p.id}),{stale:!0};const f=this._buildSavedBackgroundRemovalContext(a);if(f){const g=await this._removeBgManager.removeSavedMediaBackground(f.request);if(!this._isCurrentBackgroundRemovalContext(f,g))return this.emit("background-removal-stale",{operationId:f.request.operationId,targetLayerId:f.request.targetLayerId}),{stale:!0};const I=(t=g==null?void 0:g.result)==null?void 0:t.source;if(!I||I.kind!=="edit-asset")throw new Error("Background removal did not return a persisted layer source");const T=(n=g==null?void 0:g.result)==null?void 0:n.previewDataUrl;return typeof T=="string"&&T.startsWith("data:image/")&&(!await this._renderer.loadTexture(T,{isCurrent:()=>!this._destroyed&&this._isCurrentBackgroundRemovalContext(f,g)})||!this._isCurrentBackgroundRemovalContext(f,g))?(this.emit("background-removal-stale",{operationId:f.request.operationId,targetLayerId:f.request.targetLayerId}),{stale:!0}):this._isCurrentBackgroundRemovalContext(f,g)?(this._state.replaceLayerSource(f.request.targetLayerId,I),await((r=(i=this._renderer).renderLayerDocument)==null?void 0:r.call(i,this._state.getSerializableDocument(),{fallbackImageUrl:this._state.get("imageUrl")??null})),this.emit("background-removed",{model:(l=g==null?void 0:g.result)==null?void 0:l.model,processMs:(s=g==null?void 0:g.result)==null?void 0:s.process_ms,source:I,operationId:f.request.operationId,targetLayerId:f.request.targetLayerId}),{model:(d=g==null?void 0:g.result)==null?void 0:d.model,processMs:(c=g==null?void 0:g.result)==null?void 0:c.process_ms,source:I}):(this.emit("background-removal-stale",{operationId:f.request.operationId,targetLayerId:f.request.targetLayerId}),{stale:!0})}const h=this._buildPreviewBackgroundRemovalInput(a);if(!h)throw new Error("Failed to export image for background removal");const v=this._buildPreviewBackgroundRemovalContext(h.options),y=await this._removeBgManager.preparePreviewRequest(h.imageData,h.options),w=this._resolvePreviewBackgroundRemovalContext(v,y);if(!await this._isCurrentPreviewBackgroundRemovalContext(w))return this.emit("background-removal-stale",{operationId:w.operationId,sourceHash:w.sourceHash,targetLayerId:w.activeLayerId??null}),{stale:!0};const _=await this._removeBgManager.removeBackground(y.blob,y);if(!await this._isCurrentPreviewBackgroundRemovalContext(w,_))return this.emit("background-removal-stale",{operationId:w.operationId,sourceHash:w.sourceHash}),{stale:!0};const b=await this._applyPreviewBackgroundRemovalResult(w,_);return b?(this.emit("background-removed",{model:_.model,processMs:_.processMs,operationId:w.operationId,targetLayerId:w.activeLayerId??null,source:b.source}),{model:_.model,processMs:_.processMs,...b.source?{source:b.source}:{}}):(this.emit("background-removal-stale",{operationId:w.operationId,sourceHash:w.sourceHash,targetLayerId:w.activeLayerId??null}),{stale:!0})}catch(p){throw this.emit("error",{error:p,context:"background-removal"}),p}finally{(m=(u=this._state)==null?void 0:u.set)==null||m.call(u,"isProcessing",!1),this._hideLoadingOverlay()}}async isBackgroundRemovalAvailable(){return this._removeBgManager?this._refreshBackgroundRemovalAvailability():!1}canRemoveBackground(){if(!this._removeBgManager||this._state.get("hasImage")!==!0||this._backgroundRemovalAvailable!==!0)return!1;const a=this._state.getSerializableDocument();return(a==null?void 0:a.version)===2&&Array.isArray(a.layers)?this._activeBackgroundRemovalLayer({requireSourceHash:this._hasSavedEditorDocumentBinding()})!==null:!0}async _refreshBackgroundRemovalAvailability(){if(!this._removeBgManager)return this._backgroundRemovalAvailable=!1,this._state.set("backgroundRemovalAvailable",!1),!1;const a=await this._removeBgManager.isAvailable();return this._destroyed?!1:(this._backgroundRemovalAvailable=a,this._state.set("backgroundRemovalAvailable",a),a)}_hasSavedEditorDocumentBinding(){const a=this._state.getEditorDocumentBinding();return!!(a!=null&&a.documentId)&&!!(a!=null&&a.documentRevisionId)}_activeBackgroundRemovalLayer(a={}){var l;const t=a.requireSourceHash!==!1,n=this._state.get("activeLayerId");if(!n)return null;const i=this._state.getLayer(n);if(!i||i.type!=="image"||i.locked===!0||i.visible===!1)return null;const r=(l=i==null?void 0:i.source)==null?void 0:l.sourceHash;return t&&(typeof r!="string"||!/^[a-f0-9]{64}$/i.test(r))?null:i}_buildSavedBackgroundRemovalContext(a={}){var u,m,p,f,h;const t=this._state.getSerializableDocument(),n=this._state.getEditorDocumentBinding();if(!t||!(n!=null&&n.documentId)||!(n!=null&&n.documentRevisionId))return null;const i=typeof t.sourceMediaUuid=="string"&&t.sourceMediaUuid!==""?t.sourceMediaUuid:null;if(!i)return null;const r=this._activeBackgroundRemovalLayer({requireSourceHash:!0}),l=r==null?void 0:r.id,s=(u=r==null?void 0:r.source)==null?void 0:u.sourceHash;if(!l||typeof s!="string"||!/^[a-f0-9]{64}$/i.test(s))return null;const d=a.operationId||((p=(m=globalThis.crypto)==null?void 0:m.randomUUID)==null?void 0:p.call(m))||`op-${Date.now()}-${Math.random().toString(16).slice(2)}`,c={loadVersion:this._loadVersion,activeLayerId:l,documentRevisionId:n.documentRevisionId,documentSignature:this._documentMaterializationSignature(t),sourceHash:s,request:{targetMediaUuid:i,operationId:d,documentId:n.documentId,documentRevisionId:n.documentRevisionId,targetLayerId:l,expectedSourceHash:s,tier:a.tier||((h=(f=this._options)==null?void 0:f.backgroundRemoval)==null?void 0:h.defaultTier)||"balanced"}};return a.model&&(c.request.model=a.model),a.alpha_matting!==void 0&&(c.request.alpha_matting=a.alpha_matting),a.max_megapixels!==void 0&&(c.request.max_megapixels=a.max_megapixels),c}_buildPreviewBackgroundRemovalContext(a){const t=this._state.getSerializableDocument(),n=(t==null?void 0:t.version)===2&&Array.isArray(t.layers),i=n?this._activeBackgroundRemovalLayer({requireSourceHash:!1}):null;return{loadVersion:this._loadVersion,activeLayerId:n?(i==null?void 0:i.id)??null:null,documentSignature:n?this._documentMaterializationSignature(t):null,imageUrl:this._state.get("imageUrl")??null,operationId:a.operationId,sessionKey:a.sessionKey,sourceHash:a.sourceHash,targetRef:a.targetRef??null}}_resolvePreviewBackgroundRemovalContext(a,t){return{...a,operationId:t.operationId,sessionKey:t.sessionKey,sourceHash:t.sourceHash,targetRef:t.targetRef??a.targetRef??null}}_buildPreviewBackgroundRemovalInput(a={}){const t=this._state.getSerializableDocument();if((t==null?void 0:t.version)===2&&Array.isArray(t.layers)){const i=this._activeBackgroundRemovalLayer({requireSourceHash:!1}),r=this._sourceUrlForLayerSource(i==null?void 0:i.source);return!i||!r?null:{imageData:r,options:{...a,targetRef:i.id}}}const n=this.exportImage("png");return n?{imageData:n,options:a}:null}_sourceUrlForLayerSource(a){if(!a||typeof a!="object")return null;for(const t of["previewUrl","sourceUrl","url"]){const n=a[t];if(typeof n=="string"&&n.trim()!=="")return n}return null}async _applyPreviewBackgroundRemovalResult(a,t){var r,l;if(a.documentSignature===null||!a.activeLayerId)return await this.loadImage(t.dataUrl),{source:null};const n=await this._probeImageDimensions(t.dataUrl);if(!await this._isCurrentPreviewBackgroundRemovalContext(a,t))return null;const i={kind:"runtime",runtimeRef:`background-removal-${a.operationId||Date.now()}`,originalWidth:n.width,originalHeight:n.height,sourceHash:null,previewUrl:t.dataUrl};return this._state.replaceLayerSource(a.activeLayerId,i)?(await((l=(r=this._renderer).renderLayerDocument)==null?void 0:l.call(r,this._state.getSerializableDocument(),{fallbackImageUrl:this._state.get("imageUrl")??null})),{source:i}):null}async _isCurrentPreviewBackgroundRemovalContext(a,t=null){if(this._destroyed||this._loadVersion!==a.loadVersion||this._state.get("hasImage")!==!0||(this._state.get("imageUrl")??null)!==a.imageUrl)return!1;if(t){if(t.operationId&&t.operationId!==a.operationId||t.sessionKey&&t.sessionKey!==a.sessionKey||t.sourceHash&&t.sourceHash!==a.sourceHash)return!1;if(a.documentSignature!==null){if(!a.targetRef||a.targetRef!==a.activeLayerId||t.targetRef!==a.targetRef)return!1}else if(t.targetRef&&a.targetRef&&t.targetRef!==a.targetRef)return!1}if(a.documentSignature!==null){const i=this._state.getSerializableDocument();if(this._documentMaterializationSignature(i)!==a.documentSignature)return!1;const r=this._activeBackgroundRemovalLayer({requireSourceHash:!1});return!(!r||r.id!==a.activeLayerId)}const n=this.exportImage("png");return n?await this._removeBgManager.computeImageDataHash(n)===a.sourceHash:!1}_isCurrentBackgroundRemovalContext(a,t=null){var l;if(this._destroyed||this._loadVersion!==a.loadVersion)return!1;const n=this._state.getEditorDocumentBinding();if(!n||n.documentRevisionId!==a.documentRevisionId)return!1;const i=this._state.getSerializableDocument();if(this._documentMaterializationSignature(i)!==a.documentSignature||this._state.get("activeLayerId")!==a.activeLayerId)return!1;const r=this._state.getLayer(a.request.targetLayerId);return!(!r||((l=r==null?void 0:r.source)==null?void 0:l.sourceHash)!==a.sourceHash||r.locked===!0||r.visible===!1||t&&(t.operation_id&&t.operation_id!==a.request.operationId||t.target_layer_id&&t.target_layer_id!==a.request.targetLayerId||t.document_revision_id&&t.document_revision_id!==a.request.documentRevisionId||t.source_hash&&t.source_hash!==a.request.expectedSourceHash))}_showLoadingOverlay(a){var n;if(!this._loadingOverlay)this._loadingOverlay=de.el("div",{className:"editor-loading-overlay"},de.el("div",{className:"editor-loading-spinner"}),de.el("div",{className:"editor-loading-text"},a));else{const i=this._loadingOverlay.querySelector(".editor-loading-text");i&&(i.textContent=a)}const t=(n=this._canvasContainer)==null?void 0:n.parentElement;t&&!this._loadingOverlay.parentElement&&t.appendChild(this._loadingOverlay)}_hideLoadingOverlay(){var a;(a=this._loadingOverlay)==null||a.remove()}_buildMobileSaveBar(){var l,s;this._mobileSaveBar=de.el("div",{className:"editor-v2-mobile-save-bar",role:"region","aria-label":"Save bar"}),this._mobileSaveBtn=de.el("button",{type:"button",className:"mobile-save-btn",title:"Save Image","aria-label":"Save image",dataset:{testid:"btn-save-edit-mobile"},onClick:()=>this.save()});const a=de.el("span",{className:"mobile-save-icon"});a.innerHTML=de.save;const t=a.querySelector("svg");t&&t.setAttribute("aria-hidden","true"),this._mobileSaveBtn.appendChild(a),this._mobileSaveBtn.appendChild(de.el("span",{className:"mobile-save-label"},"Save")),this._mobileSaveBar.appendChild(this._mobileSaveBtn);const n=()=>{var m,p;if(!this._mobileSaveBtn)return;const d=((m=this._state)==null?void 0:m.get("hasImage"))===!0,c=((p=this._state)==null?void 0:p.get("isProcessing"))===!0,u=!d||c;this._mobileSaveBtn.disabled=u,this._mobileSaveBtn.setAttribute("aria-disabled",u?"true":"false")};n();const i=(l=this._state)==null?void 0:l.on("change:hasImage",n),r=(s=this._state)==null?void 0:s.on("change:isProcessing",n);this._mobileSaveUnsub=()=>{try{i==null||i()}catch{}try{r==null||r()}catch{}}}destroy(){var a,t,n,i,r,l,s,d;this._destroyed=!0,(t=(a=this._removeBgManager)==null?void 0:a.cancelActiveRequests)==null||t.call(a,"editor-destroy");for(const c of this._objectUrls)try{URL.revokeObjectURL(c)}catch{}this._objectUrls.clear(),this._activeObjectUrl=null,(n=this._resizeObserver)==null||n.disconnect(),this._renderer.destroy(),this._cropManager.disable(),this._handleWindowResize&&window.removeEventListener("resize",this._handleWindowResize),(i=this._toolbar)==null||i.destroy(),(r=this._cropControls)==null||r.destroy(),(l=this._layout)==null||l.destroy(),(s=this._mobileSaveUnsub)==null||s.call(this),this._mobileSaveUnsub=null,this._mobileSaveBtn=null,this._mobileSaveBar=null,(d=this._editorEl)==null||d.remove(),this._container=null,this._state=null,this.emit("destroyed"),this.removeAllListeners()}}function jh(o,a){try{let t=la.getFilter(o);if(t||(la.registerCorePixiFilters(),t=la.getFilter(o)),!t){try{const r=la.getAllFilters()}catch{}return null}const n={...t.defaultParams,...a};return t.createFilter(n)}catch{return null}}const Wh=78e5,Hh=e.defineComponent({__name:"ImageEditor",props:{initialImage:{},initialState:{default:null},initialDocument:{default:null},initialDocumentId:{default:null},initialDocumentRevisionId:{default:null},initialDocumentRevisionNumber:{default:null},sessionKey:{default:0},theme:{default:"auto"},cropShape:{default:"square"},preset:{},editorVersion:{default:"v2"},backgroundRemoval:{default:null},backgroundReplacement:{default:null},primaryColor:{default:"#3880ff"},secondaryColor:{default:"#5260ff"},saveButtonColor:{default:"#3880ff"},downloadButtonColor:{default:"#2dd36f"}},emits:["save","cancel","error"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null);let r=null,l=null;function s(v){return typeof v=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v)}function d(){const v={state:t.initialState??null,sessionKey:t.sessionKey};return t.initialDocument&&(v.document=t.initialDocument,v.documentId=t.initialDocumentId,v.documentRevisionId=t.initialDocumentRevisionId,v.documentRevisionNumber=t.initialDocumentRevisionNumber),v}async function c(){var v,y,w;try{if(!r){n("error",new Error("Editor not initialized"));return}const _=await((v=r.exportBlob)==null?void 0:v.call(r,"png",.92,{maxPixels:Wh}));if(!_){n("error",new Error("Failed to export image — the image could not be processed"));return}const b=r.getSerializableState(),g={blob:_.blob,mimeType:_.blob.type||"image/png",dimensions:{width:_.width,height:_.height},state:b},I=((y=r.getSerializableDocument)==null?void 0:y.call(r))??null;if(I){const T=((w=r.getEditorDocumentBinding)==null?void 0:w.call(r))??null;g.document=I,g.documentId=(T==null?void 0:T.documentId)??(s(I.id)?I.id:null),g.documentRevisionId=(T==null?void 0:T.documentRevisionId)??null,g.documentRevisionNumber=(T==null?void 0:T.documentRevisionNumber)??I.revision??null}n("save",g)}catch(_){n("error",_ instanceof Error?_:new Error("Failed to export image"))}}function u(){n("cancel")}function m(v){if(v instanceof Error)return v;if(v!==null&&typeof v=="object"&&"error"in v){const y=v.error;if(y instanceof Error)return y;if(typeof y=="string"&&y.trim()!=="")return new Error(y)}return typeof v=="string"&&v.trim()!==""?new Error(v):new Error("Failed to load image")}function p(v){n("error",m(v))}function f(){if(!i.value||r)return;window.PIXI=na,la.initializeFilterRegistry();const v={theme:t.theme};t.backgroundRemoval&&(v.backgroundRemoval=t.backgroundRemoval),t.backgroundReplacement&&(v.backgroundReplacement=t.backgroundReplacement),t.preset&&(v.preset=t.preset),t.preset?t.cropShape==="circle"&&(v.cropShape="circle",v.initialAspectRatio="1:1",v.initialMode="crop"):(v.cropShape=t.cropShape==="circle"?"circle":"free",v.initialAspectRatio=t.cropShape==="circle"?"1:1":"free",v.initialMode=t.cropShape==="circle"?"crop":"adjust");const y=t.editorVersion==="v2"?zh:de.VanillaImageEditor,w=new y(i.value,v);r=w,w.setFilterRegistry({getAllFilters:la.getAllFilters,getFilter:la.getFilter,getFiltersByCategory:la.getFiltersByCategory}),w.save=function(){c()},w.on("cancel",u),w.on("error",p),t.initialImage&&w.loadImage(t.initialImage,d())}e.onMounted(()=>{i.value&&(i.value.clientWidth>0?f():(l=new ResizeObserver(v=>{const y=v[0];y&&y.contentRect.width>0&&!r&&(f(),l==null||l.disconnect(),l=null)}),l.observe(i.value)))});const h=()=>{!r||!t.initialImage||r.loadImage(t.initialImage,d())};return e.watch(()=>t.initialImage,(v,y)=>{!r||!v||v===y||h()}),e.watch(()=>t.sessionKey,(v,y)=>{v!==y&&h()}),e.watch(()=>t.initialState,(v,y)=>{v!==y&&h()}),e.watch(()=>[t.initialDocument,t.initialDocumentId,t.initialDocumentRevisionId,t.initialDocumentRevisionNumber],(v,y)=>{v!==y&&h()}),e.onUnmounted(()=>{l==null||l.disconnect(),l=null,r&&(r.destroy(),r=null)}),(v,y)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"containerRef",ref:i,class:"vanilla-editor-wrapper","data-testid":"vanilla-image-editor"},null,512))}}),Ae=(o,a)=>{const t=o.__vccOpts||o;for(const[n,i]of a)t[n]=i;return t},hm=Ae(Hh,[["__scopeId","data-v-8ab74f83"]]),Zh={class:"editor-modal-panel"},Gh={class:"editor-fill"},Xh=e.defineComponent({__name:"ImageEditorModal",props:{modelValue:{type:Boolean,default:!1},initialImage:{},initialState:{default:null},initialDocument:{default:null},initialDocumentId:{default:null},initialDocumentRevisionId:{default:null},initialDocumentRevisionNumber:{default:null},sessionKey:{default:0},acceptedFormats:{default:"image/jpeg,image/png,image/webp,image/gif"},maxFileSize:{default:10},theme:{default:"auto"},cropShape:{default:"square"},preset:{},editorVersion:{default:"v2"},backgroundRemoval:{default:null},backgroundReplacement:{default:null},primaryColor:{default:"#3880ff"},secondaryColor:{default:"#5260ff"},saveButtonColor:{default:"#3880ff"},downloadButtonColor:{default:"#2dd36f"},saveHandler:{}},emits:["update:modelValue","save","cancel","error"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null),r=e.ref(t.modelValue),l=e.ref(!1),s=e.ref(null),d=v=>{n("error",v)},c=()=>{e.nextTick(()=>{if(i.value){const v=i.value.querySelector("button:not([disabled]), [href], input:not([disabled])");v&&v.focus()}})};e.watch(()=>t.modelValue,v=>{r.value=v,v&&(s.value=document.activeElement,c())},{immediate:!0});const u=async v=>{try{if(l.value=!0,t.saveHandler){await t.saveHandler(v);return}n("save",v)}catch(y){d(y instanceof Error?y:new Error("Failed to save image"))}finally{l.value=!1}},m=()=>{n("cancel"),f()},p=()=>{l.value||f()},f=()=>{r.value=!1,n("update:modelValue",!1),s.value&&s.value instanceof HTMLElement&&(s.value.focus(),s.value=null)},h=v=>{if(v.key==="Escape"&&r.value&&!l.value){f();return}if(v.key==="Tab"&&r.value&&i.value){const y=i.value.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])');if(y.length===0)return;const w=y[0],_=y[y.length-1];v.shiftKey&&document.activeElement===w?(v.preventDefault(),_.focus()):!v.shiftKey&&document.activeElement===_&&(v.preventDefault(),w.focus())}};return e.onMounted(()=>{document.addEventListener("keydown",h)}),e.onBeforeUnmount(()=>{document.removeEventListener("keydown",h)}),(v,y)=>(e.openBlock(),e.createBlock(e.Teleport,{to:"body"},[r.value?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"overlayRef",ref:i,role:"dialog","aria-modal":"true","aria-label":"Image editor",class:"editor-modal-overlay","data-testid":"image-editor-modal",onKeydown:e.withKeys(p,["escape"])},[e.createElementVNode("div",{class:"editor-modal-backdrop",onClick:p}),e.createElementVNode("div",Zh,[e.createElementVNode("div",Gh,[e.createVNode(hm,{"initial-image":v.initialImage,"initial-state":v.initialState,"initial-document":v.initialDocument,"initial-document-id":v.initialDocumentId,"initial-document-revision-id":v.initialDocumentRevisionId,"initial-document-revision-number":v.initialDocumentRevisionNumber,"session-key":v.sessionKey,theme:v.theme,"crop-shape":v.cropShape,preset:v.preset,"editor-version":v.editorVersion,"background-removal":v.backgroundRemoval,"background-replacement":v.backgroundReplacement,"primary-color":v.primaryColor,"secondary-color":v.secondaryColor,"save-button-color":v.saveButtonColor,"download-button-color":v.downloadButtonColor,onSave:u,onCancel:m,onError:d},null,8,["initial-image","initial-state","initial-document","initial-document-id","initial-document-revision-id","initial-document-revision-number","session-key","theme","crop-shape","preset","editor-version","background-removal","background-replacement","primary-color","secondary-color","save-button-color","download-button-color"])])])],544)):e.createCommentVNode("",!0)]))}}),vm=Ae(Xh,[["__scopeId","data-v-bd4e671f"]]),Kh={class:"media-workspace"},qh={class:"media-workspace-toolbar"},Jh={class:"media-workspace-label"},Yh=["value"],Qh={class:"media-workspace-grid"},ev=["onClick"],tv=e.defineComponent({__name:"MediaWorkspace",props:{apiScope:{},subScopes:{},initialScopeId:{}},emits:["scope-change","update:media","upload","preview"],setup(o,{emit:a}){var m;const t=o,n=a,i=ja(),r=e.ref(t.initialScopeId??((m=t.subScopes[0])==null?void 0:m.id)??""),l=e.computed(()=>t.subScopes),s=e.computed(()=>l.value.find(p=>p.id===r.value));let d=null;function c(){d&&(d(),d=null),t.apiScope&&(d=lm({apiScope:t.apiScope,isAdmin:t.apiScope==="admin"}))}async function u(){var f;const p={};(f=s.value)!=null&&f.collection&&(p.collection=s.value.collection),await i.fetchMedia(1,p),n("update:media",[...i.items])}return e.watch(()=>t.initialScopeId,p=>{p&&p!==r.value&&(r.value=p)}),e.watch(()=>t.subScopes,p=>{if(p.length===0){r.value="";return}p.some(f=>f.id===r.value)||(r.value=p[0].id)},{deep:!0}),e.watch(()=>t.apiScope,()=>{c(),u()}),e.watch(r,p=>{p&&(n("scope-change",p),u())}),e.onMounted(()=>{c(),u()}),e.onUnmounted(()=>{d&&(d(),d=null)}),(p,f)=>(e.openBlock(),e.createElementBlock("div",Kh,[e.createElementVNode("div",qh,[e.createElementVNode("label",Jh,[f[2]||(f[2]=e.createElementVNode("span",{class:"media-workspace-label-text"},"Scope",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":f[0]||(f[0]=h=>r.value=h),"data-testid":"scope-select",class:"media-workspace-select"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(l.value,h=>(e.openBlock(),e.createElementBlock("option",{key:h.id,value:h.id},e.toDisplayString(h.label),9,Yh))),128))],512),[[e.vModelSelect,r.value]])]),e.createElementVNode("button",{type:"button",class:"media-workspace-upload","data-testid":"upload-button",onClick:f[1]||(f[1]=h=>n("upload"))}," Upload ")]),e.createElementVNode("div",Qh,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(i).items,h=>(e.openBlock(),e.createElementBlock("button",{key:h.uuid,type:"button",class:"media-workspace-item","data-testid":"media-item",onClick:v=>n("preview",h)},e.toDisplayString(h.file_name),9,ev))),128))])]))}}),av=Ae(tv,[["__scopeId","data-v-895f26fe"]]),nv={class:"managed-media-gallery"},ov={class:"gallery-grid"},iv=e.defineComponent({__name:"ManagedMediaGallery",props:{media:{},selectable:{type:Boolean},multiple:{type:Boolean}},emits:["select","remove"],setup(o){return(a,t)=>(e.openBlock(),e.createElementBlock("div",nv,[e.createElementVNode("div",ov,[e.renderSlot(a.$slots,"default",{},void 0,!0)])]))}}),rv=Ae(iv,[["__scopeId","data-v-10a9b8c5"]]),Fr="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M448 256c0-106-86-192-192-192S64 150 64 256s86 192 192 192 192-86 192-192z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M256 176v160M336 256H176' class='ionicon-fill-none ionicon-stroke-width'/></svg>",md="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M256 112v288M400 256H112' class='ionicon-fill-none ionicon-stroke-width'/></svg>",lv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M256 48C141.31 48 48 141.31 48 256s93.31 208 208 208 208-93.31 208-208S370.69 48 256 48zm0 319.91a20 20 0 1120-20 20 20 0 01-20 20zm21.72-201.15l-5.74 122a16 16 0 01-32 0l-5.74-121.94v-.05a21.74 21.74 0 1143.44 0z'/></svg>",pd="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M448 256c0-106-86-192-192-192S64 150 64 256s86 192 192 192 192-86 192-192z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path d='M250.26 166.05L256 288l5.73-121.95a5.74 5.74 0 00-5.79-6h0a5.74 5.74 0 00-5.68 6z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path d='M256 367.91a20 20 0 1120-20 20 20 0 01-20 20z'/></svg>",sv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='48' d='M244 400L100 256l144-144M120 256h292' class='ionicon-fill-none'/></svg>",dv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='48' d='M268 112l144 144-144 144M392 256H100' class='ionicon-fill-none'/></svg>",bc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M448 256L272 88v96C103.57 184 64 304.77 64 424c48.61-62.24 91.6-96 208-96v96z' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",yc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M240 424v-96c116.4 0 159.39 33.76 208 96 0-119.23-39.57-240-208-240V88L64 256z' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Bi="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M452.37 59.63h0a40.49 40.49 0 00-57.26 0L184 294.74c23.08 4.7 46.12 27.29 49.26 49.26l219.11-227.11a40.49 40.49 0 000-57.26zM138 336c-29.88 0-54 24.5-54 54.86 0 23.95-20.88 36.57-36 36.57C64.56 449.74 92.82 464 120 464c39.78 0 72-32.73 72-73.14 0-30.36-24.12-54.86-54-54.86z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",cv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M350.54 148.68l-26.62-42.06C318.31 100.08 310.62 96 302 96h-92c-8.62 0-16.31 4.08-21.92 10.62l-26.62 42.06C155.85 155.23 148.62 160 140 160H80a32 32 0 00-32 32v192a32 32 0 0032 32h352a32 32 0 0032-32V192a32 32 0 00-32-32h-59c-8.65 0-16.85-4.77-22.46-11.32z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='256' cy='272' r='80' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M124 158v-22h-24v22' class='ionicon-fill-none ionicon-stroke-width'/></svg>",gm="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M256 48C141.31 48 48 141.31 48 256s93.31 208 208 208 208-93.31 208-208S370.69 48 256 48zm108.25 138.29l-134.4 160a16 16 0 01-12 5.71h-.27a16 16 0 01-11.89-5.3l-57.6-64a16 16 0 1123.78-21.4l45.29 50.32 122.59-145.91a16 16 0 0124.5 20.58z'/></svg>",bm="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M416 128L192 384l-96-96' class='ionicon-fill-none ionicon-stroke-width'/></svg>",wc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='48' d='M328 112L184 256l144 144' class='ionicon-fill-none'/></svg>",uv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='48' d='M112 184l144 144 144-144' class='ionicon-fill-none'/></svg>",mv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='48' d='M184 112l144 144-144 144' class='ionicon-fill-none'/></svg>",kc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='48' d='M184 112l144 144-144 144' class='ionicon-fill-none'/></svg>",$o="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M368 368L144 144M368 144L144 368' class='ionicon-fill-none ionicon-stroke-width'/></svg>",_c="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M320 367.79h76c55 0 100-29.21 100-83.6s-53-81.47-96-83.6c-8.89-85.06-71-136.8-144-136.8-69 0-113.44 45.79-128 91.2-60 5.7-112 43.88-112 106.4s54 106.4 120 106.4h56' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M320 255.79l-64-64-64 64M256 448.21V207.79' class='ionicon-fill-none ionicon-stroke-width'/></svg>",pv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><circle cx='256' cy='184' r='120' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='344' cy='328' r='120' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='168' cy='328' r='120' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",to="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M430.11 347.9c-6.6-6.1-16.3-7.6-24.6-9-11.5-1.9-15.9-4-22.6-10-14.3-12.7-14.3-31.1 0-43.8l30.3-26.9c46.4-41 46.4-108.2 0-149.2-34.2-30.1-80.1-45-127.8-45-55.7 0-113.9 20.3-158.8 60.1-83.5 73.8-83.5 194.7 0 268.5 41.5 36.7 97.5 55 152.9 55.4h1.7c55.4 0 110-17.9 148.8-52.4 14.4-12.7 11.99-36.6.1-47.7z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='144' cy='208' r='32'/><circle cx='152' cy='311' r='32'/><circle cx='224' cy='144' r='32'/><circle cx='256' cy='367' r='48'/><circle cx='328' cy='144' r='32'/></svg>",fv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M304 416V304h112M314.2 314.23L432 432M208 96v112H96M197.8 197.77L80 80M416 208H304V96M314.23 197.8L432 80M96 304h112v112M197.77 314.2L80 432' class='ionicon-fill-none ionicon-stroke-width'/></svg>",ki="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><circle cx='256' cy='256' r='208' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path d='M256 464c-114.88 0-208-93.12-208-208S141.12 48 256 48z'/></svg>",Ss="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><rect x='128' y='128' width='336' height='336' rx='57' ry='57' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path d='M383.5 128l.5-24a56.16 56.16 0 00-56-56H112a64.19 64.19 0 00-64 64v216a56.16 56.16 0 0056 56h24' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",hv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M384 224v184a40 40 0 01-40 40H104a40 40 0 01-40-40V168a40 40 0 0140-40h167.48' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path d='M459.94 53.25a16.06 16.06 0 00-23.22-.56L424.35 65a8 8 0 000 11.31l11.34 11.32a8 8 0 0011.34 0l12.06-12c6.1-6.09 6.67-16.01.85-22.38zM399.34 90L218.82 270.2a9 9 0 00-2.31 3.93L208.16 299a3.91 3.91 0 004.86 4.86l24.85-8.35a9 9 0 003.93-2.31L422 112.66a9 9 0 000-12.66l-9.95-10a9 9 0 00-12.71 0z'/></svg>",Ec="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M144 48v272a48 48 0 0048 48h272' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path d='M368 304V192a48 48 0 00-48-48H208M368 368v96M144 144H48' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Gr="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><circle cx='104' cy='152' r='56' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='104' cy='360' r='56' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path d='M157 175l-11 15 37 15s3.46-6.42 7-10z' stroke-linecap='square' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path d='M154.17 334.43L460 162c-2.5-6.7-28-12-64-4-29.12 6.47-121.16 29.05-159.16 56.05C205.85 236.06 227 272 192 298c-25.61 19-44.43 22.82-44.43 22.82zM344.47 278.24L295 306.67c14.23 6.74 65.54 33.27 117 36.33 14.92.89 30 .39 39-6z' stroke-linecap='round' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='256' cy='240' r='32' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",ni="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M336 176h40a40 40 0 0140 40v208a40 40 0 01-40 40H136a40 40 0 01-40-40V216a40 40 0 0140-40h40' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M176 272l80 80 80-80M256 48v288' class='ionicon-fill-none ionicon-stroke-width'/></svg>",vv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><circle cx='256' cy='256' r='32' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='416' cy='256' r='32' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='96' cy='256' r='32' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",gv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M432 320v112H320M421.8 421.77L304 304M80 192V80h112M90.2 90.23L208 208M320 80h112v112M421.77 90.2L304 208M192 432H80V320M90.23 421.8L208 304' class='ionicon-fill-none ionicon-stroke-width'/></svg>",bv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M432 320v112H320M421.8 421.77L304 304M80 192V80h112M90.2 90.23L208 208M320 80h112v112M421.77 90.2L304 208M192 432H80V320M90.23 421.8L208 304' class='ionicon-fill-none ionicon-stroke-width'/></svg>",yv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M432 448a15.92 15.92 0 01-11.31-4.69l-352-352a16 16 0 0122.62-22.62l352 352A16 16 0 01432 448zM255.66 384c-41.49 0-81.5-12.28-118.92-36.5-34.07-22-64.74-53.51-88.7-91v-.08c19.94-28.57 41.78-52.73 65.24-72.21a2 2 0 00.14-2.94L93.5 161.38a2 2 0 00-2.71-.12c-24.92 21-48.05 46.76-69.08 76.92a31.92 31.92 0 00-.64 35.54c26.41 41.33 60.4 76.14 98.28 100.65C162 402 207.9 416 255.66 416a239.13 239.13 0 0075.8-12.58 2 2 0 00.77-3.31l-21.58-21.58a4 4 0 00-3.83-1 204.8 204.8 0 01-51.16 6.47zM490.84 238.6c-26.46-40.92-60.79-75.68-99.27-100.53C349 110.55 302 96 255.66 96a227.34 227.34 0 00-74.89 12.83 2 2 0 00-.75 3.31l21.55 21.55a4 4 0 003.88 1 192.82 192.82 0 0150.21-6.69c40.69 0 80.58 12.43 118.55 37 34.71 22.4 65.74 53.88 89.76 91a.13.13 0 010 .16 310.72 310.72 0 01-64.12 72.73 2 2 0 00-.15 2.95l19.9 19.89a2 2 0 002.7.13 343.49 343.49 0 0068.64-78.48 32.2 32.2 0 00-.1-34.78z'/><path d='M256 160a95.88 95.88 0 00-21.37 2.4 2 2 0 00-1 3.38l112.59 112.56a2 2 0 003.38-1A96 96 0 00256 160zM165.78 233.66a2 2 0 00-3.38 1 96 96 0 00115 115 2 2 0 001-3.38z'/></svg>",Mi="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M255.66 112c-77.94 0-157.89 45.11-220.83 135.33a16 16 0 00-.27 17.77C82.92 340.8 161.8 400 255.66 400c92.84 0 173.34-59.38 221.79-135.25a16.14 16.14 0 000-17.47C428.89 172.28 347.8 112 255.66 112z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='256' cy='256' r='80' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Sc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M80 464V68.14a8 8 0 014-6.9C91.81 56.66 112.92 48 160 48c64 0 145 48 192 48a199.53 199.53 0 0077.23-15.77 2 2 0 012.77 1.85v219.36a4 4 0 01-2.39 3.65C421.37 308.7 392.33 320 352 320c-48 0-128-32-192-32s-80 16-80 16' stroke-linecap='round' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",es="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M315.27 33L96 304h128l-31.51 173.23a2.36 2.36 0 002.33 2.77h0a2.36 2.36 0 001.89-.95L416 208H288l31.66-173.25a2.45 2.45 0 00-2.44-2.75h0a2.42 2.42 0 00-1.95 1z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",wv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M496 152a56 56 0 00-56-56H220.11a23.89 23.89 0 01-13.31-4L179 73.41A55.77 55.77 0 00147.89 64H72a56 56 0 00-56 56v48a8 8 0 008 8h464a8 8 0 008-8zM16 392a56 56 0 0056 56h368a56 56 0 0056-56V216a8 8 0 00-8-8H24a8 8 0 00-8 8z'/></svg>",kv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><circle cx='129' cy='96' r='48' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='129' cy='416' r='48' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M129 144v224' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='385' cy='288' r='48' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path d='M129 144c0 96 112 144 208 144' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",ts="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M432 112V96a48.14 48.14 0 00-48-48H64a48.14 48.14 0 00-48 48v256a48.14 48.14 0 0048 48h16' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><rect x='96' y='128' width='400' height='336' rx='45.99' ry='45.99' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><ellipse cx='372.92' cy='219.64' rx='30.77' ry='30.55' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path d='M342.15 372.17L255 285.78a30.93 30.93 0 00-42.18-1.21L96 387.64M265.23 464l118.59-117.73a31 31 0 0141.46-1.87L496 402.91' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",_v="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M248 64C146.39 64 64 146.39 64 248s82.39 184 184 184 184-82.39 184-184S349.61 64 248 64z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M220 220h32v116' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-miterlimit='10' d='M208 340h88' class='ionicon-fill-none ionicon-stroke-width'/><path d='M248 130a26 26 0 1026 26 26 26 0 00-26-26z'/></svg>",Ev="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M368 128h80M64 128h240M368 384h80M64 384h240M208 256h240M64 256h80' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='336' cy='128' r='32' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='176' cy='256' r='32' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='336' cy='384' r='32' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Sv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M208 432h-48a16 16 0 01-16-16V96a16 16 0 0116-16h48a16 16 0 0116 16v320a16 16 0 01-16 16zM352 432h-48a16 16 0 01-16-16V96a16 16 0 0116-16h48a16 16 0 0116 16v320a16 16 0 01-16 16z'/></svg>",Cv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M256 48C141.31 48 48 141.31 48 256s93.31 208 208 208 208-93.31 208-208S370.69 48 256 48zm-32 272a16 16 0 01-32 0V192a16 16 0 0132 0zm96 0a16 16 0 01-32 0V192a16 16 0 0132 0z'/></svg>",ym="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M448 256c0-106-86-192-192-192S64 150 64 256s86 192 192 192 192-86 192-192z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-miterlimit='10' d='M208 192v128M304 192v128' class='ionicon-fill-none ionicon-stroke-width'/></svg>",fd="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M176 96h16v320h-16zM320 96h16v320h-16z' class='ionicon-fill-none ionicon-stroke-width'/></svg>",xv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M133 440a35.37 35.37 0 01-17.5-4.67c-12-6.8-19.46-20-19.46-34.33V111c0-14.37 7.46-27.53 19.46-34.33a35.13 35.13 0 0135.77.45l247.85 148.36a36 36 0 010 61l-247.89 148.4A35.5 35.5 0 01133 440z'/></svg>",Nv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M30.71 229.47l188.87-113a30.54 30.54 0 0131.09-.39 33.74 33.74 0 0116.76 29.47v79.05l180.72-108.16a30.54 30.54 0 0131.09-.39A33.74 33.74 0 01496 145.52v221A33.73 33.73 0 01479.24 396a30.54 30.54 0 01-31.09-.39L267.43 287.4v79.08A33.73 33.73 0 01250.67 396a30.54 30.54 0 01-31.09-.39l-188.87-113a31.27 31.27 0 010-53z'/></svg>",Vv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M480 145.52v221c0 13.28-13 21.72-23.63 15.35L267.5 268.8c-9.24-5.53-9.24-20.07 0-25.6l188.87-113C467 123.8 480 132.24 480 145.52zM251.43 145.52v221c0 13.28-13 21.72-23.63 15.35L38.93 268.8c-9.24-5.53-9.24-20.07 0-25.6l188.87-113c10.64-6.4 23.63 2.04 23.63 15.32z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Tv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M256 48C141.31 48 48 141.31 48 256s93.31 208 208 208 208-93.31 208-208S370.69 48 256 48zm74.77 217.3l-114.45 69.14a10.78 10.78 0 01-16.32-9.31V186.87a10.78 10.78 0 0116.32-9.31l114.45 69.14a10.89 10.89 0 010 18.6z'/></svg>",wm="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M448 256c0-106-86-192-192-192S64 150 64 256s86 192 192 192 192-86 192-192z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path d='M216.32 334.44l114.45-69.14a10.89 10.89 0 000-18.6l-114.45-69.14a10.78 10.78 0 00-16.32 9.31v138.26a10.78 10.78 0 0016.32 9.31z'/></svg>",Bv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M481.29 229.47l-188.87-113a30.54 30.54 0 00-31.09-.39 33.74 33.74 0 00-16.76 29.47v79.05L63.85 116.44a30.54 30.54 0 00-31.09-.39A33.74 33.74 0 0016 145.52v221A33.74 33.74 0 0032.76 396a30.54 30.54 0 0031.09-.39L244.57 287.4v79.08A33.74 33.74 0 00261.33 396a30.54 30.54 0 0031.09-.39l188.87-113a31.27 31.27 0 000-53z'/></svg>",Mv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M32 145.52v221c0 13.28 13 21.72 23.63 15.35l188.87-113c9.24-5.53 9.24-20.07 0-25.6l-188.87-113C45 123.8 32 132.24 32 145.52zM260.57 145.52v221c0 13.28 13 21.72 23.63 15.35l188.87-113c9.24-5.53 9.24-20.07 0-25.6l-188.87-113c-10.64-6.47-23.63 1.97-23.63 15.25z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",hd="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M112 111v290c0 17.44 17 28.52 31 20.16l247.9-148.37c12.12-7.25 12.12-26.33 0-33.58L143 90.84c-14-8.36-31 2.72-31 20.16z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Iv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M400 111v290c0 17.44-17 28.52-31 20.16L121.09 272.79c-12.12-7.25-12.12-26.33 0-33.58L369 90.84c14-8.36 31 2.72 31 20.16z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-miterlimit='10' d='M112 80v352' class='ionicon-fill-none ionicon-stroke-width'/></svg>",$v="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M112 111v290c0 17.44 17 28.52 31 20.16l247.9-148.37c12.12-7.25 12.12-26.33 0-33.58L143 90.84c-14-8.36-31 2.72-31 20.16z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-miterlimit='10' d='M400 80v352' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Uo="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M320 146s24.36-12-64-12a160 160 0 10160 160' stroke-linecap='round' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M256 58l80 80-80 80' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Fv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M448 256c0-106-86-192-192-192S64 150 64 256s86 192 192 192 192-86 192-192z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-linejoin='round' d='M336 256H176' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Dv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M400 256H112' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Cc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M304 96h112v112M405.77 106.2L111.98 400.02M208 416H96V304' class='ionicon-fill-none ionicon-stroke-width'/></svg>",pl="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M380.93 57.37A32 32 0 00358.3 48H94.22A46.21 46.21 0 0048 94.22v323.56A46.21 46.21 0 0094.22 464h323.56A46.36 46.36 0 00464 417.78V153.7a32 32 0 00-9.37-22.63zM256 416a64 64 0 1164-64 63.92 63.92 0 01-64 64zm48-224H112a16 16 0 01-16-16v-64a16 16 0 0116-16h192a16 16 0 0116 16v64a16 16 0 01-16 16z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Av="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><circle cx='256' cy='256' r='48'/><path d='M470.39 300l-.47-.38-31.56-24.75a16.11 16.11 0 01-6.1-13.33v-11.56a16 16 0 016.11-13.22L469.92 212l.47-.38a26.68 26.68 0 005.9-34.06l-42.71-73.9a1.59 1.59 0 01-.13-.22A26.86 26.86 0 00401 92.14l-.35.13-37.1 14.93a15.94 15.94 0 01-14.47-1.29q-4.92-3.1-10-5.86a15.94 15.94 0 01-8.19-11.82l-5.59-39.59-.12-.72A27.22 27.22 0 00298.76 26h-85.52a26.92 26.92 0 00-26.45 22.39l-.09.56-5.57 39.67a16 16 0 01-8.13 11.82 175.21 175.21 0 00-10 5.82 15.92 15.92 0 01-14.43 1.27l-37.13-15-.35-.14a26.87 26.87 0 00-32.48 11.34l-.13.22-42.77 73.95a26.71 26.71 0 005.9 34.1l.47.38 31.56 24.75a16.11 16.11 0 016.1 13.33v11.56a16 16 0 01-6.11 13.22L42.08 300l-.47.38a26.68 26.68 0 00-5.9 34.06l42.71 73.9a1.59 1.59 0 01.13.22 26.86 26.86 0 0032.45 11.3l.35-.13 37.07-14.93a15.94 15.94 0 0114.47 1.29q4.92 3.11 10 5.86a15.94 15.94 0 018.19 11.82l5.56 39.59.12.72A27.22 27.22 0 00213.24 486h85.52a26.92 26.92 0 0026.45-22.39l.09-.56 5.57-39.67a16 16 0 018.18-11.82c3.42-1.84 6.76-3.79 10-5.82a15.92 15.92 0 0114.43-1.27l37.13 14.95.35.14a26.85 26.85 0 0032.48-11.34 2.53 2.53 0 01.13-.22l42.71-73.89a26.7 26.7 0 00-5.89-34.11zm-134.48-40.24a80 80 0 11-83.66-83.67 80.21 80.21 0 0183.66 83.67z'/></svg>",as="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M400 304l48 48-48 48M400 112l48 48-48 48M64 352h85.19a80 80 0 0066.56-35.62L256 256' class='ionicon-fill-none ionicon-stroke-width'/><path d='M64 160h85.19a80 80 0 0166.56 35.62l80.5 120.76A80 80 0 00362.81 352H416M416 160h-53.19a80 80 0 00-66.56 35.62L288 208' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",eo="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512' class='ionicon'><path d='M259.92 262.91L216.4 149.77a9 9 0 00-16.8 0l-43.52 113.14a9 9 0 01-5.17 5.17L37.77 311.6a9 9 0 000 16.8l113.14 43.52a9 9 0 015.17 5.17l43.52 113.14a9 9 0 0016.8 0l43.52-113.14a9 9 0 015.17-5.17l113.14-43.52a9 9 0 000-16.8l-113.14-43.52a9 9 0 01-5.17-5.17zM108 68L88 16 68 68 16 88l52 20 20 52 20-52 52-20-52-20zM426.67 117.33L400 48l-26.67 69.33L304 144l69.33 26.67L400 240l26.67-69.33L496 144l-69.33-26.67z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",_i="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-miterlimit='10' d='M256 48v48M256 416v48M403.08 108.92l-33.94 33.94M142.86 369.14l-33.94 33.94M464 256h-48M96 256H48M403.08 403.08l-33.94-33.94M142.86 142.86l-33.94-33.94' class='ionicon-fill-none ionicon-stroke-width'/><circle cx='256' cy='256' r='80' stroke-linecap='round' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",xc="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M304 48l112 112-112 112M398.87 160H96M208 464L96 352l112-112M114 352h302' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Rv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M512 128v256a64.07 64.07 0 01-64 64H64a64.07 64.07 0 01-64-64V128a64.07 64.07 0 0164-64h384a64.07 64.07 0 0164 64zM32 384a32 32 0 0032 32h384a32 32 0 0032-32V128a32 32 0 00-32-32H64a32 32 0 00-32 32z'/><path d='M0 128a64.07 64.07 0 0164-64h384a64.07 64.07 0 0164 64v256a64.07 64.07 0 01-64 64H64a64.07 64.07 0 01-64-64V128m480 256V128a32 32 0 00-32-32H64a32 32 0 00-32 32v256a32 32 0 0032 32h384a32 32 0 0032-32m-16 0a16 16 0 01-16 16H64a16 16 0 01-16-16V128a16 16 0 0116-16h384a16 16 0 0116 16v256z'/></svg>",km="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-linejoin='round' d='M32 415.5l120-320 120 320M230 303.5H74M326 239.5c12.19-28.69 41-48 74-48h0c46 0 80 32 80 80v144' class='ionicon-fill-none ionicon-stroke-width'/><path d='M320 358.5c0 36 26.86 58 60 58 54 0 100-27 100-106v-15c-20 0-58 1-92 5-32.77 3.86-68 19-68 58z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Xr="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M112 112l20 320c.95 18.49 14.4 32 32 32h184c17.67 0 30.87-13.51 32-32l20-320' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path stroke-linecap='round' stroke-miterlimit='10' d='M80 112h352' class='ionicon-stroke-width'/><path d='M192 112V72h0a23.93 23.93 0 0124-24h80a23.93 23.93 0 0124 24h0v40M256 176v224M184 176l8 224M328 176l-8 224' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",_m="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M374.79 308.78L457.5 367a16 16 0 0022.5-14.62V159.62A16 16 0 00457.5 145l-82.71 58.22A16 16 0 00368 216.3v79.4a16 16 0 006.79 13.08z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path d='M268 384H84a52.15 52.15 0 01-52-52V180a52.15 52.15 0 0152-52h184.48A51.68 51.68 0 01320 179.52V332a52.15 52.15 0 01-52 52z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/></svg>",Lv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M232 416a23.88 23.88 0 01-14.2-4.68 8.27 8.27 0 01-.66-.51L125.76 336H56a24 24 0 01-24-24V200a24 24 0 0124-24h69.75l91.37-74.81a8.27 8.27 0 01.66-.51A24 24 0 01256 120v272a24 24 0 01-24 24zm-106.18-80zm-.27-159.86zM320 336a16 16 0 01-14.29-23.19c9.49-18.87 14.3-38 14.3-56.81 0-19.38-4.66-37.94-14.25-56.73a16 16 0 0128.5-14.54C346.19 208.12 352 231.44 352 256c0 23.86-6 47.81-17.7 71.19A16 16 0 01320 336z'/><path d='M368 384a16 16 0 01-13.86-24C373.05 327.09 384 299.51 384 256c0-44.17-10.93-71.56-29.82-103.94a16 16 0 0127.64-16.12C402.92 172.11 416 204.81 416 256c0 50.43-13.06 83.29-34.13 120a16 16 0 01-13.87 8z'/><path d='M416 432a16 16 0 01-13.39-24.74C429.85 365.47 448 323.76 448 256c0-66.5-18.18-108.62-45.49-151.39a16 16 0 1127-17.22C459.81 134.89 480 181.74 480 256c0 64.75-14.66 113.63-50.6 168.74A16 16 0 01416 432z'/></svg>",Pv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M296 416.19a23.92 23.92 0 01-14.21-4.69l-.66-.51-91.46-75H120a24 24 0 01-24-24V200a24 24 0 0124-24h69.65l91.46-75 .66-.51A24 24 0 01320 119.83v272.34a24 24 0 01-24 24zM384 336a16 16 0 01-14.29-23.18c9.49-18.9 14.3-38 14.3-56.82 0-19.36-4.66-37.92-14.25-56.73a16 16 0 0128.5-14.54C410.2 208.16 416 231.47 416 256c0 23.83-6 47.78-17.7 71.18A16 16 0 01384 336z'/></svg>",Uv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M264 416.19a23.92 23.92 0 01-14.21-4.69l-.66-.51-91.46-75H88a24 24 0 01-24-24V200a24 24 0 0124-24h69.65l91.46-75 .66-.51A24 24 0 01288 119.83v272.34a24 24 0 01-24 24zM352 336a16 16 0 01-14.29-23.18c9.49-18.9 14.3-38 14.3-56.82 0-19.36-4.66-37.92-14.25-56.73a16 16 0 0128.5-14.54C378.2 208.16 384 231.47 384 256c0 23.83-6 47.78-17.7 71.18A16 16 0 01352 336z'/><path d='M400 384a16 16 0 01-13.87-24C405 327.05 416 299.45 416 256c0-44.12-10.94-71.52-29.83-103.95A16 16 0 01413.83 136C434.92 172.16 448 204.88 448 256c0 50.36-13.06 83.24-34.12 120a16 16 0 01-13.88 8z'/></svg>",Ov="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M157.65 192H88a8 8 0 00-8 8v112a8 8 0 008 8h69.65a16 16 0 0110.14 3.63l91.47 75a8 8 0 0012.74-6.46V119.83a8 8 0 00-12.74-6.44l-91.47 75a16 16 0 01-10.14 3.61zM352 320c9.74-19.41 16-40.81 16-64 0-23.51-6-44.4-16-64M400 368c19.48-34 32-64 32-112s-12-77.7-32-112' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>",zv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-miterlimit='10' d='M416 432L64 80' class='ionicon-fill-none ionicon-stroke-width'/><path d='M243.33 98.86a23.89 23.89 0 00-25.55 1.82l-.66.51-28.52 23.35a8 8 0 00-.59 11.85l54.33 54.33a8 8 0 0013.66-5.66v-64.49a24.51 24.51 0 00-12.67-21.71zM251.33 335.29L96.69 180.69A16 16 0 0085.38 176H56a24 24 0 00-24 24v112a24 24 0 0024 24h69.76l92 75.31a23.9 23.9 0 0025.87 1.69A24.51 24.51 0 00256 391.45v-44.86a16 16 0 00-4.67-11.3zM352 256c0-24.56-5.81-47.87-17.75-71.27a16 16 0 10-28.5 14.55C315.34 218.06 320 236.62 320 256q0 4-.31 8.13a8 8 0 002.32 6.25l14.36 14.36a8 8 0 0013.55-4.31A146 146 0 00352 256zM416 256c0-51.18-13.08-83.89-34.18-120.06a16 16 0 00-27.64 16.12C373.07 184.44 384 211.83 384 256c0 23.83-3.29 42.88-9.37 60.65a8 8 0 001.9 8.26L389 337.4a8 8 0 0013.13-2.79C411 311.76 416 287.26 416 256z'/><path d='M480 256c0-74.25-20.19-121.11-50.51-168.61a16 16 0 10-27 17.22C429.82 147.38 448 189.5 448 256c0 46.19-8.43 80.27-22.43 110.53a8 8 0 001.59 9l11.92 11.92a8 8 0 0012.92-2.16C471.6 344.9 480 305 480 256z'/></svg>",jv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path stroke-linecap='round' stroke-miterlimit='10' d='M416 432L64 80' class='ionicon-fill-none ionicon-stroke-width'/><path d='M224 136.92v33.8a4 4 0 001.17 2.82l24 24a4 4 0 006.83-2.82v-74.15a24.53 24.53 0 00-12.67-21.72 23.91 23.91 0 00-25.55 1.83 8.27 8.27 0 00-.66.51l-31.94 26.15a4 4 0 00-.29 5.92l17.05 17.06a4 4 0 005.37.26zM224 375.08l-78.07-63.92a32 32 0 00-20.28-7.16H64v-96h50.72a4 4 0 002.82-6.83l-24-24a4 4 0 00-2.82-1.17H56a24 24 0 00-24 24v112a24 24 0 0024 24h69.76l91.36 74.8a8.27 8.27 0 00.66.51 23.93 23.93 0 0025.85 1.69A24.49 24.49 0 00256 391.45v-50.17a4 4 0 00-1.17-2.82l-24-24a4 4 0 00-6.83 2.82zM125.82 336zM352 256c0-24.56-5.81-47.88-17.75-71.27a16 16 0 00-28.5 14.54C315.34 218.06 320 236.62 320 256q0 4-.31 8.13a8 8 0 002.32 6.25l19.66 19.67a4 4 0 006.75-2A146.89 146.89 0 00352 256zM416 256c0-51.19-13.08-83.89-34.18-120.06a16 16 0 00-27.64 16.12C373.07 184.44 384 211.83 384 256c0 23.83-3.29 42.88-9.37 60.65a8 8 0 001.9 8.26l16.77 16.76a4 4 0 006.52-1.27C410.09 315.88 416 289.91 416 256z'/><path d='M480 256c0-74.26-20.19-121.11-50.51-168.61a16 16 0 10-27 17.22C429.82 147.38 448 189.5 448 256c0 47.45-8.9 82.12-23.59 113a4 4 0 00.77 4.55L443 391.39a4 4 0 006.4-1C470.88 348.22 480 307 480 256z'/></svg>",Wv="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M85.57 446.25h340.86a32 32 0 0028.17-47.17L284.18 82.58c-12.09-22.44-44.27-22.44-56.36 0L57.4 399.08a32 32 0 0028.17 47.17z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path d='M250.26 195.39l5.74 122 5.73-121.95a5.74 5.74 0 00-5.79-6h0a5.74 5.74 0 00-5.68 5.95z' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/><path d='M256 397.25a20 20 0 1120-20 20 20 0 01-20 20z'/></svg>",br="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' class='ionicon' viewBox='0 0 512 512'><path d='M400 320c0 88.37-55.63 144-144 144s-144-55.63-144-144c0-94.83 103.23-222.85 134.89-259.88a12 12 0 0118.23 0C296.77 97.15 400 225.17 400 320z' stroke-miterlimit='10' class='ionicon-fill-none ionicon-stroke-width'/><path d='M344 328a72 72 0 01-72 72' stroke-linecap='round' stroke-linejoin='round' class='ionicon-fill-none ionicon-stroke-width'/></svg>";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Nc=()=>{};function Hv(o,a){function t(...n){return new Promise((i,r)=>{Promise.resolve(o(()=>a.apply(this,n),{fn:a,thisArg:this,args:n})).then(i).catch(r)})}return t}function Zv(o,a={}){let t,n,i=Nc;const r=d=>{clearTimeout(d),i(),i=Nc};let l;return d=>{const c=e.toValue(o),u=e.toValue(a.maxWait);return t&&r(t),c<=0||u!==void 0&&u<=0?(n&&(r(n),n=null),Promise.resolve(d())):new Promise((m,p)=>{i=a.rejectOnCancel?p:m,l=d,u&&!n&&(n=setTimeout(()=>{t&&r(t),n=null,m(l())},u)),t=setTimeout(()=>{n&&r(n),n=null,m(d())},c)})}}function Gv(o,a=200,t={}){return Hv(Zv(a,t),o)}const Ei=new Map;function Xv(o){const a=e.getCurrentScope();function t(s){var d;const c=Ei.get(o)||new Set;c.add(s),Ei.set(o,c);const u=()=>i(s);return(d=a==null?void 0:a.cleanups)==null||d.push(u),u}function n(s){function d(...c){i(d),s(...c)}return t(d)}function i(s){const d=Ei.get(o);d&&(d.delete(s),d.size||r())}function r(){Ei.delete(o)}function l(s,d){var c;(c=Ei.get(o))==null||c.forEach(u=>u(s,d))}return{on:t,once:n,off:i,emit:l,reset:r}}function Em(){var r,l;const o=typeof window<"u"&&"Capacitor"in window&&((l=(r=window.Capacitor)==null?void 0:r.isNativePlatform)==null?void 0:l.call(r));return{selection:()=>{var s,d;if(o)try{const c=(d=(s=window.Capacitor)==null?void 0:s.Plugins)==null?void 0:d.Haptics;c&&c.impact({style:"LIGHT"})}catch{}else"vibrate"in navigator&&navigator.vibrate(10)},success:()=>{var s,d;if(o)try{const c=(d=(s=window.Capacitor)==null?void 0:s.Plugins)==null?void 0:d.Haptics;c&&c.impact({style:"MEDIUM"})}catch{}else"vibrate"in navigator&&navigator.vibrate(30)},error:()=>{var s,d;if(o)try{const c=(d=(s=window.Capacitor)==null?void 0:s.Plugins)==null?void 0:d.Haptics;c&&c.impact({style:"HEAVY"})}catch{}else"vibrate"in navigator&&navigator.vibrate([50,50,50])},notification:()=>{var s,d;if(o)try{const c=(d=(s=window.Capacitor)==null?void 0:s.Plugins)==null?void 0:d.Haptics;c&&c.notification({type:"SUCCESS"})}catch{}else"vibrate"in navigator&&navigator.vibrate([20,100,20])}}}function fl(o,a={}){const t=e.ref(new Set),n=e.ref(new Map),i=e.ref(null),r=e.ref(-1),l=e.ref(a.scopeKey!==void 0?e.toValue(a.scopeKey):"default"),s=e.ref(!1),d=e.ref(null),c=Xv("media-selection"),u=Em(),m=()=>{if(a.currentPage===void 0)return null;const O=e.toValue(a.currentPage);return typeof O=="number"&&Number.isFinite(O)?O:null};function p(O){t.value=O,n.value=new Map(Array.from(n.value.entries()).filter(([K])=>O.has(K)))}function f(O){if(n.value.has(O))return;const K=new Map(n.value);K.set(O,{uuid:O,selectedAt:Date.now(),page:m()}),n.value=K}const h=e.computed(()=>o.value.filter(O=>t.value.has(O.uuid))),v=e.computed(()=>t.value.size),y=e.computed(()=>Array.from(n.value.values()).sort((O,K)=>O.selectedAt-K.selectedAt).map(O=>O.uuid)),w=e.computed(()=>Math.max(0,v.value-h.value.length)),_=e.computed(()=>{const O=new Map;for(const K of n.value.values())K.page!==null&&O.set(K.page,(O.get(K.page)??0)+1);return O});e.watch(t,O=>{c.emit({type:"selection:changed",count:O.size,selectedIds:Array.from(O)})}),a.scopeKey!==void 0&&e.watch(()=>e.toValue(a.scopeKey),(O,K)=>{O!==void 0&&O!==K&&z(O)});const b=e.computed(()=>o.value.length>0&&o.value.every(O=>t.value.has(O.uuid))),g=e.computed(()=>o.value.some(O=>t.value.has(O.uuid)));function I(O){return t.value.has(O)}function T(O){const K=new Set(t.value),se=K.size===0;K.add(O),f(O),t.value=K,i.value=O,r.value=o.value.findIndex(xe=>xe.uuid===O),se&&u.selection()}function $(O){const K=new Set(t.value);K.delete(O);const se=new Map(n.value);se.delete(O),n.value=se,t.value=K,i.value===O&&(i.value=null,r.value=-1)}function N(O){if(t.value.has(O)){$(O);return}T(O)}function B(){const O=new Set(t.value);for(const K of o.value)O.add(K.uuid),f(K.uuid);t.value=O}function P(){t.value=new Set,n.value=new Map,i.value=null,r.value=-1,s.value=!1,d.value=null}function x(){if(b.value){P();return}B()}function M(O,K){const se=o.value.findIndex(xe=>xe.uuid===O);if(se!==-1){if(K!=null&&K.shiftKey&&r.value!==-1){const xe=Math.min(r.value,se),ue=Math.max(r.value,se),le=new Set(t.value);for(let Z=xe;Z<=ue;Z++){const k=o.value[Z];k!==void 0&&(le.add(k.uuid),f(k.uuid))}t.value=le;return}N(O)}}function E(){if(o.value.length===0)return;let O=r.value+1;O>=o.value.length&&(O=0),P();const K=o.value[O];K!==void 0&&T(K.uuid)}function D(){if(o.value.length===0)return;let O=r.value-1;O<0&&(O=o.value.length-1),P();const K=o.value[O];K!==void 0&&T(K.uuid)}function j(O){switch(O.key){case"ArrowDown":O.preventDefault(),E();break;case"ArrowUp":O.preventDefault(),D();break;case"a":(O.ctrlKey||O.metaKey)&&(O.preventDefault(),B());break;case"Escape":O.preventDefault(),P();break;case" ":i.value&&(O.preventDefault(),N(i.value));break}}async function L(O){var se;if(v.value===0||l.value===O)return!0;const K=(se=a.confirmScopeChange)==null?void 0:se.call(a,{from:l.value,to:O,selectedCount:v.value});return K===void 0?!0:await K}async function z(O){return l.value===O?!0:await L(O)?(l.value=O,P(),!0):!1}async function C(){if(!a.fetchMatchingUuids){const K={uuids:o.value.map(se=>se.uuid),overCap:!1,totalMatching:o.value.length};return A(K),K}const O=await a.fetchMatchingUuids();return A(O),O}function A(O){const K=new Set(O.uuids),se=new Map,xe=Date.now();O.uuids.forEach((ue,le)=>{se.set(ue,{uuid:ue,selectedAt:xe+le,page:m()})}),p(K),n.value=se,s.value=O.overCap,d.value=O.totalMatching}return{selectedIds:e.computed(()=>t.value),selectedRecords:e.computed(()=>n.value),selectedItems:h,selectedCount:v,orderedIds:y,crossPageCount:w,selectedPages:_,overCap:e.computed(()=>s.value),totalMatching:e.computed(()=>d.value),activeScopeKey:e.computed(()=>l.value),isAllSelected:b,isSomeSelected:g,lastSelectedId:e.computed(()=>i.value),isSelected:I,toggle:N,select:T,deselect:$,selectAll:B,clear:P,toggleAll:x,rangeSelect:M,selectAcrossAllPages:C,setScopeKey:z,canChangeScope:L,selectNext:E,selectPrevious:D,handleKeydown:j,selectionBus:c}}const Kv={class:"flex items-center justify-between w-full px-4"},qv={class:"p-4"},Jv={key:0,class:"mb-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg"},Yv={class:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"},Qv=["value"],eg={class:"flex gap-2 mt-4"},tg={class:"flex justify-end mb-4"},ag={key:1,class:"flex justify-center items-center h-64"},ng={key:2,class:"flex flex-col items-center justify-center h-64 text-center"},og={class:"text-sm text-theme-secondary"},ig={key:0},rg={class:"mb-4"},lg={class:"mb-4"},sg={class:"flex gap-2"},dg={class:"flex items-center justify-between px-4 py-2"},cg={class:"text-sm text-theme-secondary"},ug={key:0},mg={key:0},pg={key:1},fg={class:"flex gap-2"},hg=e.defineComponent({__name:"AdminMediaBrowser",props:{isOpen:{type:Boolean},selectionMode:{default:"single"},selectedItems:{default:()=>[]},modelType:{},modelId:{},collection:{default:"images"},maxSelection:{}},emits:["close","confirm"],setup(o,{emit:a}){const t=o,n=a,i=e.ref("recent"),r=e.ref("grid"),l=e.ref(""),s=e.ref(!1),d=e.ref([]),{selectedItems:c}=e.toRefs(t),u=e.ref(new Set(c.value)),m=e.ref(!1),p=e.ref({}),f=e.ref(["images","documents","videos"]),h=e.ref(1),v=e.ref(!0),y=e.ref(!1),w=sm(),_=fl(d);function b(Z){var be;const k=Z.conversion_urls||{},F=Z.proxy_url||Z.original_url||Z.url||"",W=k.thumb||k.preview||Z.preview_url||Z.thumbnail_url||F,J=Z.custom_properties||{},ce=J.width,Ue=J.height;return{...Z,uuid:Z.uuid,name:Z.name||Z.file_name,file_name:Z.file_name,filename:Z.file_name,mime_type:Z.mime_type,size:Z.size,collection_name:Z.collection_name||"images",disk:Z.disk,original_url:F,url:F,thumbnail_url:W,conversions:Z.conversions||{},conversion_urls:k,generated_conversions:Z.generated_conversions||{},custom_properties:J,caption:Z.caption||null,alt_text:Z.alt_text||null,created_at:Z.created_at,updated_at:Z.updated_at,is_image:((be=Z.mime_type)==null?void 0:be.startsWith("image/"))||!1,...typeof ce=="number"?{width:ce}:{},...typeof Ue=="number"?{height:Ue}:{},...Z.formatted_size!==void 0?{formatted_size:Z.formatted_size}:{}}}e.watch(()=>t.selectedItems,Z=>{u.value=new Set(Z),_.clear(),Z.forEach(k=>_.select(k))});const g=e.computed(()=>{var k;let Z=d.value;return(k=p.value.types)!=null&&k.length&&(Z=Z.filter(F=>{var J,ce;const W=(J=F.mime_type)==null?void 0:J.split("/")[0];return(ce=p.value.types)==null?void 0:ce.includes(W)})),(p.value.sizeMin!==void 0||p.value.sizeMax!==void 0)&&(Z=Z.filter(F=>{const W=F.size/1048576;return!(p.value.sizeMin!==void 0&&W<p.value.sizeMin||p.value.sizeMax!==void 0&&W>p.value.sizeMax)})),Z}),I=e.computed(()=>{var k;let Z=0;return p.value.search&&Z++,p.value.collection&&Z++,(p.value.dateFrom||p.value.dateTo)&&Z++,(k=p.value.types)!=null&&k.length&&(Z+=p.value.types.length),(p.value.sizeMin!==void 0||p.value.sizeMax!==void 0)&&Z++,Z}),T=e.computed(()=>{const Z=_.selectedCount.value;return Z===0?"Select Media":`Select ${t.selectionMode==="multiple"?`${Z} ${Z===1?"Item":"Items"}`:"Item"}`}),$=e.computed(()=>{const Z=_.selectedCount.value;return!!(Z===0||t.selectionMode==="single"&&Z>1||t.maxSelection&&Z>t.maxSelection)}),N=e.computed(()=>{switch(i.value){case"recent":return"Recent Uploads";case"model":return"Model Media";case"library":return"Media Library";default:return"Media Browser"}});async function B(Z=!0){Z?(s.value=!0,d.value=[],h.value=1,v.value=!0):y.value=!0;try{const k={collection:p.value.collection||t.collection,per_page:24};switch((l.value||p.value.search)&&(k.search=l.value||p.value.search||""),p.value.dateFrom&&(k.from_date=p.value.dateFrom),p.value.dateTo&&(k.to_date=p.value.dateTo),i.value){case"recent":await w.fetchMedia(h.value,k),Z?d.value=w.items.map(F=>b(F)):d.value=[...d.value,...w.items.map(F=>b(F))],v.value=w.currentPage<w.totalPages;break;case"model":if(t.modelType&&t.modelId){const F=await w.fetchModelMedia(t.modelType,t.modelId,k.collection,k.search);d.value=F?F.map(W=>b(W)):[],v.value=!1}break;case"library":await w.fetchMedia(h.value,k),Z?d.value=w.items.map(F=>b(F)):d.value=[...d.value,...w.items.map(F=>b(F))],v.value=w.currentPage<w.totalPages;break}}catch{}finally{s.value=!1,y.value=!1}}async function P(Z){if(!v.value||y.value){Z!=null&&Z.target&&Z.target.complete();return}h.value++,await B(!1),Z!=null&&Z.target&&(Z.target.complete(),v.value||(Z.target.disabled=!0))}function x(Z){return Z==="recent"||Z==="model"||Z==="library"}function M(Z){i.value=Z,B()}function E(Z){typeof Z=="string"&&x(Z)&&M(Z)}async function D(Z){t.selectionMode==="single"?(_.clear(),_.select(Z.uuid)):(_.toggle(Z.uuid),t.maxSelection&&_.selectedCount.value>t.maxSelection&&(_.deselect(Z.uuid),await(await G.toastController.create({message:`Maximum ${t.maxSelection} items can be selected`,duration:2e3,color:"warning"})).present()))}function j(){n("confirm",_.selectedItems.value)}function L(){n("close")}function z(Z){}const C=e.ref(null),A=e.ref(!1);function O(Z){C.value=Z,A.value=!0}function K(Z){const k=d.value.findIndex(W=>W.uuid===Z.uuid);k!==-1&&(d.value[k]=Z);const F={};Z.alt_text!==void 0&&(F.alt_text=Z.alt_text),Z.caption!==void 0&&(F.caption=Z.caption),Z.custom_properties!==void 0&&(F.custom_properties=Z.custom_properties),w.updateMedia(Z.uuid,F)}function se(){B()}function xe(){p.value={},l.value="",B()}const ue=Gv(()=>{B(!0)},300);e.watch(l,()=>{t.isOpen&&ue()});async function le(Z){try{await(await G.alertController.create({header:"Delete Media",message:"Are you sure you want to delete this media item?",buttons:[{text:"Cancel",role:"cancel"},{text:"Delete",role:"destructive",handler:async()=>{await w.deleteMedia(Z),await B()}}]})).present()}catch{}}return e.watch(()=>t.isOpen,Z=>{Z&&B()}),e.onMounted(()=>{t.selectedItems.length>0&&t.selectedItems.forEach(Z=>_.select(Z))}),(Z,k)=>{const F=e.resolveComponent("AdminMediaGrid"),W=e.resolveComponent("AdminMediaListItem");return e.openBlock(),e.createBlock(e.unref(G.IonModal),{"is-open":Z.isOpen,onDidDismiss:L,"backdrop-dismiss":!1,class:"media-browser-modal"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonToolbar),null,{end:e.withCtx(()=>[e.createVNode(e.unref(G.IonButtons),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonButton),{onClick:L},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{name:"close-outline"})]),_:1})]),_:1})]),default:e.withCtx(()=>[e.createVNode(e.unref(G.IonTitle),null,{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(N.value),1)]),_:1})]),_:1}),e.createVNode(e.unref(G.IonToolbar),null,{default:e.withCtx(()=>[e.createElementVNode("div",Kv,[e.createVNode(e.unref(G.IonSegment),{value:i.value,onIonChange:k[0]||(k[0]=J=>E(J.detail.value)),class:"max-w-xs"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonSegmentButton),{value:"recent"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonLabel),null,{default:e.withCtx(()=>[...k[15]||(k[15]=[e.createTextVNode("Recent",-1)])]),_:1})]),_:1}),t.modelType&&t.modelId?(e.openBlock(),e.createBlock(e.unref(G.IonSegmentButton),{key:0,value:"model"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonLabel),null,{default:e.withCtx(()=>[...k[16]||(k[16]=[e.createTextVNode("Model",-1)])]),_:1})]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(G.IonSegmentButton),{value:"library"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonLabel),null,{default:e.withCtx(()=>[...k[17]||(k[17]=[e.createTextVNode("Library",-1)])]),_:1})]),_:1})]),_:1},8,["value"]),e.createVNode(e.unref(G.IonButton),{fill:"clear",size:"small",onClick:k[1]||(k[1]=J=>m.value=!m.value),class:"relative"},{"icon-only":e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{name:"filter-outline"})]),default:e.withCtx(()=>[I.value>0?(e.openBlock(),e.createBlock(e.unref(G.IonBadge),{key:0,color:"primary",class:"absolute -top-1 -right-1 min-w-[20px] h-5 rounded-full flex items-center justify-center text-xs"},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(I.value),1)]),_:1})):e.createCommentVNode("",!0)]),_:1})])]),_:1})]),_:1}),e.createVNode(e.unref(G.IonContent),null,{default:e.withCtx(()=>[e.createElementVNode("div",qv,[m.value?(e.openBlock(),e.createElementBlock("div",Jv,[e.createElementVNode("div",Yv,[e.createElementVNode("div",null,[e.createVNode(e.unref(G.IonLabel),null,{default:e.withCtx(()=>[...k[18]||(k[18]=[e.createTextVNode("Collection",-1)])]),_:1}),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":k[2]||(k[2]=J=>p.value.collection=J),class:"w-full p-2 border rounded"},[k[19]||(k[19]=e.createElementVNode("option",{value:""},"All Collections",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(f.value,J=>(e.openBlock(),e.createElementBlock("option",{key:J,value:J},e.toDisplayString(J),9,Qv))),128))],512),[[e.vModelSelect,p.value.collection]])]),e.createElementVNode("div",null,[e.createVNode(e.unref(G.IonLabel),null,{default:e.withCtx(()=>[...k[20]||(k[20]=[e.createTextVNode("From Date",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":k[3]||(k[3]=J=>p.value.dateFrom=J),type:"date",class:"w-full p-2 border rounded"},null,512),[[e.vModelText,p.value.dateFrom]])]),e.createElementVNode("div",null,[e.createVNode(e.unref(G.IonLabel),null,{default:e.withCtx(()=>[...k[21]||(k[21]=[e.createTextVNode("To Date",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":k[4]||(k[4]=J=>p.value.dateTo=J),type:"date",class:"w-full p-2 border rounded"},null,512),[[e.vModelText,p.value.dateTo]])])]),e.createElementVNode("div",eg,[e.createVNode(e.unref(G.IonButton),{size:"small",onClick:se},{default:e.withCtx(()=>[...k[22]||(k[22]=[e.createTextVNode("Apply",-1)])]),_:1}),e.createVNode(e.unref(G.IonButton),{size:"small",fill:"clear",onClick:xe},{default:e.withCtx(()=>[...k[23]||(k[23]=[e.createTextVNode("Clear",-1)])]),_:1})])])):e.createCommentVNode("",!0),e.createVNode(e.unref(G.IonSearchbar),{modelValue:l.value,"onUpdate:modelValue":k[5]||(k[5]=J=>l.value=J),placeholder:"Search media...",debounce:300,class:"mb-4"},null,8,["modelValue"]),e.createElementVNode("div",tg,[e.createVNode(e.unref(G.IonButtons),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonButton),{fill:r.value==="grid"?"solid":"clear",size:"small",onClick:k[6]||(k[6]=J=>r.value="grid")},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{name:"grid-outline"})]),_:1},8,["fill"]),e.createVNode(e.unref(G.IonButton),{fill:r.value==="list"?"solid":"clear",size:"small",onClick:k[7]||(k[7]=J=>r.value="list")},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{name:"list-outline"})]),_:1},8,["fill"])]),_:1})]),s.value?(e.openBlock(),e.createElementBlock("div",ag,[e.createVNode(e.unref(G.IonSpinner),{name:"crescent"})])):g.value.length===0?(e.openBlock(),e.createElementBlock("div",ng,[e.createVNode(e.unref(G.IonIcon),{name:"images-outline",class:"text-6xl text-theme-secondary mb-4"}),k[24]||(k[24]=e.createElementVNode("h3",{class:"text-lg font-medium text-theme mb-2"}," No Media Found ",-1)),e.createElementVNode("p",og,e.toDisplayString(l.value?"Try adjusting your search":"No media items available"),1)])):r.value==="grid"?(e.openBlock(),e.createBlock(F,{key:3,"media-items":g.value,"selected-items":e.unref(_).selectedItems.value,"is-loading":!1,"selection-mode":!0,columns:{mobile:2,sm:3,md:4,lg:5,xl:6},onToggleSelect:D,onPreview:z,onEdit:O,onDelete:le},null,8,["media-items","selected-items"])):(e.openBlock(),e.createBlock(e.unref(G.IonList),{key:4,lines:"none",class:"rounded-lg overflow-hidden"},{default:e.withCtx(()=>[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.value,(J,ce)=>(e.openBlock(),e.createBlock(W,{key:J.uuid,media:J,selected:e.unref(_).isSelected(J.uuid),"selection-mode":!0,index:ce,onToggleSelect:D,onPreview:z,onEdit:O,onDelete:le},null,8,["media","selected","index"]))),128))]),_:1})),!s.value&&g.value.length>0&&i.value!=="model"?(e.openBlock(),e.createBlock(e.unref(G.IonInfiniteScroll),{key:5,threshold:"100px",onIonInfinite:k[8]||(k[8]=J=>P(J))},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonInfiniteScrollContent),{"loading-spinner":"crescent","loading-text":"Loading more media..."})]),_:1})):e.createCommentVNode("",!0)])]),_:1}),e.createVNode(e.unref(G.IonModal),{"is-open":A.value,onDidDismiss:k[14]||(k[14]=J=>A.value=!1)},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonToolbar),null,{end:e.withCtx(()=>[e.createVNode(e.unref(G.IonButtons),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonButton),{onClick:k[9]||(k[9]=J=>A.value=!1)},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{name:"close-outline"})]),_:1})]),_:1})]),default:e.withCtx(()=>[e.createVNode(e.unref(G.IonTitle),null,{default:e.withCtx(()=>[...k[25]||(k[25]=[e.createTextVNode("Edit Media Info",-1)])]),_:1})]),_:1})]),_:1}),e.createVNode(e.unref(G.IonContent),{class:"p-4"},{default:e.withCtx(()=>[C.value?(e.openBlock(),e.createElementBlock("div",ig,[e.createElementVNode("div",rg,[e.createVNode(e.unref(G.IonLabel),null,{default:e.withCtx(()=>[...k[26]||(k[26]=[e.createTextVNode("Caption",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":k[10]||(k[10]=J=>C.value.caption=J),type:"text",class:"w-full p-2 border rounded mt-1",placeholder:"Enter caption..."},null,512),[[e.vModelText,C.value.caption]])]),e.createElementVNode("div",lg,[e.createVNode(e.unref(G.IonLabel),null,{default:e.withCtx(()=>[...k[27]||(k[27]=[e.createTextVNode("Alt Text",-1)])]),_:1}),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":k[11]||(k[11]=J=>C.value.alt_text=J),type:"text",class:"w-full p-2 border rounded mt-1",placeholder:"Enter alt text..."},null,512),[[e.vModelText,C.value.alt_text]])]),e.createElementVNode("div",sg,[e.createVNode(e.unref(G.IonButton),{onClick:k[12]||(k[12]=J=>K(C.value))},{default:e.withCtx(()=>[...k[28]||(k[28]=[e.createTextVNode("Save",-1)])]),_:1}),e.createVNode(e.unref(G.IonButton),{fill:"clear",onClick:k[13]||(k[13]=J=>A.value=!1)},{default:e.withCtx(()=>[...k[29]||(k[29]=[e.createTextVNode("Cancel",-1)])]),_:1})])])):e.createCommentVNode("",!0)]),_:1})]),_:1},8,["is-open"]),e.createVNode(e.unref(G.IonFooter),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonToolbar),null,{default:e.withCtx(()=>[e.createElementVNode("div",dg,[e.createElementVNode("div",cg,[e.unref(_).selectedCount.value>0?(e.openBlock(),e.createElementBlock("span",ug,[e.createTextVNode(e.toDisplayString(e.unref(_).selectedCount.value)+" selected ",1),t.maxSelection?(e.openBlock(),e.createElementBlock("span",mg," / "+e.toDisplayString(t.maxSelection)+" max ",1)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("span",pg," Select "+e.toDisplayString(t.selectionMode==="multiple"?"items":"an item"),1))]),e.createElementVNode("div",fg,[e.createVNode(e.unref(G.IonButton),{fill:"clear",onClick:L},{default:e.withCtx(()=>[...k[30]||(k[30]=[e.createTextVNode(" Cancel ",-1)])]),_:1}),e.createVNode(e.unref(G.IonButton),{disabled:$.value,onClick:j},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(T.value),1)]),_:1},8,["disabled"])])])]),_:1})]),_:1})]),_:1},8,["is-open"])}}}),vg=Ae(hg,[["__scopeId","data-v-9a8c0954"]]),gg={key:1,class:"flex flex-col items-center justify-center py-16"},bg=["draggable","onDragstart","onDragover","onDrop"],yg={key:0,class:"absolute top-2 left-2 z-20"},wg=["checked","onChange"],kg={key:2,class:"absolute top-2 right-2 z-20 opacity-0 group-hover:opacity-100 transition-opacity cursor-move"},_g=["data-media-id"],Eg={key:0,class:"w-full h-full flex items-center justify-center"},Sg=["src","alt","onError","onLoad"],Cg={key:2,class:"w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-700"},xg={class:"text-center"},Ng={class:"text-4xl text-gray-400 mb-2"},Vg={class:"text-sm font-medium text-gray-500"},Tg={class:"absolute inset-0 bg-black/70 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2"},Bg=["onClick"],Mg=["onClick"],Ig=["onClick"],$g={class:"p-3"},Fg={class:"text-sm font-medium truncate mb-1"},Dg={class:"text-xs text-gray-600 dark:text-gray-400"},Ag={key:0},Rg={key:0,class:"text-xs text-gray-500 dark:text-gray-500 mt-1 truncate"},Lg=e.defineComponent({__name:"MediaGrid",props:{mediaItems:{default:()=>[]},selectedItems:{default:()=>[]},isLoading:{type:Boolean,default:!1},selectionMode:{type:Boolean,default:!1},reorderable:{type:Boolean,default:!1},showEditButton:{type:Boolean,default:!1},columns:{default:()=>({mobile:2,sm:3,md:4,lg:5,xl:6})}},emits:["toggleSelect","preview","edit","delete","reorder","upload"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null),r=e.ref(null),l=e.ref(new Set),s=e.ref(null),d=$=>t.selectedItems.some(N=>N.uuid===$.uuid),c=e.computed(()=>{const $=t.columns,N=["grid","gap-4"];switch($.mobile){case 1:N.push("grid-cols-1");break;case 2:N.push("grid-cols-2");break;case 3:N.push("grid-cols-3");break;case 4:N.push("grid-cols-4");break;default:N.push("grid-cols-2");break}switch($.sm){case 1:N.push("sm:grid-cols-1");break;case 2:N.push("sm:grid-cols-2");break;case 3:N.push("sm:grid-cols-3");break;case 4:N.push("sm:grid-cols-4");break;case 5:N.push("sm:grid-cols-5");break;default:N.push("sm:grid-cols-3");break}switch($.md){case 2:N.push("md:grid-cols-2");break;case 3:N.push("md:grid-cols-3");break;case 4:N.push("md:grid-cols-4");break;case 5:N.push("md:grid-cols-5");break;case 6:N.push("md:grid-cols-6");break;default:N.push("md:grid-cols-4");break}switch($.lg){case 3:N.push("lg:grid-cols-3");break;case 4:N.push("lg:grid-cols-4");break;case 5:N.push("lg:grid-cols-5");break;case 6:N.push("lg:grid-cols-6");break;case 7:N.push("lg:grid-cols-7");break;default:N.push("lg:grid-cols-5");break}switch($.xl){case 4:N.push("xl:grid-cols-4");break;case 5:N.push("xl:grid-cols-5");break;case 6:N.push("xl:grid-cols-6");break;case 7:N.push("xl:grid-cols-7");break;case 8:N.push("xl:grid-cols-8");break;default:N.push("xl:grid-cols-6");break}return N.join(" ")});function u($,N,B){t.reorderable&&(i.value=N,$.dataTransfer&&($.dataTransfer.effectAllowed="move",$.dataTransfer.setData("text/html","")))}function m($,N){t.reorderable&&($.preventDefault(),r.value=N)}function p(){r.value=null}function f($,N){if(!t.reorderable||!i.value)return;$.preventDefault();const B=[...t.mediaItems],P=B.findIndex(x=>{var M;return x.uuid===((M=i.value)==null?void 0:M.uuid)});if(P!==-1&&P!==N&&i.value){const[x]=B.splice(P,1);B.splice(N,0,x),n("reorder",B)}i.value=null,r.value=null}function h($){return $<1024?$+" B":$<1024*1024?($/1024).toFixed(1)+" KB":($/(1024*1024)).toFixed(1)+" MB"}function v($){var B;return $.thumbnail_url||((B=$.conversion_urls)==null?void 0:B.thumb)||$.original_url||$.url||""}function y($){var P,x,M;const N=((P=$.mime_type)==null?void 0:P.startsWith("image/"))||!1,B=!!($.thumbnail_url||(x=$.conversion_urls)!=null&&x.thumb||(M=$.conversion_urls)!=null&&M.preview||$.original_url||$.url);return N&&B}function w($){var N;return((N=$.split(".").pop())==null?void 0:N.toUpperCase())||""}function _($){var B;const N=((B=$.mime_type)==null?void 0:B.toLowerCase())||"";return N.startsWith("image/")?"image":N.startsWith("video/")?"videocam":N.startsWith("audio/")?"musical-notes":N.includes("pdf")?"document-text":N.includes("zip")||N.includes("rar")?"archive":N.includes("sheet")||N.includes("excel")?"grid":N.includes("document")||N.includes("word")?"document-text":"document"}e.onMounted(()=>{typeof window<"u"&&"IntersectionObserver"in window&&(s.value=new IntersectionObserver($=>{$.forEach(N=>{var B;if(N.isIntersecting){const P=N.target.getAttribute("data-media-id");P&&(l.value.add(P),(B=s.value)==null||B.unobserve(N.target))}})},{rootMargin:"50px"}))}),e.onUnmounted(()=>{s.value&&s.value.disconnect()});function b($){return!0}function g(){s.value&&e.nextTick(()=>{document.querySelectorAll("[data-media-id]").forEach(N=>{var P;const B=N.getAttribute("data-media-id");B&&!l.value.has(B)&&((P=s.value)==null||P.observe(N))})})}e.watch(()=>t.mediaItems,()=>{l.value.clear(),g()},{immediate:!0,deep:!0});function I($,N){const B=$.target;delete B.dataset.fallbackIndex}function T($,N){const B=$.target,P=B.closest("[data-media-id]"),x=[N.original_url,N.url,N.thumbnail_url,"preview_url"in N?N.preview_url:void 0].filter(M=>M&&M.trim()!==""&&M!==B.src);if(x.length>0&&B.dataset.fallbackIndex){const M=parseInt(B.dataset.fallbackIndex);if(M<x.length){B.dataset.fallbackIndex=(M+1).toString(),B.src=x[M]||"";return}}else if(x.length>0){B.dataset.fallbackIndex="1",B.src=x[0]||"";return}if(B.style.display="none",P&&!P.querySelector(".media-fallback-icon")){const E=document.createElement("div");E.className="media-fallback-icon w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-800",E.innerHTML=`
2
+ <div class="text-center">
3
+ <div class="text-4xl text-gray-400 mb-2">${_(N)}</div>
4
+ <p class="text-sm font-medium text-gray-500">${w(N.file_name)}</p>
5
+ </div>
6
+ `,P.appendChild(E)}}return($,N)=>$.isLoading?(e.openBlock(),e.createElementBlock("div",{key:0,class:e.normalizeClass(c.value)},[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(12,B=>e.createElementVNode("div",{key:`skeleton-${B}`,class:"relative"},[...N[1]||(N[1]=[e.createStaticVNode('<div class="bg-white dark:bg-gray-800 rounded-lg shadow" data-v-f0c343b7><div class="aspect-square bg-gray-200 dark:bg-gray-700 animate-pulse rounded-t-lg" data-v-f0c343b7></div><div class="p-3" data-v-f0c343b7><div class="h-4 bg-gray-200 dark:bg-gray-700 animate-pulse rounded w-3/4 mb-2" data-v-f0c343b7></div><div class="h-3 bg-gray-200 dark:bg-gray-700 animate-pulse rounded w-1/2" data-v-f0c343b7></div></div></div>',1)])])),64))],2)):!$.mediaItems||!$.mediaItems.length?(e.openBlock(),e.createElementBlock("div",gg,[N[2]||(N[2]=e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","stroke-width":"1.5",stroke:"currentColor",class:"w-16 h-16 text-gray-400 mb-4"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round",d:"m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"})],-1)),N[3]||(N[3]=e.createElementVNode("h3",{class:"text-lg font-medium mb-2"}," No Media Items ",-1)),N[4]||(N[4]=e.createElementVNode("p",{class:"text-sm text-gray-600 dark:text-gray-400 mb-4"}," Upload some files to get started ",-1)),e.createElementVNode("button",{onClick:N[0]||(N[0]=B=>n("upload")),class:"px-3 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"}," Upload Media ")])):(e.openBlock(),e.createElementBlock("div",{key:2,class:e.normalizeClass(c.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList($.mediaItems,(B,P)=>(e.openBlock(),e.createElementBlock("div",{key:B.uuid,class:e.normalizeClass(["relative group",{"ring-2 ring-blue-500 ring-offset-2":r.value===P}]),draggable:$.reorderable,onDragstart:x=>u(x,B),onDragover:x=>m(x,P),onDragleave:p,onDrop:x=>f(x,P)},[$.selectionMode?(e.openBlock(),e.createElementBlock("div",yg,[e.createElementVNode("input",{type:"checkbox",checked:d(B),onChange:x=>n("toggleSelect",B),class:"w-5 h-5 bg-white dark:bg-gray-800 rounded cursor-pointer"},null,40,wg)])):e.createCommentVNode("",!0),$.$slots.badge?(e.openBlock(),e.createElementBlock("div",{key:1,class:e.normalizeClass(["absolute top-2 z-20",$.selectionMode?"left-10":"left-2"])},[e.renderSlot($.$slots,"badge",{media:B,index:P},void 0,!0)],2)):e.createCommentVNode("",!0),$.reorderable?(e.openBlock(),e.createElementBlock("div",kg,[...N[5]||(N[5]=[e.createElementVNode("div",{class:"bg-black/70 text-white p-2 rounded"},[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","stroke-width":"1.5",stroke:"currentColor",class:"w-4 h-4"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"})])],-1)])])):e.createCommentVNode("",!0),e.createElementVNode("div",{class:e.normalizeClass(["bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden h-full",{"ring-2 ring-blue-500":d(B)}])},[e.createElementVNode("div",{class:"relative aspect-square bg-gray-100 dark:bg-gray-700 overflow-hidden","data-media-id":B.uuid},[y(B)&&!b(B.uuid)?(e.openBlock(),e.createElementBlock("div",Eg,[...N[6]||(N[6]=[e.createElementVNode("div",{class:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"},null,-1)])])):e.createCommentVNode("",!0),y(B)&&b(B.uuid)?(e.openBlock(),e.createElementBlock("img",{key:1,src:v(B),alt:B.alt_text||B.file_name,class:"w-full h-full object-cover",loading:"lazy",onError:x=>T(x,B),onLoad:x=>I(x)},null,40,Sg)):(e.openBlock(),e.createElementBlock("div",Cg,[e.createElementVNode("div",xg,[e.createElementVNode("div",Ng,e.toDisplayString(_(B)),1),e.createElementVNode("p",Vg,e.toDisplayString(w(B.file_name)),1)])])),e.createElementVNode("div",Tg,[e.createElementVNode("button",{onClick:x=>n("preview",B),class:"p-2 bg-white/20 text-white rounded hover:bg-white/30",title:"Preview"},[...N[7]||(N[7]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","stroke-width":"1.5",stroke:"currentColor",class:"w-5 h-5"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round",d:"M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"}),e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})],-1)])],8,Bg),$.showEditButton&&y(B)?(e.openBlock(),e.createElementBlock("button",{key:0,onClick:x=>n("edit",B),class:"p-2 bg-white/20 text-white rounded hover:bg-white/30",title:"Edit"},[...N[8]||(N[8]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","stroke-width":"1.5",stroke:"currentColor",class:"w-5 h-5"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round",d:"M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10"})],-1)])],8,Mg)):e.createCommentVNode("",!0),e.createElementVNode("button",{onClick:x=>n("delete",B.uuid),class:"p-2 bg-red-500/20 text-red-300 rounded hover:bg-red-500/30",title:"Delete"},[...N[9]||(N[9]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","stroke-width":"1.5",stroke:"currentColor",class:"w-5 h-5"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round",d:"M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"})],-1)])],8,Ig)])],8,_g),e.createElementVNode("div",$g,[e.createElementVNode("h4",Fg,e.toDisplayString(B.file_name),1),e.createElementVNode("p",Dg,[e.createTextVNode(e.toDisplayString(h(B.size))+" ",1),B.width&&B.height?(e.openBlock(),e.createElementBlock("span",Ag," • "+e.toDisplayString(B.width)+"x"+e.toDisplayString(B.height),1)):e.createCommentVNode("",!0)]),B.caption?(e.openBlock(),e.createElementBlock("p",Rg,e.toDisplayString(B.caption),1)):e.createCommentVNode("",!0)])],2)],42,bg))),128))],2))}}),Pg=Ae(Lg,[["__scopeId","data-v-f0c343b7"]]),Ug={class:"model-media-manager"},Og=["accept","multiple"],zg={class:"flex items-center justify-between mb-4"},jg={key:0,class:"text-lg font-medium"},Wg={class:"flex gap-2"},Hg={key:0,class:"flex items-center justify-center py-8"},Zg={key:1,class:"flex flex-col items-center justify-center py-12 text-center border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg"},Gg={class:"text-gray-600 dark:text-gray-400"},Xg={class:"flex gap-2 mt-4"},Kg={key:0,class:"px-2 py-1 bg-blue-500 text-white text-xs font-medium rounded"},qg=e.defineComponent({__name:"ModelMediaManager",props:{mediableType:{},mediableId:{},collection:{},mode:{default:"user"},initialMedia:{},maxFiles:{},acceptedMimeTypes:{},maxFileSize:{},allowReorder:{type:Boolean,default:!0},allowUpload:{type:Boolean,default:!0},allowBrowse:{type:Boolean,default:!0},allowDetach:{type:Boolean,default:!0},allowEdit:{type:Boolean,default:!1},editMode:{default:"replace"},showPrimaryBadge:{type:Boolean,default:!0},emptyText:{default:"No media attached"},title:{default:"Media"}},emits:["loading","update:media","error","attach","detach","reorder","upload-progress","edit-complete"],setup(o,{emit:a}){const t=o,n=a,i=ja(),r=e.ref(!1),l=e.ref(!1),s=e.ref(!1),d=e.ref(!1),c=e.ref(null),u=e.ref(0),m=e.ref(null),p=e.ref(null),f=e.ref(null),h=e.ref(null),v=e.ref(null),y=e.ref(void 0),w=e.ref(null),_=e.ref(null),b=e.computed(()=>{if(t.maxFiles!==void 0)return Math.max(0,t.maxFiles-i.modelMedia.length)}),g=e.computed(()=>i.modelMedia.map(ue=>ue.uuid)),I=e.computed(()=>{if(!(!t.acceptedMimeTypes||t.acceptedMimeTypes.length===0))return t.acceptedMimeTypes.join(",")});function T(){ai({isAdmin:t.mode==="admin"})}async function $(ue){await(await G.toastController.create({message:ue,duration:3e3,color:"danger",position:"bottom"})).present()}async function N(){if(!l.value)if(l.value=!0,T(),i.setModelContext(t.mediableType,t.mediableId,t.collection),t.initialMedia&&t.initialMedia.length>0)i.modelMedia=[...t.initialMedia],n("update:media",i.modelMedia);else{r.value=!0,n("loading",!0);try{await i.fetchModelMedia(t.mediableType,t.mediableId,t.collection),n("update:media",i.modelMedia)}catch(ue){const le=ue instanceof Error?ue.message:"Failed to fetch media";n("error",{operation:"fetch",message:le,details:ue})}finally{r.value=!1,n("loading",!1)}}}e.watch(()=>i.modelMedia,ue=>{l.value&&n("update:media",ue)},{deep:!0}),e.watch(()=>[t.mediableType,t.mediableId,t.collection],()=>{l.value=!1,N()}),e.watch(()=>t.mode,()=>{T()}),e.onMounted(()=>{N()}),e.onUnmounted(()=>{i.clearModelContext()});function B(){return i.modelMedia.length>0}function P(){return t.maxFiles===void 0?!1:i.modelMedia.length>=t.maxFiles}function x(ue){var Z,k,F;if(!((Z=ue.mime_type)!=null&&Z.startsWith("image/")))return null;const le=ue.original_url||ue.url||((k=ue.conversion_urls)==null?void 0:k.preview)||((F=ue.conversion_urls)==null?void 0:F.thumb)||ue.thumbnail_url;return le&&le.trim()!==""?le:null}function M(){c.value=null,y.value=void 0,m.value=null,p.value=null,f.value=null,h.value=null,v.value=null}function E(){s.value=!0}function D(){var ue;(ue=_.value)==null||ue.click()}function j(){s.value=!1}async function L(ue){if(t.allowEdit&&x(ue)){M(),c.value=ue,u.value++;try{const le=i.getHttpClient(),Z=i.getEditorApiUrl(""),k=await le(`${Z.replace(/\/$/,"")}/editor/${ue.uuid}/edit`);if(!k.editable_source_url)throw new Error("Editor source URL missing from edit context");y.value=k.editable_source_url,m.value=k.editor_state??null,p.value=k.editor_document??null,f.value=k.editor_document_id??null,h.value=k.editor_document_revision_id??null,v.value=k.editor_document_revision_number??null}catch(le){M();const Z=le instanceof Error?`Unable to load image editor: ${le.message}`:"Unable to load image editor";await $(Z);return}d.value=!0}}function z(){d.value=!1,M()}async function C(ue){if(!c.value)throw new Error("No media selected for editing");const le=c.value,Z=t.editMode==="variant";try{w.value=null;const k=await i.saveEditedImage(le.uuid,ue,{asVariant:Z});Z||await i.detachMedia(t.mediableType,t.mediableId,le.uuid,t.collection),await i.attachMedia(t.mediableType,t.mediableId,[k.uuid],t.collection),n("edit-complete",{originalMedia:le,editedMedia:k,mode:t.editMode}),d.value=!1,M()}catch(k){const F=k instanceof Error?k.message:"Failed to save edited image";throw w.value=F,await $(F),k}}function A(ue){if(w.value===ue.message){w.value=null;return}$(ue.message)}async function O(ue){const le=ue.target,Z=le.files;if(!(!Z||Z.length===0)){for(let k=0;k<Z.length;k++){const F=Z[k];if(b.value!==void 0&&b.value<=0)break;if(t.acceptedMimeTypes&&t.acceptedMimeTypes.length>0&&!t.acceptedMimeTypes.includes(F.type)){n("error",{operation:"upload",message:`File type ${F.type} is not accepted`,details:{file:F.name}});continue}if(t.maxFileSize!==void 0&&F.size>t.maxFileSize){n("error",{operation:"upload",message:`File size exceeds limit of ${t.maxFileSize} bytes`,details:{file:F.name,size:F.size}});continue}n("upload-progress",{status:"uploading",progress:0,file:F});try{const W=await i.uploadFile(F,{collection:t.collection});W!=null&&W.uuid&&(await i.attachMedia(t.mediableType,t.mediableId,[W.uuid],t.collection),n("upload-progress",{status:"complete",progress:100,file:F}),n("attach",[W]))}catch(W){const J=W instanceof Error?W.message:"Upload failed";n("error",{operation:"upload",message:J,details:W}),n("upload-progress",{status:"error",progress:0,file:F,error:J})}}le.value=""}}async function K(ue){const le=ue.map(Z=>Z.uuid);try{await i.reorderMedia(t.mediableType,t.mediableId,le,t.collection),n("reorder",i.modelMedia)}catch(Z){const k=Z instanceof Error?Z.message:"Failed to reorder media";n("error",{operation:"reorder",message:k,details:Z}),await $(k)}}async function se(ue){const le=i.modelMedia.find(Z=>Z.uuid===ue);try{await i.detachMedia(t.mediableType,t.mediableId,ue,t.collection),le&&n("detach",le)}catch(Z){const k=Z instanceof Error?Z.message:"Failed to detach media";n("error",{operation:"detach",message:k,details:Z}),await $(k)}}async function xe(ue){s.value=!1;const le=ue.map(F=>F.uuid),Z=new Set(g.value);let k=Array.from(new Set(le)).filter(F=>!Z.has(F));if(b.value!==void 0&&k.length>b.value&&(k=k.slice(0,b.value)),k.length!==0)try{await i.attachMedia(t.mediableType,t.mediableId,k,t.collection);const F=i.modelMedia.filter(W=>k.includes(W.uuid));n("attach",F)}catch(F){const W=F instanceof Error?F.message:"Failed to attach media";n("error",{operation:"attach",message:W,details:F})}}return(ue,le)=>(e.openBlock(),e.createElementBlock("div",Ug,[e.createElementVNode("input",{ref_key:"fileInputRef",ref:_,type:"file",accept:I.value,multiple:b.value===void 0||b.value>1,class:"hidden","data-testid":"upload-input",onChange:O},null,40,Og),e.createElementVNode("div",zg,[ue.title?(e.openBlock(),e.createElementBlock("h3",jg,e.toDisplayString(ue.title),1)):e.createCommentVNode("",!0),e.createElementVNode("div",Wg,[ue.allowBrowse?(e.openBlock(),e.createBlock(e.unref(G.IonButton),{key:0,fill:"outline",size:"small",disabled:P(),"data-testid":"browse-button",onClick:E},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{slot:"start",icon:e.unref(ts)},null,8,["icon"]),le[1]||(le[1]=e.createTextVNode(" Browse ",-1))]),_:1},8,["disabled"])):e.createCommentVNode("",!0),ue.allowUpload?(e.openBlock(),e.createBlock(e.unref(G.IonButton),{key:1,fill:"solid",size:"small",disabled:P(),"data-testid":"upload-button",onClick:D},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{slot:"start",icon:e.unref(_c)},null,8,["icon"]),le[2]||(le[2]=e.createTextVNode(" Upload ",-1))]),_:1},8,["disabled"])):e.createCommentVNode("",!0)])]),r.value||e.unref(i).isLoadingModelMedia?(e.openBlock(),e.createElementBlock("div",Hg,[e.createVNode(e.unref(G.IonSpinner),{"data-testid":"spinner"})])):B()?(e.openBlock(),e.createBlock(Pg,{key:2,"media-items":e.unref(i).modelMedia,reorderable:!!ue.allowReorder,"is-loading":r.value||e.unref(i).isLoadingModelMedia,"show-edit-button":!!ue.allowEdit,"selection-mode":!1,onReorder:K,onDelete:se,onEdit:L},e.createSlots({_:2},[ue.showPrimaryBadge?{name:"badge",fn:e.withCtx(({index:Z})=>[Z===0?(e.openBlock(),e.createElementBlock("div",Kg," Primary ")):e.createCommentVNode("",!0)]),key:"0"}:void 0]),1032,["media-items","reorderable","is-loading","show-edit-button"])):(e.openBlock(),e.createElementBlock("div",Zg,[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(ts),class:"w-12 h-12 text-gray-400 mb-4"},null,8,["icon"]),e.createElementVNode("p",Gg,e.toDisplayString(ue.emptyText),1),e.createElementVNode("div",Xg,[ue.allowBrowse?(e.openBlock(),e.createBlock(e.unref(G.IonButton),{key:0,fill:"outline",size:"small","data-testid":"browse-button-empty",onClick:E},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{slot:"start",icon:e.unref(ts)},null,8,["icon"]),le[3]||(le[3]=e.createTextVNode(" Browse Library ",-1))]),_:1})):e.createCommentVNode("",!0),ue.allowUpload?(e.openBlock(),e.createBlock(e.unref(G.IonButton),{key:1,fill:"solid",size:"small","data-testid":"upload-button-empty",onClick:D},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{slot:"start",icon:e.unref(_c)},null,8,["icon"]),le[4]||(le[4]=e.createTextVNode(" Upload Files ",-1))]),_:1})):e.createCommentVNode("",!0)])])),e.createVNode(vg,e.mergeProps({"is-open":s.value,"selected-items":g.value,collection:ue.collection},b.value!==null&&b.value!==void 0?{maxSelection:b.value}:{},{onConfirm:xe,onClose:j}),null,16,["is-open","selected-items","collection"]),e.createVNode(vm,{modelValue:d.value,"onUpdate:modelValue":le[0]||(le[0]=Z=>d.value=Z),"initial-image":y.value,"initial-state":m.value,"initial-document":p.value,"initial-document-id":f.value,"initial-document-revision-id":h.value,"initial-document-revision-number":v.value,"session-key":u.value,"save-handler":C,onCancel:z,onError:A},null,8,["modelValue","initial-image","initial-state","initial-document","initial-document-id","initial-document-revision-id","initial-document-revision-number","session-key"])]))}}),Jg=Ae(qg,[["__scopeId","data-v-c58d85c8"]]),Yg={class:"existing-media-selector","data-testid":"existing-media-selector"},Qg={key:0,class:"existing-media-selector__status","data-testid":"existing-media-loading"},eb=["data-testid"],tb={class:"existing-media-selector__section-header"},ab={class:"existing-media-selector__section-title"},nb=["data-testid","aria-label","onClick"],ob={class:"existing-media-selector__grid"},ib=["data-testid","aria-label","aria-pressed","onClick"],rb=["src","alt"],lb={key:0,class:"existing-media-selector__selected-badge"},sb={key:1,class:"existing-media-selector__caption"},db={key:0,class:"existing-media-selector__section existing-media-selector__section--albums","data-testid":"existing-media-albums"},cb={class:"existing-media-selector__section-header"},ub={class:"existing-media-selector__section-title"},mb={class:"existing-media-selector__albums"},pb=["data-testid","aria-label","aria-pressed","onClick"],fb={class:"existing-media-selector__album-name"},hb={key:0,class:"existing-media-selector__album-count"},vb={class:"existing-media-selector__album-panel","data-testid":"existing-media-active-album"},gb={class:"existing-media-selector__section-header"},bb={class:"existing-media-selector__section-subtitle"},yb={key:0,class:"existing-media-selector__section-description"},wb={key:0,class:"existing-media-selector__status","data-testid":"existing-media-active-album-loading"},kb={key:1,class:"existing-media-selector__grid"},_b=["data-testid","aria-label","aria-pressed","onClick"],Eb=["src","alt"],Sb={key:0,class:"existing-media-selector__selected-badge"},Cb={key:1,class:"existing-media-selector__caption"},xb={key:2,class:"existing-media-selector__empty","data-testid":"existing-media-active-album-empty"},Nb={key:1,class:"existing-media-selector__empty","data-testid":"existing-media-empty"},Vb=e.defineComponent({__name:"ExistingMediaSelector",props:{sections:{default:()=>[]},albums:{default:()=>[]},selectedId:{default:null},activeAlbumId:{default:null},activeAlbumItems:{default:()=>[]},activeAlbumTitle:{},activeAlbumDescription:{},isLoading:{type:Boolean,default:!1},isAlbumLoading:{type:Boolean,default:!1},emptyMessage:{default:"No media available yet."},albumBrowseTitle:{default:"Browse Your Albums"},albumSectionTitle:{default:"Selected Album"},activeAlbumEmptyMessage:{default:"No media available in this album yet."}},emits:["select","update:activeAlbumId"],setup(o,{emit:a}){const t=o,n=a,i=e.reactive({}),r=e.computed(()=>t.sections.filter(g=>g.items.length>0)),l=e.computed(()=>t.albums.length>0),s=e.computed(()=>r.value.length>0||l.value),d=e.computed(()=>{if(typeof t.activeAlbumTitle=="string"&&t.activeAlbumTitle.trim().length>0)return t.activeAlbumTitle.trim();const g=t.albums.find(I=>I.id===t.activeAlbumId);return g!=null&&g.name.trim().length?g.name.trim():t.albumSectionTitle}),c=e.computed(()=>{if(typeof t.activeAlbumDescription=="string"&&t.activeAlbumDescription.trim().length>0)return t.activeAlbumDescription.trim();const g=t.albums.find(I=>I.id===t.activeAlbumId);return typeof(g==null?void 0:g.description)=="string"&&g.description.trim().length>0?g.description.trim():""});function u(g){const I=g.initialVisibleCount??6;return I>0?I:6}function m(g){return i[g]===!0}function p(g){i[g]=!m(g)}function f(g){return m(g.id)?g.items:g.items.slice(0,u(g))}function h(g){return g.items.length>u(g)}function v(g){n("select",g)}function y(g){n("update:activeAlbumId",g)}function w(g){var T;const I=(T=g.description)==null?void 0:T.trim();return I&&I.length>0?`Select ${I}`:"Select existing media"}function _(g,I){var $;const T=($=I.description)==null?void 0:$.trim();return typeof I.alt=="string"&&I.alt.trim().length>0?I.alt.trim():T&&T.length>0?T:g.title}function b(g){const I=typeof g.mediaCount=="number"?` with ${g.mediaCount} item${g.mediaCount===1?"":"s"}`:"";return`Browse album ${g.name}${I}`}return(g,I)=>(e.openBlock(),e.createElementBlock("div",Yg,[g.isLoading?(e.openBlock(),e.createElementBlock("div",Qg," Loading your media... ")):(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.value,T=>(e.openBlock(),e.createElementBlock("section",{key:T.id,class:"existing-media-selector__section","data-testid":`existing-media-section-${T.id}`},[e.createElementVNode("div",tb,[e.createElementVNode("h3",ab,e.toDisplayString(T.title),1),h(T)?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"existing-media-selector__toggle","data-testid":`existing-media-toggle-${T.id}`,"aria-label":m(T.id)?`Show fewer items from ${T.title}`:`Show more items from ${T.title}`,onClick:$=>p(T.id)},e.toDisplayString(m(T.id)?"See less":"See more"),9,nb)):e.createCommentVNode("",!0)]),e.createElementVNode("div",ob,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(f(T),$=>(e.openBlock(),e.createElementBlock("button",{key:$.id,type:"button",class:e.normalizeClass(["existing-media-selector__item",{"is-selected":g.selectedId===$.id}]),"data-testid":`existing-media-item-${T.id}-${$.id}`,"aria-label":w($),"aria-pressed":g.selectedId===$.id?"true":"false",onClick:N=>v($)},[e.createElementVNode("img",{class:"existing-media-selector__image",src:$.previewUrl,alt:_(T,$)},null,8,rb),g.selectedId===$.id?(e.openBlock(),e.createElementBlock("div",lb," Selected ")):e.createCommentVNode("",!0),$.description?(e.openBlock(),e.createElementBlock("div",sb,e.toDisplayString($.description),1)):e.createCommentVNode("",!0)],10,ib))),128))])],8,eb))),128)),l.value?(e.openBlock(),e.createElementBlock("section",db,[e.createElementVNode("div",cb,[e.createElementVNode("h3",ub,e.toDisplayString(g.albumBrowseTitle),1)]),e.createElementVNode("div",mb,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.albums,T=>(e.openBlock(),e.createElementBlock("button",{key:T.id,type:"button",class:e.normalizeClass(["existing-media-selector__album",{"is-active":g.activeAlbumId===T.id}]),"data-testid":`existing-media-album-${T.id}`,"aria-label":b(T),"aria-pressed":g.activeAlbumId===T.id?"true":"false",onClick:$=>y(T.id)},[e.createElementVNode("span",fb,e.toDisplayString(T.name),1),typeof T.mediaCount=="number"?(e.openBlock(),e.createElementBlock("span",hb,e.toDisplayString(T.mediaCount),1)):e.createCommentVNode("",!0)],10,pb))),128))]),e.createElementVNode("div",vb,[e.createElementVNode("div",gb,[e.createElementVNode("div",null,[e.createElementVNode("h4",bb,e.toDisplayString(d.value),1),c.value?(e.openBlock(),e.createElementBlock("p",yb,e.toDisplayString(c.value),1)):e.createCommentVNode("",!0)])]),g.isAlbumLoading?(e.openBlock(),e.createElementBlock("div",wb," Loading album... ")):g.activeAlbumItems.length>0?(e.openBlock(),e.createElementBlock("div",kb,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.activeAlbumItems,T=>(e.openBlock(),e.createElementBlock("button",{key:T.id,type:"button",class:e.normalizeClass(["existing-media-selector__item",{"is-selected":g.selectedId===T.id}]),"data-testid":`existing-media-item-album-${T.id}`,"aria-label":w(T),"aria-pressed":g.selectedId===T.id?"true":"false",onClick:$=>v(T)},[e.createElementVNode("img",{class:"existing-media-selector__image",src:T.previewUrl,alt:T.alt||T.description||d.value},null,8,Eb),g.selectedId===T.id?(e.openBlock(),e.createElementBlock("div",Sb," Selected ")):e.createCommentVNode("",!0),T.description?(e.openBlock(),e.createElementBlock("div",Cb,e.toDisplayString(T.description),1)):e.createCommentVNode("",!0)],10,_b))),128))])):(e.openBlock(),e.createElementBlock("div",xb,[e.renderSlot(g.$slots,"active-album-empty",{},()=>[e.createTextVNode(e.toDisplayString(g.activeAlbumEmptyMessage),1)],!0)]))])])):e.createCommentVNode("",!0),s.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",Nb,[e.renderSlot(g.$slots,"empty",{},()=>[e.createTextVNode(e.toDisplayString(g.emptyMessage),1)],!0)]))],64))]))}}),Tb=Ae(Vb,[["__scopeId","data-v-904abb6b"]]);function yr(o,a,t,n){if(t<=0||n<=0)return!1;try{return a.drawImage(o,0,0,t,n),!0}catch(i){return i instanceof DOMException&&i.name==="InvalidStateError",!1}}function Bb(o,a){return o?{display:"block",position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:a,opacity:"0",pointerEvents:"none"}:{display:"block",position:"relative",inset:"auto",width:"100%",height:"100%",objectFit:a,opacity:"1",pointerEvents:"auto"}}const Mb=["src","crossorigin"],Ib={class:"preview-controls"},$b=["aria-label"],Fb={class:"time-display"},Db={class:"current-time"},Ab={class:"total-time"},Rb={key:0,class:"fps-display"},Lb={key:0,class:"loading-overlay"},Pb={key:1,class:"error-overlay"},Ub=.1,Ob=e.defineComponent({__name:"VideoPreview",props:{source:{},filters:{},playhead:{},fallbackDuration:{default:0},isPlaying:{type:Boolean,default:!1},showFps:{type:Boolean,default:!1},targetFps:{default:30},fitMode:{default:"contain"},active:{type:Boolean,default:!0}},emits:["frame-update","play-pause","duration-change","error"],setup(o,{expose:a,emit:t}){const{ColorMatrixFilter:n,BlurFilter:i}=na,r=o,l=t,s=e.ref(),d=e.ref(),c=e.ref(),u=e.ref(!0),m=e.ref(),p=e.ref(0),f=e.ref(0),h=e.ref(!1);let v,y,w=null,_=null,b=null,g=[],I="",T=null,$=0,N=0,B=0,P=0,x=!1,M=0,E=0,D,j=null,L=!1,z=!1,C=0;const A=e.computed(()=>r.source&&typeof r.source=="string"?r.source:""),O=e.computed(()=>{const Ce=A.value;if(!(!Ce||Ce.startsWith("blob:")))return"anonymous"}),K=e.computed(()=>Bb(h.value,r.fitMode));function se(Ce){return typeof Ce=="number"&&Number.isFinite(Ce)&&Ce>=0?Ce:Number.isFinite(r.fallbackDuration)&&r.fallbackDuration>0?r.fallbackDuration:0}function xe(Ce){const Ve=se(Ce.duration);return Ve<=0?!1:Ce.currentTime>=Math.max(0,Ve-Ub)}async function ue(){var Ce,Ve;if(!z&&d.value&&!v&&!(!c.value||c.value.readyState<3)){z=!0;try{m.value=void 0;let Le=((Ce=s.value)==null?void 0:Ce.clientWidth)||800,nt=((Ve=s.value)==null?void 0:Ve.clientHeight)||450;if((Le<=0||nt<=0)&&(Le=c.value.videoWidth||800,nt=c.value.videoHeight||450),v=new na.Application,await v.init({width:Le,height:nt,background:0,resolution:window.devicePixelRatio||1,autoDensity:!0,antialias:!0,powerPreference:"high-performance",preserveDrawingBuffer:!0}),d.value.appendChild(v.canvas),c.value){if(c.value.videoWidth===0||c.value.videoHeight===0){setTimeout(()=>{c.value&&c.value.videoWidth>0&&!v&&ue()},100),v&&(v.destroy(!0),v=null);return}if($=c.value.videoWidth,N=c.value.videoHeight,_=document.createElement("canvas"),_.width=$,_.height=N,b=_.getContext("2d"),!b)throw new Error("Unable to create 2D canvas context for video preview");const Ge=yr(c.value,b,$,N),Je=na.Texture.from(_);w=Je.source,y=new na.Sprite(Je),y.visible=!0,y.alpha=1,Ct(),v.stage.addChild(y),v.renderer&&!v.renderer.destroyed&&v.render()}F(),r.targetFps<60?le():v.ticker.add(Z),h.value=!0,"ResizeObserver"in window&&(T=new ResizeObserver(Ge=>{x||(x=!0,requestAnimationFrame(()=>{x=!1;const Je=Ge[Ge.length-1],{width:_t,height:ht}=Je.contentRect;if(_t<=0||ht<=0)return;const Wt=Math.round(_t),Pe=Math.round(ht);Wt===B&&Pe===P||(B=Wt,P=Pe,Ct())}))}),T.observe(s.value)),r.filters&&r.filters.length>0&&F(),r.showFps&&Oe(),C=0}catch{if(Pt(),!L&&!!c.value&&c.value.readyState>=2&&c.value.videoWidth>0&&c.value.videoHeight>0&&C<2){C+=1,window.setTimeout(()=>{L||ue()},C*150);return}m.value="Failed to initialize video preview",l("error",m.value)}finally{z=!1}}}function le(){const Ce=1e3/r.targetFps;let Ve=performance.now();function Le(){if(L||!v)return;const nt=performance.now(),Ge=nt-Ve;Ge>=Ce&&(Z(),Ve=nt-Ge%Ce),j=requestAnimationFrame(Le)}j=requestAnimationFrame(Le)}function Z(){if(!(!v||!y||L)&&r.active)try{b&&_&&w&&c.value&&(c.value.readyState>=2&&yr(c.value,b,_.width,_.height)&&w.update(),c.value.paused||l("frame-update",ce())),r.showFps&&E++,v.renderer&&!v.renderer.destroyed&&v.render()}catch{L=!0}}function k(){for(const Ce of g)try{Ce.destroy()}catch{}g=[]}function F(){if(y){if(!r.filters||r.filters.length===0){y.filters=null,k();return}k(),r.filters.forEach(Ce=>{const Ve=W(Ce);Ve&&g.push(Ve)}),y.filters=g.length>0?g:null,I=JSON.stringify(r.filters),v&&v.render()}}function W(Ce){const Ve=Ce.filterId,Le=Ce.params||{},nt=la.getFilter(Ve);if(nt&&!la.isFilterCompatibleWithMedia(Ve,"video"))return null;if(nt&&nt.createFilter)try{return nt.createFilter(Le)}catch{}const Ge=(Je,_t,ht)=>Math.min(ht,Math.max(_t,Je));switch(Ve){case"brightness":{const Je=new n,_t=Ge(typeof Le.brightness=="number"?Le.brightness:typeof Le.value=="number"?Le.value:1,0,5);return Je.brightness(_t,!0),Je}case"contrast":{const Je=new n,_t=Ge(typeof Le.contrast=="number"?Le.contrast:typeof Le.value=="number"?Le.value:1,0,5);return Je.contrast(_t,!0),Je}case"saturation":{const Je=new n,_t=Ge(typeof Le.saturation=="number"?Le.saturation:typeof Le.value=="number"?Le.value:1,0,5);return Je.saturate(_t,!0),Je}case"hue":{const Je=new n,_t=Ge(typeof Le.value=="number"?Le.value:0,-180,180);return Je.hue(_t,!0),Je}case"gaussian-blur":case"blur":{const Je=Ge(typeof Le.blur=="number"?Le.blur:typeof Le.value=="number"?Le.value:2,0,10);return new i(Je)}case"grayscale":{const Je=new n;return Je.desaturate(),Je}case"sepia":case"color-matrix":{const Je=new n;return Je.sepia(!0),Je}case"vignette":{const Je=typeof Le.value=="number"?Le.value:.3;return J(Ge(Je,0,1))}default:return null}}function J(Ce){const Ve=`
7
+ precision mediump float;
8
+ varying vec2 vTextureCoord;
9
+ uniform sampler2D uSampler;
10
+ uniform float strength;
11
+ void main(void){
12
+ vec2 uv = vTextureCoord - 0.5;
13
+ float dist = length(uv) * 2.0;
14
+ float vignette = smoothstep(1.0, 1.0 - strength, dist);
15
+ vec4 color = texture2D(uSampler, vTextureCoord);
16
+ gl_FragColor = vec4(color.rgb * (1.0 - vignette), color.a);
17
+ }
18
+ `;return new na.Filter(void 0,Ve,{strength:Ce})}function ce(){var Ve;return!v||!y?null:{dataUrl:v.canvas.toDataURL("image/jpeg",.8),timestamp:((Ve=c.value)==null?void 0:Ve.currentTime)||0,width:$||0,height:N||0}}function Ue(){var Ce;p.value=se((Ce=c.value)==null?void 0:Ce.duration),l("duration-change",p.value)}function be(){u.value=!1,m.value=void 0}function _e(){u.value&&(u.value=!1),!h.value&&r.active?ue():h.value}function ye(){var Ve,Le,nt;const Ce=((Ve=c.value)==null?void 0:Ve.currentTime)||0;l("frame-update",{dataUrl:null,timestamp:Ce,width:((Le=c.value)==null?void 0:Le.videoWidth)||0,height:((nt=c.value)==null?void 0:nt.videoHeight)||0})}function Ne(){c.value&&(c.value.currentTime=0),l("play-pause")}function Se(Ce){var Le;const Ve=Ce.target;if(Ve!=null&&Ve.error)switch(Ve.error.code){case Ve.error.MEDIA_ERR_ABORTED:m.value="Video playback aborted";break;case Ve.error.MEDIA_ERR_NETWORK:m.value="Network error loading video";break;case Ve.error.MEDIA_ERR_DECODE:m.value="Video format not supported";break;case Ve.error.MEDIA_ERR_SRC_NOT_SUPPORTED:m.value=`Video source not supported: ${(Le=Ve.src)==null?void 0:Le.substring(0,100)}`;break;default:m.value="Failed to load video"}else m.value="Failed to load video";l("error",m.value),u.value=!1}function Re(Ce){c.value&&(c.value.currentTime=Math.max(0,Math.min(Ce,p.value)))}function Oe(){D=window.setInterval(()=>{const Ce=performance.now(),Ve=Ce-M;f.value=Math.round(E*1e3/Ve),E=0,M=Ce},1e3)}function it(Ce){if(!Number.isFinite(Ce)||Ce<0)return"00:00";const Ve=Math.floor(Ce/60),Le=Math.floor(Ce%60);return`${Ve.toString().padStart(2,"0")}:${Le.toString().padStart(2,"0")}`}function rt(){m.value=void 0,u.value=!0,C=0,Pt(),c.value&&c.value.load()}function Pt(){if(T&&(T.disconnect(),T=null),j&&(cancelAnimationFrame(j),j=null),v!=null&&v.ticker&&(v.ticker.stop(),v.ticker.remove(Z)),v)try{v.destroy(!0,{children:!0,texture:!0})}catch{}d.value&&(d.value.innerHTML=""),k(),v=null,y=null,w=null,_=null,b=null,h.value=!1,x=!1,I=""}function bt(){v&&(x||(x=!0,requestAnimationFrame(()=>{x=!1,Ct()})))}function Ct(){if(!v||!y||!$||!N||!s.value)return;const Ce=Math.round(s.value.clientWidth),Ve=Math.round(s.value.clientHeight);if(Ce<=0||Ve<=0)return;v.renderer.resize(Ce,Ve);const Le=v.screen.width/$,nt=v.screen.height/N;let Ge=1;switch(r.fitMode){case"cover":Ge=Math.max(Le,nt);break;case"none":Ge=1;break;case"contain":default:Ge=Math.min(Le,nt);break}y.scale.set(Ge),y.anchor.set(.5),y.position.set(v.screen.width/2,v.screen.height/2),y.visible=!0,y.alpha=1,v.renderer&&!v.renderer.destroyed&&v.render()}e.watch(()=>r.filters,()=>{h.value&&F()},{deep:!0}),e.watch(()=>r.active,async Ce=>{if(Ce&&!v&&c.value&&c.value.readyState>=2){await ue();return}v&&(Ce&&(await e.nextTick(),s.value&&s.value.getBoundingClientRect(),y&&b&&_&&w&&(c.value&&c.value.readyState>=2&&yr(c.value,b,_.width,_.height)&&w.update(),Ct(),v.renderer&&!v.renderer.destroyed&&v.render())),r.targetFps>=60&&v.ticker&&(Ce?v.ticker.start():v.ticker.stop()))}),e.watch(A,Ce=>{Ce?(u.value=!0,m.value=void 0,e.nextTick(()=>{c.value&&c.value.load()})):(u.value=!1,m.value="No video source provided")},{immediate:!0});async function mt(){if(c.value){m.value=void 0,xe(c.value)&&(c.value.currentTime=0);try{await c.value.play();return}catch{if(!c.value.muted){c.value.muted=!0;try{await c.value.play();return}catch{}}}m.value="Unable to start preview playback",l("error",m.value)}}e.watch(()=>r.isPlaying,Ce=>{c.value&&(Ce?mt():c.value.pause())}),e.watch(()=>r.playhead,Ce=>{c.value&&Math.abs(c.value.currentTime-Ce)>.5&&Re(Ce)}),e.watch(()=>r.fitMode,()=>{Ct()}),e.onMounted(()=>{L=!1,e.nextTick(()=>{s.value&&s.value.getBoundingClientRect(),c.value}),window.addEventListener("resize",bt),M=performance.now(),e.nextTick(()=>{c.value&&c.value.readyState>=2&&!h.value?ue():c.value&&c.value.src&&c.value.readyState===0&&c.value.load()})}),e.onUnmounted(()=>{if(L=!0,j&&(cancelAnimationFrame(j),j=null),window.removeEventListener("resize",bt),T&&(T.disconnect(),T=null),D&&clearInterval(D),v&&v.ticker&&(v.ticker.stop(),v.ticker.remove(Z)),v){try{v.destroy(!0,{children:!0,texture:!0})}catch{}v=null}g.forEach(Ce=>{try{Ce.destroy()}catch{}}),g=[],y=null,w=null,_=null,b=null,c.value&&(c.value.pause(),c.value.removeAttribute("src"),c.value.load())});async function pt(Ce){if(!await Nt()||!c.value||!b||!_||!w)return null;const Le=c.value,nt=Number.isFinite(p.value)&&p.value>0?p.value:Number.isFinite(Le.duration)&&Le.duration>0?Le.duration:0,Ge=Math.max(0,Math.min(Ce,nt));return await new Promise(_t=>{let ht=!1,Wt=0;const Pe=()=>{ht||(ht=!0,Le.removeEventListener("seeked",Ht),window.clearTimeout(Wt),_t())},Ht=()=>{Pe()},Zt=Number.isFinite(Le.currentTime)?Le.currentTime:0;if(Math.abs(Zt-Ge)<.016){requestAnimationFrame(()=>Pe());return}Le.addEventListener("seeked",Ht),Wt=window.setTimeout(()=>Pe(),700),Le.currentTime=Ge}),yr(Le,b,_.width,_.height)?(w.update(),v.render(),v.canvas):null}async function Nt(){if(!c.value)return!1;if(!v){if(!(c.value.readyState>=2))return!1;await ue()}if(!v||!y||!b||!_||!w)return!1;if(r.filters&&r.filters.length>0){const Ce=y.filters,Ve=Array.isArray(Ce)?Ce.length:0,nt=JSON.stringify(r.filters)!==I;(Ve===0||Ve!==r.filters.length||nt)&&F()}return await e.nextTick(),await new Promise(Ce=>{requestAnimationFrame(()=>Ce())}),!0}return a({captureFrameAt:pt,ensureReadyForCapture:Nt,duration:p,pixiCanvas:e.computed(()=>v?v.canvas:null),videoElement:e.computed(()=>c.value??null)}),(Ce,Ve)=>(e.openBlock(),e.createElementBlock("div",{class:"video-preview",ref_key:"containerRef",ref:s},[e.createElementVNode("div",{class:"canvas-container",ref_key:"canvasContainerRef",ref:d},null,512),e.createElementVNode("video",{ref_key:"videoRef",ref:c,src:A.value,onLoadedmetadata:Ue,onLoadeddata:be,onCanplay:_e,onTimeupdate:ye,onEnded:Ne,onError:Se,style:e.normalizeStyle(K.value),crossorigin:O.value,preload:"auto",playsinline:"",controls:""},null,44,Mb),e.createElementVNode("div",Ib,[e.createElementVNode("button",{class:"play-button",onClick:Ve[0]||(Ve[0]=Le=>Ce.$emit("play-pause")),"aria-label":Ce.isPlaying?"Pause":"Play"},[e.createVNode(e.unref(G.IonIcon),{icon:Ce.isPlaying?e.unref(ym):e.unref(wm)},null,8,["icon"])],8,$b),e.createElementVNode("div",Fb,[e.createElementVNode("span",Db,e.toDisplayString(it(Ce.playhead)),1),Ve[1]||(Ve[1]=e.createElementVNode("span",{class:"separator"},"/",-1)),e.createElementVNode("span",Ab,e.toDisplayString(it(p.value)),1)]),Ce.showFps?(e.openBlock(),e.createElementBlock("div",Rb,e.toDisplayString(f.value)+" FPS ",1)):e.createCommentVNode("",!0)]),u.value?(e.openBlock(),e.createElementBlock("div",Lb,[e.createVNode(e.unref(G.IonSpinner),{name:"crescent"}),Ve[2]||(Ve[2]=e.createElementVNode("p",null,"Loading video...",-1))])):e.createCommentVNode("",!0),m.value?(e.openBlock(),e.createElementBlock("div",Pb,[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(pd)},null,8,["icon"]),e.createElementVNode("p",null,e.toDisplayString(m.value),1),e.createElementVNode("button",{onClick:rt},"Retry")])):e.createCommentVNode("",!0)],512))}}),Cs=Ae(Ob,[["__scopeId","data-v-dd1744f4"]]);var vd=(o,a,t)=>{if(!a.has(o))throw TypeError("Cannot "+t)},ee=(o,a,t)=>(vd(o,a,"read from private field"),t?t.call(o):a.get(o)),ft=(o,a,t)=>{if(a.has(o))throw TypeError("Cannot add the same private member more than once");a instanceof WeakSet?a.add(o):a.set(o,t)},ma=(o,a,t,n)=>(vd(o,a,"write to private field"),a.set(o,t),t),zb=(o,a,t,n)=>({set _(i){ma(o,a,i)},get _(){return ee(o,a,n)}}),kt=(o,a,t)=>(vd(o,a,"access private method"),t),St=new Uint8Array(8),En=new DataView(St.buffer),ra=o=>[(o%256+256)%256],Dt=o=>(En.setUint16(0,o,!1),[St[0],St[1]]),jb=o=>(En.setInt16(0,o,!1),[St[0],St[1]]),Sm=o=>(En.setUint32(0,o,!1),[St[1],St[2],St[3]]),Xe=o=>(En.setUint32(0,o,!1),[St[0],St[1],St[2],St[3]]),Wb=o=>(En.setInt32(0,o,!1),[St[0],St[1],St[2],St[3]]),Fo=o=>(En.setUint32(0,Math.floor(o/2**32),!1),En.setUint32(4,o,!1),[St[0],St[1],St[2],St[3],St[4],St[5],St[6],St[7]]),gd=o=>(En.setInt16(0,2**8*o,!1),[St[0],St[1]]),wn=o=>(En.setInt32(0,2**16*o,!1),[St[0],St[1],St[2],St[3]]),ns=o=>(En.setInt32(0,2**30*o,!1),[St[0],St[1],St[2],St[3]]),qa=(o,a=!1)=>{let t=Array(o.length).fill(null).map((n,i)=>o.charCodeAt(i));return a&&t.push(0),t},Kr=o=>o&&o[o.length-1],bd=o=>{let a;for(let t of o)(!a||t.presentationTimestamp>a.presentationTimestamp)&&(a=t);return a},_n=(o,a,t=!0)=>{let n=o*a;return t?Math.round(n):n},Cm=o=>{let a=o*(Math.PI/180),t=Math.cos(a),n=Math.sin(a);return[t,n,0,-n,t,0,0,0,1]},xm=Cm(0),Nm=o=>[wn(o[0]),wn(o[1]),ns(o[2]),wn(o[3]),wn(o[4]),ns(o[5]),wn(o[6]),wn(o[7]),ns(o[8])],Ai=o=>!o||typeof o!="object"?o:Array.isArray(o)?o.map(Ai):Object.fromEntries(Object.entries(o).map(([a,t])=>[a,Ai(t)])),oi=o=>o>=0&&o<2**32,ia=(o,a,t)=>({type:o,contents:a&&new Uint8Array(a.flat(10)),children:t}),Xt=(o,a,t,n,i)=>ia(o,[ra(a),Sm(t),n??[]],i),Hb=o=>{let a=512;return o.fragmented?ia("ftyp",[qa("iso5"),Xe(a),qa("iso5"),qa("iso6"),qa("mp41")]):ia("ftyp",[qa("isom"),Xe(a),qa("isom"),o.holdsAvc?qa("avc1"):[],qa("mp41")])},xs=o=>({type:"mdat",largeSize:o}),Zb=o=>({type:"free",size:o}),Dr=(o,a,t=!1)=>ia("moov",null,[Gb(a,o),...o.map(n=>Xb(n,a)),t?Cy(o):null]),Gb=(o,a)=>{let t=_n(Math.max(0,...a.filter(l=>l.samples.length>0).map(l=>{const s=bd(l.samples);return s.presentationTimestamp+s.duration})),Ts),n=Math.max(...a.map(l=>l.id))+1,i=!oi(o)||!oi(t),r=i?Fo:Xe;return Xt("mvhd",+i,0,[r(o),r(o),Xe(Ts),r(t),wn(1),gd(1),Array(10).fill(0),Nm(xm),Array(24).fill(0),Xe(n)])},Xb=(o,a)=>ia("trak",null,[Kb(o,a),qb(o,a)]),Kb=(o,a)=>{let t=bd(o.samples),n=_n(t?t.presentationTimestamp+t.duration:0,Ts),i=!oi(a)||!oi(n),r=i?Fo:Xe,l;return o.info.type==="video"?l=typeof o.info.rotation=="number"?Cm(o.info.rotation):o.info.rotation:l=xm,Xt("tkhd",+i,3,[r(a),r(a),Xe(o.id),Xe(0),r(n),Array(8).fill(0),Dt(0),Dt(0),gd(o.info.type==="audio"?1:0),Dt(0),Nm(l),wn(o.info.type==="video"?o.info.width:0),wn(o.info.type==="video"?o.info.height:0)])},qb=(o,a)=>ia("mdia",null,[Jb(o,a),Yb(o.info.type==="video"?"vide":"soun"),Qb(o)]),Jb=(o,a)=>{let t=bd(o.samples),n=_n(t?t.presentationTimestamp+t.duration:0,o.timescale),i=!oi(a)||!oi(n),r=i?Fo:Xe;return Xt("mdhd",+i,0,[r(a),r(a),Xe(o.timescale),r(n),Dt(21956),Dt(0)])},Yb=o=>Xt("hdlr",0,0,[qa("mhlr"),qa(o),Xe(0),Xe(0),Xe(0),qa("mp4-muxer-hdlr",!0)]),Qb=o=>ia("minf",null,[o.info.type==="video"?ey():ty(),ay(),iy(o)]),ey=()=>Xt("vmhd",0,1,[Dt(0),Dt(0),Dt(0),Dt(0)]),ty=()=>Xt("smhd",0,0,[Dt(0),Dt(0)]),ay=()=>ia("dinf",null,[ny()]),ny=()=>Xt("dref",0,0,[Xe(1)],[oy()]),oy=()=>Xt("url ",0,1),iy=o=>{const a=o.compositionTimeOffsetTable.length>1||o.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return ia("stbl",null,[ry(o),yy(o),wy(o),ky(o),_y(o),Ey(o),a?Sy(o):null])},ry=o=>Xt("stsd",0,0,[Xe(1)],[o.info.type==="video"?ly(Dy[o.info.codec],o):vy(Ry[o.info.codec],o)]),ly=(o,a)=>ia(o,[Array(6).fill(0),Dt(1),Dt(0),Dt(0),Array(12).fill(0),Dt(a.info.width),Dt(a.info.height),Xe(4718592),Xe(4718592),Xe(0),Dt(1),Array(32).fill(0),Dt(24),jb(65535)],[Ay[a.info.codec](a),a.info.decoderConfig.colorSpace?uy(a):null]),sy={bt709:1,bt470bg:5,smpte170m:6},dy={bt709:1,smpte170m:6,"iec61966-2-1":13},cy={rgb:0,bt709:1,bt470bg:5,smpte170m:6},uy=o=>ia("colr",[qa("nclx"),Dt(sy[o.info.decoderConfig.colorSpace.primaries]),Dt(dy[o.info.decoderConfig.colorSpace.transfer]),Dt(cy[o.info.decoderConfig.colorSpace.matrix]),ra((o.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),my=o=>o.info.decoderConfig&&ia("avcC",[...new Uint8Array(o.info.decoderConfig.description)]),py=o=>o.info.decoderConfig&&ia("hvcC",[...new Uint8Array(o.info.decoderConfig.description)]),fy=o=>{if(!o.info.decoderConfig)return null;let a=o.info.decoderConfig;if(!a.colorSpace)throw new Error("'colorSpace' is required in the decoder config for VP9.");let t=a.codec.split("."),n=Number(t[1]),i=Number(t[2]),s=(Number(t[3])<<4)+(0<<1)+Number(a.colorSpace.fullRange);return Xt("vpcC",1,0,[ra(n),ra(i),ra(s),ra(2),ra(2),ra(2),Dt(0)])},hy=()=>{let t=(1<<7)+1;return ia("av1C",[t,0,0,0])},vy=(o,a)=>ia(o,[Array(6).fill(0),Dt(1),Dt(0),Dt(0),Xe(0),Dt(a.info.numberOfChannels),Dt(16),Dt(0),Dt(0),wn(a.info.sampleRate)],[Ly[a.info.codec](a)]),gy=o=>{let a=new Uint8Array(o.info.decoderConfig.description);return Xt("esds",0,0,[Xe(58753152),ra(32+a.byteLength),Dt(1),ra(0),Xe(75530368),ra(18+a.byteLength),ra(64),ra(21),Sm(0),Xe(130071),Xe(130071),Xe(92307584),ra(a.byteLength),...a,Xe(109084800),ra(1),ra(2)])},by=o=>{var i;let a=3840,t=0;const n=(i=o.info.decoderConfig)==null?void 0:i.description;if(n){if(n.byteLength<18)throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");const r=ArrayBuffer.isView(n)?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n);a=r.getUint16(10,!0),t=r.getInt16(14,!0)}return ia("dOps",[ra(0),ra(o.info.numberOfChannels),Dt(a),Xe(o.info.sampleRate),gd(t),ra(0)])},yy=o=>Xt("stts",0,0,[Xe(o.timeToSampleTable.length),o.timeToSampleTable.map(a=>[Xe(a.sampleCount),Xe(a.sampleDelta)])]),wy=o=>{if(o.samples.every(t=>t.type==="key"))return null;let a=[...o.samples.entries()].filter(([,t])=>t.type==="key");return Xt("stss",0,0,[Xe(a.length),a.map(([t])=>Xe(t+1))])},ky=o=>Xt("stsc",0,0,[Xe(o.compactlyCodedChunkTable.length),o.compactlyCodedChunkTable.map(a=>[Xe(a.firstChunk),Xe(a.samplesPerChunk),Xe(1)])]),_y=o=>Xt("stsz",0,0,[Xe(0),Xe(o.samples.length),o.samples.map(a=>Xe(a.size))]),Ey=o=>o.finalizedChunks.length>0&&Kr(o.finalizedChunks).offset>=2**32?Xt("co64",0,0,[Xe(o.finalizedChunks.length),o.finalizedChunks.map(a=>Fo(a.offset))]):Xt("stco",0,0,[Xe(o.finalizedChunks.length),o.finalizedChunks.map(a=>Xe(a.offset))]),Sy=o=>Xt("ctts",0,0,[Xe(o.compositionTimeOffsetTable.length),o.compositionTimeOffsetTable.map(a=>[Xe(a.sampleCount),Xe(a.sampleCompositionTimeOffset)])]),Cy=o=>ia("mvex",null,o.map(xy)),xy=o=>Xt("trex",0,0,[Xe(o.id),Xe(1),Xe(0),Xe(0),Xe(0)]),Vc=(o,a)=>ia("moof",null,[Ny(o),...a.map(Vy)]),Ny=o=>Xt("mfhd",0,0,[Xe(o)]),Vm=o=>{let a=0,t=0,n=0,i=0,r=o.type==="delta";return t|=+r,r?a|=1:a|=2,a<<24|t<<16|n<<8|i},Vy=o=>ia("traf",null,[Ty(o),By(o),My(o)]),Ty=o=>{let a=0;a|=8,a|=16,a|=32,a|=131072;let t=o.currentChunk.samples[1]??o.currentChunk.samples[0],n={duration:t.timescaleUnitsToNextSample,size:t.size,flags:Vm(t)};return Xt("tfhd",0,a,[Xe(o.id),Xe(n.duration),Xe(n.size),Xe(n.flags)])},By=o=>Xt("tfdt",1,0,[Fo(_n(o.currentChunk.startTimestamp,o.timescale))]),My=o=>{let a=o.currentChunk.samples.map(v=>v.timescaleUnitsToNextSample),t=o.currentChunk.samples.map(v=>v.size),n=o.currentChunk.samples.map(Vm),i=o.currentChunk.samples.map(v=>_n(v.presentationTimestamp-v.decodeTimestamp,o.timescale)),r=new Set(a),l=new Set(t),s=new Set(n),d=new Set(i),c=s.size===2&&n[0]!==n[1],u=r.size>1,m=l.size>1,p=!c&&s.size>1,f=d.size>1||[...d].some(v=>v!==0),h=0;return h|=1,h|=4*+c,h|=256*+u,h|=512*+m,h|=1024*+p,h|=2048*+f,Xt("trun",1,h,[Xe(o.currentChunk.samples.length),Xe(o.currentChunk.offset-o.currentChunk.moofOffset||0),c?Xe(n[0]):[],o.currentChunk.samples.map((v,y)=>[u?Xe(a[y]):[],m?Xe(t[y]):[],p?Xe(n[y]):[],f?Wb(i[y]):[]])])},Iy=o=>ia("mfra",null,[...o.map($y),Fy()]),$y=(o,a)=>Xt("tfra",1,0,[Xe(o.id),Xe(63),Xe(o.finalizedChunks.length),o.finalizedChunks.map(n=>[Fo(_n(n.startTimestamp,o.timescale)),Fo(n.moofOffset),Xe(a+1),Xe(1),Xe(1)])]),Fy=()=>Xt("mfro",0,0,[Xe(0)]),Dy={avc:"avc1",hevc:"hvc1",vp9:"vp09",av1:"av01"},Ay={avc:my,hevc:py,vp9:fy,av1:hy},Ry={aac:"mp4a",opus:"Opus"},Ly={aac:gy,opus:by},hl=class{},yd=class extends hl{constructor(){super(...arguments),this.buffer=null}},Tm=class extends hl{constructor(o){if(super(),this.options=o,typeof o!="object")throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");if(o.onData){if(typeof o.onData!="function")throw new TypeError("options.onData, when provided, must be a function.");if(o.onData.length<2)throw new TypeError("options.onData, when provided, must be a function that takes in at least two arguments (data and position). Ignoring the position argument, which specifies the byte offset at which the data is to be written, can lead to broken outputs.")}if(o.chunked!==void 0&&typeof o.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(o.chunkSize!==void 0&&(!Number.isInteger(o.chunkSize)||o.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.")}},Py=class extends hl{constructor(o,a){if(super(),this.stream=o,this.options=a,!(o instanceof FileSystemWritableFileStream))throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");if(a!==void 0&&typeof a!="object")throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");if(a&&a.chunkSize!==void 0&&(!Number.isInteger(a.chunkSize)||a.chunkSize<=0))throw new TypeError("options.chunkSize, when provided, must be a positive integer")}},_o,Ko,Bm=class{constructor(){this.pos=0,ft(this,_o,new Uint8Array(8)),ft(this,Ko,new DataView(ee(this,_o).buffer)),this.offsets=new WeakMap}seek(o){this.pos=o}writeU32(o){ee(this,Ko).setUint32(0,o,!1),this.write(ee(this,_o).subarray(0,4))}writeU64(o){ee(this,Ko).setUint32(0,Math.floor(o/2**32),!1),ee(this,Ko).setUint32(4,o,!1),this.write(ee(this,_o).subarray(0,8))}writeAscii(o){for(let a=0;a<o.length;a++)ee(this,Ko).setUint8(a%8,o.charCodeAt(a)),a%8===7&&this.write(ee(this,_o));o.length%8!==0&&this.write(ee(this,_o).subarray(0,o.length%8))}writeBox(o){if(this.offsets.set(o,this.pos),o.contents&&!o.children)this.writeBoxHeader(o,o.size??o.contents.byteLength+8),this.write(o.contents);else{let a=this.pos;if(this.writeBoxHeader(o,0),o.contents&&this.write(o.contents),o.children)for(let i of o.children)i&&this.writeBox(i);let t=this.pos,n=o.size??t-a;this.seek(a),this.writeBoxHeader(o,n),this.seek(t)}}writeBoxHeader(o,a){this.writeU32(o.largeSize?1:a),this.writeAscii(o.type),o.largeSize&&this.writeU64(a)}measureBoxHeader(o){return 8+(o.largeSize?8:0)}patchBox(o){let a=this.pos;this.seek(this.offsets.get(o)),this.writeBox(o),this.seek(a)}measureBox(o){if(o.contents&&!o.children)return this.measureBoxHeader(o)+o.contents.byteLength;{let a=this.measureBoxHeader(o);if(o.contents&&(a+=o.contents.byteLength),o.children)for(let t of o.children)t&&(a+=this.measureBox(t));return a}}};_o=new WeakMap;Ko=new WeakMap;var Ar,Mo,Xi,Ii,Rr,Ns,Uy=class extends Bm{constructor(o){super(),ft(this,Rr),ft(this,Ar,void 0),ft(this,Mo,new ArrayBuffer(2**16)),ft(this,Xi,new Uint8Array(ee(this,Mo))),ft(this,Ii,0),ma(this,Ar,o)}write(o){kt(this,Rr,Ns).call(this,this.pos+o.byteLength),ee(this,Xi).set(o,this.pos),this.pos+=o.byteLength,ma(this,Ii,Math.max(ee(this,Ii),this.pos))}finalize(){kt(this,Rr,Ns).call(this,this.pos),ee(this,Ar).buffer=ee(this,Mo).slice(0,Math.max(ee(this,Ii),this.pos))}};Ar=new WeakMap;Mo=new WeakMap;Xi=new WeakMap;Ii=new WeakMap;Rr=new WeakSet;Ns=function(o){let a=ee(this,Mo).byteLength;for(;a<o;)a*=2;if(a===ee(this,Mo).byteLength)return;let t=new ArrayBuffer(a),n=new Uint8Array(t);n.set(ee(this,Xi),0),ma(this,Mo,t),ma(this,Xi,n)};var Oy=2**24,zy=2,Ri,Eo,$i,Rn,Ha,qr,Vs,wd,Mm,kd,Im,Li,Jr,_d=class extends Bm{constructor(o){var a,t;super(),ft(this,qr),ft(this,wd),ft(this,kd),ft(this,Li),ft(this,Ri,void 0),ft(this,Eo,[]),ft(this,$i,void 0),ft(this,Rn,void 0),ft(this,Ha,[]),ma(this,Ri,o),ma(this,$i,((a=o.options)==null?void 0:a.chunked)??!1),ma(this,Rn,((t=o.options)==null?void 0:t.chunkSize)??Oy)}write(o){ee(this,Eo).push({data:o.slice(),start:this.pos}),this.pos+=o.byteLength}flush(){var t,n;if(ee(this,Eo).length===0)return;let o=[],a=[...ee(this,Eo)].sort((i,r)=>i.start-r.start);o.push({start:a[0].start,size:a[0].data.byteLength});for(let i=1;i<a.length;i++){let r=o[o.length-1],l=a[i];l.start<=r.start+r.size?r.size=Math.max(r.size,l.start+l.data.byteLength-r.start):o.push({start:l.start,size:l.data.byteLength})}for(let i of o){i.data=new Uint8Array(i.size);for(let r of ee(this,Eo))i.start<=r.start&&r.start<i.start+i.size&&i.data.set(r.data,r.start-i.start);ee(this,$i)?(kt(this,qr,Vs).call(this,i.data,i.start),kt(this,Li,Jr).call(this)):(n=(t=ee(this,Ri).options).onData)==null||n.call(t,i.data,i.start)}ee(this,Eo).length=0}finalize(){ee(this,$i)&&kt(this,Li,Jr).call(this,!0)}};Ri=new WeakMap;Eo=new WeakMap;$i=new WeakMap;Rn=new WeakMap;Ha=new WeakMap;qr=new WeakSet;Vs=function(o,a){let t=ee(this,Ha).findIndex(s=>s.start<=a&&a<s.start+ee(this,Rn));t===-1&&(t=kt(this,kd,Im).call(this,a));let n=ee(this,Ha)[t],i=a-n.start,r=o.subarray(0,Math.min(ee(this,Rn)-i,o.byteLength));n.data.set(r,i);let l={start:i,end:i+r.byteLength};if(kt(this,wd,Mm).call(this,n,l),n.written[0].start===0&&n.written[0].end===ee(this,Rn)&&(n.shouldFlush=!0),ee(this,Ha).length>zy){for(let s=0;s<ee(this,Ha).length-1;s++)ee(this,Ha)[s].shouldFlush=!0;kt(this,Li,Jr).call(this)}r.byteLength<o.byteLength&&kt(this,qr,Vs).call(this,o.subarray(r.byteLength),a+r.byteLength)};wd=new WeakSet;Mm=function(o,a){let t=0,n=o.written.length-1,i=-1;for(;t<=n;){let r=Math.floor(t+(n-t+1)/2);o.written[r].start<=a.start?(t=r+1,i=r):n=r-1}for(o.written.splice(i+1,0,a),(i===-1||o.written[i].end<a.start)&&i++;i<o.written.length-1&&o.written[i].end>=o.written[i+1].start;)o.written[i].end=Math.max(o.written[i].end,o.written[i+1].end),o.written.splice(i+1,1)};kd=new WeakSet;Im=function(o){let t={start:Math.floor(o/ee(this,Rn))*ee(this,Rn),data:new Uint8Array(ee(this,Rn)),written:[],shouldFlush:!1};return ee(this,Ha).push(t),ee(this,Ha).sort((n,i)=>n.start-i.start),ee(this,Ha).indexOf(t)};Li=new WeakSet;Jr=function(o=!1){var a,t;for(let n=0;n<ee(this,Ha).length;n++){let i=ee(this,Ha)[n];if(!(!i.shouldFlush&&!o)){for(let r of i.written)(t=(a=ee(this,Ri).options).onData)==null||t.call(a,i.data.subarray(r.start,r.end),i.start+r.start);ee(this,Ha).splice(n--,1)}}};var jy=class extends _d{constructor(o){var a;super(new Tm({onData:(t,n)=>o.stream.write({type:"write",data:t,position:n}),chunked:!0,chunkSize:(a=o.options)==null?void 0:a.chunkSize}))}},Ts=1e3,Wy=["avc","hevc","vp9","av1"],Hy=["aac","opus"],Zy=2082844800,Gy=["strict","offset","cross-track-offset"],et,at,Yr,Wa,pa,ua,Jo,Yo,Ed,So,Co,Pi,Bs,$m,Ms,Fm,Sd,Dm,Is,Am,Cd,Rm,Lr,$s,yn,An,xd,Lm,Ui,Qr,el,Nd,ii,ar,Pr,Fs,Pm=class{constructor(o){if(ft(this,Bs),ft(this,Ms),ft(this,Sd),ft(this,Is),ft(this,Cd),ft(this,Lr),ft(this,yn),ft(this,xd),ft(this,Ui),ft(this,el),ft(this,ii),ft(this,Pr),ft(this,et,void 0),ft(this,at,void 0),ft(this,Yr,void 0),ft(this,Wa,void 0),ft(this,pa,null),ft(this,ua,null),ft(this,Jo,Math.floor(Date.now()/1e3)+Zy),ft(this,Yo,[]),ft(this,Ed,1),ft(this,So,[]),ft(this,Co,[]),ft(this,Pi,!1),kt(this,Bs,$m).call(this,o),o.video=Ai(o.video),o.audio=Ai(o.audio),o.fastStart=Ai(o.fastStart),this.target=o.target,ma(this,et,{firstTimestampBehavior:"strict",...o}),o.target instanceof yd)ma(this,at,new Uy(o.target));else if(o.target instanceof Tm)ma(this,at,new _d(o.target));else if(o.target instanceof Py)ma(this,at,new jy(o.target));else throw new Error(`Invalid target: ${o.target}`);kt(this,Is,Am).call(this),kt(this,Ms,Fm).call(this)}addVideoChunk(o,a,t,n){if(!(o instanceof EncodedVideoChunk))throw new TypeError("addVideoChunk's first argument (sample) must be of type EncodedVideoChunk.");if(a&&typeof a!="object")throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");if(t!==void 0&&(!Number.isFinite(t)||t<0))throw new TypeError("addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number.");if(n!==void 0&&!Number.isFinite(n))throw new TypeError("addVideoChunk's fourth argument (compositionTimeOffset), when provided, must be a real number.");let i=new Uint8Array(o.byteLength);o.copyTo(i),this.addVideoChunkRaw(i,o.type,t??o.timestamp,o.duration,a,n)}addVideoChunkRaw(o,a,t,n,i,r){if(!(o instanceof Uint8Array))throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");if(a!=="key"&&a!=="delta")throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(t)||t<0)throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(n)||n<0)throw new TypeError("addVideoChunkRaw's fourth argument (duration) must be a non-negative real number.");if(i&&typeof i!="object")throw new TypeError("addVideoChunkRaw's fifth argument (meta), when provided, must be an object.");if(r!==void 0&&!Number.isFinite(r))throw new TypeError("addVideoChunkRaw's sixth argument (compositionTimeOffset), when provided, must be a real number.");if(kt(this,Pr,Fs).call(this),!ee(this,et).video)throw new Error("No video track declared.");if(typeof ee(this,et).fastStart=="object"&&ee(this,pa).samples.length===ee(this,et).fastStart.expectedVideoChunks)throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${ee(this,et).fastStart.expectedVideoChunks}).`);let l=kt(this,Lr,$s).call(this,ee(this,pa),o,a,t,n,i,r);if(ee(this,et).fastStart==="fragmented"&&ee(this,ua)){for(;ee(this,Co).length>0&&ee(this,Co)[0].decodeTimestamp<=l.decodeTimestamp;){let s=ee(this,Co).shift();kt(this,yn,An).call(this,ee(this,ua),s)}l.decodeTimestamp<=ee(this,ua).lastDecodeTimestamp?kt(this,yn,An).call(this,ee(this,pa),l):ee(this,So).push(l)}else kt(this,yn,An).call(this,ee(this,pa),l)}addAudioChunk(o,a,t){if(!(o instanceof EncodedAudioChunk))throw new TypeError("addAudioChunk's first argument (sample) must be of type EncodedAudioChunk.");if(a&&typeof a!="object")throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");if(t!==void 0&&(!Number.isFinite(t)||t<0))throw new TypeError("addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number.");let n=new Uint8Array(o.byteLength);o.copyTo(n),this.addAudioChunkRaw(n,o.type,t??o.timestamp,o.duration,a)}addAudioChunkRaw(o,a,t,n,i){if(!(o instanceof Uint8Array))throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");if(a!=="key"&&a!=="delta")throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");if(!Number.isFinite(t)||t<0)throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");if(!Number.isFinite(n)||n<0)throw new TypeError("addAudioChunkRaw's fourth argument (duration) must be a non-negative real number.");if(i&&typeof i!="object")throw new TypeError("addAudioChunkRaw's fifth argument (meta), when provided, must be an object.");if(kt(this,Pr,Fs).call(this),!ee(this,et).audio)throw new Error("No audio track declared.");if(typeof ee(this,et).fastStart=="object"&&ee(this,ua).samples.length===ee(this,et).fastStart.expectedAudioChunks)throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${ee(this,et).fastStart.expectedAudioChunks}).`);let r=kt(this,Lr,$s).call(this,ee(this,ua),o,a,t,n,i);if(ee(this,et).fastStart==="fragmented"&&ee(this,pa)){for(;ee(this,So).length>0&&ee(this,So)[0].decodeTimestamp<=r.decodeTimestamp;){let l=ee(this,So).shift();kt(this,yn,An).call(this,ee(this,pa),l)}r.decodeTimestamp<=ee(this,pa).lastDecodeTimestamp?kt(this,yn,An).call(this,ee(this,ua),r):ee(this,Co).push(r)}else kt(this,yn,An).call(this,ee(this,ua),r)}finalize(){if(ee(this,Pi))throw new Error("Cannot finalize a muxer more than once.");if(ee(this,et).fastStart==="fragmented"){for(let a of ee(this,So))kt(this,yn,An).call(this,ee(this,pa),a);for(let a of ee(this,Co))kt(this,yn,An).call(this,ee(this,ua),a);kt(this,el,Nd).call(this,!1)}else ee(this,pa)&&kt(this,Ui,Qr).call(this,ee(this,pa)),ee(this,ua)&&kt(this,Ui,Qr).call(this,ee(this,ua));let o=[ee(this,pa),ee(this,ua)].filter(Boolean);if(ee(this,et).fastStart==="in-memory"){let a;for(let n=0;n<2;n++){let i=Dr(o,ee(this,Jo)),r=ee(this,at).measureBox(i);a=ee(this,at).measureBox(ee(this,Wa));let l=ee(this,at).pos+r+a;for(let s of ee(this,Yo)){s.offset=l;for(let{data:d}of s.samples)l+=d.byteLength,a+=d.byteLength}if(l<2**32)break;a>=2**32&&(ee(this,Wa).largeSize=!0)}let t=Dr(o,ee(this,Jo));ee(this,at).writeBox(t),ee(this,Wa).size=a,ee(this,at).writeBox(ee(this,Wa));for(let n of ee(this,Yo))for(let i of n.samples)ee(this,at).write(i.data),i.data=null}else if(ee(this,et).fastStart==="fragmented"){let a=ee(this,at).pos,t=Iy(o);ee(this,at).writeBox(t);let n=ee(this,at).pos-a;ee(this,at).seek(ee(this,at).pos-4),ee(this,at).writeU32(n)}else{let a=ee(this,at).offsets.get(ee(this,Wa)),t=ee(this,at).pos-a;ee(this,Wa).size=t,ee(this,Wa).largeSize=t>=2**32,ee(this,at).patchBox(ee(this,Wa));let n=Dr(o,ee(this,Jo));if(typeof ee(this,et).fastStart=="object"){ee(this,at).seek(ee(this,Yr)),ee(this,at).writeBox(n);let i=a-ee(this,at).pos;ee(this,at).writeBox(Zb(i))}else ee(this,at).writeBox(n)}kt(this,ii,ar).call(this),ee(this,at).finalize(),ma(this,Pi,!0)}};et=new WeakMap;at=new WeakMap;Yr=new WeakMap;Wa=new WeakMap;pa=new WeakMap;ua=new WeakMap;Jo=new WeakMap;Yo=new WeakMap;Ed=new WeakMap;So=new WeakMap;Co=new WeakMap;Pi=new WeakMap;Bs=new WeakSet;$m=function(o){if(typeof o!="object")throw new TypeError("The muxer requires an options object to be passed to its constructor.");if(!(o.target instanceof hl))throw new TypeError("The target must be provided and an instance of Target.");if(o.video){if(!Wy.includes(o.video.codec))throw new TypeError(`Unsupported video codec: ${o.video.codec}`);if(!Number.isInteger(o.video.width)||o.video.width<=0)throw new TypeError(`Invalid video width: ${o.video.width}. Must be a positive integer.`);if(!Number.isInteger(o.video.height)||o.video.height<=0)throw new TypeError(`Invalid video height: ${o.video.height}. Must be a positive integer.`);const a=o.video.rotation;if(typeof a=="number"&&![0,90,180,270].includes(a))throw new TypeError(`Invalid video rotation: ${a}. Has to be 0, 90, 180 or 270.`);if(Array.isArray(a)&&(a.length!==9||a.some(t=>typeof t!="number")))throw new TypeError(`Invalid video transformation matrix: ${a.join()}`);if(o.video.frameRate!==void 0&&(!Number.isInteger(o.video.frameRate)||o.video.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${o.video.frameRate}. Must be a positive integer.`)}if(o.audio){if(!Hy.includes(o.audio.codec))throw new TypeError(`Unsupported audio codec: ${o.audio.codec}`);if(!Number.isInteger(o.audio.numberOfChannels)||o.audio.numberOfChannels<=0)throw new TypeError(`Invalid number of audio channels: ${o.audio.numberOfChannels}. Must be a positive integer.`);if(!Number.isInteger(o.audio.sampleRate)||o.audio.sampleRate<=0)throw new TypeError(`Invalid audio sample rate: ${o.audio.sampleRate}. Must be a positive integer.`)}if(o.firstTimestampBehavior&&!Gy.includes(o.firstTimestampBehavior))throw new TypeError(`Invalid first timestamp behavior: ${o.firstTimestampBehavior}`);if(typeof o.fastStart=="object"){if(o.video){if(o.fastStart.expectedVideoChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedVideoChunks'.");if(!Number.isInteger(o.fastStart.expectedVideoChunks)||o.fastStart.expectedVideoChunks<0)throw new TypeError("'expectedVideoChunks' must be a non-negative integer.")}if(o.audio){if(o.fastStart.expectedAudioChunks===void 0)throw new TypeError("'fastStart' is an object but is missing property 'expectedAudioChunks'.");if(!Number.isInteger(o.fastStart.expectedAudioChunks)||o.fastStart.expectedAudioChunks<0)throw new TypeError("'expectedAudioChunks' must be a non-negative integer.")}}else if(![!1,"in-memory","fragmented"].includes(o.fastStart))throw new TypeError("'fastStart' option must be false, 'in-memory', 'fragmented' or an object.");if(o.minFragmentDuration!==void 0&&(!Number.isFinite(o.minFragmentDuration)||o.minFragmentDuration<0))throw new TypeError("'minFragmentDuration' must be a non-negative number.")};Ms=new WeakSet;Fm=function(){var o;if(ee(this,at).writeBox(Hb({holdsAvc:((o=ee(this,et).video)==null?void 0:o.codec)==="avc",fragmented:ee(this,et).fastStart==="fragmented"})),ma(this,Yr,ee(this,at).pos),ee(this,et).fastStart==="in-memory")ma(this,Wa,xs(!1));else if(ee(this,et).fastStart!=="fragmented"){if(typeof ee(this,et).fastStart=="object"){let a=kt(this,Sd,Dm).call(this);ee(this,at).seek(ee(this,at).pos+a)}ma(this,Wa,xs(!0)),ee(this,at).writeBox(ee(this,Wa))}kt(this,ii,ar).call(this)};Sd=new WeakSet;Dm=function(){if(typeof ee(this,et).fastStart!="object")return;let o=0,a=[ee(this,et).fastStart.expectedVideoChunks,ee(this,et).fastStart.expectedAudioChunks];for(let t of a)t&&(o+=8*Math.ceil(2/3*t),o+=4*t,o+=12*Math.ceil(2/3*t),o+=4*t,o+=8*t);return o+=4096,o};Is=new WeakSet;Am=function(){if(ee(this,et).video&&ma(this,pa,{id:1,info:{type:"video",codec:ee(this,et).video.codec,width:ee(this,et).video.width,height:ee(this,et).video.height,rotation:ee(this,et).video.rotation??0,decoderConfig:null},timescale:ee(this,et).video.frameRate??57600,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),ee(this,et).audio&&(ma(this,ua,{id:ee(this,et).video?2:1,info:{type:"audio",codec:ee(this,et).audio.codec,numberOfChannels:ee(this,et).audio.numberOfChannels,sampleRate:ee(this,et).audio.sampleRate,decoderConfig:null},timescale:ee(this,et).audio.sampleRate,samples:[],finalizedChunks:[],currentChunk:null,firstDecodeTimestamp:void 0,lastDecodeTimestamp:-1,timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,compactlyCodedChunkTable:[]}),ee(this,et).audio.codec==="aac")){let o=kt(this,Cd,Rm).call(this,2,ee(this,et).audio.sampleRate,ee(this,et).audio.numberOfChannels);ee(this,ua).info.decoderConfig={codec:ee(this,et).audio.codec,description:o,numberOfChannels:ee(this,et).audio.numberOfChannels,sampleRate:ee(this,et).audio.sampleRate}}};Cd=new WeakSet;Rm=function(o,a,t){let i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350].indexOf(a),r=t,l="";l+=o.toString(2).padStart(5,"0"),l+=i.toString(2).padStart(4,"0"),i===15&&(l+=a.toString(2).padStart(24,"0")),l+=r.toString(2).padStart(4,"0");let s=Math.ceil(l.length/8)*8;l=l.padEnd(s,"0");let d=new Uint8Array(l.length/8);for(let c=0;c<l.length;c+=8)d[c/8]=parseInt(l.slice(c,c+8),2);return d};Lr=new WeakSet;$s=function(o,a,t,n,i,r,l){let s=n/1e6,d=(n-(l??0))/1e6,c=i/1e6,u=kt(this,xd,Lm).call(this,s,d,o);return s=u.presentationTimestamp,d=u.decodeTimestamp,r!=null&&r.decoderConfig&&(o.info.decoderConfig===null?o.info.decoderConfig=r.decoderConfig:Object.assign(o.info.decoderConfig,r.decoderConfig)),{presentationTimestamp:s,decodeTimestamp:d,duration:c,data:a,size:a.byteLength,type:t,timescaleUnitsToNextSample:_n(c,o.timescale)}};yn=new WeakSet;An=function(o,a){ee(this,et).fastStart!=="fragmented"&&o.samples.push(a);const t=_n(a.presentationTimestamp-a.decodeTimestamp,o.timescale);if(o.lastTimescaleUnits!==null){let i=_n(a.decodeTimestamp,o.timescale,!1),r=Math.round(i-o.lastTimescaleUnits);if(o.lastTimescaleUnits+=r,o.lastSample.timescaleUnitsToNextSample=r,ee(this,et).fastStart!=="fragmented"){let l=Kr(o.timeToSampleTable);l.sampleCount===1?(l.sampleDelta=r,l.sampleCount++):l.sampleDelta===r?l.sampleCount++:(l.sampleCount--,o.timeToSampleTable.push({sampleCount:2,sampleDelta:r}));const s=Kr(o.compositionTimeOffsetTable);s.sampleCompositionTimeOffset===t?s.sampleCount++:o.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:t})}}else o.lastTimescaleUnits=0,ee(this,et).fastStart!=="fragmented"&&(o.timeToSampleTable.push({sampleCount:1,sampleDelta:_n(a.duration,o.timescale)}),o.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:t}));o.lastSample=a;let n=!1;if(!o.currentChunk)n=!0;else{let i=a.presentationTimestamp-o.currentChunk.startTimestamp;if(ee(this,et).fastStart==="fragmented"){let r=ee(this,pa)??ee(this,ua);const l=ee(this,et).minFragmentDuration??1;o===r&&a.type==="key"&&i>=l&&(n=!0,kt(this,el,Nd).call(this))}else n=i>=.5}n&&(o.currentChunk&&kt(this,Ui,Qr).call(this,o),o.currentChunk={startTimestamp:a.presentationTimestamp,samples:[]}),o.currentChunk.samples.push(a)};xd=new WeakSet;Lm=function(o,a,t){var l,s;const n=ee(this,et).firstTimestampBehavior==="strict",i=t.lastDecodeTimestamp===-1;if(n&&i&&a!==0)throw new Error(`The first chunk for your media track must have a timestamp of 0 (received DTS=${a}).Non-zero first timestamps are often caused by directly piping frames or audio data from a MediaStreamTrack into the encoder. Their timestamps are typically relative to the age of thedocument, which is probably what you want.
19
+
20
+ If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.
21
+ `);if(ee(this,et).firstTimestampBehavior==="offset"||ee(this,et).firstTimestampBehavior==="cross-track-offset"){t.firstDecodeTimestamp===void 0&&(t.firstDecodeTimestamp=a);let d;ee(this,et).firstTimestampBehavior==="offset"?d=t.firstDecodeTimestamp:d=Math.min(((l=ee(this,pa))==null?void 0:l.firstDecodeTimestamp)??1/0,((s=ee(this,ua))==null?void 0:s.firstDecodeTimestamp)??1/0),a-=d,o-=d}if(a<t.lastDecodeTimestamp)throw new Error(`Timestamps must be monotonically increasing (DTS went from ${t.lastDecodeTimestamp*1e6} to ${a*1e6}).`);return t.lastDecodeTimestamp=a,{presentationTimestamp:o,decodeTimestamp:a}};Ui=new WeakSet;Qr=function(o){if(ee(this,et).fastStart==="fragmented")throw new Error("Can't finalize individual chunks if 'fastStart' is set to 'fragmented'.");if(o.currentChunk){if(o.finalizedChunks.push(o.currentChunk),ee(this,Yo).push(o.currentChunk),(o.compactlyCodedChunkTable.length===0||Kr(o.compactlyCodedChunkTable).samplesPerChunk!==o.currentChunk.samples.length)&&o.compactlyCodedChunkTable.push({firstChunk:o.finalizedChunks.length,samplesPerChunk:o.currentChunk.samples.length}),ee(this,et).fastStart==="in-memory"){o.currentChunk.offset=0;return}o.currentChunk.offset=ee(this,at).pos;for(let a of o.currentChunk.samples)ee(this,at).write(a.data),a.data=null;kt(this,ii,ar).call(this)}};el=new WeakSet;Nd=function(o=!0){if(ee(this,et).fastStart!=="fragmented")throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");let a=[ee(this,pa),ee(this,ua)].filter(s=>s&&s.currentChunk);if(a.length===0)return;let t=zb(this,Ed)._++;if(t===1){let s=Dr(a,ee(this,Jo),!0);ee(this,at).writeBox(s)}let n=ee(this,at).pos,i=Vc(t,a);ee(this,at).writeBox(i);{let s=xs(!1),d=0;for(let u of a)for(let m of u.currentChunk.samples)d+=m.size;let c=ee(this,at).measureBox(s)+d;c>=2**32&&(s.largeSize=!0,c=ee(this,at).measureBox(s)+d),s.size=c,ee(this,at).writeBox(s)}for(let s of a){s.currentChunk.offset=ee(this,at).pos,s.currentChunk.moofOffset=n;for(let d of s.currentChunk.samples)ee(this,at).write(d.data),d.data=null}let r=ee(this,at).pos;ee(this,at).seek(ee(this,at).offsets.get(i));let l=Vc(t,a);ee(this,at).writeBox(l),ee(this,at).seek(r);for(let s of a)s.finalizedChunks.push(s.currentChunk),ee(this,Yo).push(s.currentChunk),s.currentChunk=null;o&&kt(this,ii,ar).call(this)};ii=new WeakSet;ar=function(){ee(this,at)instanceof _d&&ee(this,at).flush()};Pr=new WeakSet;Fs=function(){if(ee(this,Pi))throw new Error("Cannot add new video or audio chunks after the file has been finalized.")};const Ki=30;class ri extends Error{constructor({message:t="",code:n=""},...i){super(t,...i);ie(this,"message");ie(this,"code");this.code=n,this.message=t}}class Ln extends ri{}class oa extends ri{}class tl extends ri{}class Tc extends ri{}function Xy(o,a=Ki){if(a<1)throw new oa({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(o*a)}function Qo(o,a=Ki){if(a<1)throw new oa({code:"invalidArgument",message:"FPS must be greater or equal to 1"});return Math.round(o/a*1e3)}class Ze{constructor(a=0){ie(this,"time");this.time=Math.round(a)}get millis(){return this.time}set millis(a){this.time=Math.round(a)}get frames(){return Xy(this.millis/1e3)}set frames(a){this.millis=Qo(a)}get seconds(){return this.millis/1e3}set seconds(a){this.millis=a*1e3}addMillis(a){return this.millis=this.millis+a,this}addFrames(a){const t=Qo(a);return this.millis=this.millis+t,this}add(a){return new Ze(a.millis+this.millis)}subtract(a){return new Ze(this.millis-a.millis)}static fromSeconds(a){const t=new Ze;return t.millis=a*1e3,t}static fromFrames(a,t){const n=new Ze;return n.millis=Qo(a,t),n}copy(){return new Ze(this.millis)}toJSON(){return this.millis}static fromJSON(a){return new Ze(a)}}function Bc(o,a){return[o.slice(0,a),o.slice(a)].filter(t=>t.length>0)}function Ur(o,a){return a?Math.floor(Math.random()*(a-o+1)+o):o}function Ky(o,a,t){t<0&&(t=0);const n=o[a];o.splice(a,1),o.splice(t,0,n)}function Mc(o){return typeof o!="function"?!1:/^class\s/.test(Function.prototype.toString.call(o))}function qy(o){const a=o.numberOfChannels,t=o.length,n=new Int16Array(t*a);for(let i=0;i<t;i++)for(let r=0;r<a;r++){let l=o.getChannelData(r)[i]*32767;l>32767&&(l=32767),l<-32767&&(l=-32767),n[i*a+r]=l}return n}function Jy(o,a=44100,t=2){if(o.sampleRate==a&&o.numberOfChannels==t)return o;const n=Math.floor(o.duration*a),i=new OfflineAudioContext(t,1,a).createBuffer(t,n,a);for(let r=0;r<o.numberOfChannels;r++){const l=o.getChannelData(r),s=i.getChannelData(r),d=o.sampleRate/a;for(let c=0;c<s.length;c++){const u=c*d,m=Math.floor(u),p=Math.ceil(u);if(p>=l.length)s[c]=l[m];else{const f=u-m;s[c]=l[m]*(1-f)+l[p]*f}}}return i}async function Yy(o){const{fps:a,height:t,width:n,bitrate:i}=o,r=["avc1.640034","avc1.4d0034","avc1.640028","avc1.640C32","avc1.64001f","avc1.42001E"],l=["prefer-hardware","prefer-software"],s=[];for(const c of r)for(const u of l)s.push({codec:c,hardwareAcceleration:u,width:n,height:t,bitrate:i,framerate:a});const d=[];if(!("VideoEncoder"in window))return d;for(const c of s){const u=await VideoEncoder.isConfigSupported(c);u.supported&&d.push(u.config??c)}return d.sort(Qy)}function Qy(o,a){const t=o.hardwareAcceleration??"",n=a.hardwareAcceleration??"";return t<n?-1:t>n?1:0}async function e0(o,a="untitled"){const t=document.createElement("a");if(document.head.appendChild(t),t.download=a,typeof o=="string"&&o.startsWith("data:image/svg+xml;base64,")){const n=o.split(",")[1],i=atob(n),r=new Array(i.length);for(let d=0;d<i.length;d++)r[d]=i.charCodeAt(d);const l=new Uint8Array(r),s=new Blob([l],{type:"image/svg+xml"});t.href=URL.createObjectURL(s),t.download=a.split(".")[0]+".svg"}else typeof o=="string"?t.href=o:t.href=URL.createObjectURL(o);t.click(),t.remove()}function Ic(o){return`${o.hours.toString().padStart(2,"0")}:${o.minutes.toString().padStart(2,"0")}:${o.seconds.toString().padStart(2,"0")},`+o.milliseconds.toString().padStart(3,"0")}function $c(o){const a=new Date(1970,0,1);return a.setSeconds(o),a.setMilliseconds(Math.round(o%1*1e3)),{hours:a.getHours(),minutes:a.getMinutes(),seconds:a.getSeconds(),milliseconds:a.getMilliseconds()}}class wr{constructor(a){ie(this,"words",[]);a&&(this.words=a)}get duration(){return this.stop.subtract(this.start)}get text(){return this.words.map(({text:a})=>a).join(" ")}get start(){var a;return((a=this.words.at(0))==null?void 0:a.start)??new Ze}get stop(){var a;return((a=this.words.at(-1))==null?void 0:a.stop)??new Ze}}var Ds=(o=>(o.en="en",o.de="de",o))(Ds||{});class Fc{constructor(a,t,n,i){ie(this,"id",crypto.randomUUID());ie(this,"text");ie(this,"start");ie(this,"stop");ie(this,"confidence");this.text=a,this.start=new Ze(t),this.stop=new Ze(n),this.confidence=i}get duration(){return this.stop.subtract(this.start)}}class No{constructor(a=[],t=Ds.en){ie(this,"id",crypto.randomUUID());ie(this,"language",Ds.en);ie(this,"groups",[]);this.groups=a,this.language=t}get text(){return this.groups.map(({text:a})=>a).join(" ")}get words(){return this.groups.flatMap(({words:a})=>a)}*iter({count:a,duration:t,length:n}){for(const i of this.groups){let r;for(const[l,s]of i.words.entries())r&&(a&&r.words.length>=Ur(...a)?(yield r,r=void 0):t&&(r==null?void 0:r.duration.seconds)>=Ur(...t)?(yield r,r=void 0):n&&r.text.length>=Ur(...n)&&(yield r,r=void 0)),r?r.words.push(s):r=new wr([s]),l==i.words.length-1&&(yield r)}}optimize(){const a=this.groups.flatMap(t=>t.words);for(let t=0;t<a.length-1;t++){const n=a[t],i=a[t+1];i.start.millis-n.stop.millis<0?i.start.millis=n.stop.millis+1:n.stop.millis=i.start.millis-1}return this}toSRT(a={}){let t=1,n="";for(const i of this.iter(a)){const r=$c(i.start.seconds),l=$c(i.stop.seconds);n+=`${t}
22
+ `+Ic(r)+" --> "+Ic(l)+`
23
+ ${i.text}
24
+
25
+ `,t+=1}return{text:n,blob:new Blob([n],{type:"text/plain;charset=utf8"})}}toJSON(){return this.groups.map(a=>a.words.map(t=>({token:t.text,start:t.start.millis,stop:t.stop.millis})))}slice(a,t=!0){let n=0;const i=[];for(const r of this.groups)for(const l of r.words)if(i.length==0&&t&&(n=l.start.millis),i.push(new Fc(l.text,l.start.millis-n,l.stop.millis-n)),i.length==a)return new No([new wr(i)]);return new No([new wr(i)])}copy(){return No.fromJSON(this.toJSON())}static fromJSON(a){const t=new No;for(const n of a){const i=new wr;for(const r of n)i.words.push(new Fc(r.token,r.start,r.stop));t.groups.push(i)}return t}static async from(a,t){const n=await fetch(a,t);if(!n.ok)throw new Ln({code:"unexpectedIOError",message:"An unexpected error occurred while fetching the file"});return No.fromJSON(await n.json())}}function Or(o,a,t){return o+(a-o)*t}function t0(o,a,t){const n=Number.parseInt(o.slice(1),16),i=Number.parseInt(a.slice(1),16),r=n>>16&255,l=n>>8&255,s=n&255,d=i>>16&255,c=i>>8&255,u=i&255,m=Math.round(Or(r,d,t)),p=Math.round(Or(l,c,t)),f=Math.round(Or(s,u,t));return`#${((1<<24)+(m<<16)+(p<<8)+f).toString(16).slice(1)}`}const a0={linear:o=>o,easeIn:o=>o*o,easeOut:o=>o*(2-o),easeInOut:o=>o<.5?2*o*o:-1+(4-2*o)*o};class Ye{constructor(a,t,n={}){ie(this,"input");ie(this,"output");ie(this,"options");if(a.length!==t.length)throw new oa({code:"invalidKeyframes",message:"inputRange and outputRange must have the same length"});this.input=a.map(i=>Qo(i)),this.output=t,this.options={extrapolate:"clamp",easing:"linear",type:"number",...JSON.parse(JSON.stringify(n))}}normalize(a){const{input:t}=this;if(a<t[0])return this.options.extrapolate==="clamp"?{t:0,segment:0}:{t:(a-t[0])/(t[1]-t[0]),segment:0};if(a>t[t.length-1])return this.options.extrapolate==="clamp"?{t:1,segment:t.length-2}:{t:(a-t[t.length-2])/(t[t.length-1]-t[t.length-2]),segment:t.length-2};for(let n=0;n<t.length-1;n++){const i=t[n],r=t[n+1];if(a>=i&&a<=r)return{t:(a-i)/(r-i),segment:n}}return{t:0,segment:0}}interpolate(a,t){const n=this.output[t],i=this.output[t+1],r=a0[this.options.easing](a);if(typeof n=="number"&&typeof i=="number")return Or(n,i,r);if(typeof n=="string"&&typeof i=="string")return t0(n,i,r);if(this.output.length==1)return this.output[0];throw new oa({code:"invalidKeyframes",message:"Unsupported output range types"})}value(a){const{t,segment:n}=this.normalize(typeof a=="number"?a:a.millis);return this.interpolate(t,n)}push(a,t){return this.input.push(Qo(a)),this.output.push(t),this}toJSON(){return this}static fromJSON(a){const t=new Ye([],[]);return Object.assign(t,a),t}}class Ya{constructor(){ie(this,"id",crypto.randomUUID())}toJSON(){const a={};return(this.constructor.__serializableProperties||[]).forEach(({propertyKey:t,serializer:n})=>{const i=this[t];n&&i instanceof n?a[t]=i.toJSON():a[t]=i}),a}static fromJSON(a){const t=new this;return(this.__serializableProperties||[]).forEach(({propertyKey:n,serializer:i})=>{if(a.hasOwnProperty(n))if(i){const r=i.fromJSON(a[n]);t[n]=r}else t[n]=a[n]}),t}}function We(o){return function(a,t){a.constructor.__serializableProperties||(a.constructor.__serializableProperties=[]),a.constructor.__serializableProperties.push({propertyKey:t,serializer:o})}}function nr(o){return class extends o{constructor(){super(...arguments);ie(this,"_handlers",{})}on(t,n){if(typeof n!="function")throw new Error("The callback of an event listener needs to be a function.");const i=crypto.randomUUID();return this._handlers[t]?this._handlers[t][i]=n:this._handlers[t]={[i]:n},i}off(t,...n){if(t){if(t==="*"){this._handlers={};return}for(const i of Object.values(this._handlers))t in i&&delete i[t];for(const i of n)this.off(i)}}trigger(t,n){var r,l;const i=new CustomEvent(t,{detail:n});Object.defineProperty(i,"currentTarget",{writable:!1,value:this});for(const s in this._handlers[t]??{})(r=this._handlers[t])==null||r[s](i);for(const s in this._handlers["*"]??{})(l=this._handlers["*"])==null||l[s](i)}bubble(t){return this.on("*",n=>{t.trigger(n.type,n.detail)})}resolve(t){return(n,i)=>{this.on("error",i),this.on(t,n)}}}}function Vd(o,a,t=0){if(!(o instanceof jt.Container||o instanceof jt.Filter||t==3))for(const n in o){const i=o[n];n&&(i instanceof Ye&&(o[n]=i.value(a)),i!=null&&typeof i=="object"&&Object.keys(i).length&&Vd(i,a,t+1))}}var n0=Object.defineProperty,vl=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&n0(a,t,i),i};const or=class Um extends nr(Ya){constructor(t={}){super();ie(this,"_name");ie(this,"_start",new Ze);ie(this,"_stop",Ze.fromSeconds(16));ie(this,"type","base");ie(this,"source");ie(this,"view",new jt.Container);ie(this,"createdAt",new Date);ie(this,"disabled",!1);ie(this,"state","IDLE");ie(this,"track");Object.assign(this,t)}get name(){var t;return this._name??((t=this.source)==null?void 0:t.name)}set name(t){this._name=t}get start(){return this._start}get stop(){return this._stop}async connect(t){this.state="ATTACHED",this.track=t,this.trigger("attach",void 0)}set start(t){typeof t=="number"?this.start.frames=t:this._start=t,this.start.millis>=this.stop.millis&&(this.stop.millis=this.start.millis+1),this.trigger("frame",this.start.frames)}set stop(t){typeof t=="number"?this.stop.frames=t:this._stop=t,this.stop.millis<=this.start.millis&&(this.start.millis=this.stop.millis-1),this.trigger("frame",this.stop.frames)}offsetBy(t){return typeof t=="number"?(this.start.addFrames(t),this.stop.addFrames(t),this.trigger("offsetBy",Ze.fromFrames(t))):(this.start.addMillis(t.millis),this.stop.addMillis(t.millis),this.trigger("offsetBy",t)),this.trigger("frame",void 0),this}async init(){}enter(){}update(t){}exit(){}detach(){var t;return(t=this.track)==null||t.remove(this),this}async split(t){var r,l;if(t||(t=(l=(r=this.track)==null?void 0:r.composition)==null?void 0:l.frame),typeof t=="number"&&(t=Ze.fromFrames(t)),!t||t.millis<=this.start.millis||t.millis>=this.stop.millis)throw new oa({code:"splitOutOfRange",message:"Cannot split clip at the specified time"});if(!this.track)throw new oa({code:"trackNotAttached",message:"Track must be attached to a track"});const n=this.copy();this.stop=t.copy(),n.start=t.copy().addMillis(1),Vd(n,n.start.subtract(this.start));const i=this.track.clips.findIndex(s=>s.id==this.id);return await this.track.add(n,i+1),n}copy(){return Um.fromJSON(JSON.parse(JSON.stringify(this)))}set(t){return t&&Object.assign(this,t),this.trigger("update",void 0),this}};vl([We()],or.prototype,"_name");vl([We(Ze)],or.prototype,"_start");vl([We(Ze)],or.prototype,"_stop");vl([We()],or.prototype,"disabled");let ir=or;var o0=Object.defineProperty,Oo=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&o0(a,t,i),i};class Sn extends nr(Ya){constructor(){super(...arguments);ie(this,"state","IDLE");ie(this,"metadata");ie(this,"objectURL");ie(this,"duration",Ze.fromSeconds(16));ie(this,"added",!1);ie(this,"type","base");ie(this,"name","");ie(this,"mimeType");ie(this,"externalURL");ie(this,"external",!1);ie(this,"file")}async createObjectURL(){return this.objectURL?this.objectURL:(this.objectURL=URL.createObjectURL(await this.getFile()),this.objectURL)}async getFile(){if(!this.file&&this.state=="LOADING"&&await new Promise(this.resolve("load")),!this.file)throw new oa({code:"fileNotAccessible",message:"The desired file cannot be accessed"});return this.file}async loadFile(t){this.name=t.name,this.mimeType=Ps(t.type),this.external=!1,this.file=t}async loadUrl(t,n){const i=await fetch(t,n);if(!(i!=null&&i.ok))throw new Ln({code:"unexpectedIOError",message:"An unexpected error occurred while fetching the file"});const r=await i.blob();this.name=t.toString().split("/").at(-1)??"",this.external=!0,this.file=new File([r],this.name,{type:r.type}),this.externalURL=t,this.mimeType=Ps(r.type)}async from(t,n){try{this.state="LOADING",t instanceof File?await this.loadFile(t):await this.loadUrl(t,n),this.state="READY",this.trigger("load",void 0)}catch(i){throw this.state=="ERROR",this.trigger("error",new Error(String(i))),i}return this}async arrayBuffer(){return await(await this.getFile()).arrayBuffer()}async remove(){this.state="IDLE",this.objectURL&&(URL.revokeObjectURL(this.objectURL),this.objectURL=void 0),delete this.file}async download(){const t=await this.getFile();e0(t,this.name)}async thumbnail(){return document.createElement("div")}static async from(t,n,i=new this){return i.from(t,n)}}Oo([We()],Sn.prototype,"objectURL");Oo([We()],Sn.prototype,"duration");Oo([We()],Sn.prototype,"type");Oo([We()],Sn.prototype,"name");Oo([We()],Sn.prototype,"mimeType");Oo([We()],Sn.prototype,"externalURL");Oo([We()],Sn.prototype,"external");const Dc="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E";function i0(o){const a=new TextEncoder().encode(o);let t="";const n=a.byteLength;for(let i=0;i<n;i++)t+=String.fromCharCode(a[i]);return btoa(t)}function Ac(o){if(!o||!o.body)return Dc;const a=o.body.scrollWidth,t=o.body.scrollHeight,n=o.cloneNode(!0),i=n.getElementsByTagName("style").item(0),r=n.getElementsByTagName("body").item(0);if(r==null||r.setAttribute("xmlns","http://www.w3.org/1999/xhtml"),!r)return Dc;const l=new XMLSerializer,s=i?l.serializeToString(i):"",d=l.serializeToString(r),c=`
26
+ <svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${t}">
27
+ body { padding: 0; }
28
+ ${s}
29
+ <foreignObject width="100%" height="100%">
30
+ ${d}
31
+ </foreignObject>
32
+ </svg>`;return"data:image/svg+xml;base64,"+i0(c)}class Rc extends Sn{constructor(){super();ie(this,"type","html");ie(this,"iframe");const t=document.createElement("iframe");t.style.position="absolute",t.style.width="0",t.style.height="0",t.style.border="0",t.style.visibility="hidden",document.body.appendChild(t),this.iframe=t}get document(){var t;return(t=this.iframe.contentWindow)==null?void 0:t.document}async createObjectURL(){return!this.file&&this.state=="LOADING"&&await new Promise(this.resolve("load")),this.objectURL?this.objectURL:(this.objectURL=Ac(this.document),this.objectURL)}async loadUrl(t,n){await super.loadUrl(t,n),this.iframe.setAttribute("src",URL.createObjectURL(this.file)),await new Promise((i,r)=>{this.iframe.onload=()=>i(),this.iframe.onerror=l=>r(l)})}async loadFile(t){await super.loadFile(t),this.iframe.setAttribute("src",URL.createObjectURL(this.file)),await new Promise((n,i)=>{this.iframe.onload=()=>n(),this.iframe.onerror=r=>i(r)})}update(){this.objectURL&&(this.objectURL=Ac(this.document))}async thumbnail(){const t=new Image;return t.src=await this.createObjectURL(),t.className="object-contain w-full aspect-video h-auto",t}}function r0(o,a={}){const{threshold:t=.02,hopSize:n=1024,minDuration:i=500}=a,r=[],l=o.getChannelData(0),s=o.sampleRate,d=Math.floor(i/1e3*s);let c=null,u=0;for(let m=0;m<l.length;m+=n){let p=0;const f=Math.min(m+n,l.length);for(let h=m;h<f;h++)p+=l[h]*l[h];p=Math.sqrt(p/(f-m)),p<t?(u+=n,c===null&&(c=m)):(c!==null&&u>=d&&r.push({start:Ze.fromSeconds(c/s),stop:Ze.fromSeconds(m/s)}),c=null,u=0)}return c!==null&&u>=d&&r.push({start:Ze.fromSeconds(c/s),stop:Ze.fromSeconds(l.length/s)}),r}const os=3e3;class ao extends Sn{constructor(){super(...arguments);ie(this,"type","audio");ie(this,"decoding",!1);ie(this,"_silences");ie(this,"transcript");ie(this,"audioBuffer")}async decode(t=2,n=48e3,i=!1){if(this.decoding&&i&&(await new Promise(this.resolve("update")),this.audioBuffer))return this.audioBuffer;this.decoding=!0;const r=await this.arrayBuffer(),l=await new OfflineAudioContext(t,1,n).decodeAudioData(r);return this.duration.seconds=l.duration,i&&(this.audioBuffer=l),this.decoding=!1,this.trigger("update",void 0),l}async samples(t=60,n=50,i=0){const r=this.audioBuffer??await this.decode(1,3e3,!0),l=Math.round(r.sampleRate/n),s=r.sampleRate*r.duration-l,d=Math.ceil(s/t),c=r.getChannelData(0),u=[];for(let m=0;m<s;m+=d){let p=0;for(let f=m;f<m+l;f++)p+=Math.abs(c[m]);u.push(Math.log1p(p/l*100))}return u.map(m=>Math.round(m/Math.max(...u)*(100-i))+i)}async fastsampler({length:t=60,start:n=0,stop:i,logarithmic:r=!1}={}){typeof n=="object"&&(n=n.millis),typeof i=="object"&&(i=i.millis);const l=this.audioBuffer??await this.decode(1,os,!0),s=l.getChannelData(0),d=Math.floor(Math.max(n*os/1e3,0)),c=i?Math.floor(Math.min(i*os/1e3,l.length)):l.length,u=Math.floor((c-d)/t),m=new Float32Array(t);for(let p=0;p<t;p++){const f=d+p*u,h=f+u;let v=-1/0;for(let y=f;y<h;y++){const w=s[y];w>v&&(v=w)}m[p]=r?Math.log2(1+v):v}return m}async thumbnail(...t){const n=await this.samples(...t),i=document.createElement("div");i.className="flex flex-row absolute space-between inset-0 audio-samples";for(const r of n){const l=document.createElement("div");l.className="audio-sample-item",l.style.height=`${r}%`,i.appendChild(l)}return i}async silences(t={}){if(this._silences)return this._silences;const n=await this.arrayBuffer(),i=new AudioContext,r=await i.decodeAudioData(n);return this._silences=r0(r,t),i.close(),this._silences}}class As extends Sn{constructor(){super(...arguments);ie(this,"type","image")}async thumbnail(){const t=new Image;return t.src=await this.createObjectURL(),t.className="object-cover w-full aspect-video h-auto",t}}class To extends ao{constructor(){super(...arguments);ie(this,"type","video");ie(this,"downloadInProgress",!0)}async loadUrl(t,n){const i=await fetch(t,n);if(!(i!=null&&i.ok))throw new Ln({code:"unexpectedIOError",message:"An unexpected error occurred while fetching the file"});this.name=t.toString().split("/").at(-1)??"",this.external=!0,this.externalURL=t,this.objectURL=String(t),this.mimeType=Ps(i.headers.get("Content-type")),this.getBlob(i)}async getFile(){if(!this.file&&this.downloadInProgress&&await new Promise(this.resolve("load")),!this.file)throw new oa({code:"fileNotAccessible",message:"The desired file cannot be accessed"});return this.file}async thumbnail(){const t=document.createElement("video");return t.className="object-cover w-full aspect-video h-auto",t.controls=!1,t.addEventListener("loadedmetadata",()=>{this.duration.seconds=t.duration,this.trigger("update",void 0)}),t.addEventListener("mousemove",n=>{const i=n.currentTarget,r=i==null?void 0:i.getBoundingClientRect(),l=n.clientX-((r==null?void 0:r.left)??0),s=i==null?void 0:i.duration;s&&r&&r.width>0&&(i.currentTime=Math.round(s*(l/r.width)))}),t.src=await this.createObjectURL(),t}async getBlob(t){try{this.downloadInProgress=!0;const n=await t.blob();this.file=new File([n],this.name,{type:n.type}),this.trigger("load",void 0)}catch(n){this.state=="ERROR",this.trigger("error",new Error(String(n)))}finally{this.downloadInProgress=!1}}}class l0{static fromJSON(a){return[new Ze(a[0]),new Ze(a[1])]}}var s0=Object.defineProperty,d0=Object.getOwnPropertyDescriptor,di=(o,a,t,n)=>{for(var i=n>1?void 0:n?d0(a,t):a,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=(n?l(a,t,i):l(i))||i);return n&&i&&s0(a,t,i),i};const zo=class Om extends ir{constructor(t={}){super();ie(this,"source",new ao);ie(this,"_offset",new Ze);ie(this,"playing",!1);ie(this,"duration",new Ze);ie(this,"range",[new Ze,this.duration]);Object.assign(this,t)}get transcript(){return this.source.transcript}set transcript(t){this.source.transcript=t}get start(){return this.range[0].add(this.offset)}get stop(){return this.range[1].add(this.offset)}set start(t){typeof t=="number"&&(t=Ze.fromFrames(t));const n=t.subtract(this.offset);n.millis>=0&&n.millis<this.range[1].millis?this.range[0].millis=n.millis:n.millis<0?this.range[0].millis=0:this.range[0].millis=this.range[1].millis-1,this.trigger("frame",void 0)}set stop(t){typeof t=="number"&&(t=Ze.fromFrames(t));const n=t.subtract(this.offset);n.millis>this.range[0].millis&&n.millis<=this.duration.millis?this.range[1]=n:n.millis>this.duration.millis?this.range[1]=this.duration:this.range[1].millis=this.range[0].millis+1,this.trigger("frame",void 0)}get offset(){return this._offset}set offset(t){typeof t=="number"?this._offset.frames=t:this._offset=t,this.trigger("frame",this.offset.frames)}offsetBy(t){return typeof t=="number"?(this.offset.addFrames(t),this.trigger("offsetBy",Ze.fromFrames(t))):(this.offset.addMillis(t.millis),this.trigger("offsetBy",t)),this.trigger("frame",void 0),this}get muted(){var t;return((t=this.element)==null?void 0:t.muted)??!1}set muted(t){this.element&&(this.element.muted=t)}seek(t){return new Promise((n,i)=>{if(!this.element)return i(new Tc({code:"elementNotDefined",message:"Cannot seek on undefined element"}));(t.millis<this.start.millis||t.millis>this.stop.millis)&&(t=this.start),this.element.onerror=()=>{var r;return i((r=this.element)==null?void 0:r.error)},this.element.pause(),this.element.currentTime=t.subtract(this.offset).seconds,this.element.onseeked=()=>n()})}subclip(t,n){if(t||(t=this.range[0]),n||(n=this.range[1]),typeof t=="number"&&(t=Ze.fromFrames(t)),typeof n=="number"&&(n=Ze.fromFrames(n)),t.millis>=n.millis)throw new oa({code:"invalidKeyframe",message:"Start can't lower than or equal the stop"});return t.millis<0&&(this.range[0].millis=0,t=this.range[0]),n.millis>this.duration.millis&&this.duration.millis&&(n=this.duration),this.range=[t,n],this.trigger("frame",void 0),this}get volume(){var t;return((t=this.element)==null?void 0:t.volume)??1}set volume(t){this.element&&(this.element.volume=t)}copy(){const t=Om.fromJSON(JSON.parse(JSON.stringify(this)));return t.source=this.source,t}async split(t){var r,l;if(t||(t=(l=(r=this.track)==null?void 0:r.composition)==null?void 0:l.frame),typeof t=="number"&&(t=Ze.fromFrames(t)),!t||t.millis<=this.start.millis||t.millis>=this.stop.millis)throw new oa({code:"invalidKeyframe",message:"Cannot split clip at the specified time"});if(!this.track)throw new Tc({code:"trackNotDefined",message:"Clip must be attached to a track"});t=t.subtract(this.offset);const n=this.copy();this.range[1]=t.copy(),n.range[0]=t.copy().addMillis(1),Vd(n,n.start.subtract(this.start));const i=this.track.clips.findIndex(s=>s.id==this.id);return await this.track.add(n,i+1),n}async addCaptions(t){var n;if(!((n=this.track)!=null&&n.composition))throw new oa({code:"compositionNotDefined",message:"Captions can only be generated after the clip has been added to the composition"});return await this.track.composition.createTrack("caption").from(this).generate(t)}set(t){return super.set(t)}async generateCaptions(t){return this.addCaptions(t)}async removeSilences(t={}){["READY","ATTACHED"].includes(this.state)||await this.init();const n=(await this.source.silences(t)).filter(l=>Lc(l,this.range)).sort((l,s)=>l.start.millis-s.start.millis);if(n.length==0)return[this];const i=t.padding??500,r=[this];for(const l of n){const s=r.at(-1);if(!s)break;if(!Lc(l,s.range))continue;const d=new Ze(Math.min(l.start.millis+i,l.stop.millis));if(l.start.millis>s.range[0].millis&&l.stop.millis<s.range[1].millis){const c=s.copy();s.range[1]=d,c.range[0]=l.stop,r.push(c)}else l.start.millis<=s.range[0].millis?s.range[0]=l.stop:l.stop.millis>=s.range[1].millis&&(s.range[1]=d)}return r}};di([We(Ze)],zo.prototype,"_offset",2);di([We(Ze)],zo.prototype,"duration",2);di([We(l0)],zo.prototype,"range",2);di([We(No)],zo.prototype,"transcript",1);di([We()],zo.prototype,"muted",1);di([We()],zo.prototype,"volume",1);let gl=zo;function Lc(o,a){return o.start.millis>=a[0].millis&&o.start.millis<=a[1].millis||o.stop.millis<=a[1].millis&&o.stop.millis>=a[0].millis}class kr{static fromJSON(a){return typeof a=="object"?Ye.fromJSON(a):a}}class is{static fromJSON(a){return typeof a.x=="object"&&(a.x=Ye.fromJSON(a.x)),typeof a.y=="object"&&(a.y=Ye.fromJSON(a.y)),a}}let c0=class{constructor(o){ie(this,"target");ie(this,"animation");this.target=o}init(o,a,t=0,n){if(!(o in this.target))throw new Error(`Property [${String(o)}] cannot be assigned`);const i=[t],r=[a];typeof this.target[o]==typeof a&&t!=0&&(i.unshift(0),r.unshift(this.target[o])),this.target[o]=this.animation=new Ye(i,r,{easing:n})}};function u0(o){const a=new Proxy(o,{get(t,n){return n=="to"?(i,r)=>{if(!t.animation)throw new oa({code:"undefinedKeyframe",message:"Cannot use 'to() before selecting a property"});const l=new Ze(t.animation.input.at(-1)).frames+r;return t.animation.push(l,i),a}:(i,r,l)=>(t.init(n,i,r,l),a)}});return a}class m0 extends c0{}var p0=Object.defineProperty,f0=Object.getOwnPropertyDescriptor,Qn=(o,a,t,n)=>{for(var i=n>1?void 0:n?f0(a,t):a,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=(n?l(a,t,i):l(i))||i);return n&&i&&p0(a,t,i),i};function bl(o){class a extends o{constructor(){super(...arguments);ie(this,"filters");ie(this,"_height");ie(this,"_width");ie(this,"_position",{x:this.view.position.x,y:this.view.position.y});ie(this,"_scale");ie(this,"rotation",this.view.angle);ie(this,"alpha",1);ie(this,"translate",{x:0,y:0})}get position(){return this._position}set position(i){typeof i=="string"?(this._position={x:"50%",y:"50%"},this.anchor={x:.5,y:.5}):this._position=i}get scale(){return this._scale??{x:this.view.scale.x,y:this.view.scale.y}}set scale(i){typeof i=="number"||i instanceof Ye||typeof i=="function"?this._scale={x:i,y:i}:this._scale=i}get x(){return this._position.x}set x(i){this._position.x=i}get y(){return this._position.y}set y(i){this._position.y=i}get translateX(){return this.translate.x}set translateX(i){this.translate.x=i}get translateY(){return this.translate.y}set translateY(i){this.translate.y=i}get height(){return this._height??this.view.height}set height(i){this._height=i}get width(){return this._width??this.view.width}set width(i){this._width=i}get mask(){return this.view.mask}set mask(i){this.view.mask=i??null}get anchor(){return this.view.children[0]instanceof jt.Sprite?{x:this.view.children[0].anchor.x,y:this.view.children[0].anchor.y}:{x:0,y:0}}set anchor(i){const r=typeof i=="number"?{x:i,y:i}:i;for(const l of this.view.children)l instanceof jt.Sprite&&l.anchor.set(r.x,r.y)}enter(){this.filters&&!this.view.filters&&(this.view.filters=this.filters)}exit(){this.filters&&this.view.filters&&(this.view.filters=null)}animate(){return u0(new m0(this))}}return Qn([We(kr)],a.prototype,"_height",2),Qn([We(kr)],a.prototype,"_width",2),Qn([We(is)],a.prototype,"_position",2),Qn([We(is)],a.prototype,"_scale",2),Qn([We(kr)],a.prototype,"rotation",2),Qn([We(kr)],a.prototype,"alpha",2),Qn([We(is)],a.prototype,"translate",2),Qn([We()],a.prototype,"anchor",1),a}function yl(o,a,t){const n=t.value;return t.value=function(...i){var m,p,f,h;const r=i[0].subtract(this.start),l={width:((p=(m=this.track)==null?void 0:m.composition)==null?void 0:p.width)??1920,height:((h=(f=this.track)==null?void 0:f.composition)==null?void 0:h.height)??1080};let s;typeof this.translate.x=="number"?s=this.translate.x:typeof this.translate.x=="function"?s=this.translate.x.bind(this)(r):s=this.translate.x.value(r);let d;typeof this.translate.y=="number"?d=this.translate.y:typeof this.translate.y=="function"?d=this.translate.y.bind(this)(r):d=this.translate.y.value(r);let c;typeof this._position.x=="number"?c=this._position.x:typeof this._position.x=="string"?c=Number.parseFloat(this._position.x)*l.width/100:typeof this._position.x=="function"?c=this._position.x.bind(this)(r):c=this._position.x.value(r);let u;if(typeof this._position.y=="number"?u=this._position.y:typeof this._position.y=="string"?u=Number.parseFloat(this._position.y)*l.height/100:typeof this._position.y=="function"?u=this._position.y.bind(this)(r):u=this._position.y.value(r),this.view.position.set(c+s,u+d),typeof this._height=="string"?this.view.height=Math.round(Number.parseFloat(this._height)*l.height/100):typeof this._height=="object"?this.view.height=this._height.value(r):typeof this._height=="function"?this.view.height=this._height.bind(this)(r):this._height&&(this.view.height=this._height),this._height&&!this._width&&this.view.scale.set(this.view.scale.y),typeof this._width=="string"?this.view.width=Math.round(Number.parseFloat(this._width)*l.width/100):typeof this._width=="object"?this.view.width=this._width.value(r):typeof this._width=="function"?this.view.width=this._width.bind(this)(r):this._width&&(this.view.width=this._width),this._width&&!this._height&&this.view.scale.set(this.view.scale.x),this._scale){let v;typeof this._scale.x=="number"?v=this._scale.x:typeof this._scale.x=="function"?v=this._scale.x.bind(this)(r):v=this._scale.x.value(r);let y;typeof this._scale.y=="number"?y=this._scale.y:typeof this._scale.y=="function"?y=this._scale.y.bind(this)(r):y=this._scale.y.value(r),(this._width||this._height)&&(v*=this.view.scale._x,y*=this.view.scale._y),this.view.scale.set(v,y)}return typeof this.rotation=="number"?this.view.angle=this.rotation:typeof this.rotation=="function"?this.view.angle=this.rotation.bind(this)(r):this.view.angle=this.rotation.value(r),typeof this.alpha=="number"?this.view.alpha=this.alpha:typeof this.alpha=="function"?this.view.alpha=this.alpha.bind(this)(r):this.view.alpha=this.alpha.value(r),n.apply(this,i)},t}var h0=Object.defineProperty,v0=Object.getOwnPropertyDescriptor,g0=(o,a,t,n)=>{for(var i=v0(a,t),r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&h0(a,t,i),i};const zm=class jm extends bl(ir){constructor(t,n={}){super();ie(this,"type","image");ie(this,"element",new Image);ie(this,"source",new As);ie(this,"sprite",new jt.Sprite);this.view.addChild(this.sprite),t instanceof As&&(this.source=t),t instanceof File&&this.source.from(t),Object.assign(this,n)}async init(){this.element.setAttribute("src",await this.source.createObjectURL()),await new Promise((t,n)=>{this.element.onload=()=>{this.sprite.texture=jt.Texture.from(this.element),this.state="READY",t()},this.element.onerror=i=>{this.state="ERROR",n(new Ln({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."}))}})}update(t){}copy(){const t=jm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.source=this.source,t}};g0([yl],zm.prototype,"update");let b0=zm;const _r={"The Bold Font":{weights:["500"],url:"https://diffusion-studio-public.s3.eu-central-1.amazonaws.com/fonts/the-bold-font.ttf"},"Komika Axis":{weights:["400"],url:"https://diffusion-studio-public.s3.eu-central-1.amazonaws.com/fonts/komika-axis.ttf"},Geologica:{weights:["100","200","300","400","500","600","700","800","900"],url:"https://fonts.gstatic.com/s/geologica/v1/oY1l8evIr7j9P3TN9YwNAdyjzUyDKkKdAGOJh1UlCDUIhAIdhCZOn1fLsig7jfvCCPHZckUWE1lELWNN-w.woff2"},Figtree:{weights:["300","400","500","600","700","800","900"],url:"https://fonts.gstatic.com/s/figtree/v5/_Xms-HUzqDCFdgfMm4S9DaRvzig.woff2"},Urbanist:{weights:["100","200","300","400","500","600","700","800","900"],url:"https://fonts.gstatic.com/s/urbanist/v15/L0x-DF02iFML4hGCyMqlbS1miXK2.woff2"},Montserrat:{weights:["100","200","300","400","500","600","700","800","900"],url:"https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459WlhyyTh89Y.woff2"},Bangers:{weights:["400"],url:"https://fonts.gstatic.com/s/bangers/v20/FeVQS0BTqb0h60ACH55Q2J5hm24.woff2"},Chewy:{weights:["400"],url:"https://fonts.gstatic.com/s/chewy/v18/uK_94ruUb-k-wn52KjI9OPec.woff2"},"Source Code Pro":{weights:["200","300","400","500","600","700","800","900"],url:"https://fonts.gstatic.com/s/sourcecodepro/v22/HI_SiYsKILxRpg3hIP6sJ7fM7PqlPevWnsUnxg.woff2"}};var y0=Object.defineProperty,wl=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&y0(a,t,i),i};const rr=class Rs extends nr(Ya){constructor(t){super();ie(this,"loaded",!1);ie(this,"family");ie(this,"weight");ie(this,"source");ie(this,"style");t!=null&&t.source.startsWith("https://")&&(t.source=`url(${t.source})`),this.family=(t==null?void 0:t.family)??"Arial",this.source=t==null?void 0:t.source,this.style=t==null?void 0:t.style,this.weight=t==null?void 0:t.weight}get name(){return this.family+" "+(this.style??this.weight)}async load(){if(this.loaded||!this.source||!this.family)return this;const t=new FontFace(this.name,this.source);return this.weight&&(t.weight=this.weight),await new Promise(n=>{t.load().then(i=>{document.fonts.add(i),n(null)})}),this.loaded=!0,this.trigger("load",void 0),this}copy(){const t=Rs.fromJSON(JSON.parse(JSON.stringify(this)));return t.loaded=this.loaded,t}static async localFonts(){const t={};"queryLocalFonts"in window||Object.assign(window,{queryLocalFonts:()=>[]});for(const n of await window.queryLocalFonts()){if(n.family in t){t[n.family].push(n);continue}t[n.family]=[n]}return Object.keys(t).map(n=>({family:n,variants:t[n].map(i=>({family:n,style:i.style,source:`local('${i.fullName}'), local('${i.postscriptName}')`}))}))}static webFonts(){return Object.keys(_r).map(t=>({family:t,variants:_r[t].weights.map(n=>({family:t,source:`url(${_r[t].url})`,weight:n}))}))}static fromFamily({family:t,weight:n}){return new Rs({family:t,source:`url(${_r[t].url})`,weight:n})}};wl([We()],rr.prototype,"family");wl([We()],rr.prototype,"weight");wl([We()],rr.prototype,"source");wl([We()],rr.prototype,"style");let Ea=rr;const kn=4,Wm={center:.5,justify:.5,left:0,right:1},Hm={alphabetic:0,top:0,middle:.5,hanging:1,bottom:1,ideographic:1};var w0=Object.defineProperty,k0=Object.getOwnPropertyDescriptor,Da=(o,a,t,n)=>{for(var i=k0(a,t),r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&w0(a,t,i),i};const Va=class Zm extends bl(ir){constructor(t){super();ie(this,"type","text");ie(this,"_text","");ie(this,"_textCase");ie(this,"_anchor",{x:0,y:0});ie(this,"_font",new Ea);ie(this,"style",new jt.TextStyle({fill:"#FFFFFF",fontFamily:this._font.family,fontSize:16}));this.style.padding=20,typeof t=="string"?(this.text=t,this.reflectUpdate()):t&&(Object.assign(this,t),this.reflectUpdate()),this.on("update",this.reflectUpdate.bind(this))}get text(){return this._text}set text(t){if(this._text=t,!this.view.children.length){const n=new jt.Text({text:this.transformedText,style:this.style,resolution:kn,scale:kn});this.view.addChild(n)}this.view.children[0]instanceof jt.Text&&this.transformedText&&(this.view.children[0].text=this.transformedText)}get name(){return this._text}get font(){return this._font}set font(t){if(this._font=t,t.loaded){this.style.fontFamily=t.name;return}this._font.load().then(()=>{this.style.fontFamily=t.name,this.trigger("update",void 0)})}get maxWidth(){if(this.style.wordWrap)return this.style.wordWrapWidth*kn}set maxWidth(t){t?(this.style.wordWrap=!0,this.style.wordWrapWidth=t/kn):this.style.wordWrap=!1}get textAlign(){return this.style.align}set textAlign(t){this.style.align=t,this.anchor.x=Wm[t]}get padding(){return this.style.padding}set padding(t){this.style.padding=t}get textBaseline(){return this.style.textBaseline}set textBaseline(t){this.style.textBaseline=t,this.anchor.y=Hm[t]}get fillStyle(){const{fill:t}=this.style;return new jt.Color(t.toString()).toHex().toUpperCase()}set fillStyle(t){this.style.fill=t}get anchor(){return this._anchor}set anchor(t){typeof t=="number"?this._anchor={x:t,y:t}:this._anchor=t}get stroke(){if(!this.style.stroke)return;let{color:t="#000000",alpha:n=1,width:i=3,join:r="round",miterLimit:l}=this.style.stroke;return t=new jt.Color(t).toHex().toUpperCase(),{color:t,alpha:n,width:i,join:r,miterLimit:l}}set stroke(t){if(!t){this.style.stroke=void 0;return}const{color:n="#000000",alpha:i=1,width:r=3,join:l="round",miterLimit:s}=t;this.style.stroke={color:n,alpha:i,width:r,join:l,miterLimit:s}}get textCase(){return this._textCase}set textCase(t){this._textCase=t,this.view.children[0]instanceof jt.Text&&this.transformedText&&(this.view.children[0].text=this.transformedText)}get shadow(){if(!this.style.dropShadow)return;const{alpha:t,angle:n,blur:i,color:r,distance:l}=this.style.dropShadow,s=new jt.Color(r).toHex().toUpperCase();return{alpha:t,angle:n,blur:i,color:s,distance:l}}set shadow(t){t?this.style.dropShadow=t:this.style.dropShadow=!1}get fontFamily(){return Array.isArray(this.style.fontFamily)?this.style.fontFamily[0]:this.style.fontFamily}get fontSize(){return this.style.fontSize}set fontSize(t){this.style.fontSize=t}get leading(){return this.style.leading}set leading(t){this.style.leading=t}update(t){}copy(){const t=Zm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.font=this.font,t}get transformedText(){return this.textCase=="lower"?this._text.toLocaleLowerCase():this.textCase=="upper"?this._text.toUpperCase():this._text}reflectUpdate(){var r,l,s;const t=((r=this.view.children[0])==null?void 0:r.width)??0,n=((l=this.view.children[0])==null?void 0:l.height)??0,i=(((s=this.style.dropShadow)==null?void 0:s.distance)??0)*kn;this.view.pivot={x:(t-i)*this._anchor.x,y:(n-i)*this._anchor.y}}set(t){return super.set(t)}};Da([We()],Va.prototype,"text");Da([We(Ea)],Va.prototype,"font");Da([We()],Va.prototype,"maxWidth");Da([We()],Va.prototype,"textAlign");Da([We()],Va.prototype,"padding");Da([We()],Va.prototype,"textBaseline");Da([We()],Va.prototype,"fillStyle");Da([We()],Va.prototype,"anchor");Da([We()],Va.prototype,"stroke");Da([We()],Va.prototype,"textCase");Da([We()],Va.prototype,"shadow");Da([We()],Va.prototype,"fontSize");Da([We()],Va.prototype,"leading");Da([yl],Va.prototype,"update");let ci=Va;function rs(o){const a=o.split(" ").map(t=>`${t} `);return a[a.length-1]=a[a.length-1].replace(/ $/,""),a}const _0={get(o,a){const t=o[a];return typeof t=="number"?t*kn:Array.isArray(t)&&typeof t[0]=="number"?t.map(n=>n*kn):t}};function E0(o){return new Proxy(o,_0)}class S0{constructor(){ie(this,"tokens",[])}get width(){return this.tokens.reduce((a,t)=>a+t.metrics.lineWidths[0],0)}get height(){return Math.max(...this.tokens.map(a=>a.metrics.lineHeight))}}class Pc{constructor(){ie(this,"lines",[])}get width(){return Math.max(...this.lines.map(a=>a.width))}get height(){return this.lines.reduce((a,t)=>a+t.height,0)}}class C0{static fromJSON(a){return a.map(t=>(t.font&&(t.font=Ea.fromJSON(t.font)),t))}}var x0=Object.defineProperty,N0=Object.getOwnPropertyDescriptor,ui=(o,a,t,n)=>{for(var i=n>1?void 0:n?N0(a,t):a,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=(n?l(a,t,i):l(i))||i);return n&&i&&x0(a,t,i),i};const jo=class Gm extends ci{constructor(t){super();ie(this,"type","complex_text");ie(this,"_maxWidth");ie(this,"_textAlign","left");ie(this,"_textBaseline","top");ie(this,"model",new jt.Container);ie(this,"segments",[]);ie(this,"metrics",new Pc);ie(this,"background");ie(this,"styles");this.view.addChild(this.model),typeof t=="string"?(this.text=t,this.reflectUpdate()):t&&(Object.assign(this,t),this.reflectUpdate())}get text(){return this._text}set text(t){this._text=t}get maxWidth(){return this._maxWidth}set maxWidth(t){this._maxWidth=t}get textAlign(){return this._textAlign}set textAlign(t){this._textAlign=t,this._anchor.x=Wm[t];const n=this.metrics.width;for(const i of this.metrics.lines){let r=0;(t=="center"||t=="justify")&&(r=(n-i.width)/2),t=="right"&&(r=n-i.width);for(const l of i.tokens)this.model.children[l.index].x=r,r+=l.metrics.lineWidths[0]}}get textBaseline(){return this._textBaseline}set textBaseline(t){this._textBaseline=t,this._anchor.y=Hm[t];let n=0;for(const i of this.metrics.lines){const r=i.height;for(const l of i.tokens){let s=0;t=="middle"&&(s=(r-l.metrics.lineHeight)/2),t=="bottom"&&(s=r-l.metrics.lineHeight),this.model.children[l.index].y=n+s}n+=r}}copy(){const t=Gm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.font=this.font,t}createRenderSplits(t=[]){var r,l;const n=this.transformedText??"",i=[{index:void 0,tokens:rs(n.substring(0,(r=t==null?void 0:t.at(0))==null?void 0:r.start))}];for(let s=0;s<t.length;s++)i.push({index:t[s].index,tokens:rs(n.substring(t[s].start,t[s].stop))}),!((t[s].stop??n.length)>=n.length)&&i.push({index:void 0,tokens:rs(n.substring(t[s].stop,(l=t.at(s+1))==null?void 0:l.start))});return i.filter(s=>s.tokens.join("").trim().length)}createTextMetrics(t,n){var r,l,s;const i=new Pc;for(const d of t){const c=d.index!=null?n[d.index]:this.style;for(let u=0;u<d.tokens.length;u++){const m=E0(jt.CanvasTextMetrics.measureText(d.tokens[u],c)),p=(((r=i.lines.at(-1))==null?void 0:r.width)??0)+m.lineWidths[0],f=this.maxWidth??Number.POSITIVE_INFINITY,h=(l=d.tokens.at(u-1))==null?void 0:l.match(/(\n|\\n).$/gim);(p>f||h||!i.lines.length)&&i.lines.push(new S0),this.model.addChild(new jt.Text({text:d.tokens[u],style:c,resolution:kn,scale:kn})),(s=i.lines.at(-1))==null||s.tokens.push({metrics:m,index:this.model.children.length-1})}}return i}createTextStyles(){var t;return((t=this.styles)==null?void 0:t.map(n=>{var r;const i=this.style.clone();return i.fill=n.fillStyle??this.style.fill,i.fontSize=n.fontSize??this.style.fontSize,i.stroke=n.stroke??this.style.stroke,i.fontFamily=((r=n.font)==null?void 0:r.name)??this.style.fontFamily,i}))??[]}drawBackground(){var s,d;if(this.view.children.length>1&&this.view.removeChildAt(0),!this.background)return;const t=this.model.width,n=this.model.height,i=((s=this.background.padding)==null?void 0:s.x)??40,r=((d=this.background.padding)==null?void 0:d.y)??10,l=new jt.Graphics;l.roundRect(0-i/2,2-r/2,t+i,n+r,this.background.borderRadius??20),l.fill(this.background.fill??"#000000"),l.alpha=this.background.alpha??1,this.view.addChildAt(l,0)}reflectUpdate(){var s;if(!this.transformedText)return;this.model.removeChildren();const t=this.createRenderSplits(this.segments),n=this.createTextStyles();this.metrics=this.createTextMetrics(t,n),this.textAlign=this.textAlign,this.textBaseline=this.textBaseline;const i=this.view.width,r=this.view.height,l=(((s=this.style.dropShadow)==null?void 0:s.distance)??0)*kn;this.view.pivot={x:(i-l)*this._anchor.x,y:(r-l)*this._anchor.y},this.drawBackground()}};ui([We()],jo.prototype,"background",2);ui([We(C0)],jo.prototype,"styles",2);ui([We()],jo.prototype,"text",1);ui([We()],jo.prototype,"maxWidth",1);ui([We()],jo.prototype,"textAlign",1);ui([We()],jo.prototype,"textBaseline",1);let kl=jo;const Xm="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO3ZhciBtPSh0PT4odFt0LkFWTUVESUFfVFlQRV9VTktOT1dOPS0xXT0iQVZNRURJQV9UWVBFX1VOS05PV04iLHRbdC5BVk1FRElBX1RZUEVfVklERU89MF09IkFWTUVESUFfVFlQRV9WSURFTyIsdFt0LkFWTUVESUFfVFlQRV9BVURJTz0xXT0iQVZNRURJQV9UWVBFX0FVRElPIix0W3QuQVZNRURJQV9UWVBFX0RBVEE9Ml09IkFWTUVESUFfVFlQRV9EQVRBIix0W3QuQVZNRURJQV9UWVBFX1NVQlRJVExFPTNdPSJBVk1FRElBX1RZUEVfU1VCVElUTEUiLHRbdC5BVk1FRElBX1RZUEVfQVRUQUNITUVOVD00XT0iQVZNRURJQV9UWVBFX0FUVEFDSE1FTlQiLHRbdC5BVk1FRElBX1RZUEVfTkI9NV09IkFWTUVESUFfVFlQRV9OQiIsdCkpKG18fHt9KSxvPSh0PT4odC5GRm1wZWdXb3JrZXJMb2FkZWQ9IkZGbXBlZ1dvcmtlckxvYWRlZCIsdC5XQVNNUnVudGltZUluaXRpYWxpemVkPSJXQVNNUnVudGltZUluaXRpYWxpemVkIix0LkxvYWRXQVNNPSJMb2FkV0FTTSIsdC5HZXRBVlBhY2tldD0iR2V0QVZQYWNrZXQiLHQuR2V0QVZQYWNrZXRzPSJHZXRBVlBhY2tldHMiLHQuR2V0QVZTdHJlYW09IkdldEFWU3RyZWFtIix0LkdldEFWU3RyZWFtcz0iR2V0QVZTdHJlYW1zIix0LlJlYWRBVlBhY2tldD0iUmVhZEFWUGFja2V0Iix0LkFWUGFja2V0U3RyZWFtPSJBVlBhY2tldFN0cmVhbSIsdC5SZWFkTmV4dEFWUGFja2V0PSJSZWFkTmV4dEFWUGFja2V0Iix0LlN0b3BSZWFkQVZQYWNrZXQ9IlN0b3BSZWFkQVZQYWNrZXQiLHQpKShvfHx7fSk7Y29uc3QgQT0iS0daMWJtTjBhVzl1S0NsN0luVnpaU0J6ZEhKcFkzUWlPMnhsZENCbU8zTmxiR1l1Y0c5emRFMWxjM05oWjJVb2UzUjVjR1U2SWtaR2JYQmxaMWR2Y210bGNreHZZV1JsWkNKOUtTeHpaV3htTG1Ga1pFVjJaVzUwVEdsemRHVnVaWElvSW0xbGMzTmhaMlVpTEdGemVXNWpJR1oxYm1OMGFXOXVLR3dwZTJOdmJuTjBlM1I1Y0dVNmRDeGtZWFJoT21NOWUzMHNiWE5uU1dRNmIzMDliQzVrWVhSaE8zUnllWHRwWmloMFBUMDlJa3h2WVdSWFFWTk5JaWw3WTI5dWMzUjdkMkZ6YlV4dllXUmxjbEJoZEdnNlpYMDlZM3g4ZTMwN1pqMWhkMkZwZENoaGQyRnBkQ0JwYlhCdmNuUW9aU2twTG1SbFptRjFiSFFvS1gxbGJITmxJR2xtS0hROVBUMGlSMlYwUVZaVGRISmxZVzBpS1h0amIyNXpkSHRtYVd4bE9tVXNjM1J5WldGdFZIbHdaVHB6TEhOMGNtVmhiVWx1WkdWNE9tRjlQV01zY2oxbUxtZGxkRUZXVTNSeVpXRnRLR1VzY3l4aEtUdHpaV3htTG5CdmMzUk5aWE56WVdkbEtIdDBlWEJsT25Rc2JYTm5TV1E2Ynl4eVpYTjFiSFE2Y24wc1czSXVZMjlrWldOd1lYSXVaWGgwY21Ga1lYUmhMbUoxWm1abGNsMHBmV1ZzYzJVZ2FXWW9kRDA5UFNKSFpYUkJWbE4wY21WaGJYTWlLWHRqYjI1emRIdG1hV3hsT21WOVBXTXNjejFtTG1kbGRFRldVM1J5WldGdGN5aGxLVHR6Wld4bUxuQnZjM1JOWlhOellXZGxLSHQwZVhCbE9uUXNiWE5uU1dRNmJ5eHlaWE4xYkhRNmMzMHNjeTV0WVhBb1lUMCtZUzVqYjJSbFkzQmhjaTVsZUhSeVlXUmhkR0V1WW5WbVptVnlLU2w5Wld4elpTQnBaaWgwUFQwOUlrZGxkRUZXVUdGamEyVjBJaWw3WTI5dWMzUjdabWxzWlRwbExIUnBiV1U2Y3l4emRISmxZVzFVZVhCbE9tRXNjM1J5WldGdFNXNWtaWGc2Y24wOVl5eHVQV1l1WjJWMFFWWlFZV05yWlhRb1pTeHpMR0VzY2lrN2MyVnNaaTV3YjNOMFRXVnpjMkZuWlNoN2RIbHdaVHAwTEcxelowbGtPbThzY21WemRXeDBPbTU5TEZ0dUxtUmhkR0V1WW5WbVptVnlYU2w5Wld4elpTQnBaaWgwUFQwOUlrZGxkRUZXVUdGamEyVjBjeUlwZTJOdmJuTjBlMlpwYkdVNlpTeDBhVzFsT25OOVBXTXNZVDFtTG1kbGRFRldVR0ZqYTJWMGN5aGxMSE1wTzNObGJHWXVjRzl6ZEUxbGMzTmhaMlVvZTNSNWNHVTZkQ3h0YzJkSlpEcHZMSEpsYzNWc2REcGhmU3hoTG0xaGNDaHlQVDV5TG1SaGRHRXVZblZtWm1WeUtTbDlaV3h6WlNCcFppaDBQVDA5SWxKbFlXUkJWbEJoWTJ0bGRDSXBlMk52Ym5OMGUyWnBiR1U2WlN4emRHRnlkRHB6TEdWdVpEcGhMSE4wY21WaGJWUjVjR1U2Y2l4emRISmxZVzFKYm1SbGVEcHVmVDFqTEdROVppNXlaV0ZrUVZaUVlXTnJaWFFvYnl4bExITXNZU3h5TEc0cE8zTmxiR1l1Y0c5emRFMWxjM05oWjJVb2UzUjVjR1U2ZEN4dGMyZEpaRHB2TEhKbGMzVnNkRHBrZlNsOWZXTmhkR05vS0dVcGUzTmxiR1l1Y0c5emRFMWxjM05oWjJVb2UzUjVjR1U2ZEN4dGMyZEpaRHB2TEdWeWNrMXpaenBsSUdsdWMzUmhibU5sYjJZZ1JYSnliM0kvWlM1dFpYTnpZV2RsT2lKVmJtdHViM2R1SUVWeWNtOXlJbjBwZlgwcGZTa29LVHNLIixnPXQ9PlVpbnQ4QXJyYXkuZnJvbShhdG9iKHQpLGU9PmUuY2hhckNvZGVBdCgwKSksVj10eXBlb2Ygc2VsZjwidSImJnNlbGYuQmxvYiYmbmV3IEJsb2IoW2coQSldLHt0eXBlOiJ0ZXh0L2phdmFzY3JpcHQ7Y2hhcnNldD11dGYtOCJ9KTtmdW5jdGlvbiBFKHQpe2xldCBlO3RyeXtpZihlPVYmJihzZWxmLlVSTHx8c2VsZi53ZWJraXRVUkwpLmNyZWF0ZU9iamVjdFVSTChWKSwhZSl0aHJvdyIiO2NvbnN0IHM9bmV3IFdvcmtlcihlLHtuYW1lOnQ/Lm5hbWV9KTtyZXR1cm4gcy5hZGRFdmVudExpc3RlbmVyKCJlcnJvciIsKCk9Pnsoc2VsZi5VUkx8fHNlbGYud2Via2l0VVJMKS5yZXZva2VPYmplY3RVUkwoZSl9KSxzfWNhdGNoe3JldHVybiBuZXcgV29ya2VyKCJkYXRhOnRleHQvamF2YXNjcmlwdDtiYXNlNjQsIitBLHtuYW1lOnQ/Lm5hbWV9KX1maW5hbGx5e2UmJihzZWxmLlVSTHx8c2VsZi53ZWJraXRVUkwpLnJldm9rZU9iamVjdFVSTChlKX19Y29uc3QgdT0xZTY7Y2xhc3MgcHtmZm1wZWdXb3JrZXI7ZmZtcGVnV29ya2VyTG9hZFN0YXR1czttc2dJZDtmaWxlO2NvbnN0cnVjdG9yKGUpe3RoaXMuZmZtcGVnV29ya2VyPW5ldyBFLHRoaXMuZmZtcGVnV29ya2VyTG9hZFN0YXR1cz1uZXcgUHJvbWlzZSgocyxhKT0+e3RoaXMuZmZtcGVnV29ya2VyLmFkZEV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGk9Pntjb25zdHt0eXBlOnIsZXJyTXNnOmR9PWkuZGF0YTtyPT09by5GRm1wZWdXb3JrZXJMb2FkZWQmJnRoaXMucG9zdChvLkxvYWRXQVNNLHt3YXNtTG9hZGVyUGF0aDplLndhc21Mb2FkZXJQYXRofSkscj09PW8uV0FTTVJ1bnRpbWVJbml0aWFsaXplZCYmcyghMCkscj09PW8uTG9hZFdBU00mJmQmJmEoZCl9KX0pLHRoaXMubXNnSWQ9MH1wb3N0KGUscyxhKXt0aGlzLmZmbXBlZ1dvcmtlci5wb3N0TWVzc2FnZSh7dHlwZTplLG1zZ0lkOmE/P3RoaXMubXNnSWQrKyxkYXRhOnN9KX1hc3luYyBsb2FkKGUpe2NvbnN0IHM9YXdhaXQgdGhpcy5mZm1wZWdXb3JrZXJMb2FkU3RhdHVzO3JldHVybiB0aGlzLmZpbGU9ZSxzfWRlc3Ryb3koKXt0aGlzLmZpbGU9dm9pZCAwLHRoaXMuZmZtcGVnV29ya2VyLnRlcm1pbmF0ZSgpfWdldEFWU3RyZWFtKGU9bS5BVk1FRElBX1RZUEVfVklERU8scz0tMSl7cmV0dXJuIG5ldyBQcm9taXNlKChhLGkpPT57aWYoIXRoaXMuZmlsZSl7aSgiZmlsZSBpcyBub3QgbG9hZGVkIik7cmV0dXJufWNvbnN0IHI9dGhpcy5tc2dJZCxkPSh7ZGF0YTpufSk9PntuLnR5cGU9PT1vLkdldEFWU3RyZWFtJiZuLm1zZ0lkPT09ciYmKG4uZXJyTXNnP2kobi5lcnJNc2cpOmEobi5yZXN1bHQpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGQpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsZCksdGhpcy5wb3N0KG8uR2V0QVZTdHJlYW0se2ZpbGU6dGhpcy5maWxlLHN0cmVhbVR5cGU6ZSxzdHJlYW1JbmRleDpzfSl9KX1nZXRBVlN0cmVhbXMoKXtyZXR1cm4gbmV3IFByb21pc2UoKGUscyk9PntpZighdGhpcy5maWxlKXtzKCJmaWxlIGlzIG5vdCBsb2FkZWQiKTtyZXR1cm59Y29uc3QgYT10aGlzLm1zZ0lkLGk9KHtkYXRhOnJ9KT0+e3IudHlwZT09PW8uR2V0QVZTdHJlYW1zJiZyLm1zZ0lkPT09YSYmKHIuZXJyTXNnP3Moci5lcnJNc2cpOmUoci5yZXN1bHQpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGkpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsaSksdGhpcy5wb3N0KG8uR2V0QVZTdHJlYW1zLHtmaWxlOnRoaXMuZmlsZX0pfSl9Z2V0QVZQYWNrZXQoZSxzPW0uQVZNRURJQV9UWVBFX1ZJREVPLGE9LTEpe3JldHVybiBuZXcgUHJvbWlzZSgoaSxyKT0+e2lmKCF0aGlzLmZpbGUpe3IoImZpbGUgaXMgbm90IGxvYWRlZCIpO3JldHVybn1jb25zdCBkPXRoaXMubXNnSWQsbj1oPT57Y29uc3QgbD1oLmRhdGE7bC50eXBlPT09by5HZXRBVlBhY2tldCYmbC5tc2dJZD09PWQmJihsLmVyck1zZz9yKGwuZXJyTXNnKTppKGwucmVzdWx0KSx0aGlzLmZmbXBlZ1dvcmtlci5yZW1vdmVFdmVudExpc3RlbmVyKCJtZXNzYWdlIixuKSl9O3RoaXMuZmZtcGVnV29ya2VyLmFkZEV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLG4pLHRoaXMucG9zdChvLkdldEFWUGFja2V0LHtmaWxlOnRoaXMuZmlsZSx0aW1lOmUsc3RyZWFtVHlwZTpzLHN0cmVhbUluZGV4OmF9KX0pfWdldEFWUGFja2V0cyhlKXtyZXR1cm4gbmV3IFByb21pc2UoKHMsYSk9PntpZighdGhpcy5maWxlKXthKCJmaWxlIGlzIG5vdCBsb2FkZWQiKTtyZXR1cm59Y29uc3QgaT10aGlzLm1zZ0lkLHI9ZD0+e2NvbnN0IG49ZC5kYXRhO24udHlwZT09PW8uR2V0QVZQYWNrZXRzJiZuLm1zZ0lkPT09aSYmKG4uZXJyTXNnP2Eobi5lcnJNc2cpOnMobi5yZXN1bHQpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLHIpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsciksdGhpcy5wb3N0KG8uR2V0QVZQYWNrZXRzLHtmaWxlOnRoaXMuZmlsZSx0aW1lOmV9KX0pfXJlYWRBVlBhY2tldChlPTAscz0wLGE9bS5BVk1FRElBX1RZUEVfVklERU8saT0tMSl7Y29uc3Qgcj1uZXcgQ291bnRRdWV1aW5nU3RyYXRlZ3koe2hpZ2hXYXRlck1hcms6MX0pLGQ9dGhpcy5tc2dJZDtsZXQgbj0wO3JldHVybiBuZXcgUmVhZGFibGVTdHJlYW0oe3N0YXJ0Omg9PntpZighdGhpcy5maWxlKXtoLmVycm9yKCJmaWxlIGlzIG5vdCBsb2FkZWQiKTtyZXR1cm59Y29uc3QgbD1mPT57Y29uc3QgYz1mLmRhdGE7Yy50eXBlPT09by5SZWFkQVZQYWNrZXQmJmMubXNnSWQ9PT1kJiZjLmVyck1zZyYmKGguZXJyb3IoYy5lcnJNc2cpLHRoaXMuZmZtcGVnV29ya2VyLnJlbW92ZUV2ZW50TGlzdGVuZXIoIm1lc3NhZ2UiLGwpKSxjLnR5cGU9PT1vLkFWUGFja2V0U3RyZWFtJiZjLm1zZ0lkPT09ZCYmKGMucmVzdWx0P2guZW5xdWV1ZShjLnJlc3VsdCk6aC5jbG9zZSgpKX07dGhpcy5mZm1wZWdXb3JrZXIuYWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsbCksdGhpcy5wb3N0KG8uUmVhZEFWUGFja2V0LHtmaWxlOnRoaXMuZmlsZSxzdGFydDplLGVuZDpzLHN0cmVhbVR5cGU6YSxzdHJlYW1JbmRleDppfSl9LHB1bGw6KCk9PntuPjAmJnRoaXMucG9zdChvLlJlYWROZXh0QVZQYWNrZXQsdm9pZCAwLGQpLG4rK30sY2FuY2VsOigpPT57dGhpcy5wb3N0KG8uU3RvcFJlYWRBVlBhY2tldCx2b2lkIDAsZCl9fSxyKX1nZXRWaWRlb1N0cmVhbShlKXtyZXR1cm4gdGhpcy5nZXRBVlN0cmVhbShtLkFWTUVESUFfVFlQRV9WSURFTyxlKX1nZXRBdWRpb1N0cmVhbShlKXtyZXR1cm4gdGhpcy5nZXRBVlN0cmVhbShtLkFWTUVESUFfVFlQRV9BVURJTyxlKX1zZWVrVmlkZW9QYWNrZXQoZSl7cmV0dXJuIHRoaXMuZ2V0QVZQYWNrZXQoZSxtLkFWTUVESUFfVFlQRV9WSURFTyl9c2Vla0F1ZGlvUGFja2V0KGUpe3JldHVybiB0aGlzLmdldEFWUGFja2V0KGUsbS5BVk1FRElBX1RZUEVfQVVESU8pfXJlYWRWaWRlb1BhY2tldChlLHMpe3JldHVybiB0aGlzLnJlYWRBVlBhY2tldChlLHMsbS5BVk1FRElBX1RZUEVfVklERU8pfXJlYWRBdWRpb1BhY2tldChlLHMpe3JldHVybiB0aGlzLnJlYWRBVlBhY2tldChlLHMsbS5BVk1FRElBX1RZUEVfQVVESU8pfWdlblZpZGVvRGVjb2RlckNvbmZpZyhlKXtyZXR1cm57Y29kZWM6ZS5jb2RlY3Bhci5jb2RlY19zdHJpbmcsY29kZWRXaWR0aDplLmNvZGVjcGFyLndpZHRoLGNvZGVkSGVpZ2h0OmUuY29kZWNwYXIuaGVpZ2h0LGRlc2NyaXB0aW9uOmUuY29kZWNwYXIuZXh0cmFkYXRhPy5sZW5ndGg+MD9lLmNvZGVjcGFyLmV4dHJhZGF0YTp2b2lkIDB9fWdlbkVuY29kZWRWaWRlb0NodW5rKGUpe3JldHVybiBuZXcgRW5jb2RlZFZpZGVvQ2h1bmsoe3R5cGU6ZS5rZXlmcmFtZT09PTE/ImtleSI6ImRlbHRhIix0aW1lc3RhbXA6ZS50aW1lc3RhbXAqdSxkdXJhdGlvbjplLmR1cmF0aW9uKnUsZGF0YTplLmRhdGF9KX1nZW5BdWRpb0RlY29kZXJDb25maWcoZSl7cmV0dXJue2NvZGVjOmUuY29kZWNwYXIuY29kZWNfc3RyaW5nfHwiIixzYW1wbGVSYXRlOmUuY29kZWNwYXIuc2FtcGxlX3JhdGUsbnVtYmVyT2ZDaGFubmVsczplLmNvZGVjcGFyLmNoYW5uZWxzLGRlc2NyaXB0aW9uOmUuY29kZWNwYXIuZXh0cmFkYXRhPy5sZW5ndGg+MD9lLmNvZGVjcGFyLmV4dHJhZGF0YTp2b2lkIDB9fWdlbkVuY29kZWRBdWRpb0NodW5rKGUpe3JldHVybiBuZXcgRW5jb2RlZEF1ZGlvQ2h1bmsoe3R5cGU6ZS5rZXlmcmFtZT09PTE/ImtleSI6ImRlbHRhIix0aW1lc3RhbXA6ZS50aW1lc3RhbXAqdSxkdXJhdGlvbjplLmR1cmF0aW9uKnUsZGF0YTplLmRhdGF9KX1hc3luYyBnZXRWaWRlb0RlY29kZXJDb25maWcoKXtjb25zdCBlPWF3YWl0IHRoaXMuZ2V0VmlkZW9TdHJlYW0oKTtyZXR1cm4gdGhpcy5nZW5WaWRlb0RlY29kZXJDb25maWcoZSl9YXN5bmMgc2Vla0VuY29kZWRWaWRlb0NodW5rKGUpe2NvbnN0IHM9YXdhaXQgdGhpcy5zZWVrVmlkZW9QYWNrZXQoZSk7cmV0dXJuIHRoaXMuZ2VuRW5jb2RlZFZpZGVvQ2h1bmsocyl9YXN5bmMgZ2V0QXVkaW9EZWNvZGVyQ29uZmlnKCl7Y29uc3QgZT1hd2FpdCB0aGlzLmdldEF1ZGlvU3RyZWFtKCk7cmV0dXJuIHRoaXMuZ2VuQXVkaW9EZWNvZGVyQ29uZmlnKGUpfWFzeW5jIHNlZWtFbmNvZGVkQXVkaW9DaHVuayhlKXtjb25zdCBzPWF3YWl0IHRoaXMuc2Vla0F1ZGlvUGFja2V0KGUpO3JldHVybiB0aGlzLmdlbkVuY29kZWRBdWRpb0NodW5rKHMpfX1jbGFzcyBre3ZpZGVvO2N1cnJlbnRGcmFtZXM9MDt0b3RhbEZyYW1lcztjdXJyZW50VGltZTtmcHM7Zmlyc3RUaW1lc3RhbXA7Y29uc3RydWN0b3IoZSxzKXt0aGlzLmN1cnJlbnRUaW1lPWVbMF0qMWU2LHRoaXMuZmlyc3RUaW1lc3RhbXA9ZVswXSoxZTYsdGhpcy50b3RhbEZyYW1lcz0oZVsxXS1lWzBdKSpzKzEsdGhpcy5mcHM9cyx0aGlzLnZpZGVvPW5ldyBWaWRlb0RlY29kZXIoe291dHB1dDp0aGlzLmhhbmRsZUZyYW1lT3V0cHV0LmJpbmQodGhpcyksZXJyb3I6dGhpcy5oYW5kbGVFcnJvci5iaW5kKHRoaXMpfSl9cG9zdEZyYW1lKGUpe3NlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImZyYW1lIixmcmFtZTplfSksdGhpcy5jdXJyZW50VGltZSs9TWF0aC5mbG9vcigxL3RoaXMuZnBzKjFlNiksdGhpcy5jdXJyZW50RnJhbWVzKz0xfWhhbmRsZUZyYW1lT3V0cHV0KGUpe2NvbnN0IHM9ZS50aW1lc3RhbXAsYT1lLmR1cmF0aW9uPz8wLGk9cythO2lmKCF0aGlzLmlzRnJhbWVJblJhbmdlKHMpKXtlLmNsb3NlKCk7cmV0dXJufWZvcig7aT50aGlzLmN1cnJlbnRUaW1lJiZ0aGlzLmN1cnJlbnRGcmFtZXM8PXRoaXMudG90YWxGcmFtZXM7KXRoaXMucG9zdEZyYW1lKGUpO2UuY2xvc2UoKX1pc0ZyYW1lSW5SYW5nZShlKXtyZXR1cm4gZT49dGhpcy5maXJzdFRpbWVzdGFtcH1oYW5kbGVFcnJvcihlKXtjb25zb2xlLmVycm9yKCJlcnJvciBpbiB3b3JrZXIiLGUpLHNlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImVycm9yIixtZXNzYWdlOmUubWVzc2FnZT8/IkFuIHVua25vd24gd29ya2VyIGVycm9yIG9jY3VycmVkIn0pLHNlbGYuY2xvc2UoKX19ZnVuY3Rpb24gSSh0KXtyZXR1cm4gYXN5bmMgZT0+e3RyeXthd2FpdCB0KGUpfWNhdGNoKHMpe3NlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImVycm9yIixtZXNzYWdlOnM/Lm1lc3NhZ2U/PyJBbiB1bmtvd24gd29ya2VyIGVycm9yIG9jY3VyZWQifSl9fX1mdW5jdGlvbiBXKHQpe3JldHVybiB0LmNvZGVjPT0idnAwOSImJih0LmNvZGVjPSJ2cDA5LjAwLjEwLjA4IiksdH1jb25zdCBaPTMwO2FzeW5jIGZ1bmN0aW9uIFAodCl7aWYodC5kYXRhPy50eXBlIT0iaW5pdCIpcmV0dXJuO2NvbnN0e2ZpbGU6ZSxyYW5nZTpzLGZwczphfT10LmRhdGEsaT1uZXcgcCh7d2FzbUxvYWRlclBhdGg6Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9ucG0vQGRpZmZ1c2lvbnN0dWRpby9mZm1wZWctd2FzbUAxLjAuMC9kaXN0L2ZmbXBlZy5qcyJ9KTthd2FpdCBpLmxvYWQoZSk7Y29uc3Qgcj1hd2FpdCBpLmdldFZpZGVvRGVjb2RlckNvbmZpZygpO1cocik7Y29uc3QgZD1uZXcgayhzLGEpO2QudmlkZW8uY29uZmlndXJlKHIpO2NvbnN0IG49aS5yZWFkQVZQYWNrZXQoc1swXSxzWzFdKS5nZXRSZWFkZXIoKTtuLnJlYWQoKS50aGVuKGFzeW5jIGZ1bmN0aW9uIGgoe2RvbmU6bCx2YWx1ZTpmfSl7aWYobCl7YXdhaXQgZC52aWRlby5mbHVzaCgpLHNlbGYucG9zdE1lc3NhZ2Uoe3R5cGU6ImRvbmUifSksc2VsZi5jbG9zZSgpO3JldHVybn1jb25zdCBjPWkuZ2VuRW5jb2RlZFZpZGVvQ2h1bmsoZik7cmV0dXJuIGQudmlkZW8uZGVjb2RlUXVldWVTaXplPlomJmF3YWl0IG5ldyBQcm9taXNlKEw9PntkLnZpZGVvLm9uZGVxdWV1ZT0oKT0+TCgpfSksYy50aW1lc3RhbXA8PXNbMV0qMWU2JiZkLnZpZGVvLmRlY29kZShjKSxuLnJlYWQoKS50aGVuKGgpfSl9c2VsZi5hZGRFdmVudExpc3RlbmVyKCJtZXNzYWdlIixJKFApKX0pKCk7Cg==",V0=o=>Uint8Array.from(atob(o),a=>a.charCodeAt(0)),Uc=typeof self<"u"&&self.Blob&&new Blob([V0(Xm)],{type:"text/javascript;charset=utf-8"});function T0(o){let a;try{if(a=Uc&&(self.URL||self.webkitURL).createObjectURL(Uc),!a)throw"";const t=new Worker(a,{name:o==null?void 0:o.name});return t.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(a)}),t}catch{return new Worker("data:text/javascript;base64,"+Xm,{name:o==null?void 0:o.name})}finally{a&&(self.URL||self.webkitURL).revokeObjectURL(a)}}class B0{constructor(){ie(this,"frames",[]);ie(this,"state","active");ie(this,"onenqueue");ie(this,"onclose")}enqueue(a){var t;this.frames.unshift(a),(t=this.onenqueue)==null||t.call(this)}async dequeue(){if(this.frames.length==0&&this.state=="active"&&await this.waitFor(2e4),!(this.frames.length==0&&this.state=="closed"))return this.frames.pop()}close(){var a;this.state="closed",(a=this.onclose)==null||a.call(this)}terminate(){for(const a of this.frames)a.close()}async waitFor(a){await new Promise((t,n)=>{const i=setTimeout(()=>{n(`Promise timed out after ${a} ms`)},a);this.onenqueue=()=>{clearTimeout(i),t()},this.onclose=()=>{clearTimeout(i),t()}})}}function M0(o,a,t){const n=t.value;return t.value=function(...i){var r,l,s,d;return(l=(r=this.track)==null?void 0:r.composition)!=null&&l.rendering&&this.sprite.texture.source.uid!=this.textrues.canvas.source.uid&&(this.sprite.texture=this.textrues.canvas),!((d=(s=this.track)==null?void 0:s.composition)!=null&&d.rendering)&&this.sprite.texture.source.uid!=this.textrues.html5.source.uid&&(this.sprite.texture=this.textrues.html5),n.apply(this,i)},t}var I0=Object.defineProperty,$0=Object.getOwnPropertyDescriptor,F0=(o,a,t,n)=>{for(var i=$0(a,t),r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&I0(a,t,i),i};const Km=class qm extends bl(gl){constructor(t,n={}){super();ie(this,"source",new To);ie(this,"type","video");ie(this,"worker");ie(this,"buffer");ie(this,"canvas",document.createElement("canvas"));ie(this,"context",this.canvas.getContext("2d"));ie(this,"element",document.createElement("video"));ie(this,"textrues",{html5:jt.Texture.from(this.element),canvas:jt.Texture.from(this.canvas)});ie(this,"sprite",new jt.Sprite);this.element.controls=!1,this.element.playsInline=!0,this.element.style.display="hidden",this.element.crossOrigin="anonymous",this.textrues.html5.source.autoPlay=!1,this.textrues.html5.source.loop=!1,this.sprite.texture=this.textrues.html5,this.view.addChild(this.sprite),t instanceof To&&(this.source=t),t instanceof File&&this.source.from(t),this.element.addEventListener("play",()=>{this.playing=!0}),this.element.addEventListener("pause",()=>{this.playing=!1}),Object.assign(this,n)}async init(){const t=await this.source.createObjectURL();this.element.setAttribute("src",t),await new Promise((n,i)=>{this.element.oncanplay=()=>{this.duration.seconds=this.element.duration,this.state="READY",n()},this.element.onerror=()=>{this.state="ERROR";const r=new Ln({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."});i(this.element.error??r)}})}async connect(t){var i;super.connect(t);const n=((i=t.composition)==null?void 0:i.frame)??0;await this.seek(Ze.fromFrames(n))}enter(){var t,n,i;super.enter(),(n=(t=this.track)==null?void 0:t.composition)!=null&&n.rendering&&((i=this.buffer)==null?void 0:i.state)!="active"&&this.decodeVideo()}update(t){var n,i,r,l,s,d;if((i=(n=this.track)==null?void 0:n.composition)!=null&&i.playing&&!this.playing)this.element.play();else if(!((l=(r=this.track)==null?void 0:r.composition)!=null&&l.playing)&&this.playing)this.element.pause();else if((d=(s=this.track)==null?void 0:s.composition)!=null&&d.rendering)return this.nextFrame()}exit(){this.playing&&this.element.pause(),this.filters&&this.view.filters&&(this.view.filters=null)}copy(){const t=qm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.source=this.source,t}async decodeVideo(){var t,n;return this.buffer=new B0,this.worker=new T0,this.worker.addEventListener("message",i=>{var r,l;i.data.type=="frame"?(r=this.buffer)==null||r.enqueue(i.data.frame):i.data.type=="error"?this.cancelDecoding():i.data.type=="done"&&((l=this.buffer)==null||l.close())}),this.worker.postMessage({type:"init",file:await this.source.getFile(),range:this.demuxRange,fps:((n=(t=this.track)==null?void 0:t.composition)==null?void 0:n.fps)??Ki}),this.buffer}async nextFrame(){if(!this.buffer)return;const t=await this.buffer.dequeue();t&&(this.canvas.width=t.displayWidth,this.canvas.height=t.displayHeight,this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.context.drawImage(t,0,0),this.textrues.canvas.source.update(),t.close())}get demuxRange(){var r;const t=(r=this.track)==null?void 0:r.composition;let n;this.start.millis<0?n=Math.abs(this.offset.seconds):n=this.range[0].seconds;let i;return t&&this.stop.millis>t.duration.millis?i=t.duration.subtract(this.offset).seconds:i=this.range[1].seconds,[n,i]}cancelDecoding(){var t,n;(t=this.worker)==null||t.terminate(),this.worker=void 0,(n=this.buffer)==null||n.terminate(),this.buffer=void 0}};F0([yl,M0],Km.prototype,"update");let Ls=Km;class Oi extends gl{constructor(t,n={}){super();ie(this,"type","audio");ie(this,"source",new ao);ie(this,"element",new Audio);t instanceof ao&&(this.source=t),t instanceof File&&this.source.from(t),this.element.addEventListener("play",()=>{this.playing=!0}),this.element.addEventListener("pause",()=>{this.playing=!1}),Object.assign(this,n)}async init(){const t=await this.source.createObjectURL();this.element.setAttribute("src",t),this.element.load(),await new Promise((n,i)=>{this.element.oncanplay=()=>{this.duration.seconds=this.element.duration,this.state="READY",n()},this.element.onerror=()=>{this.state="ERROR";const r=new Ln({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."});i(this.element.error??r)}})}update(){var t,n,i,r,l,s;if((n=(t=this.track)==null?void 0:t.composition)!=null&&n.rendering)return this.exit();(r=(i=this.track)==null?void 0:i.composition)!=null&&r.playing&&!this.playing?this.element.play():!((s=(l=this.track)==null?void 0:l.composition)!=null&&s.playing)&&this.playing&&this.element.pause()}exit(){this.playing&&this.element.pause()}copy(){const t=Oi.fromJSON(JSON.parse(JSON.stringify(this)));return t.source=this.source,t}}const D0={IMAGE:{"image/jpeg":"jpg","image/png":"png","image/webp":"webp","image/svg+xml":"svg"},VIDEO:{"video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov"},AUDIO:{"audio/mp3":"mp3","audio/mpeg":"mp3","audio/aac":"aac","audio/wav":"wav","audio/x-wav":"wav"},DOCUMENT:{"text/html":"html"},get MIXED(){return{...this.IMAGE,...this.VIDEO,...this.AUDIO,...this.DOCUMENT}}};function Ps(o){if(!Object.keys(D0.MIXED).includes(o??""))throw new oa({message:`${o} is not an accepted mime type`,code:"invalid_mimetype"});return o}var A0=Object.defineProperty,R0=Object.getOwnPropertyDescriptor,L0=(o,a,t,n)=>{for(var i=R0(a,t),r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&A0(a,t,i),i};const P0=class Jm extends bl(ir){constructor(t,n={}){super();ie(this,"type","html");ie(this,"source",new Rc);ie(this,"element",new Image);ie(this,"canvas",document.createElement("canvas"));ie(this,"context",this.canvas.getContext("2d"));ie(this,"sprite",new jt.Sprite);this.view.addChild(this.sprite),Object.assign(this,n),t instanceof Rc&&(this.source=t),t instanceof File&&this.source.from(t),this.element.addEventListener("load",()=>{var l,s,d,c;const i=(s=(l=this.source.document)==null?void 0:l.body)==null?void 0:s.scrollWidth,r=(c=(d=this.source.document)==null?void 0:d.body)==null?void 0:c.scrollHeight;!i||!r||(this.canvas.width=i,this.canvas.height=r,this.context.imageSmoothingEnabled=!1,this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.context.drawImage(this.element,0,0),this.sprite.texture=jt.Texture.from(this.canvas,!0),this.trigger("load",void 0))}),this.element.addEventListener("error",i=>{this.state="ERROR",this.trigger("error",new Ln({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."})),this.track&&this.detach()}),this.on("update",async()=>{this.source.update(),this.element.setAttribute("src",await this.source.createObjectURL())})}async init(){this.element.setAttribute("src",await this.source.createObjectURL()),await new Promise((t,n)=>{this.element.onload=()=>{var l,s,d,c;const i=(s=(l=this.source.document)==null?void 0:l.body)==null?void 0:s.scrollWidth,r=(c=(d=this.source.document)==null?void 0:d.body)==null?void 0:c.scrollHeight;if(!i||!r)return n(new Ln({code:"sourceNotProcessable",message:"Cannot display source with height or width at 0"}));this.state="READY",t()},this.element.onerror=i=>{n(new Ln({code:"sourceNotProcessable",message:"An error occurred while processing the input medium."}))}})}update(t){}copy(){const t=Jm.fromJSON(JSON.parse(JSON.stringify(this)));return t.filters=this.filters,t.source=this.source,t}};L0([yl],P0.prototype,"update");const Ym=["DEFAULT","STACK"];class Oc{constructor(){ie(this,"mode",Ym[0]);ie(this,"pauseAlignmet",!1)}add(a,t){let n=!0;for(let i=0;i<t.clips.length&&(n=Wc(a,t.clips[i]),!!n);i++)jc(a,t.clips[i]);n&&(t.clips.push(a),t.clips.sort(zc))}update(a,t){if(!this.pauseAlignmet){t.clips.sort(zc);for(let n=0;n<t.clips.length;n++)if(a.id!=t.clips[n].id){if(!Wc(a,t.clips[n]))break;jc(a,t.clips[n])}}}offset(a,t){this.pauseAlignmet=!0;for(const n of t.clips)n.offsetBy(a);this.pauseAlignmet=!1}}class U0{constructor(){ie(this,"mode",Ym[1])}add(a,t,n=void 0){var r;let i=-1;(n!=null&&n>0||n==null)&&(i=((r=t.clips.at((n??0)-1))==null?void 0:r.stop.millis)??-1),a.offsetBy(new Ze(i-a.start.millis+1)),n==null?t.clips.push(a):(t.clips.splice(n,0,a),t.clips.slice(n+1).forEach(l=>{l.offsetBy(a.stop.subtract(a.start))}))}update(a,t){let n=0;for(const i of t.clips){if(i.start.millis!=n){const r=n-i.start.millis;i.offsetBy(new Ze(r))}n=i.stop.millis+1}}offset(){}}function zc(o,a){return o.start.millis-a.start.millis}function jc(o,a){o.start.millis>=a.start.millis&&o.start.millis<=a.stop.millis&&(o.start=a.stop.copy().addMillis(1)),o.stop.millis>=a.start.millis&&o.stop.millis<=a.stop.millis&&(o.stop=a.start.copy().addMillis(-1))}function Wc(o,a){var t,n,i,r,l;if(o.start.millis>=a.start.millis&&o.stop.millis<=a.stop.millis){const s=(n=(t=a.track)==null?void 0:t.composition)==null?void 0:n.tracks.find(d=>d.type==o.type&&!d.clips.some(c=>o.id!=c.id&&o.start.millis>=c.start.millis&&o.stop.millis<=c.stop.millis));return s?(s.add(o.detach()),!1):((l=(r=(i=a.track)==null?void 0:i.composition)==null?void 0:r.createTrack(o.type))==null||l.add(o.detach()),!1)}return!0}class mi extends nr(Ya){constructor(){super(...arguments);ie(this,"_disabled",!1);ie(this,"view",new jt.Container);ie(this,"clips",[]);ie(this,"pointer",0);ie(this,"composition");ie(this,"type","base");ie(this,"strategy",new Oc)}get disabled(){return this._disabled}set disabled(t){var n;t&&this.clipRef&&ss(this.clipRef)&&(this.view.removeChild(this.clipRef.view),(n=this.clipRef)==null||n.exit()),this._disabled=t,this.trigger("update",void 0)}connect(t){this.composition=t}stacked(t=!0){return t?(this.strategy=new U0,this.strategy.update(new ir,this)):this.strategy=new Oc,this.trigger("update",void 0),this}layer(t){var s,d;const n=((s=this.composition)==null?void 0:s.tracks)??[],i=n.findIndex(c=>c.id==this.id),r=n.length-1;if(i==-1)return this;let l=0;return t=="bottom"?l=r:t=="top"||t<0?l=0:t>r?l=r:l=t,Ky(n,i,l),(d=this.composition)==null||d.stage.setChildIndex(this.view,r-l),this.trigger("update",void 0),this}seek(t){}offsetBy(t){return typeof t=="number"?this.strategy.offset(Ze.fromFrames(t),this):this.strategy.offset(t,this),this}update(t){var i,r;if(this.disabled||!this.clips.length)return;const{millis:n}=t;if(ss(this.clipRef)&&(!ls(n,this.clipRef)||(i=this.clipRef)!=null&&i.disabled)&&(this.clipRef&&this.view.removeChild(this.clipRef.view),(r=this.clipRef)==null||r.exit()),!!ls(n,this))for(let l=0;l<this.clips.length;l++){const s=(this.pointer+l)%this.clips.length,d=this.clips[s],c=this.clips[s-1];if(ls(n,d)&&!d.disabled)return this.pointer=s,ss(d)||(d.enter(),this.view.addChild(d.view)),d.update(t);if(n<d.start.millis&&n>((c==null?void 0:c.stop.millis)??0)){this.pointer=s;return}}}async add(t,n){return this.composition&&!this.composition.renderer&&await new Promise(this.composition.resolve("init")),await t.init(),await t.connect(this),await this.strategy.add(t,this,n),t.on("frame",()=>{this.strategy.update(t,this)}),t.bubble(this),this.trigger("attach",void 0),t}remove(t){const n=this.clips.findIndex(i=>i.id==t.id);if(t.state=="ATTACHED"&&(t.state="READY"),t.view.parent&&this.view.removeChild(t.view),n!=null&&n>=0)return this.clips.splice(n,1),this.strategy.update(t,this),this.trigger("detach",void 0),t.off("*"),t}get stop(){var t;return((t=this.clips.at(-1))==null?void 0:t.stop)??new Ze}get start(){var t;return((t=this.clips.at(0))==null?void 0:t.start)??new Ze}apply(t){this.clips.forEach(t)}detach(){var t;return(t=this.composition)==null||t.removeTrack(this),this}get clipRef(){return this.clips[this.pointer]}}function ls(o,a){return a?o>=a.start.millis&&o<=a.stop.millis:!1}function ss(o){return o?!!o.view.parent:!1}class O0{static fromType(a){switch(a.type){case"video":return new z0;case"audio":return new W0;case"html":return new H0;case"image":return new j0;case"text":return new Hc;case"complex_text":return new Hc;case"caption":return new G0;default:return new mi}}}class Qm extends mi{constructor(){super(...arguments);ie(this,"clips",[])}async seek(t){for(const n of this.clips)await n.seek(t)}async removeSilences(t={}){const n=[];for(const i of this.clips.map(r=>r.detach()))n.push(...await i.removeSilences(t));for(const i of n)await this.add(i)}}class z0 extends Qm{constructor(){super(...arguments);ie(this,"type","video")}async seek(t){var n;(n=this.composition)!=null&&n.rendering?this.view.removeChildren():super.seek(t)}}class j0 extends mi{constructor(){super(...arguments);ie(this,"type","image")}}class W0 extends Qm{constructor(){super(...arguments);ie(this,"type","audio")}}class Hc extends mi{constructor(){super(...arguments);ie(this,"type","text")}}class H0 extends mi{constructor(){super(...arguments);ie(this,"type","html")}}var Z0=Object.defineProperty,Td=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&Z0(a,t,i),i};class lr extends Ya{constructor(t={}){super();ie(this,"generatorOptions");ie(this,"type","CLASSIC");ie(this,"position");this.generatorOptions=t.generatorOptions??{duration:[.2]},this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var r,l,s;if(!((r=t.clip)!=null&&r.transcript)||!((l=t.composition)!=null&&l.width))throw new oa({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((s=t.clip)==null?void 0:s.offset)??new Ze,i=await Ea.fromFamily({family:"Figtree",weight:"700"}).load();for(const d of t.clip.transcript.iter(this.generatorOptions))await t.add(new ci({text:d.words.map(c=>c.text).join(" "),textAlign:"center",textBaseline:"middle",fontSize:21,fillStyle:"#FFFFFF",font:i,stroke:{color:"#000000",width:4,join:"round"},maxWidth:t.composition.width*.85,shadow:{color:"#000000",blur:0,distance:1.1,angle:Math.PI*.4,alpha:1},position:this.position,stop:d.stop.add(n),start:d.start.add(n),scale:new Ye([0,8],[.96,1],{easing:"easeOut"}),alpha:new Ye([0,4],[0,1],{easing:"easeOut"})}))}}Td([We()],lr.prototype,"generatorOptions");Td([We()],lr.prototype,"type");Td([We()],lr.prototype,"position");class G0 extends mi{constructor(){super(...arguments);ie(this,"clip");ie(this,"type","caption");ie(this,"preset",new lr)}from(t){var n;return this.clip=t,(n=this.clip)==null||n.on("offsetBy",i=>this.offsetBy(i.detail)),this}async generate(t){let n=this.preset;return typeof t=="object"?n=t:t&&(n=new t),this.clips=[],this.trigger("update",void 0),this.preset=n,await n.applyTo(this),this.trigger("update",void 0),this}}var X0=Object.defineProperty,_l=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&X0(a,t,i),i};class sr extends Ya{constructor(t={}){super();ie(this,"generatorOptions");ie(this,"type","SPOTLIGHT");ie(this,"color");ie(this,"position");this.generatorOptions=t.generatorOptions??{duration:[.2]},this.color=t.color??"#00FF4C",this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var r,l,s;if(!((r=t.clip)!=null&&r.transcript)||!((l=t.composition)!=null&&l.width))throw new oa({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((s=t.clip)==null?void 0:s.offset)??new Ze,i=await Ea.fromFamily({family:"The Bold Font",weight:"500"}).load();for(const d of t.clip.transcript.iter(this.generatorOptions))for(let c=0;c<d.words.length;c++){const u=d.words.map(m=>m.text);await t.add(new kl({text:u.join(" "),textAlign:"center",textBaseline:"middle",fillStyle:"#FFFFFF",fontSize:22,maxWidth:t.composition.width*.8,font:i,stroke:{width:5,color:"#000000"},shadow:{color:"#000000",blur:12,alpha:.7,angle:Math.PI/4,distance:2},position:this.position,styles:[{fillStyle:this.color}],segments:d.words.length>1?[{index:0,start:u.slice(0,c).join(" ").length,stop:u.slice(0,c+1).join(" ").length}]:void 0,stop:d.words[c].stop.add(n),start:d.words[c].start.add(n)}))}}}_l([We()],sr.prototype,"generatorOptions");_l([We()],sr.prototype,"type");_l([We()],sr.prototype,"color");_l([We()],sr.prototype,"position");var K0=Object.defineProperty,Bd=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&K0(a,t,i),i};class El extends Ya{constructor(t={}){super();ie(this,"type","GUINEA");ie(this,"colors");ie(this,"position");this.colors=t.colors??["#1BD724","#FFEE0C","#FF2E17"],this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var r,l,s,d,c,u,m;if(!((r=t.clip)!=null&&r.transcript)||!((l=t.composition)!=null&&l.width))throw new oa({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((s=t.clip)==null?void 0:s.offset)??new Ze,i=await Ea.fromFamily({family:"The Bold Font",weight:"500"}).load();for(const p of t.clip.transcript.iter({length:[18]})){const{segments:f,words:h}=this.splitSequence(p);for(let v=0;v<p.words.length;v++){const y=(c=(d=h[v])==null?void 0:d.at(0))==null?void 0:c.start,w=(m=(u=h[v])==null?void 0:u.at(-1))==null?void 0:m.stop;!y||!w||await t.add(new kl({text:f.join(`
33
+ `),textAlign:"center",textBaseline:"middle",fontSize:20,fillStyle:"#FFFFFF",shadow:{color:"#000000",blur:16,alpha:.8,angle:Math.PI/4,distance:1},stroke:{width:4,color:"#000000"},maxWidth:t.composition.width*.8,leading:1.3,font:i,textCase:"upper",position:this.position,stop:w.add(n),start:y.add(n),styles:[{fillStyle:this.colors[0],fontSize:23},{fillStyle:this.colors[1],fontSize:23},{fillStyle:this.colors[2],fontSize:23}],segments:[{index:Ur(0,2),start:f.slice(0,v).join(" ").length,stop:f.slice(0,v+1).join(" ").length+v*2}]}))}}}splitSequence(t){const n=t.text,i=Math.ceil(n.length/2);let r=n.length;for(let d=i,c=i;d>0&&c<t.text.length-1;d--,c++){if(n[d].match(/ /)){r=d;break}if(n[c].match(/ /)){r=c;break}}const l=[...Bc(n,r).map(d=>d.trim())],s=Bc(t.words,l[0].split(/ /).length);return{segments:l,words:s}}}Bd([We()],El.prototype,"type");Bd([We()],El.prototype,"colors");Bd([We()],El.prototype,"position");var q0=Object.defineProperty,Md=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&q0(a,t,i),i};class Sl extends Ya{constructor(t={}){super();ie(this,"generatorOptions");ie(this,"type","CASCADE");ie(this,"position");this.generatorOptions=t.generatorOptions??{duration:[1.4]},this.position=t.position??{x:"12%",y:"44%"}}async applyTo(t){var r,l,s;if(!((r=t.clip)!=null&&r.transcript)||!((l=t.composition)!=null&&l.width))throw new oa({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((s=t.clip)==null?void 0:s.offset)??new Ze,i=await Ea.fromFamily({family:"Geologica",weight:"400"}).load();for(const d of t.clip.transcript.iter(this.generatorOptions))for(let c=0;c<d.words.length;c++){const u=()=>d.words.length==1?d.text:d.words.map(m=>m.text).slice(0,c+1).join(" ");await t.add(new ci({text:u(),textAlign:"left",textBaseline:"top",fillStyle:"#FFFFFF",fontSize:16,font:i,maxWidth:t.composition.width*.7,stroke:{color:"#000000",width:4,join:"round"},shadow:{color:"#000000",blur:8,alpha:.4,angle:Math.PI/4,distance:2},position:this.position,stop:d.words[c].stop.add(n),start:d.words[c].start.add(n)}))}}}Md([We()],Sl.prototype,"generatorOptions");Md([We()],Sl.prototype,"type");Md([We()],Sl.prototype,"position");var J0=Object.defineProperty,Id=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&J0(a,t,i),i};class Cl extends Ya{constructor(t={}){super();ie(this,"generatorOptions");ie(this,"type","SOLAR");ie(this,"position");this.generatorOptions=t.generatorOptions??{duration:[.2]},this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var l,s,d;if(!((l=t.clip)!=null&&l.transcript)||!((s=t.composition)!=null&&s.width))throw new oa({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=await Ea.fromFamily({family:"Urbanist",weight:"800"}).load(),i=((d=t.clip)==null?void 0:d.offset)??new Ze,r=new xh.GlowFilter({color:"#fffe41",alpha:.25,distance:90,quality:.05});for(const c of t.clip.transcript.iter(this.generatorOptions))await t.add(new ci({text:c.words.map(u=>u.text).join(" "),textAlign:"center",textBaseline:"middle",fontSize:19,fillStyle:"#fffe41",font:n,maxWidth:t.composition.width*.85,textCase:"upper",shadow:{color:"#ab7a00",blur:0,distance:2.1,angle:Math.PI/2.5,alpha:1},position:this.position,stop:c.stop.add(i),start:c.start.add(i),scale:new Ye([0,8],[.96,1],{easing:"easeOut"}),alpha:new Ye([0,4],[0,1],{easing:"easeOut"}),filters:r}))}}Id([We()],Cl.prototype,"generatorOptions");Id([We()],Cl.prototype,"type");Id([We()],Cl.prototype,"position");var Y0=Object.defineProperty,xl=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&Y0(a,t,i),i};class dr extends Ya{constructor(t={}){super();ie(this,"generatorOptions");ie(this,"type","WHISPER");ie(this,"color");ie(this,"position");this.generatorOptions=t.generatorOptions??{length:[20]},this.color=t.color??"#8c8c8c",this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var r,l,s;if(!((r=t.clip)!=null&&r.transcript)||!((l=t.composition)!=null&&l.width))throw new oa({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((s=t.clip)==null?void 0:s.offset)??new Ze,i=await Ea.fromFamily({family:"Montserrat",weight:"300"}).load();for(const d of t.clip.transcript.iter(this.generatorOptions))for(let c=0;c<d.words.length;c++){const u=d.words.map(m=>m.text);await t.add(new kl({text:u.join(" "),textAlign:"center",textBaseline:"middle",fillStyle:"#FFFFFF",fontSize:13,background:{alpha:.3,padding:{x:50,y:30}},maxWidth:t.composition.width*.8,font:i,position:this.position,styles:[{fillStyle:this.color}],stop:d.words[c].stop.add(n),start:d.words[c].start.add(n),segments:u.length>1?[{index:0,start:u.slice(0,c+1).join(" ").length}]:void 0}))}}}xl([We()],dr.prototype,"generatorOptions");xl([We()],dr.prototype,"type");xl([We()],dr.prototype,"color");xl([We()],dr.prototype,"position");var Q0=Object.defineProperty,Nl=(o,a,t,n)=>{for(var i=void 0,r=o.length-1,l;r>=0;r--)(l=o[r])&&(i=l(a,t,i)||i);return i&&Q0(a,t,i),i};class Vl extends Ya{constructor(t={}){super();ie(this,"type","VERDANT");ie(this,"generatorOptions");ie(this,"color");ie(this,"position");this.generatorOptions=t.generatorOptions??{duration:[1]},this.color=t.color??"#69E34C",this.position=t.position??{x:"50%",y:"50%"}}async applyTo(t){var r,l,s;if(!((r=t.clip)!=null&&r.transcript)||!((l=t.composition)!=null&&l.width))throw new oa({code:"referenceError",message:"Captions need to be applied with a defined transcript and composition"});const n=((s=t.clip)==null?void 0:s.offset)??new Ze,i=await Ea.fromFamily({family:"Montserrat",weight:"800"}).load();for(const d of t.clip.transcript.iter(this.generatorOptions))for(let c=0;c<d.words.length;c++){const u=d.words.map(m=>m.text);await t.add(new kl({text:u.join(" "),textAlign:"center",textBaseline:"middle",fontSize:15,fillStyle:"#FFFFFF",shadow:{color:"#000000",blur:4,alpha:.7,angle:Math.PI/4,distance:2},stroke:{width:3,color:"#000000"},maxWidth:t.composition.width*.5,leading:1.1,font:i,textCase:"upper",styles:[{fillStyle:this.color,fontSize:19}],position:this.position,stop:d.words[c].stop.add(n),start:d.words[c].start.add(n),segments:[{index:0,start:u.slice(0,c).join(" ").length,stop:u.slice(0,c+1).join(" ").length}]}))}}}Nl([We()],Vl.prototype,"type");Nl([We()],Vl.prototype,"generatorOptions");Nl([We()],Vl.prototype,"color");Nl([We()],Vl.prototype,"position");class e1 extends nr(Ya){constructor({height:t=1080,width:n=1920,background:i="#000000",backend:r="webgpu"}={}){super();ie(this,"_duration",new Ze);ie(this,"renderer");ie(this,"stage",new jt.Container);ie(this,"settings");ie(this,"tracks",[]);ie(this,"frame",0);ie(this,"fixedDuration");ie(this,"state","IDLE");ie(this,"fps",Ki);ie(this,"canvas");ie(this,"context");this.settings={height:t,width:n,background:i,backend:r},this.on("update",this.update.bind(this)),this.on("attach",this.update.bind(this)),this.on("detach",this.update.bind(this)),this.on("load",this.update.bind(this)),this.on("frame",this.update.bind(this)),this.on("error",this.update.bind(this)),jt.autoDetectRenderer({...this.settings,preference:r}).then(l=>{this.renderer=l,this.trigger("init",void 0)}).catch(l=>{this.trigger("error",new ri({code:"backendDetectionError",message:`${l}`}))})}get playing(){return this.state=="PLAY"}get rendering(){return this.state=="RENDER"}get width(){return this.settings.width}get height(){return this.settings.height}get duration(){return this.fixedDuration?this.fixedDuration:this._duration}set duration(t){var n;t?t instanceof Ze?this.fixedDuration=t:this.fixedDuration=Ze.fromFrames(t):this.fixedDuration=void 0,this.trigger("frame",((n=this.fixedDuration)==null?void 0:n.frames)??0)}resize(t,n){var i;this.settings.width=t,this.settings.height=n,(i=this.renderer)==null||i.resize(t,n),this.canvas&&(this.canvas.height=n,this.canvas.width=t),this.trigger("resize",void 0),this.computeFrame()}attachPlayer(t){this.canvas||(this.canvas=document.createElement("canvas"),this.canvas.height=this.settings.height,this.canvas.width=this.settings.width,this.canvas.style.background="black",this.context=this.canvas.getContext("2d"),this.context.imageSmoothingEnabled=!1,this.computeFrame()),t.appendChild(this.canvas)}detachPlayer(t){this.canvas&&t.removeChild(this.canvas)}shiftTrack(t){const n=typeof t=="object"?t:new t;return n.connect(this),this.stage.addChild(n.view),this.tracks.unshift(n),n.bubble(this),this.trigger("update",void 0),n}createTrack(t){const n=O0.fromType({type:t});return this.shiftTrack(n),n}async add(t){return await this.createTrack(t.type).add(t),t}remove(t){for(const n of this.tracks)if(n.clips.find(i=>i.id==t.id))return n.remove(t)}removeTracks(t){const n=this.tracks.filter(i=>i instanceof t);return this.tracks=this.tracks.filter(i=>!(i instanceof t)),n.forEach(i=>this.removeTrack(i)),n}findTracks(t){return this.tracks.filter(n=>{let i;return Mc(t)?i=n instanceof t:i=t(n),i})}findClips(t){const n=[];for(const i of this.tracks)for(const r of i.clips){let l;Mc(t)?l=r instanceof t:l=t(r),l&&n.push(r)}return n}computeFrame(){var t,n;if(this.renderer){for(let i=0;i<this.tracks.length;i++)this.tracks[i].update(Ze.fromFrames(this.frame));this.renderer.render(this.stage),(t=this.context)==null||t.clearRect(0,0,this.settings.width,this.settings.height),(n=this.context)==null||n.drawImage(this.renderer.canvas,0,0),this.trigger("currentframe",this.frame),this.playing&&this.frame++}}screenshot(t="png",n=1){if(this.computeFrame(),!this.renderer)throw new ri({code:"rendererNotDefined",message:"Please wait until the renderer is defined"});return this.renderer.canvas.toDataURL(`image/${t}`,n)}async seek(t){typeof t=="number"?this.frame=Math.round(t>0?t:0):this.frame=t.frames>0?t.frames:0,this.playing&&this.pause();for(const n of this.tracks)await n.seek(Ze.fromFrames(this.frame));this.rendering||this.computeFrame()}async play(){if(!this.rendering){this.state="PLAY",this.frame>=this.duration.frames&&(this.frame=0);for(const t of this.tracks)await t.seek(Ze.fromFrames(this.frame));this.ticker(),this.trigger("play",this.frame)}}async pause(){this.state="IDLE",this.computeFrame(),this.trigger("pause",this.frame)}async audio(t=2,n=48e3){var l;const i=this.duration.seconds*n,r=new OfflineAudioContext({sampleRate:n,length:i,numberOfChannels:t}).createBuffer(t,i,n);for(const s of this.findClips(gl)){if(s.disabled||s.muted||(l=s.track)!=null&&l.disabled)continue;const d=Math.round(s.offset.seconds*r.sampleRate),c=Math.round(s.range[0].seconds*r.sampleRate),u=Math.round(s.range[1].seconds*r.sampleRate);try{const m=await s.source.decode(t,n),p=m.numberOfChannels-1;for(let f=0;f<t;f++){const h=r.getChannelData(f),v=m.getChannelData(f>p?p:f);for(let y=0;y<h.length-1;y++)y<d+c||y>d+u||y-d<0||(h[y]+=(v[y-d]??0)*s.volume,h[y]>1&&(h[y]=1),h[y]<-1&&(h[y]=-1));r.getChannelData(f).set(h)}}catch{}}return r}time(t){const n=Qo(this.frame),i=t!=null&&t.hours?11:14,r=t!=null&&t.milliseconds?23:19;return new Date(n).toISOString().slice(i,r)+" / "+new Date(this.duration.millis).toISOString().slice(i,r)}removeTrack(t){const n=this.tracks.findIndex(i=>i.id==t.id);if(t.view.parent&&this.stage.removeChild(t.view),n!=null&&n>=0)return this.tracks.splice(n,1),this.trigger("detach",void 0),t.off("*"),t}async ticker(){const t=1e3/Ki;let n=performance.now(),i=0;do{const r=await new Promise(requestAnimationFrame);r-n<t-i||(i=Math.min(t,i+r-n-t),n=r,this.computeFrame())}while(this.frame<=this.duration.frames&&this.playing);this.playing&&this.seek(0)}update(){this._duration.frames=Math.max(...this.tracks.filter(t=>!t.disabled).map(t=>{var n;return((n=t.stop)==null?void 0:n.frames)??0}),0),this.computeFrame()}}function t1(o,a){const t=new Uint8Array(19);return t[0]=79,t[1]=112,t[2]=117,t[3]=115,t[4]=72,t[5]=101,t[6]=97,t[7]=100,t[8]=1,t[9]=a,t[10]=0,t[11]=0,t[12]=o&255,t[13]=o>>8&255,t[14]=o>>16&255,t[15]=o>>24&255,t[16]=0,t[17]=0,t[18]=0,t}const Us=[8e3,12e3,16e3,24e3,48e3],a1="https://cdn.jsdelivr.net/npm/@diffusionstudio/libopus-wasm@1.0.0/dist/opus.wasm",n1="https://cdn.jsdelivr.net/npm/@diffusionstudio/libopus-wasm@1.0.0/dist/opus.js";class o1{constructor(a){ie(this,"output");ie(this,"error");ie(this,"config");ie(this,"encoder");ie(this,"opus");ie(this,"meta");this.output=a.output,this.error=a.error}async configure(a){const t=await import(n1),{numberOfChannels:n,sampleRate:i}=this.config=a;if(!Us.includes(i))throw new tl({code:"sampleRateNotSupported",message:`Unsupported sample rate, supported: ${Us.join()}`});this.opus=await t.default({locateFile(r,l){return r.endsWith(".wasm")?a1:l+r}}),this.encoder=this.opus._opus_encoder_create(i,n,2048),this.meta={decoderConfig:{codec:"opus",description:t1(i,n).buffer,numberOfChannels:n,sampleRate:i}}}encode({data:a,numberOfFrames:t,timestamp:n=0}){if(!this.encoder||!this.opus||!this.config||!this.meta)throw new tl({code:"unconfiguredEncoder",message:"Cannot encode samples using an unconfigured encoder"});const{sampleRate:i,numberOfChannels:r}=this.config,l=Math.floor(i/1e3*20);let s=0;const d=l/i*1e6;for(;s<t;){const c=a.subarray(s*r,(s+l)*r),u=this.opus._malloc(c.length*2);this.opus.HEAP16.set(c,u>>1);const m=4e3,p=this.opus._malloc(m),f=this.opus._opus_encode(this.encoder,u,l,p,m);if(f>0){const h=new Uint8Array(this.opus.HEAPU8.subarray(p,p+f));this.output({data:h,timestamp:n,type:"key",duration:d},this.meta)}else this.error(new DOMException("PCM chunk could not be encoded"));this.opus._free(u),this.opus._free(p),s+=l,n+=d}}}function i1(o){const a=Us;let t=48e3;for(const n of a)Math.abs(o-n)<Math.abs(o-t)&&(t=n);return t}class r1{constructor(a,t){ie(this,"canvas");ie(this,"muxer");ie(this,"videoEncoder");ie(this,"frame",0);ie(this,"sampleRate");ie(this,"numberOfChannels");ie(this,"videoBitrate");ie(this,"gpuBatchSize");ie(this,"fps");ie(this,"height");ie(this,"width");ie(this,"audio");this.canvas=a,this.width=a.width,this.height=a.height,this.fps=(t==null?void 0:t.fps)??30,this.sampleRate=i1((t==null?void 0:t.sampleRate)??48e3),this.numberOfChannels=(t==null?void 0:t.numberOfChannels)??2,this.videoBitrate=(t==null?void 0:t.videoBitrate)??1e7,this.gpuBatchSize=(t==null?void 0:t.gpuBatchSize)??5,this.audio=(t==null?void 0:t.audio)??!1}async init(){const a=await Yy({height:Math.round(this.height),width:Math.round(this.width),bitrate:this.videoBitrate,fps:this.fps});this.muxer=new Pm({target:new yd,video:{...a[0],codec:"avc"},firstTimestampBehavior:"offset",fastStart:"in-memory",audio:this.audio?{numberOfChannels:this.numberOfChannels,sampleRate:this.sampleRate,codec:"opus"}:void 0});const t={output:(n,i)=>{i&&this.muxer.addVideoChunk(n,i)},error:console.error};this.videoEncoder=new VideoEncoder(t),this.videoEncoder.configure(a[0])}async encodeVideo(a){var n;this.videoEncoder||await this.init(),this.videoEncoder.encodeQueueSize>this.gpuBatchSize&&await new Promise(i=>{this.videoEncoder.ondequeue=()=>i(null)});const t=new VideoFrame(a??this.canvas,{timestamp:Math.floor(this.frame/this.fps*1e6),duration:Math.floor(1e6/this.fps)});(n=this.videoEncoder)==null||n.encode(t,{keyFrame:this.frame%(3*this.fps)==0}),t.close(),this.frame++}async encodeAudio(a){if(!this.audio)throw new tl({code:"initializationError",message:"Encoder must be initialized using {audio: true} to use this method"});this.muxer||await this.init();const t=Jy(a,this.sampleRate,this.numberOfChannels),n=new o1({output:(i,r)=>{var l;(l=this.muxer)==null||l.addAudioChunkRaw(i.data,i.type,i.timestamp,i.duration,r)},error:console.error});await n.configure({numberOfChannels:this.numberOfChannels,sampleRate:this.sampleRate}),n.encode({data:qy(t),numberOfFrames:t.length})}async blob(){var t,n,i;await((t=this.videoEncoder)==null?void 0:t.flush()),(n=this.muxer)==null||n.finalize();const a=(i=this.muxer)==null?void 0:i.target.buffer;if(!a)throw new tl({code:"unexpectedRenderError",message:"Muxer could not be finalized because the target buffer is not defined"});return new Blob([a],{type:"video/mp4"})}async export(){return this.blob()}}async function l1(o){var n,i;const a=(n=o.metadata)==null?void 0:n.source_url;if(a)return a;const t=(i=o.source)==null?void 0:i.media_uuid;if(t){if(typeof window<"u"){const r=window;if(r.MEDIABLES_MEDIA_URLS&&r.MEDIABLES_MEDIA_URLS[t])return r.MEDIABLES_MEDIA_URLS[t]}if(!t.startsWith("temp-"))try{if(typeof fetch<"u"){const r=await fetch(`/api/media/${t}`);if(r.ok){const l=await r.json();return l.playback_url||l.url||void 0}}}catch{}}}const Gi=class Gi{constructor(a){this.transitions=new Map,this.nextId=0,this.composition=a}async applyTransition(a,t,n){const i=`transition-${this.nextId++}`,r=Math.round(n.duration*30),l=n.easing||"linear",s=this.findTrackForClip(a),d=this.findTrackForClip(t);if(!s||!d)throw new Error("Clips must be added to composition before applying transitions");const c=a.stop.frames-r,u=a.stop.frames;switch(n.type){case"fade":await this.applyFadeTransition(a,t,c,u,l);break;case"dissolve":case"cross-fade":await this.applyCrossFadeTransition(a,t,c,u,l);break;case"wipe-left":case"wipe-right":case"wipe-up":case"wipe-down":await this.applyWipeTransition(a,t,n.type,c,u,l);break;case"slide-left":case"slide-right":case"slide-up":case"slide-down":await this.applySlideTransition(a,t,n.type,c,u,l);break;case"zoom-in":case"zoom-out":await this.applyZoomTransition(a,t,n.type,c,u,l);break;case"dip-to-black":case"dip-to-white":await this.applyDipTransition(a,t,n.type,c,u,l);break}return this.transitions.set(i,n),i}async applyFadeTransition(a,t,n,i,r){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Fade transitions require VideoClip instances");a.alpha=new Ye([n,i],[1,0],{easing:r}),t.alpha=new Ye([n,i],[0,1],{easing:r}),t.start=Ze.fromFrames(n)}async applyCrossFadeTransition(a,t,n,i,r){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Cross-fade transitions require VideoClip instances");a.alpha=new Ye([n,i],[1,0],{easing:r}),t.alpha=new Ye([n,i],[0,1],{easing:r}),t.start=Ze.fromFrames(n)}async applyWipeTransition(a,t,n,i,r,l){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Wipe transitions require VideoClip instances");const s={x:0,y:0},d={x:0,y:0};switch(n){case"wipe-left":s.x=new Ye([i,r],[0,-1920],{easing:l}),d.x=new Ye([i,r],[1920,0],{easing:l});break;case"wipe-right":s.x=new Ye([i,r],[0,1920],{easing:l}),d.x=new Ye([i,r],[-1920,0],{easing:l});break;case"wipe-up":s.y=new Ye([i,r],[0,-1080],{easing:l}),d.y=new Ye([i,r],[1080,0],{easing:l});break;case"wipe-down":s.y=new Ye([i,r],[0,1080],{easing:l}),d.y=new Ye([i,r],[-1080,0],{easing:l});break}a.translate=s,t.translate=d,t.start=Ze.fromFrames(i)}async applySlideTransition(a,t,n,i,r,l){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Slide transitions require VideoClip instances");const s={x:0,y:0},d={x:0,y:0};switch(n){case"slide-left":s.x=new Ye([i,r],[0,-1920],{easing:l}),d.x=new Ye([i,r],[1920,0],{easing:l});break;case"slide-right":s.x=new Ye([i,r],[0,1920],{easing:l}),d.x=new Ye([i,r],[-1920,0],{easing:l});break;case"slide-up":s.y=new Ye([i,r],[0,-1080],{easing:l}),d.y=new Ye([i,r],[1080,0],{easing:l});break;case"slide-down":s.y=new Ye([i,r],[0,1080],{easing:l}),d.y=new Ye([i,r],[-1080,0],{easing:l});break}a.translate=s,t.translate=d,t.start=Ze.fromFrames(i)}async applyZoomTransition(a,t,n,i,r,l){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Zoom transitions require VideoClip instances");n==="zoom-in"?(a.scale=new Ye([i,r],[1,2],{easing:l}),a.alpha=new Ye([i,r],[1,0],{easing:l}),t.scale=new Ye([i,r],[.5,1],{easing:l}),t.alpha=new Ye([i,r],[0,1],{easing:l})):(a.scale=new Ye([i,r],[1,.5],{easing:l}),a.alpha=new Ye([i,r],[1,0],{easing:l}),t.scale=new Ye([i,r],[2,1],{easing:l}),t.alpha=new Ye([i,r],[0,1],{easing:l})),t.start=Ze.fromFrames(i)}async applyDipTransition(a,t,n,i,r,l){if(!this.isVideoClip(a)||!this.isVideoClip(t))throw new Error("Dip transitions require VideoClip instances");const s=Math.round((i+r)/2),d=n==="dip-to-black"?"#000000":"#ffffff",c=await As.fromColor(d),u=new b0(c,{start:Ze.fromFrames(i),stop:Ze.fromFrames(r)});a.alpha=new Ye([i,s],[1,0],{easing:l}),u.alpha=new Ye([i,s,r],[0,1,0],{easing:l}),t.alpha=new Ye([s,r],[0,1],{easing:l}),await this.composition.add(u),t.start=Ze.fromFrames(s)}findTrackForClip(a){for(const t of this.composition.tracks)if(t.clips.includes(a))return t}removeTransition(a){this.transitions.delete(a)}getTransitions(){return new Map(this.transitions)}static getAvailableTransitions(){return[...Gi.TRANSITIONS]}static previewTransition(a){return Gi.TRANSITIONS.find(t=>t.type===a)}isVideoClip(a){return"alpha"in a&&"scale"in a&&"translate"in a}};Gi.TRANSITIONS=[{type:"fade",name:"Fade",description:"Simple fade transition"},{type:"dissolve",name:"Dissolve",description:"Cross-dissolve between clips"},{type:"wipe-left",name:"Wipe Left",description:"Wipe from right to left"},{type:"wipe-right",name:"Wipe Right",description:"Wipe from left to right"},{type:"wipe-up",name:"Wipe Up",description:"Wipe from bottom to top"},{type:"wipe-down",name:"Wipe Down",description:"Wipe from top to bottom"},{type:"slide-left",name:"Slide Left",description:"Slide out to the left"},{type:"slide-right",name:"Slide Right",description:"Slide out to the right"},{type:"slide-up",name:"Slide Up",description:"Slide out upward"},{type:"slide-down",name:"Slide Down",description:"Slide out downward"},{type:"zoom-in",name:"Zoom In",description:"Zoom into the next clip"},{type:"zoom-out",name:"Zoom Out",description:"Zoom out to the next clip"},{type:"cross-fade",name:"Cross Fade",description:"Cross-fade between clips"},{type:"dip-to-black",name:"Dip to Black",description:"Fade through black"},{type:"dip-to-white",name:"Dip to White",description:"Fade through white"}];let qi=Gi;function Ka(o,a){if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"){const t=Number(o);if(Number.isFinite(t))return t}return a}function zi(o){return o>5?o/100:o}function s1(o){if(o.value!==void 0){const a=Ka(o.value,0);return a>=-1&&a<=1?1+a:zi(a)}return zi(Ka(o.brightness,1))}function on(o,a,t){return Math.min(t,Math.max(a,o))}function Ma(){return new na.ColorMatrixFilter}function d1(o,a){switch(o){case"brightness":{const t=Ma();return t.brightness(on(s1(a),0,5),!1),t}case"contrast":{const t=Ma(),n=Ka(a.value??a.contrast,1);return t.contrast(on(zi(n),0,5),!1),t}case"saturation":{const t=Ma(),n=Ka(a.value??a.saturation,1);return t.saturate(on(zi(n),0,5),!1),t}case"hue":{const t=Ma(),n=Ka(a.degrees??a.value,0);return t.hue(on(n,-180,180),!1),t}case"blur":case"softFocus":{const t=o==="softFocus"?1:0,n=Ka(a.radius??a.blur??a.value,t);return new na.BlurFilter({strength:on(n,0,32),quality:4})}case"grayscale":{const t=Ma(),n=on(Ka(a.amount,100),0,100);return n<=0?null:(n>=100?t.desaturate():t.saturate(1-n/100,!1),t)}case"sepia":{if(on(Ka(a.amount,100),0,100)<=0)return null;const n=Ma();return n.sepia(!1),n}case"invert":{if(on(Ka(a.amount,100),0,100)<=0)return null;const n=Ma();return n.negative(!1),n}case"warmth":{const t=Ma(),n=on(Ka(a.value,0),-50,50);return n>0?(t.sepia(!1),t.saturate(1+n/100,!1)):n<0&&t.hue(Math.abs(n)/50*-20,!1),t}case"tint":{const t=Ma(),n=on(Ka(a.intensity,.3),0,1),i=typeof a.color=="string"?a.color:"#ff0000",r=i.startsWith("#")?i.slice(1):i;if(r.length===6){const l=parseInt(r.slice(0,2),16)/255,s=parseInt(r.slice(2,4),16)/255,d=parseInt(r.slice(4,6),16)/255;t.matrix=[1-n+n*l,0,0,0,0,0,1-n+n*s,0,0,0,0,0,1-n+n*d,0,0,0,0,0,1,0]}return t}case"vintage":{const t=Ma();return t.sepia(!1),t.saturate(1.4,!1),t.contrast(1.1,!1),t}case"blackAndWhite":{const t=Ma(),n=on(zi(Ka(a.contrast,120)),.5,3);return t.desaturate(),t.contrast(n,!1),t}case"cinematic":{const t=Ma();return t.contrast(1.2,!1),t.brightness(.95,!1),t.saturate(.85,!1),t}case"dramatic":{const t=Ma();return t.contrast(1.4,!1),t.brightness(.9,!1),t.saturate(1.1,!1),t.sepia(!1),t}case"dreamy":{const t=Ma();return t.brightness(1.05,!1),t.saturate(.9,!1),t.contrast(.95,!1),t}default:return null}}typeof window<"u"&&!window.PIXI&&(window.PIXI=na);class ep{constructor(a=1920,t=1080,n=30,i){this.player=null,this.clips=new Map,this.clipTimelineStart=new Map,this.resizeObserver=null,this.recipeSourceDimensions=null,this.filterCache=new Map,this.animationFrameId=null,this.lastRenderedFrame=-1,this.fps=n,this.fitMode=(i==null?void 0:i.fitMode)??"contain",this.composition=new e1({width:a,height:t,background:"#000000"}),this.initPromise=new Promise(r=>{const l=()=>{this.isDebug()&&this.dbg("init:renderer-ready"),r()};this.composition.on("init",l),queueMicrotask(()=>{var d,c,u,m;const s=this.composition;((c=(d=s==null?void 0:s.app)==null?void 0:d.renderer)!=null&&c.view||(u=s==null?void 0:s.renderer)!=null&&u.view||(m=s==null?void 0:s.renderer)!=null&&m.canvas)&&l()})}),this.setupEventHandlers()}isDebug(){try{if(typeof window<"u"&&window.MEDIABLES_DEBUG===1||typeof localStorage<"u"&&localStorage.getItem("mediables.debug")==="1")return!0}catch{}return!1}dbg(...a){this.isDebug()}setupEventHandlers(){this.composition.on("play",()=>this.onPlay()),this.composition.on("pause",()=>this.onPause()),this.composition.on("currentframe",()=>this.onFrameUpdate())}onPlay(){}onPause(){}onFrameUpdate(){}async attachPlayer(a){this.player=a,this.isDebug()&&this.dbg("attachPlayer:begin",{w:a.clientWidth,h:a.clientHeight}),this.composition.attachPlayer(a),await this.initPromise;const t=this.composition;this.isDebug()&&this.dbg("attachPlayer:ready",{hasRenderer:!!(t!=null&&t.renderer),hasCanvas:!!(t!=null&&t.canvas),canvasSize:t!=null&&t.canvas?{w:t.canvas.width,h:t.canvas.height}:null}),this.setupResponsiveScaling(),this.composition.seek(0),this.startRenderLoop()}setupResponsiveScaling(){this.player&&(this.player.style.position="absolute",this.player.style.top="50%",this.player.style.left="50%",this.resizeObserver=new ResizeObserver(()=>{var n;const a=(n=this.player)==null?void 0:n.parentElement;if(!this.player||!a)return;const t=Math.min(a.clientWidth/this.composition.width,a.clientHeight/this.composition.height);this.player.style.width=`${this.composition.width}px`,this.player.style.height=`${this.composition.height}px`,this.player.style.transform=`translate(-50%, -50%) scale(${t})`,this.player.style.transformOrigin="center"}),this.resizeObserver.observe(this.player.parentElement??this.player))}async loadFromRecipe(a){var n,i,r;await this.initPromise,this.clips.clear(),this.recipeSourceDimensions=Number.isFinite((n=a.source)==null?void 0:n.original_width)&&a.source.original_width>0&&Number.isFinite((i=a.source)==null?void 0:i.original_height)&&a.source.original_height>0?{width:a.source.original_width,height:a.source.original_height}:null;const t=await l1(a);for(const l of a.timeline)await this.addTimelineClip(l,t);if(a.textOverlays)for(const l of a.textOverlays)await this.addTextOverlay(l);await new Promise(l=>requestAnimationFrame(l));for(const l of a.timeline)(r=l.filters)!=null&&r.length&&this.applyFiltersToClip(l.id,l.filters);a.transitions&&a.transitions.length>0&&await this.applyTransitionsToClips(a.transitions),this.composition.seek(0),this.applyFitModeToClips(),this.composition.computeFrame()}async applyTransitionsToClips(a){const t=new qi(this.composition);for(const n of a){if(n.type==="cut")continue;const i=this.clips.get(n.fromClipId),r=this.clips.get(n.toClipId),l=this.mapTransitionType(n.type);if(!i||!r||!l)continue;const s={type:l,duration:n.duration,easing:this.mapTransitionEasing(n.easing)};try{await t.applyTransition(i,r,s)}catch{}}}mapTransitionType(a){switch(a){case"fade":return"fade";case"crossfade":return"cross-fade";case"dip-to-black":return"dip-to-black";case"wipe-left":return"wipe-left";case"wipe-right":return"wipe-right";case"slide-left":return"slide-left";case"slide-right":return"slide-right";case"zoom":return"zoom-in";case"cut":return null}}mapTransitionEasing(a){switch(a){case"ease-in":return"easeIn";case"ease-out":return"easeOut";case"ease-in-out":return"easeInOut";case"linear":return"linear"}}async addTimelineClip(a,t){var n,i;try{const r=a.url||t;if(!r)throw new Error("No video source URL available for clip");if(!r.startsWith("blob:")){if(!/^https?:/i.test(String(r)))return}const l=await((n=To.from)==null?void 0:n.call(To,r,{crossOrigin:"anonymous"}))??await To.from(r),s=new Ls(l,{muted:a.muted||!1,scale:a.scale||1,position:"center"});let d=0,c=null;if(a.sourceIn!==void 0||a.sourceOut!==void 0){const p=Math.max(0,Math.floor((a.sourceIn||0)*this.fps)),f=a.sourceOut!==void 0?Math.max(p+1,Math.floor(a.sourceOut*this.fps)):null;d=p,c=f;try{if(s.offset=s.offset||{frames:0},s.offset.frames=p,f!==null){const h=Math.max(1,f-p);s.duration=s.duration||{frames:h},s.duration.frames=h}}catch{}}const u=await this.composition.add(s);if(c!==null&&d>=0)try{const p=Math.max(1,c-d);u.offset=u.offset||{frames:0},u.offset.frames=d,u.duration=u.duration||{frames:p},u.duration.frames=p}catch{}const m=Math.floor(a.timelineStart*this.fps);m>0&&u.offsetBy(m),this.clipTimelineStart.set(a.id,a.timelineStart),this.applyFitToClip(u),this.clips.set(a.id,u),(i=a.filters)!=null&&i.length&&(await new Promise(p=>requestAnimationFrame(p)),this.applyFiltersToClip(a.id,a.filters))}catch{}}async addTextOverlay(a){try{const t=Ea.fromFamily({family:a.fontFamily||"Arial",weight:a.fontWeight||"400"}),n=new ci({text:a.content,font:t,fontSize:a.fontSize||34,position:a.position||"center",fillStyle:a.color||"#FFFFFF",textAlign:a.textAlign||"center",textBaseline:a.textBaseline||"middle"});if(a.animation){const r=a.animation.duration||1,l=0,s=r*this.fps,d=a.animation.easing||"linear";a.animation.type==="rotate"&&a.animation.rotation?n.rotation=new Ye([l,s],[a.animation.rotation.from,a.animation.rotation.to],{easing:d}):a.animation.type==="scale"&&a.animation.scale&&(n.scale=new Ye([l,s],[a.animation.scale.from,a.animation.scale.to],{easing:d}))}a.startTime&&a.startTime>0&&n.offsetBy(a.startTime*this.fps),a.duration&&n.subclip(0,a.duration*this.fps);const i=await this.composition.add(n);this.clips.set(a.id||`text-${Date.now()}`,i)}catch{}}applyFiltersToClip(a,t){const n=this.clips.get(a);if(!n)return;const i=this.filterCache.get(a)??new Map,r=new Set(t.map(d=>d.id));for(const[d,c]of i.entries())if(!r.has(d)){try{typeof c.instance.destroy=="function"&&c.instance.destroy()}catch{}i.delete(d)}const l=[];for(const d of t){const c=this.buildFilterSignature(d),u=i.get(d.id);let m=null;if(u&&u.signature===c)m=u.instance;else{if(u)try{u.instance.destroy()}catch{}m=this.createPixiFilter(d),m?i.set(d.id,{instance:m,signature:c}):i.delete(d.id)}m&&l.push(m)}this.filterCache.set(a,i);const s=n.view??n.sprite??n.displayObject??null;if("filters"in n)try{n.filters=l}catch{}if(s&&"filters"in s)try{s.filters=l}catch{}typeof n.enter=="function"&&n.enter()}buildFilterSignature(a){const t=typeof a.params=="object"&&a.params!==null?a.params:{},n=Object.keys(t).sort((i,r)=>i.localeCompare(r)).map(i=>[i,t[i]]);return JSON.stringify({filterId:a.filterId,intensity:a.intensity??1,params:n})}setClipFilters(a,t){this.applyFiltersToClip(a,t),this.composition.computeFrame()}createPixiFilter(a){const t=a.intensity??1,n=a.params||{};if(la.getFilter(a.filterId)&&!la.isFilterCompatibleWithMedia(a.filterId,"video"))return null;let r=jh(a.filterId,n);return r||(r=d1(a.filterId,n)),r?(t!==1&&r&&(a.filterId==="colorOverlay"||a.filterId==="alpha"||("alpha"in r&&!n.alpha&&(r.alpha*=t),"strength"in r&&(r.strength*=t))),r):null}play(){this.composition.play(),this.startRenderLoop()}pause(){this.composition.pause(),this.composition.computeFrame()}seek(a){this.composition.seek(a)}seekToTime(a){this.composition.seek(a*this.fps)}get currentFrame(){return this.composition.frame}get currentTime(){return this.composition.time().seconds.toFixed(2)}get currentTimeInSeconds(){return this.composition.frame/this.fps}get duration(){return this.composition.duration.frames}get durationInSeconds(){return this.composition.duration.frames/this.fps}async export(a={}){var l,s,d,c,u,m,p,f,h;const t=a.fps??this.fps,n=this.composition.canvas??((s=(l=this.composition)==null?void 0:l.renderer)==null?void 0:s.view)??((u=(c=(d=this.composition)==null?void 0:d.app)==null?void 0:c.renderer)==null?void 0:u.view)??((p=(m=this.composition)==null?void 0:m.renderer)==null?void 0:p.canvas);if(!n)throw new Error("Export failed: composition canvas is not initialized");(f=a.onProgress)==null||f.call(a,0);const i=new r1(n,{fps:t});await i.init();const r=await i.export();return(h=a.onProgress)==null||h.call(a,100),r}destroy(){if(this.stopRenderLoop(),this.composition.pause(),this.clips.clear(),this.clipTimelineStart.clear(),this.filterCache.clear(),this.player&&this.composition.detachPlayer(this.player),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}this.player=null}startRenderLoop(){this.stopRenderLoop(),this.isDebug()&&this.dbg("renderLoop:start");const a=()=>{(this.composition.state==="PLAY"||this.composition.frame!==this.lastRenderedFrame)&&(this.composition.computeFrame(),this.lastRenderedFrame=this.composition.frame),this.animationFrameId=requestAnimationFrame(a)};a()}stopRenderLoop(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null,this.isDebug()&&this.dbg("renderLoop:stop"))}moveClip(a,t){const n=this.clips.get(a);if(!n)return;const i=this.clipTimelineStart.get(a)||0,r=t-i;r!==0&&(n.offsetBy(r*this.fps),this.clipTimelineStart.set(a,t),this.composition.computeFrame())}setFitMode(a){this.fitMode=a,this.applyFitModeToClips()}applyFitModeToClips(){for(const a of this.clips.values())"scale"in a&&typeof a.scale<"u"&&this.applyFitToClip(a);this.composition.computeFrame()}applyFitToClip(a){var t,n;if(this.fitMode!=="none")try{const i=this.composition.width,r=this.composition.height,l=a.source,s=(l==null?void 0:l.width)??(l==null?void 0:l.videoWidth)??((t=this.recipeSourceDimensions)==null?void 0:t.width),d=(l==null?void 0:l.height)??(l==null?void 0:l.videoHeight)??((n=this.recipeSourceDimensions)==null?void 0:n.height);if(!s||!d)return;const c=Math.min(i/s,r/d),u=Math.max(i/s,r/d),m=this.fitMode==="contain"?c:u;a.scale=m}catch{}}trimClip(a,t,n){const i=this.clips.get(a);if(!i)return;const r=Math.max(0,Math.floor(t*this.fps)),l=Math.max(r+1,Math.floor(n*this.fps));try{i.offset=i.offset||{frames:0},i.offset.frames=r,i.duration=i.duration||{frames:l-r},i.duration.frames=l-r,this.composition.computeFrame()}catch{}}resolveSourceFrame(a){var t,n;for(const[i,r]of this.clips.entries()){const l=this.clipTimelineStart.get(i)||0,s=Math.floor(l*this.fps),d=((t=r.duration)==null?void 0:t.frames)??Math.round(r.duration.seconds*this.fps),c=s+d;if(a>=s&&a<c){const u=a-s;return{sourceFrame:(((n=r.offset)==null?void 0:n.frames)??0)+u,clipId:i}}}return{sourceFrame:0,clipId:null}}}const c1=["src"],u1={class:"preview-controls"},m1=["aria-label"],p1={class:"time-display"},f1={class:"current-time"},h1={class:"total-time"},v1={key:2,class:"loading-overlay"},g1={key:3,class:"error-overlay"},b1=e.defineComponent({__name:"VideoPreviewEngine",props:{mediaUuid:{},recipe:{},media:{},autoPlay:{type:Boolean,default:!1},enableEngine:{type:Boolean,default:!0},fitMode:{default:"contain"}},emits:["time-update","duration-change","play-state-change","error","engine-ready"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(),r=e.ref(),l=e.ref(),s=e.ref(!1),d=e.ref("Initializing..."),c=e.ref(null),u=e.ref(!1),m=e.ref(0),p=e.ref(0);let f=null;const h=e.computed(()=>!!t.enableEngine&&!!t.recipe),v=e.computed(()=>{switch(t.fitMode){case"cover":return"cover";case"none":return"none";default:return"contain"}}),y=e.computed(()=>{var x,M;return(x=t.media)!=null&&x.url?t.media.url:(((M=t.media)==null?void 0:M.file)instanceof File,"")});async function w(){var x,M,E;if(!(!r.value||!t.recipe))try{s.value=!0,d.value="Initializing video engine...";const D=((x=t.recipe.source)==null?void 0:x.original_width)||1920,j=((M=t.recipe.source)==null?void 0:M.original_height)||1080,L=((E=t.recipe.output)==null?void 0:E.fps)||30;f=new ep(D,j,L,{fitMode:t.fitMode}),f.attachPlayer(r.value),d.value="Loading composition...",await f.loadFromRecipe(t.recipe),p.value=f.durationInSeconds,n("duration-change",p.value),_(),s.value=!1,n("engine-ready",f),t.autoPlay&&(f.play(),u.value=!0)}catch(D){const j=D instanceof Error?D.message:String(D);c.value=`Failed to initialize: ${j}`,s.value=!1}}function _(){if(!f)return;const x=setInterval(()=>{f&&u.value&&(m.value=f.currentTimeInSeconds,n("time-update",m.value))},100);P.value=x}function b(){h.value&&f?(u.value?f.pause():f.play(),u.value=!u.value,n("play-state-change",u.value)):l.value&&(u.value?l.value.pause():l.value.play(),u.value=!u.value,n("play-state-change",u.value))}function g(x){const M=Math.floor(x/60),E=Math.floor(x%60);return`${M}:${E.toString().padStart(2,"0")}`}function I(){c.value=null,h.value&&w()}function T(){!h.value&&l.value&&(p.value=l.value.duration,n("duration-change",p.value))}function $(){!h.value&&l.value&&(m.value=l.value.currentTime,n("time-update",m.value))}function N(){u.value=!1,n("play-state-change",!1)}function B(x){c.value="Failed to load video",n("error",c.value)}e.onMounted(()=>{h.value&&t.recipe&&w()}),e.onUnmounted(()=>{f&&(f.destroy(),f=null),P.value&&(clearInterval(P.value),P.value=null),l.value&&(l.value.pause(),l.value.removeAttribute("src"),l.value.load())}),e.watch(()=>t.recipe,async x=>{if(h.value&&x)if(x.timeline,f)try{await f.loadFromRecipe(x),p.value=f.durationInSeconds,n("duration-change",p.value)}catch{}else await w()}),e.watch(()=>t.enableEngine,async x=>{x?(await e.nextTick(),await w()):f&&(P.value&&(clearInterval(P.value),P.value=null),f.destroy(),f=null)}),e.watch(()=>t.fitMode,async x=>{if(!(!h.value||!f))try{f.setFitMode(x||"contain")}catch{}});const P=e.ref(null);return(x,M)=>(e.openBlock(),e.createElementBlock("div",{class:"video-preview-engine",ref_key:"containerRef",ref:i},[h.value?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"videoEnginePlayer",ref:r,class:"video-engine-player",style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"}},null,512)):(e.openBlock(),e.createElementBlock("video",{key:1,ref_key:"videoRef",ref:l,src:y.value,onLoadedmetadata:T,onTimeupdate:$,onEnded:N,onError:B,style:e.normalizeStyle({width:"100%",height:"100%",objectFit:v.value}),playsinline:"",controls:""},null,44,c1)),e.createElementVNode("div",u1,[e.createElementVNode("button",{class:"play-button",onClick:b,"aria-label":u.value?"Pause":"Play"},[e.createVNode(e.unref(G.IonIcon),{icon:u.value?e.unref(ym):e.unref(wm)},null,8,["icon"])],8,m1),e.createElementVNode("div",p1,[e.createElementVNode("span",f1,e.toDisplayString(g(m.value)),1),M[0]||(M[0]=e.createElementVNode("span",{class:"separator"},"/",-1)),e.createElementVNode("span",h1,e.toDisplayString(g(p.value)),1)])]),s.value?(e.openBlock(),e.createElementBlock("div",v1,[e.createVNode(e.unref(G.IonSpinner),{name:"crescent"}),e.createElementVNode("p",null,e.toDisplayString(d.value),1)])):e.createCommentVNode("",!0),c.value?(e.openBlock(),e.createElementBlock("div",g1,[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(pd)},null,8,["icon"]),e.createElementVNode("p",null,e.toDisplayString(c.value),1),e.createElementVNode("button",{onClick:I},"Retry")])):e.createCommentVNode("",!0)],512))}}),Os=Ae(b1,[["__scopeId","data-v-e199ac48"]]),y1=["aria-label"],w1=["aria-label"],k1={class:"clip-content"},_1={key:0,class:"clip-thumbnail"},E1=["src","alt"],S1=["src"],C1=["data-visual-mode"],x1={class:"clip-info"},N1={class:"clip-label"},V1={class:"clip-duration"},T1={key:3,class:"filter-indicators"},B1={key:4,class:"speed-indicator"},M1=["aria-label","data-testid"],I1={key:1,class:"selection-overlay"},$1=420,F1=8,D1=48,A1=32,Zc=1,R1=e.defineComponent({__name:"TimelineClip",props:{clip:{},scale:{},scrollOffset:{default:0},selected:{type:Boolean,default:!1},isMobile:{type:Boolean,default:!1},canDelete:{type:Boolean,default:!1}},emits:["select","delete","long-press","trim-start","trim-end","drag","trim-start-abs","trim-end-abs","drag-abs"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null),r=e.ref(!1),l=e.ref(null),s=e.ref(0),d=e.ref(0),c=e.ref(0),u=e.ref(0),m=e.ref(!1),p=e.ref(!1),f=e.ref(null),h=e.computed(()=>{const F=(t.clip.timelineEnd-t.clip.timelineStart)*t.scale;return{left:`${t.clip.timelineStart*t.scale-t.scrollOffset}px`,width:`${F}px`}}),v=e.computed(()=>t.clip.label||`Clip ${t.clip.id.slice(-4)}`),y=e.computed(()=>{const k=t.clip.timelineEnd-t.clip.timelineStart;return $(k)}),w=e.computed(()=>t.clip.filters&&t.clip.filters.length>0),_=e.computed(()=>t.clip.filters||[]),b=e.computed(()=>t.clip.waveformSamples??[]),g=e.computed(()=>t.clip.filmstripFrames??[]),I=e.computed(()=>b.value.length>0),T=e.computed(()=>g.value.length>0);function $(k){if(k<1)return`${Math.round(k*30)}f`;if(k<60)return`${k.toFixed(1)}s`;{const F=Math.floor(k/60),W=Math.floor(k%60);return`${F}:${W.toString().padStart(2,"0")}`}}function N(k){return!k||typeof k!="string"?Cc:k.includes("color")||k.includes("brightness")?to:k.includes("blur")?yv:k.includes("style")?Bi:k.includes("effect")?eo:Cc}function B(){r.value||n("select")}function P(k){k.button===0&&(E("move",k.clientX),k.preventDefault())}function x(k){if(k.touches.length!==1)return;const F=k.touches[0];if(!t.isMobile){E("move",F.clientX),k.preventDefault();return}c.value=F.clientX,u.value=F.clientY,m.value=!1,p.value=!1,D(),j(),f.value=window.setTimeout(()=>{p.value=!0,j(),t.selected||n("select"),n("long-press")},$1),document.addEventListener("touchmove",L),document.addEventListener("touchend",z),document.addEventListener("touchcancel",z),k.preventDefault()}function M(k,F){const W="touches"in F?F.touches[0].clientX:F.clientX;l.value=k==="start"?"trim-start":"trim-end",E(l.value,W),F.preventDefault(),F.stopPropagation()}function E(k,F){D(),j(),r.value=!0,l.value=k,s.value=F,k==="move"?d.value=t.clip.timelineStart:k==="trim-start"?d.value=t.clip.sourceIn:k==="trim-end"&&(d.value=t.clip.sourceOut),document.addEventListener("mousemove",C),document.addEventListener("mouseup",O),document.addEventListener("touchmove",A),document.addEventListener("touchend",O),t.selected||n("select")}function D(){f.value!==null&&(window.clearTimeout(f.value),f.value=null)}function j(){document.removeEventListener("touchmove",L),document.removeEventListener("touchend",z),document.removeEventListener("touchcancel",z)}function L(k){if(k.touches.length!==1)return;const F=k.touches[0],W=F.clientX-c.value,J=F.clientY-u.value;Math.hypot(W,J)<F1||(m.value=!0,D(),j(),E("move",F.clientX),C(k),k.preventDefault())}function z(){const k=!m.value&&!p.value&&!r.value;D(),j(),m.value=!1,p.value=!1,k&&n("select")}function C(k){if(!r.value||!l.value)return;const F="touches"in k?k.touches[0].clientX:k.clientX,W="touches"in k?k.touches[0].clientY:k.clientY,ce=F-s.value;l.value==="move"?(n("drag",ce),n("drag-abs",F,W)):l.value==="trim-start"?(n("trim-start",ce),n("trim-start-abs",F)):l.value==="trim-end"&&(n("trim-end",ce),n("trim-end-abs",F))}function A(k){C(k)}function O(){r.value=!1,l.value=null,document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",O),document.removeEventListener("touchmove",A),document.removeEventListener("touchend",O)}function K(){e.nextTick(()=>{xe()})}function se(k){var be,_e;const F=Math.max(0,t.clip.timelineEnd-t.clip.timelineStart),W=Math.max(1,Math.round(F*t.scale)),J=t.isMobile?A1:D1,ce=Math.max(1,Math.round(k.clientWidth||((be=k.parentElement)==null?void 0:be.clientWidth)||W)),Ue=Math.max(1,Math.round(k.clientHeight||((_e=k.parentElement)==null?void 0:_e.clientHeight)||J));return{width:ce,height:Ue}}function xe(){if(T.value||!i.value)return;const k=i.value,F=k.getContext("2d");if(!F)return;const{width:W,height:J}=se(k),ce=window.devicePixelRatio||1;if(k.width=Math.max(1,Math.round(W*ce)),k.height=Math.max(1,Math.round(J*ce)),F.setTransform(ce,0,0,ce,0,0),F.clearRect(0,0,W,J),b.value.length>0){le(F,W,J,b.value);return}ue(F,W,J)}function ue(k,F,W){const J=W/2;k.strokeStyle="rgba(255, 255, 255, 0.3)",k.lineWidth=1,k.beginPath(),k.moveTo(0,J),k.lineTo(F,J);for(let ce=0;ce<F;ce+=4){const Ue=Math.sin(ce*.05)*(W*.3);k.moveTo(ce,J-Ue),k.lineTo(ce,J+Ue)}k.stroke()}function le(k,F,W,J){const ce=t.clip.sourceIn,Ue=t.clip.sourceOut,be=Math.max(.001,Ue-ce),_e=J.filter(Re=>Re.endTime>=ce&&Re.time<=Ue);if(_e.length===0){ue(k,F,W);return}const ye=W/2,Ne=W*.44,Se=W*.32;k.fillStyle="rgba(255, 255, 255, 0.26)",_e.forEach(Re=>{const Oe=Math.max(Re.time,ce),it=Math.min(Re.endTime,Ue),rt=(Oe-ce)/be*F,Pt=Math.max(Zc,(it-Oe)/be*F),bt=Z(Re.rms)*Se;k.fillRect(rt,ye-bt,Pt,bt*2)}),k.fillStyle="rgba(255, 255, 255, 0.72)",_e.forEach(Re=>{const Oe=Math.max(Re.time,ce),it=Math.min(Re.endTime,Ue),rt=(Oe-ce)/be*F,Pt=Math.max(Zc,(it-Oe)/be*F),bt=Z(Re.peak)*Ne;k.fillRect(rt,ye-bt,Pt,bt*2)})}function Z(k){return Math.min(1,Math.max(0,k))}return e.watch(()=>[t.clip.id,t.clip.timelineStart,t.clip.timelineEnd,t.clip.sourceIn,t.clip.sourceOut,t.clip.waveformSamples,t.clip.filmstripFrames,t.scale,t.isMobile],K,{deep:!0,flush:"post"}),e.onMounted(()=>{K(),window.addEventListener("resize",xe)}),e.onUnmounted(()=>{O(),D(),j(),window.removeEventListener("resize",xe)}),(k,F)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["timeline-clip",{selected:k.selected,mobile:k.isMobile,"has-filters":w.value}]),style:e.normalizeStyle(h.value),onClick:B,onMousedown:P,onTouchstart:x},[e.createElementVNode("div",{class:"trim-handle trim-start",onMousedown:F[0]||(F[0]=e.withModifiers(W=>M("start",W),["stop"])),onTouchstart:F[1]||(F[1]=e.withModifiers(W=>M("start",W),["stop"])),"aria-label":`Trim start of ${k.clip.label||"clip"}`},[...F[7]||(F[7]=[e.createElementVNode("div",{class:"trim-grip"},null,-1)])],40,y1),e.createElementVNode("div",{class:"trim-handle trim-end",onMousedown:F[2]||(F[2]=e.withModifiers(W=>M("end",W),["stop"])),onTouchstart:F[3]||(F[3]=e.withModifiers(W=>M("end",W),["stop"])),"aria-label":`Trim end of ${k.clip.label||"clip"}`},[...F[8]||(F[8]=[e.createElementVNode("div",{class:"trim-grip"},null,-1)])],40,w1),e.createElementVNode("div",k1,[k.clip.thumbnail?(e.openBlock(),e.createElementBlock("div",_1,[e.createElementVNode("img",{src:k.clip.thumbnail,alt:k.clip.label||"Video clip"},null,8,E1)])):e.createCommentVNode("",!0),T.value?(e.openBlock(),e.createElementBlock("div",{key:1,class:e.normalizeClass(["clip-analysis-strip clip-filmstrip",{compact:k.isMobile}]),"aria-hidden":"true"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.value,W=>(e.openBlock(),e.createElementBlock("img",{key:W.id,class:"clip-filmstrip-frame",src:W.uri,alt:"",draggable:"false"},null,8,S1))),128))],2)):(e.openBlock(),e.createElementBlock("div",{key:2,class:e.normalizeClass(["clip-analysis-strip clip-waveform",{compact:k.isMobile}]),"data-visual-mode":I.value?"waveform":"placeholder","aria-hidden":"true"},[e.createElementVNode("canvas",{ref_key:"waveformCanvas",ref:i},null,512)],10,C1)),e.createElementVNode("div",x1,[e.createElementVNode("span",N1,e.toDisplayString(v.value),1),e.createElementVNode("span",V1,e.toDisplayString(y.value),1)]),w.value?(e.openBlock(),e.createElementBlock("div",T1,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(_.value,W=>(e.openBlock(),e.createBlock(e.unref(G.IonIcon),{key:W.id||W.filterId,icon:N(W.filterId||W.id),title:`Filter: ${W.filterId||W.id}`},null,8,["icon","title"]))),128))])):e.createCommentVNode("",!0),k.clip.speed&&k.clip.speed!==1?(e.openBlock(),e.createElementBlock("div",B1,e.toDisplayString(k.clip.speed)+"x ",1)):e.createCommentVNode("",!0)]),k.selected&&k.canDelete?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"clip-delete-button","aria-label":`Delete ${k.clip.label||"clip"}`,"data-testid":`timeline-clip-delete-${k.clip.id}`,title:"Delete clip",onClick:F[4]||(F[4]=e.withModifiers(W=>n("delete"),["stop"])),onMousedown:F[5]||(F[5]=e.withModifiers(()=>{},["stop"])),onTouchstart:F[6]||(F[6]=e.withModifiers(()=>{},["stop"]))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Xr)},null,8,["icon"])],40,M1)):e.createCommentVNode("",!0),k.selected?(e.openBlock(),e.createElementBlock("div",I1)):e.createCommentVNode("",!0)],38))}}),Gc=Ae(R1,[["__scopeId","data-v-deeaa999"]]),L1={class:"timeline-track-header__meta"},P1=["data-testid"],U1=["data-testid","value","aria-label","onKeydown"],O1={class:"timeline-track-header__type"},z1=["aria-label"],j1=["aria-pressed","aria-label"],W1=["aria-pressed","aria-label"],H1=["aria-pressed","aria-label"],Z1=["aria-pressed","aria-label"],G1={class:"timeline-track-header__menu-row"},X1=["data-testid","aria-label","aria-expanded"],K1=["aria-label"],q1=["data-testid"],J1=["data-testid"],Y1=["data-testid"],Q1=["data-testid"],ew=e.defineComponent({__name:"TimelineTrackHeader",props:{track:{}},emits:["toggle-lock","toggle-hidden","toggle-muted","toggle-solo","rename-track","delete-track","reorder-track"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.ref(!1),l=e.ref(""),s=e.ref(null);function d(){i.value=!i.value}function c(){i.value=!1}function u(){c(),m()}async function m(){var w,_;l.value=t.track.name,r.value=!0,await e.nextTick(),(w=s.value)==null||w.focus(),(_=s.value)==null||_.select()}function p(w){const _=w.target;_&&(l.value=_.value)}function f(){if(!r.value)return;const w=l.value.trim();r.value=!1,!(w===""||w===t.track.name)&&n("rename-track",t.track.id,w)}function h(){r.value=!1}function v(w){c(),n("reorder-track",t.track.id,w)}function y(){c(),n("delete-track",t.track.id)}return(w,_)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["timeline-track-header",{"is-hidden":w.track.hidden===!0}])},[e.createElementVNode("div",L1,[r.value?(e.openBlock(),e.createElementBlock("input",{key:1,ref_key:"renameInput",ref:s,class:"timeline-track-header__rename-input","data-testid":`timeline-track-rename-${w.track.id}`,value:l.value,"aria-label":`Rename ${w.track.name}`,onInput:p,onKeydown:[e.withKeys(e.withModifiers(f,["prevent"]),["enter"]),e.withKeys(e.withModifiers(h,["prevent"]),["escape"])],onBlur:f},null,40,U1)):(e.openBlock(),e.createElementBlock("span",{key:0,class:"timeline-track-header__name","data-testid":`timeline-track-name-${w.track.id}`,onDblclick:m},e.toDisplayString(w.track.name),41,P1)),e.createElementVNode("span",O1,e.toDisplayString(w.track.type),1)]),e.createElementVNode("div",{class:"timeline-track-header__actions","aria-label":`Track controls for ${w.track.name}`},[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":w.track.locked===!0}]),"aria-pressed":w.track.locked===!0,"aria-label":w.track.locked===!0?`Unlock ${w.track.name}`:`Lock ${w.track.name}`,title:"Lock",onClick:_[0]||(_[0]=b=>n("toggle-lock",w.track.id))}," Lock ",10,j1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":w.track.hidden===!0}]),"aria-pressed":w.track.hidden===!0,"aria-label":w.track.hidden===!0?`Show ${w.track.name}`:`Hide ${w.track.name}`,title:"Hide",onClick:_[1]||(_[1]=b=>n("toggle-hidden",w.track.id))}," Hide ",10,W1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":w.track.muted===!0}]),"aria-pressed":w.track.muted===!0,"aria-label":w.track.muted===!0?`Unmute ${w.track.name}`:`Mute ${w.track.name}`,title:"Mute",onClick:_[2]||(_[2]=b=>n("toggle-muted",w.track.id))}," Mute ",10,H1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["timeline-track-header__button",{"is-active":w.track.solo===!0}]),"aria-pressed":w.track.solo===!0,"aria-label":w.track.solo===!0?`Disable solo for ${w.track.name}`:`Solo ${w.track.name}`,title:"Solo",onClick:_[3]||(_[3]=b=>n("toggle-solo",w.track.id))}," Solo ",10,Z1)],8,z1),e.createElementVNode("div",G1,[e.createElementVNode("button",{type:"button",class:"timeline-track-header__menu-button","data-testid":`timeline-track-menu-${w.track.id}`,"aria-label":`More actions for ${w.track.name}`,"aria-expanded":i.value,"aria-haspopup":!0,onClick:d}," ⋯ ",8,X1),i.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"timeline-track-header__menu",role:"menu","aria-label":`${w.track.name} actions`},[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`timeline-track-rename-action-${w.track.id}`,onClick:u}," Rename ",8,q1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`timeline-track-move-up-${w.track.id}`,onClick:_[4]||(_[4]=b=>v("up"))}," Move up ",8,J1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`timeline-track-move-down-${w.track.id}`,onClick:_[5]||(_[5]=b=>v("down"))}," Move down ",8,Y1),e.createElementVNode("button",{type:"button",role:"menuitem",class:"timeline-track-header__menu-button--danger","data-testid":`timeline-track-delete-${w.track.id}`,onClick:y}," Delete track ",8,Q1)],8,K1)):e.createCommentVNode("",!0)])],2))}}),tw=Ae(ew,[["__scopeId","data-v-54e2bc6a"]]);class tp{constructor(a=30){this.fps=30,this.fps=a}setFps(a){this.fps=a}async convertTimelineClipToEngine(a,t){const n=new Ls(t,{muted:a.muted||!1,scale:a.scale||1,position:"center"});if(a.sourceIn!==void 0||a.sourceOut!==void 0){const i=this.secondsToFrames(a.sourceIn||0),r=a.sourceOut?this.secondsToFrames(a.sourceOut):n.duration.frames;n.subclip(i,r)}return a.timelineStart&&a.timelineStart>0&&n.offsetBy(this.secondsToFrames(a.timelineStart)),a.transform&&this.applyTransformations(n,a.transform),n}convertEngineClipToTimeline(a,t,n){const i=this.framesToSeconds(a.duration.frames),r=a.offset?this.framesToSeconds(a.offset.frames):0;return{id:t,url:n,type:"video",timelineStart:r,timelineEnd:r+i,sourceIn:0,sourceOut:i,duration:i,muted:a.muted||!1,scale:a.scale.x||1}}async buildCompositionFromRecipe(a,t){var n;(n=t.clear)==null||n.call(t);for(const i of a.timeline)try{if(!i.url)continue;const r=await To.from(i.url),l=await this.convertTimelineClipToEngine(i,r);await t.add(l)}catch{}a.duration&&(t.duration=Ze.fromFrames(this.secondsToFrames(a.duration)))}extractTimelineFromComposition(a){const t=[];return(a.clips||[]).forEach((i,r)=>{var l,s;i instanceof Ls&&t.push(this.convertEngineClipToTimeline(i,`clip-${r}`,((l=i.source)==null?void 0:l.externalURL)||((s=i.source)==null?void 0:s.objectURL)||""))}),t}applyTransformations(a,t){(t.x!==void 0||t.y!==void 0)&&(a.x=t.x||0,a.y=t.y||0),t.rotation!==void 0&&(a.rotation=t.rotation),t.opacity!==void 0&&(a.alpha=t.opacity),t.scale!==void 0&&(a.scale={x:t.scale,y:t.scale})}secondsToFrames(a){return Math.round(a*this.fps)}framesToSeconds(a){return a/this.fps}framesToTime(a){const t=this.framesToSeconds(a),n=Math.floor(t/60),i=Math.floor(t%60),r=Math.floor(t%1*1e3);return`${n.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}.${r.toString().padStart(3,"0")}`}formatTime(a){const t=Math.floor(a/3600),n=Math.floor(a%3600/60),i=Math.floor(a%60);return`${t.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`}parseTime(a){const t=a.split(":");let n=0;if(t.length===2){const[i,r]=t;n=parseInt(i)*60+parseFloat(r)}else if(t.length===3){const[i,r,l]=t;n=parseInt(i)*3600+parseInt(r)*60+parseFloat(l)}else n=parseFloat(a);return n}timeToFrames(a){const t=a.split(":");let n=0;if(t.length===2){const[i,r]=t;n=parseInt(i)*60+parseFloat(r)}else if(t.length===3){const[i,r,l]=t;n=parseInt(i)*3600+parseInt(r)*60+parseFloat(l)}else n=parseFloat(a);return this.secondsToFrames(n)}}const aw={class:"time-markers"},nw=["data-track-id"],ow=["data-track-id"],iw=["aria-label","title"],rw={key:0,class:"timeline-scrollbar"},Xc=152,Kc=80,lw=e.defineComponent({__name:"VideoTimeline",props:{playhead:{},clips:{},tracks:{},duration:{},zoomLevel:{default:50},isMobile:{type:Boolean,default:!1},snapEnabled:{type:Boolean,default:!0},selectedClipId:{},fps:{default:30},useFrameMode:{type:Boolean,default:!1},sensitivity:{default:.25}},emits:["update:playhead","trim","split","clip-select","clip-delete","clip-move","clip-long-press","snap-state-change","toggle-frame-mode","toggle-lock","toggle-hidden","toggle-muted","toggle-solo","rename-track","delete-track","reorder-track"],setup(o,{expose:a,emit:t}){const n=o,i=e.computed(()=>n.isMobile===!0),r=t,l=e.ref(),s=e.ref(n.selectedClipId||null),d=e.ref(!1),c=e.ref(0),u=e.ref(),m=e.ref(0),p=e.computed(()=>n.selectedClipId??s.value);e.watch(()=>n.selectedClipId,ae=>{ae!==void 0&&(s.value=ae)});const f=new tp(n.fps);e.watch(()=>n.fps,ae=>{f.setFps(ae)});const h=e.ref(!1),v=e.ref(null),y=e.ref(0),w=e.ref(0),_=e.ref(null),b=e.ref(null),g=e.ref(0),I=e.ref(0),T=e.ref(0),$=e.ref(!1),N=e.ref(0),B=e.ref(n.zoomLevel),P=e.computed(()=>n.zoomLevel),x=e.computed(()=>n.tracks!==void 0&&n.tracks.length>0&&!i.value),M=e.computed(()=>x.value?Xc:0),E=e.computed(()=>Math.max(0,Z.value-M.value));function D(ae){return ae.trackId??`legacy-track-${ae.track??0}`}function j(ae,ge){return{id:ae,type:"video",name:`Track ${ge+1}`,order:ge}}const L=e.computed(()=>{const ae=new Map;for(const ge of n.clips){const pe=D(ge),me=ae.get(pe);if(me){me.push(ge);continue}ae.set(pe,[ge])}return ae}),z=e.computed(()=>{if(!x.value)return[];const ae=[...n.tracks??[]].sort((me,Be)=>me.order-Be.order),ge=new Set(ae.map(me=>me.id)),pe=[];for(const me of L.value.keys())ge.has(me)||pe.push(j(me,ae.length+pe.length));return[...ae,...pe].map(me=>({track:me,clips:L.value.get(me.id)??[],height:me.height??Kc}))}),C=e.computed(()=>new Set(z.value.filter(ae=>ae.track.locked===!0).map(ae=>ae.track.id)));function A(ae){const ge=n.clips.find(pe=>pe.id===ae);return ge?!C.value.has(D(ge)):!1}function O(ae){const ge=n.clips.find(Be=>Be.id===ae);if(!ge)return null;const pe=D(ge),me=n.clips.filter(Be=>Be.id!==ae&&D(Be)===pe&&Be.timelineStart>=ge.timelineEnd-1e-9).map(Be=>Be.timelineStart);return me.length?Math.min(...me):null}function K(ae){const ge=ae.sourceMaxOut??n.duration,pe=ae.timelineStart+(ge-ae.sourceIn),me=O(ae.id),Be=me!=null?Math.max(ae.timelineStart,me):1/0;return Math.min(pe,Be)}function se(ae,ge=Kc){const pe=ae.sourceMinIn??0,Be=(ae.sourceMaxOut??n.duration)-pe,He=ae.sourceIn-pe;return{left:`${(ae.timelineStart-He)*P.value-c.value}px`,width:`${Be*P.value}px`,top:"0px",height:`${ge}px`,opacity:p.value===ae.id?.25:.15}}const xe=e.computed(()=>n.useFrameMode?n.zoomLevel:n.zoomLevel/n.fps),ue=e.computed(()=>f.secondsToFrames(n.duration)),le=e.computed(()=>n.useFrameMode?ue.value*xe.value:n.duration*P.value),Z=e.computed(()=>{var ae;return m.value||((ae=l.value)==null?void 0:ae.clientWidth)||800}),k=e.computed(()=>le.value>E.value),F=e.computed(()=>Math.max(0,le.value-E.value)),W=e.computed(()=>c.value>0),J=e.computed(()=>c.value<F.value),ce=e.computed(()=>n.useFrameMode?f.secondsToFrames(n.playhead)*xe.value-c.value:n.playhead*P.value-c.value),Ue=e.computed(()=>_.value===null?null:n.useFrameMode?f.secondsToFrames(_.value)*xe.value-c.value:_.value*P.value-c.value),be=e.computed(()=>{const ae=E.value,ge=Math.max(50,ae/le.value*ae),pe=c.value/F.value*(ae-ge);return{width:`${ge}px`,left:`${pe}px`}}),_e=e.computed(()=>{const ae=[],ge=ye();for(let pe=0;pe<=n.duration;pe+=ge){const me=pe*P.value-c.value;me>=-50&&me<=E.value+50&&ae.push({position:me+M.value,label:Ne(pe),time:pe})}return ae});function ye(){const ge=80/P.value;return ge<=1?1:ge<=5?5:ge<=10?10:ge<=30?30:ge<=60?60:Math.ceil(ge/60)*60}function Ne(ae){if(n.useFrameMode)return`F${f.secondsToFrames(ae)}`;{const ge=Math.floor(ae/60),pe=Math.floor(ae%60),me=Math.floor(ae%1*n.fps);return P.value>100?`${ge}:${pe.toString().padStart(2,"0")}:${me.toString().padStart(2,"0")}`:`${ge}:${pe.toString().padStart(2,"0")}`}}function Se(ae){const ge=l.value.getBoundingClientRect();let me=(ae.clientX-ge.left-M.value+c.value)/P.value;const Be=n.clips.find(He=>me>=He.timelineStart&&me<=He.timelineEnd);if(Be)me=Math.max(Be.timelineStart,Math.min(Be.timelineEnd,me));else if(n.selectedClipId){const He=n.clips.find(lt=>lt.id===n.selectedClipId);if(He){const lt=Math.abs(me-He.timelineStart),Vt=Math.abs(me-He.timelineEnd);me=lt<Vt?He.timelineStart:He.timelineEnd}}else me=Math.max(0,Math.min(me,n.duration));r("update:playhead",me)}function Re(ae){if(!k.value)return;const ge=Math.abs(ae.deltaX)>Math.abs(ae.deltaY)?ae.deltaX:ae.deltaY;ge!==0&&(ae.preventDefault(),c.value=Math.max(0,Math.min(F.value,c.value+ge)))}function Oe(ae){return[...ae===void 0?n.clips:n.clips.filter(pe=>D(pe)===ae)].sort((pe,me)=>pe.timelineStart-me.timelineStart)}function it(ae){const ge=n.clips.find(Be=>Be.id===ae),pe=Oe(ge?D(ge):void 0),me=pe.findIndex(Be=>Be.id===ae);return{previous:me>0?pe[me-1]:null,next:me!==-1&&me<pe.length-1?pe[me+1]:null}}function rt(ae){const ge=ae.timelineEnd-ae.timelineStart,{previous:pe,next:me}=it(ae.id),Be=pe?pe.timelineEnd:0,He=me?me.timelineStart-ge:Math.max(ae.timelineStart,n.duration-ge);return{minStart:Be,maxStart:Math.max(Be,He)}}function Pt(){return 12/Math.max(P.value,1)}function bt(ae){return Array.from(new Set(ae.filter(ge=>typeof ge=="number"&&Number.isFinite(ge))))}function Ct(ae,ge,pe,me){const Be=Math.max(pe,Math.min(ae,me));if(!n.snapEnabled)return{value:Be,guideTime:null};const He=Pt();let lt=Be,Vt=null,Ot=Number.POSITIVE_INFINITY;for(const $t of bt(ge)){if($t<pe||$t>me)continue;const st=Math.abs($t-Be);st<=He&&st<Ot&&(lt=$t,Vt=$t,Ot=st)}return{value:lt,guideTime:Vt}}function mt(ae){if(ae.touches.length===2){$.value=!0;const ge=ae.touches[0],pe=ae.touches[1];N.value=Math.hypot(pe.clientX-ge.clientX,pe.clientY-ge.clientY),B.value=n.zoomLevel}else ae.touches.length===1&&(g.value=ae.touches[0].clientX,I.value=ae.touches[0].clientY,T.value=g.value)}function pt(ae){if($.value&&ae.touches.length===2){const ge=ae.touches[0],pe=ae.touches[1],Be=Math.hypot(pe.clientX-ge.clientX,pe.clientY-ge.clientY)/N.value;Math.max(10,Math.min(200,B.value*Be)),r("update:playhead",n.playhead)}else if(ae.touches.length===1&&!$.value){const ge=ae.touches[0],pe=T.value-ge.clientX;Math.abs(pe)>Math.abs(ge.clientY-I.value)&&(ae.preventDefault(),c.value=Math.max(0,Math.min(F.value,c.value+pe)),T.value=ge.clientX)}}function Nt(){$.value=!1}function Ce(ae){const ge=ae.target;if(ge.closest(".playhead-handle"))return;const pe=ae.button===1,me=!!ge.closest(".video-track");(pe||!me&&k.value)&&Ve(ae)}function Ve(ae){h.value=!0,v.value="pan",y.value=ae.clientX,w.value=c.value,document.addEventListener("mousemove",Ge),document.addEventListener("mouseup",Je)}function Le(ae){ae.preventDefault(),ae.stopPropagation(),h.value=!0,v.value="playhead";const ge="touches"in ae?ae.touches[0].clientX:ae.clientX;y.value=ge,w.value=n.playhead,"touches"in ae?(document.addEventListener("touchmove",Ge),document.addEventListener("touchend",Je)):(document.addEventListener("mousemove",Ge),document.addEventListener("mouseup",Je))}function nt(ae){ae.preventDefault(),ae.stopPropagation(),h.value=!0,v.value="scrollbar";const ge="touches"in ae?ae.touches[0].clientX:ae.clientX;y.value=ge,w.value=c.value,"touches"in ae?(document.addEventListener("touchmove",Ge),document.addEventListener("touchend",Je)):(document.addEventListener("mousemove",Ge),document.addEventListener("mouseup",Je))}function Ge(ae){if(!h.value)return;const pe=("touches"in ae?ae.touches[0].clientX:ae.clientX)-y.value;if(v.value==="playhead"){const me=pe/P.value;let Be=w.value+me;if(n.selectedClipId){const He=n.clips.find(lt=>lt.id===n.selectedClipId);He?Be=Math.max(He.timelineStart,Math.min(He.timelineEnd,Be)):Be=Math.max(0,Math.min(n.duration,Be))}else{const He=n.clips.find(lt=>n.playhead>=lt.timelineStart&&n.playhead<=lt.timelineEnd);He?Be=Math.max(He.timelineStart,Math.min(He.timelineEnd,Be)):Be=Math.max(0,Math.min(n.duration,Be))}r("update:playhead",Be)}else if(v.value==="scrollbar"){const me=pe/E.value*le.value;c.value=Math.max(0,Math.min(F.value,w.value+me))}else if(v.value==="pan"){const me=w.value-pe;c.value=Math.max(0,Math.min(F.value,me))}}function Je(){h.value=!1,v.value=null,_.value=null,b.value=null,document.removeEventListener("mousemove",Ge),document.removeEventListener("mouseup",Je),document.removeEventListener("touchmove",Ge),document.removeEventListener("touchend",Je)}function _t(ae){s.value=s.value===ae?null:ae,r("clip-select",s.value)}function ht(ae){A(ae)&&(s.value=ae,r("clip-select",ae),r("clip-long-press",ae))}function Wt(ae){!A(ae)||n.clips.length<=1||(s.value=ae,r("clip-select",ae),r("clip-delete",ae))}function Pe(ae,ge){if(!A(ae))return;const pe=n.clips.find(Be=>Be.id===ae);if(!pe||Math.abs(ge)<2)return;const me=ge/P.value*n.sensitivity;if(n.useFrameMode){const Be=f.secondsToFrames(pe.sourceIn),He=f.secondsToFrames(me),lt=Math.max(0,Be+He),Vt=f.framesToSeconds(lt);r("trim",ae,"start",Vt)}else{const Be=Math.max(0,pe.sourceIn+me);r("trim",ae,"start",Be)}}function Ht(ae,ge){if(!A(ae))return;const pe=n.clips.find(q=>q.id===ae);if(!pe||!l.value)return;const me=l.value.getBoundingClientRect(),Be=ge-me.left-M.value,He=80;Be<He?c.value=Math.max(0,c.value-8):Be>me.width-M.value-He&&(c.value=Math.min(F.value,c.value+8));const lt=Be+c.value,Vt=1/n.fps;let Ot=lt/P.value;const{previous:$t}=it(pe.id),st=Ct(Ot,[0,$t==null?void 0:$t.timelineEnd,n.playhead],0,pe.timelineEnd-Vt);Ot=st.value,_.value=st.guideTime;let Jt=pe.sourceIn+(Ot-pe.timelineStart);Jt=Math.round(Jt*n.fps)/n.fps,r("trim",ae,"start",Jt)}function Zt(ae,ge){if(!A(ae))return;const pe=n.clips.find(ke=>ke.id===ae);if(!pe||!l.value)return;const me=l.value.getBoundingClientRect(),Be=ge-me.left-M.value,He=80;Be<He?c.value=Math.max(0,c.value-8):Be>me.width-M.value-He&&(c.value=Math.min(F.value,c.value+8));const lt=Be+c.value,Vt=1/n.fps,Ot=K(pe);let $t=lt/P.value;const{next:st}=it(pe.id),Jt=Ct($t,[st==null?void 0:st.timelineStart,n.playhead],pe.timelineStart+Vt,Ot);$t=Jt.value,_.value=Jt.guideTime;let q=pe.sourceIn+($t-pe.timelineStart);q=Math.round(q*n.fps)/n.fps,r("trim",ae,"end",q)}function It(ae){var pe;if(!x.value||!l.value)return null;const ge=Array.from(l.value.querySelectorAll(".timeline-track-lane__body"));for(const me of ge){const Be=me.getBoundingClientRect();if(ae>=Be.top&&ae<=Be.bottom){const He=me.getAttribute("data-track-id");if(!He)continue;return((pe=n.tracks)==null?void 0:pe.find(Vt=>Vt.id===He))??null}}return null}function Ut(ae,ge,pe){if(!A(ae))return;const me=n.clips.find(ke=>ke.id===ae);if(!me||!l.value)return;const Be=l.value.getBoundingClientRect(),He=ge-Be.left-M.value,lt=80;He<lt?c.value=Math.max(0,c.value-8):He>Be.width-M.value-lt&&(c.value=Math.min(F.value,c.value+8));const Vt=He+c.value,Ot=me.timelineEnd-me.timelineStart,$t=rt(me);let st=Vt/P.value;const Jt=Ct(st,[$t.minStart,$t.maxStart,n.playhead,n.playhead-Ot],$t.minStart,$t.maxStart);st=Jt.value,_.value=Jt.guideTime,st=Math.round(st*n.fps)/n.fps;let q;if(typeof pe=="number"){const ke=It(pe);b.value=(ke==null?void 0:ke.id)??null,ke&&ke.id!==(me.trackId??null)&&ke.locked!==!0&&(q=ke.id)}q!==void 0?r("clip-move",ae,st,q):r("clip-move",ae,st)}function Gt(ae,ge){if(!A(ae))return;const pe=n.clips.find(He=>He.id===ae);if(!pe||Math.abs(ge)<2)return;const me=ge/P.value*n.sensitivity,Be=He=>Math.max(0,Math.round(He*n.fps)/n.fps);if(n.useFrameMode){const He=f.secondsToFrames(pe.sourceOut),lt=f.secondsToFrames(me),Vt=K(pe),Ot=pe.sourceIn+(Vt-pe.timelineStart),$t=f.secondsToFrames(Ot),st=Math.min($t,He+lt),Jt=f.framesToSeconds(st);r("trim",ae,"end",Jt)}else{const He=K(pe),lt=pe.sourceIn+(He-pe.timelineStart),Vt=Math.min(lt,pe.sourceOut+me),Ot=Be(Vt);r("trim",ae,"end",Ot)}}function sa(ae,ge){if(!A(ae))return;const pe=n.clips.find(He=>He.id===ae);if(!pe||Math.abs(ge)<2)return;const me=ge/P.value*n.sensitivity,Be=He=>Math.max(0,Math.round(He*n.fps)/n.fps);if(n.useFrameMode){const He=f.secondsToFrames(pe.timelineStart),lt=f.secondsToFrames(me),Vt=Math.max(0,He+lt),Ot=f.framesToSeconds(Vt);r("clip-move",ae,Ot)}else{const He=Math.max(0,pe.timelineStart+me),lt=Be(He);r("clip-move",ae,lt)}}return a({handleTrimStart:Pe,handleTrimEnd:Gt,handleClipDrag:sa,handleTrimStartAbs:Ht,handleTrimEndAbs:Zt,handleClipDragAbs:Ut,handleClipLongPress:ht}),e.watch(()=>n.playhead,ae=>{const ge=ae*P.value;ge<c.value+50?c.value=Math.max(0,ge-50):ge>c.value+E.value-50&&(c.value=Math.min(F.value,ge-E.value+50))}),e.onMounted(()=>{const ae=new ResizeObserver(ge=>{ge[0]&&(m.value=Math.round(ge[0].contentRect.width))});l.value&&ae.observe(l.value),e.onUnmounted(()=>ae.disconnect())}),e.onUnmounted(()=>{Je()}),e.watch([le,Z],()=>{c.value>F.value&&(c.value=F.value)}),e.watch(_,(ae,ge)=>{const pe=ae!==null;pe!==(ge!==null)&&r("snap-state-change",pe)}),(ae,ge)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-timeline",{mobile:i.value}]),ref_key:"timelineRef",ref:l,onWheel:Re},[e.createElementVNode("div",{class:"timeline-ruler",onClick:Se},[e.createElementVNode("div",aw,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(_e.value,pe=>(e.openBlock(),e.createElementBlock("span",{key:pe.position,class:"time-marker",style:e.normalizeStyle({left:`${pe.position}px`})},e.toDisplayString(pe.label),5))),128))])]),e.createElementVNode("div",{class:e.normalizeClass(["timeline-content",{"is-pannable":k.value,"is-panning":h.value&&v.value==="pan","overflow-left":W.value,"overflow-right":J.value}]),onTouchstart:mt,onTouchmove:pt,onTouchend:Nt,onMousedown:Ce},[x.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"timeline-track-lanes",style:e.normalizeStyle({"--timeline-track-header-width":`${Xc}px`})},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(z.value,pe=>(e.openBlock(),e.createElementBlock("div",{key:pe.track.id,class:e.normalizeClass(["timeline-track-lane",{"timeline-track-lane--locked":pe.track.locked,"timeline-track-lane--hidden":pe.track.hidden,"timeline-track-lane--drop-target":b.value===pe.track.id&&pe.track.locked!==!0,"timeline-track-lane--drop-rejected":b.value===pe.track.id&&pe.track.locked===!0}]),style:e.normalizeStyle({height:`${pe.height}px`}),"data-track-id":pe.track.id},[e.createVNode(tw,{class:"timeline-track-lane__header",track:pe.track,onToggleLock:ge[0]||(ge[0]=me=>r("toggle-lock",me)),onToggleHidden:ge[1]||(ge[1]=me=>r("toggle-hidden",me)),onToggleMuted:ge[2]||(ge[2]=me=>r("toggle-muted",me)),onToggleSolo:ge[3]||(ge[3]=me=>r("toggle-solo",me)),onRenameTrack:ge[4]||(ge[4]=(me,Be)=>r("rename-track",me,Be)),onDeleteTrack:ge[5]||(ge[5]=me=>r("delete-track",me)),onReorderTrack:ge[6]||(ge[6]=(me,Be)=>r("reorder-track",me,Be))},null,8,["track"]),e.createElementVNode("div",{class:"video-track timeline-track-lane__body","data-track-id":pe.track.id},[pe.track.hidden?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(pe.clips,me=>(e.openBlock(),e.createElementBlock("div",{key:`${me.id}-extent`,class:"clip-extent",style:e.normalizeStyle(se(me,pe.height)),"aria-hidden":"true"},null,4))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(pe.clips,me=>(e.openBlock(),e.createBlock(Gc,{key:me.id,clip:me,scale:P.value,"scroll-offset":c.value,selected:p.value===me.id,"is-mobile":i.value,"can-delete":n.clips.length>1&&A(me.id),"data-locked":pe.track.locked===!0?"true":void 0,onSelect:Be=>_t(me.id),onDelete:Be=>Wt(me.id),onLongPress:Be=>ht(me.id),onTrimStartAbs:Be=>Ht(me.id,Be),onTrimEndAbs:Be=>Zt(me.id,Be),onDragAbs:(Be,He)=>Ut(me.id,Be,He)},null,8,["clip","scale","scroll-offset","selected","is-mobile","can-delete","data-locked","onSelect","onDelete","onLongPress","onTrimStartAbs","onTrimEndAbs","onDragAbs"]))),128))],64))],8,ow)],14,nw))),128))],4)):(e.openBlock(),e.createElementBlock("div",{key:1,class:"video-track",ref_key:"trackRef",ref:u},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(ae.clips,pe=>(e.openBlock(),e.createElementBlock("div",{key:`${pe.id}-extent`,class:"clip-extent",style:e.normalizeStyle(se(pe)),"aria-hidden":"true"},null,4))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(ae.clips,pe=>(e.openBlock(),e.createBlock(Gc,{key:pe.id,clip:pe,scale:P.value,"scroll-offset":c.value,selected:p.value===pe.id,"is-mobile":i.value,"can-delete":n.clips.length>1&&A(pe.id),onSelect:me=>_t(pe.id),onDelete:me=>Wt(pe.id),onLongPress:me=>ht(pe.id),onTrimStartAbs:me=>Ht(pe.id,me),onTrimEndAbs:me=>Zt(pe.id,me),onDragAbs:(me,Be)=>Ut(pe.id,me,Be)},null,8,["clip","scale","scroll-offset","selected","is-mobile","can-delete","onSelect","onDelete","onLongPress","onTrimStartAbs","onTrimEndAbs","onDragAbs"]))),128))],512)),e.createElementVNode("div",{class:"playhead",style:e.normalizeStyle({left:`${M.value+ce.value}px`}),onMousedown:Le,onTouchstart:Le},[...ge[8]||(ge[8]=[e.createElementVNode("div",{class:"playhead-handle"},[e.createElementVNode("div",{class:"playhead-line"})],-1)])],36),d.value?(e.openBlock(),e.createElementBlock("div",{key:2,class:"split-indicator",style:e.normalizeStyle({left:`${M.value+ce.value}px`})},null,4)):e.createCommentVNode("",!0),Ue.value!==null?(e.openBlock(),e.createElementBlock("div",{key:3,class:"snap-guide",style:e.normalizeStyle({left:`${M.value+Ue.value}px`}),"aria-hidden":"true"},null,4)):e.createCommentVNode("",!0),i.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:4,class:"frame-mode-toggle",onClick:ge[7]||(ge[7]=pe=>ae.$emit("toggle-frame-mode")),"aria-label":ae.useFrameMode?"Switch to time mode":"Switch to frame mode",title:ae.useFrameMode?"Switch to time mode":"Switch to frame mode"},e.toDisplayString(ae.useFrameMode?"F":"T"),9,iw))],34),k.value?(e.openBlock(),e.createElementBlock("div",rw,[e.createElementVNode("div",{class:"scrollbar-thumb",style:e.normalizeStyle(be.value),onMousedown:nt,onTouchstart:nt},null,36)])):e.createCommentVNode("",!0)],34))}}),zs=Ae(lw,[["__scopeId","data-v-2484f443"]]),sw={key:0,class:"control-group primary-controls"},dw=["disabled"],cw=["disabled"],uw=["disabled"],mw=["disabled"],pw=["disabled"],fw=["disabled"],hw={key:1,class:"control-group mobile-action-controls"},vw=["aria-expanded"],gw={key:0,class:"mobile-action-menu",role:"menu","aria-label":"Clip actions","data-testid":"timeline-mobile-action-menu"},bw=["disabled"],yw=["disabled"],ww=["disabled"],kw=["disabled"],_w=["disabled"],Ew=["disabled"],Sw={class:"control-group zoom-controls"},Cw={class:"zoom-slider"},xw=["value"],Nw={class:"control-group playback-controls"},Vw=["aria-label"],Tw={key:2,class:"control-group speed-control"},Bw=["value"],Mw=e.defineComponent({__name:"TimelineControls",props:{selectedClip:{},canSplit:{type:Boolean,default:!1},canDelete:{type:Boolean,default:!1},canAddTrack:{type:Boolean,default:!0},showAddTrack:{type:Boolean,default:!1},canUndo:{type:Boolean,default:!1},canRedo:{type:Boolean,default:!1},isPlaying:{type:Boolean,default:!1},zoomLevel:{default:50},playbackSpeed:{default:1},isMobile:{type:Boolean,default:!1}},emits:["split","delete","duplicate","add-track","undo","redo","zoom-in","zoom-out","zoom-change","fit-to-window","play-pause","frame-forward","frame-backward","skip-to-start","skip-to-end","speed-change"],setup(o,{emit:a}){const t=a,n=e.ref(!1);function i(p){switch(p){case"split":t("split");break;case"delete":t("delete");break;case"duplicate":t("duplicate");break;case"add-track":t("add-track");break;case"undo":t("undo");break;case"redo":t("redo");break}n.value=!1}function r(p){const f=p.target;t("zoom-change",Number(f.value))}function l(){t("fit-to-window")}function s(){t("frame-forward")}function d(){t("frame-backward")}function c(){t("skip-to-start")}function u(){t("skip-to-end")}function m(p){const f=p.target;t("speed-change",Number(f.value))}return(p,f)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["timeline-controls",{mobile:p.isMobile}])},[p.isMobile?(e.openBlock(),e.createElementBlock("div",hw,[e.createElementVNode("button",{class:"control-button","data-testid":"timeline-btn-mobile-actions","aria-expanded":n.value?"true":"false","aria-label":"Clip actions",onClick:f[6]||(f[6]=h=>n.value=!n.value)},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(vv)},null,8,["icon"]),f[20]||(f[20]=e.createElementVNode("span",{class:"control-label"},"Actions",-1))],8,vw),n.value?(e.openBlock(),e.createElementBlock("div",gw,[p.showAddTrack?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",role:"menuitem",disabled:!p.canAddTrack,"data-testid":"timeline-mobile-btn-add-track",onClick:f[7]||(f[7]=h=>i("add-track"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Fr)},null,8,["icon"]),f[21]||(f[21]=e.createTextVNode(" Add Track ",-1))],8,bw)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!p.canUndo,"data-testid":"timeline-mobile-btn-undo",onClick:f[8]||(f[8]=h=>i("undo"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(yc)},null,8,["icon"]),f[22]||(f[22]=e.createTextVNode(" Undo ",-1))],8,yw),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!p.canRedo,"data-testid":"timeline-mobile-btn-redo",onClick:f[9]||(f[9]=h=>i("redo"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(bc)},null,8,["icon"]),f[23]||(f[23]=e.createTextVNode(" Redo ",-1))],8,ww),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!p.canSplit,"data-testid":"timeline-mobile-btn-split",onClick:f[10]||(f[10]=h=>i("split"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Gr)},null,8,["icon"]),f[24]||(f[24]=e.createTextVNode(" Split ",-1))],8,kw),e.createElementVNode("button",{type:"button",role:"menuitem",disabled:!p.selectedClip,"data-testid":"timeline-mobile-btn-duplicate",onClick:f[11]||(f[11]=h=>i("duplicate"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Ss)},null,8,["icon"]),f[25]||(f[25]=e.createTextVNode(" Duplicate ",-1))],8,_w),e.createElementVNode("button",{type:"button",role:"menuitem",class:"danger-menu-item",disabled:!p.canDelete,"data-testid":"timeline-mobile-btn-delete",onClick:f[12]||(f[12]=h=>i("delete"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Xr)},null,8,["icon"]),f[26]||(f[26]=e.createTextVNode(" Delete ",-1))],8,Ew)])):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("div",sw,[p.showAddTrack?(e.openBlock(),e.createElementBlock("button",{key:0,class:"control-button",disabled:!p.canAddTrack,"data-testid":"timeline-btn-add-track","aria-label":"Add video track",title:"Add Track",onClick:f[0]||(f[0]=h=>p.$emit("add-track"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Fr)},null,8,["icon"]),f[16]||(f[16]=e.createElementVNode("span",{class:"control-label"},"Add Track",-1))],8,dw)):e.createCommentVNode("",!0),e.createElementVNode("button",{class:"control-button",disabled:!p.canUndo,"data-testid":"timeline-btn-undo","aria-label":"Undo",title:"Undo",onClick:f[1]||(f[1]=h=>p.$emit("undo"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(yc)},null,8,["icon"])],8,cw),e.createElementVNode("button",{class:"control-button",disabled:!p.canRedo,"data-testid":"timeline-btn-redo","aria-label":"Redo",title:"Redo",onClick:f[2]||(f[2]=h=>p.$emit("redo"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(bc)},null,8,["icon"])],8,uw),e.createElementVNode("button",{class:"control-button",disabled:!p.canSplit,"data-testid":"timeline-btn-split","aria-label":"Split selected clip at playhead",title:"Split",onClick:f[3]||(f[3]=h=>p.$emit("split"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Gr)},null,8,["icon"]),f[17]||(f[17]=e.createElementVNode("span",{class:"control-label"},"Split",-1))],8,mw),e.createElementVNode("button",{class:"control-button",disabled:!p.selectedClip,"data-testid":"timeline-btn-duplicate","aria-label":"Duplicate selected clip",title:"Duplicate",onClick:f[4]||(f[4]=h=>p.$emit("duplicate"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Ss)},null,8,["icon"]),f[18]||(f[18]=e.createElementVNode("span",{class:"control-label"},"Duplicate",-1))],8,pw),e.createElementVNode("button",{class:"control-button danger-button",disabled:!p.canDelete,"data-testid":"timeline-btn-delete","aria-label":"Delete selected clip",title:"Delete",onClick:f[5]||(f[5]=h=>p.$emit("delete"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Xr)},null,8,["icon"]),f[19]||(f[19]=e.createElementVNode("span",{class:"control-label"},"Delete",-1))],8,fw)])),e.createElementVNode("div",Sw,[e.createElementVNode("button",{class:"control-button zoom-button",onClick:f[13]||(f[13]=h=>p.$emit("zoom-out")),"aria-label":"Zoom out"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Fv)},null,8,["icon"])]),e.createElementVNode("div",Cw,[e.createElementVNode("input",{type:"range",value:p.zoomLevel,onInput:r,min:"10",max:"200",step:"5","aria-label":"Timeline zoom"},null,40,xw)]),e.createElementVNode("button",{class:"control-button zoom-button",onClick:f[14]||(f[14]=h=>p.$emit("zoom-in")),"aria-label":"Zoom in"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Fr)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button",onClick:l,"aria-label":"Fit timeline to window"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(bv)},null,8,["icon"]),f[27]||(f[27]=e.createElementVNode("span",{class:"control-label"},"Fit",-1))])]),e.createElementVNode("div",Nw,[e.createElementVNode("button",{class:"control-button",onClick:c,"aria-label":"Skip to start"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Iv)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button",onClick:d,"aria-label":"Previous frame"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Vv)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button play-button",onClick:f[15]||(f[15]=h=>p.$emit("play-pause")),"aria-label":p.isPlaying?"Pause":"Play"},[e.createVNode(e.unref(G.IonIcon),{icon:p.isPlaying?e.unref(fd):e.unref(hd)},null,8,["icon"])],8,Vw),e.createElementVNode("button",{class:"control-button",onClick:s,"aria-label":"Next frame"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Mv)},null,8,["icon"])]),e.createElementVNode("button",{class:"control-button",onClick:u,"aria-label":"Skip to end"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref($v)},null,8,["icon"])])]),p.isMobile?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",Tw,[f[29]||(f[29]=e.createElementVNode("label",{class:"speed-label"},"Speed:",-1)),e.createElementVNode("select",{value:p.playbackSpeed,onChange:m,class:"speed-select","aria-label":"Playback speed"},[...f[28]||(f[28]=[e.createStaticVNode('<option value="0.25" data-v-c7b0395a>0.25x</option><option value="0.5" data-v-c7b0395a>0.5x</option><option value="1" data-v-c7b0395a>1x</option><option value="1.5" data-v-c7b0395a>1.5x</option><option value="2" data-v-c7b0395a>2x</option>',5)])],40,Bw)]))],2))}}),js=Ae(Mw,[["__scopeId","data-v-c7b0395a"]]),Iw={key:0,class:"category-section"},$w={class:"category-carousel-wrapper"},Fw=["disabled"],Dw=["onClick","data-testid","aria-label"],Aw={class:"category-name"},Rw=["disabled"],Lw={class:"filter-section"},Pw={class:"filter-carousel-wrapper"},Uw=["disabled"],Ow=["onClick","onKeydown","data-testid","aria-label"],zw=["onClick"],jw={class:"filter-preview"},Ww={class:"filter-placeholder"},Hw={class:"filter-name"},Zw=["disabled"],Gw={class:"carousel-pagination"},Xw=["onClick"],Kw={key:1,class:"filter-adjustments"},qw={class:"adjustment-header"},Jw={class:"adjustment-actions"},Yw={key:0},Qw={key:0,class:"slider-control"},ek={class:"control-label"},tk={class:"slider-wrapper"},ak={class:"slider-value"},nk={key:1,class:"color-control"},ok={class:"control-label"},ik={class:"color-wrapper"},rk=["value","onInput","disabled"],lk={class:"color-value"},sk={key:2,class:"toggle-control"},dk={class:"control-label"},ck={key:3,class:"select-control"},uk={class:"control-label"},mk=["value","onChange","disabled"],pk=["value"],fk={key:1,class:"no-params"},hk=e.defineComponent({__name:"VideoFilterCarousel",props:{filters:{},activeFilters:{},thumbnailUrl:{},showCategories:{type:Boolean,default:!0},compact:{type:Boolean,default:!1}},emits:["apply-filter","remove-filter","update-param","preview-filter"],setup(o,{emit:a}){const t=o,n=a,i=e.ref("all"),r=e.ref(null),l=e.ref(0),s=e.ref(0),d=e.ref(new Map),c=e.ref(),u=e.ref(),m={all:eo,adjust:ki,color:to,blur:br,light:_i,effects:es,stylize:Bi,advanced:eo,distortion:Mi,transform:Mi};function p(C){return C.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function f(C){return C.replace(/[-_]/g," ").replace(/\b\w/g,A=>A.toUpperCase())}function h(C){return m[C.toLowerCase()]??eo}const v=e.computed(()=>{const C=Array.from(new Set(t.filters.map(A=>A.category).filter(A=>typeof A=="string"&&A.length>0))).sort((A,O)=>A.localeCompare(O));return[{id:"all",name:"All",icon:eo},...C.map(A=>({id:A,name:f(A),icon:h(A)}))]}),y=e.computed(()=>i.value==="all"?t.filters:t.filters.filter(C=>C.category===i.value));e.watch(v,C=>{new Set(C.map(K=>K.id)).has(i.value)||(i.value="all");const O=Math.max(0,C.length-3);l.value>O&&(l.value=O)},{immediate:!0});function w(C){var A;return((A=t.activeFilters)==null?void 0:A.has(C))||!1}function _(C){if(r.value=C,!w(C.id)&&(n("apply-filter",C),C.params&&C.params.length>0)){const A=new Map;C.params.forEach(O=>{A.set(O.id,O.default)}),d.value.set(C.id,A)}n("preview-filter",C)}function b(C){var A;n("remove-filter",C),d.value.delete(C),((A=r.value)==null?void 0:A.id)===C&&(r.value=null)}function g(C){if(typeof C=="number"&&Number.isFinite(C))return C;if(typeof C=="string"){const A=Number(C);return Number.isFinite(A)?A:null}return null}function I(C,A){var Z;const O=t.filters.find(k=>k.id===C),K=O==null?void 0:O.params.find(k=>k.id===A),se=(K==null?void 0:K.default)??0,xe=k=>typeof se=="number"?g(k)??se:typeof se=="boolean"?typeof k=="boolean"?k:se:typeof k=="string"?k:se,ue=(Z=t.activeFilters)==null?void 0:Z.get(C);if(ue&&ue.params){const k=ue.params[A];if(k!=null)return xe(k)}const le=d.value.get(C);if(le){const k=le.get(A);if(k!=null)return xe(k)}return se}function T(C,A,O){var K;d.value.has(C)||d.value.set(C,new Map),(K=d.value.get(C))==null||K.set(A,O),n("update-param",C,A,O)}function $(C){if(typeof C=="boolean")return C?"On":"Off";if(typeof C=="string"){const O=g(C);return O===null?"0":Number.isInteger(O)?O.toString():O.toFixed(2)}const A=g(C);return A===null?"0":Number.isInteger(A)?A.toString():A.toFixed(2)}function N(){if(r.value&&(n("apply-filter",r.value),r.value.params&&r.value.params.length>0)){const C=new Map;r.value.params.forEach(A=>{C.set(A.id,A.default)}),d.value.set(r.value.id,C)}}function B(C){const A=t.filters.find(O=>O.id===C);A&&A.params&&A.params.forEach(O=>{T(C,O.id,O.default)})}function P(C){return{basic:ki,color:to,blur:br,light:_i,effects:es,stylize:Bi,adjustment:ki,"color-matrix":to,glow:eo,distortion:Mi}[C]||eo}function x(C){return{adjustment:ki,brightness:_i,contrast:ki,saturation:to,blur:br,"gaussian-blur":br,"color-matrix":to,grayscale:Bi,sepia:Bi,vignette:Mi,glow:eo,glitch:es,godray:_i,lightmap:_i}[C.id]||P(C.category)}function M(){l.value>0&&(l.value--,z(c.value,l.value))}function E(){l.value<v.value.length-3&&(l.value++,z(c.value,l.value))}function D(){s.value>0&&(s.value--,z(u.value,s.value))}function j(){s.value<y.value.length-4&&(s.value++,z(u.value,s.value))}function L(C){s.value=C*4,z(u.value,s.value)}function z(C,A){var O;if(C){const K=((O=C.querySelector(".category-chip, .filter-card"))==null?void 0:O.clientWidth)||100;C.scrollTo({left:A*(K+8),behavior:"smooth"})}}return(C,A)=>{var O;return e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-filter-carousel-container",{compact:C.compact}])},[C.showCategories?(e.openBlock(),e.createElementBlock("div",Iw,[e.createElementVNode("div",$w,[e.createElementVNode("button",{onClick:M,class:"carousel-nav carousel-nav-left",disabled:l.value===0,"aria-label":"Previous categories","data-testid":"btn-filter-category-prev"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(wc)},null,8,["icon"])],8,Fw),e.createElementVNode("div",{ref_key:"categoryCarouselRef",ref:c,class:"category-carousel"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(v.value,K=>(e.openBlock(),e.createElementBlock("button",{key:K.id,onClick:se=>i.value=K.id,class:e.normalizeClass(["category-chip",{active:i.value===K.id}]),"data-testid":`btn-filter-category-${p(K.id)}`,"aria-label":`Filter category ${K.name}`},[e.createVNode(e.unref(G.IonIcon),{icon:K.icon,class:"category-icon"},null,8,["icon"]),e.createElementVNode("span",Aw,e.toDisplayString(K.name),1)],10,Dw))),128))],512),e.createElementVNode("button",{onClick:E,class:"carousel-nav carousel-nav-right",disabled:l.value>=v.value.length-3,"aria-label":"Next categories","data-testid":"btn-filter-category-next"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(kc)},null,8,["icon"])],8,Rw)])])):e.createCommentVNode("",!0),e.createElementVNode("div",Lw,[e.createElementVNode("div",Pw,[e.createElementVNode("button",{onClick:D,class:"carousel-nav carousel-nav-left",disabled:s.value===0,"aria-label":"Previous filters","data-testid":"btn-filter-carousel-prev"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(wc)},null,8,["icon"])],8,Uw),e.createElementVNode("div",{ref_key:"filterCarouselRef",ref:u,class:"filter-carousel"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(y.value,K=>{var se;return e.openBlock(),e.createElementBlock("div",{key:K.id,class:e.normalizeClass(["filter-card",{active:w(K.id),selected:((se=r.value)==null?void 0:se.id)===K.id}]),onClick:xe=>_(K),onKeydown:[e.withKeys(xe=>_(K),["enter"]),e.withKeys(e.withModifiers(xe=>_(K),["prevent"]),["space"])],role:"button",tabindex:"0","data-testid":`btn-video-filter-${p(K.id)}`,"aria-label":`Select filter ${K.name}`},[w(K.id)?(e.openBlock(),e.createElementBlock("div",{key:0,class:"filter-checkmark",onClick:e.withModifiers(xe=>b(K.id),["stop"])},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(gm)},null,8,["icon"])],8,zw)):e.createCommentVNode("",!0),e.createElementVNode("div",jw,[e.createElementVNode("div",Ww,[e.createVNode(e.unref(G.IonIcon),{icon:x(K),class:"filter-icon"},null,8,["icon"])])]),e.createElementVNode("span",Hw,e.toDisplayString(K.name),1)],42,Ow)}),128))],512),e.createElementVNode("button",{onClick:j,class:"carousel-nav carousel-nav-right",disabled:s.value>=Math.max(0,y.value.length-4),"aria-label":"Next filters","data-testid":"btn-filter-carousel-next"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(kc)},null,8,["icon"])],8,Zw)]),e.createElementVNode("div",Gw,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Math.ceil(y.value.length/4),(K,se)=>(e.openBlock(),e.createElementBlock("span",{key:se,class:e.normalizeClass(["pagination-dot",{active:Math.floor(s.value/4)===se}]),onClick:xe=>L(se)},null,10,Xw))),128))])]),r.value?(e.openBlock(),e.createElementBlock("div",Kw,[e.createElementVNode("div",qw,[e.createElementVNode("h4",null,e.toDisplayString(r.value.name),1),e.createElementVNode("div",Jw,[w(r.value.id)?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:0,onClick:N,class:"apply-btn","data-testid":"btn-apply-selected-filter"}," Apply Filter ")),w(r.value.id)?(e.openBlock(),e.createElementBlock("button",{key:1,onClick:A[0]||(A[0]=K=>b(r.value.id)),class:"remove-btn","data-testid":"btn-remove-selected-filter"}," Remove Filter ")):e.createCommentVNode("",!0),w(r.value.id)&&((O=r.value.params)==null?void 0:O.length)>0?(e.openBlock(),e.createElementBlock("button",{key:2,onClick:A[1]||(A[1]=K=>B(r.value.id)),class:"reset-btn","data-testid":"btn-reset-selected-filter"}," Reset ")):e.createCommentVNode("",!0)])]),r.value.params&&r.value.params.length>0?(e.openBlock(),e.createElementBlock("div",Yw,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.value.params,K=>(e.openBlock(),e.createElementBlock("div",{key:K.id,class:"adjustment-control"},[!K.type||K.type==="slider"?(e.openBlock(),e.createElementBlock("div",Qw,[e.createElementVNode("label",ek,e.toDisplayString(K.label||K.id),1),e.createElementVNode("div",tk,[e.createVNode(e.unref(G.IonRange),{value:I(r.value.id,K.id),onIonChange:se=>T(r.value.id,K.id,se.detail.value),min:K.min,max:K.max,step:K.step||.01,color:"primary",class:"compact-slider",disabled:!w(r.value.id),"data-testid":`range-filter-${p(r.value.id)}-${p(K.id)}`,"aria-label":`Adjust ${K.label||K.id} for ${r.value.name}`},null,8,["value","onIonChange","min","max","step","disabled","data-testid","aria-label"]),e.createElementVNode("span",ak,e.toDisplayString($(I(r.value.id,K.id))),1)])])):K.type==="color"?(e.openBlock(),e.createElementBlock("div",nk,[e.createElementVNode("label",ok,e.toDisplayString(K.label||K.id),1),e.createElementVNode("div",ik,[e.createElementVNode("input",{type:"color",value:I(r.value.id,K.id),onInput:se=>T(r.value.id,K.id,se.target.value),disabled:!w(r.value.id),class:"color-input"},null,40,rk),e.createElementVNode("span",lk,e.toDisplayString(I(r.value.id,K.id)),1)])])):K.type==="toggle"?(e.openBlock(),e.createElementBlock("div",sk,[e.createElementVNode("label",dk,e.toDisplayString(K.label||K.id),1),e.createVNode(e.unref(G.IonToggle),{checked:!!I(r.value.id,K.id),onIonChange:se=>T(r.value.id,K.id,se.detail.checked),disabled:!w(r.value.id),color:"primary"},null,8,["checked","onIonChange","disabled"])])):K.type==="select"?(e.openBlock(),e.createElementBlock("div",ck,[e.createElementVNode("label",uk,e.toDisplayString(K.label||K.id),1),e.createElementVNode("select",{value:I(r.value.id,K.id),onChange:se=>T(r.value.id,K.id,se.target.value),disabled:!w(r.value.id),class:"select-input"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(K.options,se=>(e.openBlock(),e.createElementBlock("option",{key:String(se.value),value:se.value},e.toDisplayString(se.label),9,pk))),128))],40,mk)])):e.createCommentVNode("",!0)]))),128))])):(e.openBlock(),e.createElementBlock("div",fk," This filter has no adjustable parameters "))])):e.createCommentVNode("",!0)],2)}}}),Ws=Ae(hk,[["__scopeId","data-v-9efd15d9"]]);class vk{constructor(a){this.pixiFilters=new Map,this.filterParams=new Map,this.filterTypes=new Map,this.filterIntensity=new Map,this.composition=a}setComposition(a){this.composition=a}mapMediablesToPIXI(a){switch(a.filterId){case"blur":return this.createBlurFilter(a.params);case"brightness":return this.createBrightnessFilter(a.params);case"contrast":return this.createContrastFilter(a.params);case"saturation":return this.createSaturationFilter(a.params);case"hue":return this.createHueFilter(a.params);case"vintage":return this.createVintageFilter(a.params);case"grayscale":return this.createGrayscaleFilter();case"sepia":return this.createSepiaFilter();default:return null}}createBlurFilter(a){var t,n;try{const i=(n=(t=window.PIXI)==null?void 0:t.filters)==null?void 0:n.BlurFilter;if(!i)return null;const r=new i;return r.blur=a.intensity||5,r.quality=a.quality||4,r}catch{return null}}createBrightnessFilter(a){var t,n;try{const i=(n=(t=window.PIXI)==null?void 0:t.filters)==null?void 0:n.ColorMatrixFilter;if(!i)return null;const r=new i;return r.brightness(a.value||1,!1),r}catch{return null}}createContrastFilter(a){var t,n;try{const i=(n=(t=window.PIXI)==null?void 0:t.filters)==null?void 0:n.ColorMatrixFilter;if(!i)return null;const r=new i;return r.contrast(a.value||1,!1),r}catch{return null}}createSaturationFilter(a){var t,n;try{const i=(n=(t=window.PIXI)==null?void 0:t.filters)==null?void 0:n.ColorMatrixFilter;if(!i)return null;const r=new i;return r.saturate(a.value||1,!1),r}catch{return null}}createHueFilter(a){var t,n;try{const i=(n=(t=window.PIXI)==null?void 0:t.filters)==null?void 0:n.ColorMatrixFilter;if(!i)return null;const r=new i;return r.hue(a.rotation||0,!1),r}catch{return null}}createVintageFilter(a){var t,n;try{const i=(n=(t=window.PIXI)==null?void 0:t.filters)==null?void 0:n.ColorMatrixFilter;if(!i)return null;const r=new i;return r.vintage(!1),a.intensity&&(r.contrast(1.2,!1),r.saturate(.8,!1)),r}catch{return null}}createGrayscaleFilter(){var a,t;try{const n=(t=(a=window.PIXI)==null?void 0:a.filters)==null?void 0:t.ColorMatrixFilter;if(!n)return null;const i=new n;return i.desaturate(),i}catch{return null}}createSepiaFilter(){var a,t;try{const n=(t=(a=window.PIXI)==null?void 0:a.filters)==null?void 0:t.ColorMatrixFilter;if(!n)return null;const i=new n;return i.sepia(!1),i}catch{return null}}async applyFilters(a){if(this.composition){this.clearFilters();for(const t of a){const n=this.mapMediablesToPIXI(t);n&&(this.pixiFilters.set(t.id,n),this.filterParams.set(t.id,t.params),this.filterTypes.set(t.id,t.filterId),this.filterIntensity.set(t.id,t.intensity),await this.applyToComposition(t.id,n))}}}async applyToComposition(a,t){try{this.composition.applyFilter&&await this.composition.applyFilter(a,t)}catch{}}updateFilterParams(a,t){var i;const n=this.pixiFilters.get(a);n&&(this.filterParams.set(a,t),"blur"in n&&(n.blur=t.intensity||n.blur),"brightness"in n&&n.brightness(t.value||1,!1),"contrast"in n&&n.contrast(t.value||1,!1),"saturate"in n&&n.saturate(t.value||1,!1),"hue"in n&&n.hue(t.rotation||0,!1),(i=this.composition)!=null&&i.update&&this.composition.update())}getFilterParams(a){return this.filterParams.get(a)||{}}removeFilter(a){var t;this.pixiFilters.delete(a),this.filterParams.delete(a),this.filterTypes.delete(a),this.filterIntensity.delete(a),(t=this.composition)!=null&&t.removeFilter&&this.composition.removeFilter(a)}clearFilters(){var a;this.pixiFilters.clear(),this.filterParams.clear(),this.filterTypes.clear(),this.filterIntensity.clear(),(a=this.composition)!=null&&a.clearFilters&&this.composition.clearFilters()}getActiveFilters(){return Array.from(this.pixiFilters.values())}exportFilterConfig(){const a=[];return this.pixiFilters.forEach((t,n)=>{const i=this.filterParams.get(n)??{},r=this.filterTypes.get(n)??"unknown",l=this.filterIntensity.get(n)??1;a.push({id:n,filterId:r,params:i,intensity:l})}),a}async importFilterConfig(a){await this.applyFilters(a)}destroy(){this.clearFilters(),this.composition=null}}const gk={class:"video-filter-preview"},bk={class:"preview-title"},yk={class:"filter-controls"},wk={class:"control-input"},kk=["value","onInput","min","max","step"],_k={class:"param-value"},Ek={class:"preview-container"},Sk={key:0,class:"filter-presets"},Ck=["onClick"],xk={class:"preview-actions"},Nk=e.defineComponent({__name:"VideoFilterPreview",props:{filter:{},currentFrame:{},useVideoEngine:{type:Boolean,default:!1},composition:{}},emits:["update-params","apply"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(),r=e.ref(!1),l=e.ref({});let s,d,c=null,u=null;const m=e.computed(()=>{var N;return((N=t.filter)==null?void 0:N.paramRanges)||{}}),p=e.computed(()=>f.value.length>0),f=e.computed(()=>t.filter?{brightness:[{name:"Subtle",params:{value:.1}},{name:"Medium",params:{value:.3}},{name:"Strong",params:{value:.5}}],contrast:[{name:"Low",params:{value:.8}},{name:"Normal",params:{value:1}},{name:"High",params:{value:1.5}}],"gaussian-blur":[{name:"Subtle",params:{value:1}},{name:"Medium",params:{value:3}},{name:"Strong",params:{value:5}}]}[t.filter.id]||[]:[]);async function h(){var N;if(i.value){t.useVideoEngine&&t.composition&&(u=new vk(t.composition));try{if(s=new na.Application,await s.init({width:i.value.clientWidth,height:i.value.clientHeight,background:0,resolution:window.devicePixelRatio||1,autoDensity:!0,canvas:i.value}),(N=t.currentFrame)!=null&&N.dataUrl){const B=await na.Assets.load(t.currentFrame.dataUrl);d=new na.Sprite(B);const P=Math.min(s.screen.width/d.texture.width,s.screen.height/d.texture.height);d.scale.set(P),d.anchor.set(.5),d.position.set(s.screen.width/2,s.screen.height/2),s.stage.addChild(d)}v()}catch{}}}function v(){if(!(!d||!t.filter))if(t.useVideoEngine&&u){const N={id:t.filter.id,filterId:t.filter.id,params:l.value,intensity:l.value.value??l.value.intensity??1};u.applyFilters([N]).then(()=>{}).catch(B=>{}),c&&(c.destroy(),c=null),c=y(t.filter.id,l.value),c&&(d.filters=r.value?null:[c])}else c&&(c.destroy(),c=null),c=y(t.filter.id,l.value),c&&(d.filters=r.value?null:[c])}function y(N,B){switch(N){case"brightness":{const P=new na.ColorMatrixFilter,x=1+(B.value??0);return typeof P.brightness=="function"&&P.brightness(x,!1),P}case"contrast":{const P=new na.ColorMatrixFilter,x=B.value??1;return typeof P.contrast=="function"&&P.contrast(x,!1),P}case"saturation":{const P=new na.ColorMatrixFilter,x=B.value??1;return typeof P.saturate=="function"&&P.saturate(x,!1),P}case"hue":{const P=new na.ColorMatrixFilter,x=B.value??0;return typeof P.hue=="function"&&P.hue(x,!1),P}case"gaussian-blur":{const P=B.value??5;return new na.BlurFilter({strength:P,quality:4})}case"sepia":{const P=new na.ColorMatrixFilter;return typeof P.sepia=="function"&&P.sepia(!1),P}case"grayscale":{const P=new na.ColorMatrixFilter;return typeof P.desaturate=="function"&&P.desaturate(),P}default:return null}}function w(N,B){const P=B.target,x=Number.parseFloat(P.value),M=Number.isFinite(x)?x:0;l.value={...l.value,[N]:M},t.useVideoEngine&&u&&t.filter&&u.updateFilterParams(t.filter.id,l.value),n("update-params",l.value),v()}function _(N){return N.charAt(0).toUpperCase()+N.slice(1).replace(/_/g," ")}function b(N,B){var x;const P=typeof N=="number"?N:Number(N);return Number.isFinite(P)?B==="hue"||B==="angle"?`${P}°`:B==="value"&&((x=t.filter)==null?void 0:x.id)==="brightness"?`${Math.round((1+P)*100)}%`:Number.isInteger(P)?P.toString():P.toFixed(2):"0"}function g(){var N;l.value=((N=t.filter)==null?void 0:N.defaultParams)||{},n("update-params",l.value),v()}function I(N){l.value={...N.params},n("update-params",l.value),v()}function T(N){return JSON.stringify(N.params)===JSON.stringify(l.value)}function $(){n("apply")}return e.watch(()=>t.filter,N=>{N&&(l.value={...N.defaultParams},v())}),e.watch(()=>t.currentFrame,async N=>{if(N!=null&&N.dataUrl&&d){const B=await na.Assets.load(N.dataUrl);d.texture=B}}),e.watch(r,v),e.onMounted(()=>{t.filter&&(l.value={...t.filter.defaultParams}),h()}),e.onUnmounted(()=>{s&&s.destroy(!0,{children:!0,texture:!0}),c&&c.destroy(),u&&u.destroy()}),(N,B)=>{var P;return e.openBlock(),e.createElementBlock("div",gk,[e.createElementVNode("h4",bk,e.toDisplayString((P=N.filter)==null?void 0:P.name)+" Settings",1),e.createElementVNode("div",yk,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(m.value,(x,M)=>(e.openBlock(),e.createElementBlock("div",{key:M,class:"control-group"},[e.createElementVNode("label",null,e.toDisplayString(_(M)),1),e.createElementVNode("div",wk,[e.createElementVNode("input",{type:"range",value:l.value[M],onInput:E=>w(M,E),min:x.min,max:x.max,step:x.step,class:"param-slider"},null,40,kk),e.createElementVNode("span",_k,e.toDisplayString(b(l.value[M],M)),1)])]))),128))]),e.createElementVNode("div",Ek,[e.createElementVNode("canvas",{ref_key:"previewCanvas",ref:i,class:"preview-canvas"},null,512),e.createElementVNode("button",{class:"compare-button",onMousedown:B[0]||(B[0]=x=>r.value=!0),onMouseup:B[1]||(B[1]=x=>r.value=!1),onTouchstart:B[2]||(B[2]=x=>r.value=!0),onTouchend:B[3]||(B[3]=x=>r.value=!1)},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Mi)},null,8,["icon"]),B[4]||(B[4]=e.createTextVNode(" Hold to compare ",-1))],32)]),p.value?(e.openBlock(),e.createElementBlock("div",Sk,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(f.value,x=>(e.openBlock(),e.createElementBlock("button",{key:x.name,class:e.normalizeClass(["preset-button",{active:T(x)}]),onClick:M=>I(x)},e.toDisplayString(x.name),11,Ck))),128))])):e.createCommentVNode("",!0),e.createElementVNode("div",xk,[e.createElementVNode("button",{class:"action-button",onClick:g},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Uo)},null,8,["icon"]),B[5]||(B[5]=e.createTextVNode(" Reset ",-1))]),e.createElementVNode("button",{class:"action-button primary",onClick:$},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(bm)},null,8,["icon"]),B[6]||(B[6]=e.createTextVNode(" Apply Filter ",-1))])])])}}}),Hs=Ae(Nk,[["__scopeId","data-v-3de3dd04"]]),ap={id:"mobile-share",label:"Mobile share",description:"Fast H.264 MP4 export for short social clips and mobile uploads.",settings:{format:"mp4",codec:"h264",quality:"720p",fps:30,bitrate:45e5,routePreference:"client",maxClientDurationSeconds:90,mobileSuitable:!0,advancedVisibility:"standard"}},np={id:"hd-web",label:"HD web",description:"Balanced 1080p H.264 MP4 export for web playback.",settings:{format:"mp4",codec:"h264",quality:"1080p",fps:30,bitrate:8e6,routePreference:"auto",maxClientDurationSeconds:180,mobileSuitable:!0,advancedVisibility:"standard"}},op={id:"original",label:"Original",description:"Server-rendered MP4 export that preserves the editor output quality target.",settings:{format:"mp4",codec:"h264",quality:"1080p",fps:30,routePreference:"server",maxClientDurationSeconds:null,mobileSuitable:!1,advancedVisibility:"standard"}},ip={id:"server-master",label:"Server master",description:"High-bitrate master render for archival and downstream transcodes.",settings:{format:"mov",codec:"h265",quality:"2160p",fps:60,bitrate:32e6,routePreference:"server",maxClientDurationSeconds:null,mobileSuitable:!1,advancedVisibility:"advanced"}},rp=[ap,np,op,ip],$d={"mobile-share":ap,"hd-web":np,original:op,"server-master":ip},Vk=["mobile-share","hd-web"],Tk=["hd-web","original","mobile-share"],Bk=["server-master","hd-web","original","mobile-share"];function Tl(o){return typeof o=="string"?$d[o]:o}function Mk(o){const{bitrate:a,codec:t,format:n,fps:i,quality:r}=Tl(o).settings,l={format:n,codec:t,quality:r,fps:i};return typeof a=="number"&&(l.bitrate=a),l}function Ik(o){const a=Tl(o);return a.settings.mobileSuitable&&a.settings.advancedVisibility==="standard"}function $k(o=rp){return o.filter(a=>Ik(a))}function Fk(o,a){const t=Tl(o).settings.maxClientDurationSeconds;return t!==null&&Number.isFinite(a)&&a>=0&&a<=t}function Dk(o,a){const t=Tl(o),n=a.endpoints.client&&Fk(t,a.durationSeconds),i=a.endpoints.server;return t.settings.routePreference==="client"?n?"client":i?"server":null:t.settings.routePreference==="server"?i?"server":n?"client":null:n?"client":i?"server":null}function Ak(o,a){return Dk(o,a)!==null}function Rk(o){const a=Lk(o);for(const t of a){const n=$d[t];if(Pk(n,o.includeAdvanced===!0)&&!(o.device==="mobile"&&!n.settings.mobileSuitable)&&Ak(n,o))return n}return null}function Lk(o){return o.device==="mobile"?Vk:o.includeAdvanced===!0?Bk:Tk}function Pk(o,a){return o.settings.advancedVisibility==="hidden"?!1:o.settings.advancedVisibility==="standard"||a}const Uk={class:"export-settings"},Ok={class:"setting-group preset-setting"},zk={class:"setting-copy"},jk={class:"setting-description"},Wk=["value"],Hk={key:0,class:"advanced-toggle","data-testid":"export-advanced-toggle"},Zk={class:"preset-summary","data-testid":"export-preset-summary"},Gk={class:"estimated-size"},Xk={key:0,class:"export-progress"},Kk={class:"progress-header"},qk={class:"progress-percentage"},Jk={class:"progress-time"},Yk={class:"action-buttons"},Qk=["disabled"],e_=["disabled"],t_=["disabled"],a_={class:"export-options"},n_="hd-web",o_=e.defineComponent({__name:"EditorControls",props:{canExport:{type:Boolean,default:!1},isExporting:{type:Boolean,default:!1},exportProgress:{default:0},isMobile:{type:Boolean,default:!1},duration:{default:0}},emits:["export","save-draft","reset","cancel-export"],setup(o,{emit:a}){const t=o,n=a,i={client:!0,server:!0},r=rp,l={"360p":1,"480p":2.5,"720p":5,"1080p":8,"1440p":16,"2160p":35},s=e.ref(!1),d=e.ref(g()),c=e.ref(!0),u=e.ref(!1),m=e.ref(0),p=e.ref(0),f=e.ref(0);let h=null;const v=e.computed(()=>t.isMobile?$k():r.filter(x=>x.settings.advancedVisibility==="hidden"?!1:x.settings.advancedVisibility==="standard"||s.value)),y=e.computed(()=>v.value.find(x=>x.id===d.value)??$d[g()]),w=e.computed(()=>Mk(y.value)),_=e.computed(()=>{const x=w.value,M=[x.quality,x.format.toUpperCase(),x.codec.toUpperCase(),`${x.fps} fps`],E=I(x.bitrate);return E!==null&&M.push(E),M.join(" / ")}),b=e.computed(()=>{const x=w.value,E=(typeof x.bitrate=="number"?x.bitrate/1e6:l[x.quality])*t.duration/8;return E<1e3?`~${Math.round(E)} MB`:`~${(E/1e3).toFixed(1)} GB`});function g(){var x;return((x=Rk({durationSeconds:t.duration,device:t.isMobile?"mobile":"desktop",endpoints:i,includeAdvanced:s.value}))==null?void 0:x.id)??n_}function I(x){return typeof x!="number"?null:`${Number((x/1e6).toFixed(1))} Mbps`}function T(){t.isExporting?(n("cancel-export"),B()):$()}function $(){const x=w.value,M={quality:x.quality,format:x.format,optimizeForWeb:c.value,includeWatermark:u.value,presetId:y.value.id,codec:x.codec,fps:x.fps};typeof x.bitrate=="number"&&(M.bitrate=x.bitrate),n("export",M),N()}function N(){m.value=Date.now(),p.value=0,h=window.setInterval(()=>{if(p.value=Math.floor((Date.now()-m.value)/1e3),t.exportProgress>0){const x=p.value/t.exportProgress*100;f.value=Math.max(0,x-p.value)}},1e3)}function B(){h&&(clearInterval(h),h=null)}function P(x){const M=Math.floor(x/60),E=Math.floor(x%60);return`${M}:${E.toString().padStart(2,"0")}`}return e.watch([()=>t.isMobile,()=>s.value],()=>{v.value.some(M=>M.id===d.value)||(d.value=g())},{immediate:!0}),e.watch(()=>t.isExporting,x=>{x||B()}),e.onUnmounted(()=>{B()}),(x,M)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["editor-controls",{mobile:x.isMobile}])},[e.createElementVNode("div",Uk,[M[8]||(M[8]=e.createElementVNode("h3",{class:"section-title"},"Export Settings",-1)),e.createElementVNode("div",Ok,[e.createElementVNode("div",zk,[M[6]||(M[6]=e.createElementVNode("label",{for:"export-preset-select"},"Preset",-1)),e.createElementVNode("span",jk,e.toDisplayString(y.value.description),1)]),e.withDirectives(e.createElementVNode("select",{id:"export-preset-select","onUpdate:modelValue":M[0]||(M[0]=E=>d.value=E),class:"setting-select preset-select","data-testid":"export-preset-select"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(v.value,E=>(e.openBlock(),e.createElementBlock("option",{key:E.id,value:E.id},e.toDisplayString(E.label),9,Wk))),128))],512),[[e.vModelSelect,d.value]])]),x.isMobile?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("label",Hk,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":M[1]||(M[1]=E=>s.value=E),type:"checkbox","data-testid":"export-advanced-toggle-input"},null,512),[[e.vModelCheckbox,s.value]]),M[7]||(M[7]=e.createElementVNode("span",null,"Advanced presets",-1))])),e.createElementVNode("div",Zk,e.toDisplayString(_.value),1),e.createElementVNode("div",Gk,[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(_v)},null,8,["icon"]),e.createElementVNode("span",null,"Estimated size: "+e.toDisplayString(b.value),1)])]),x.isExporting?(e.openBlock(),e.createElementBlock("div",Xk,[e.createElementVNode("div",Kk,[M[9]||(M[9]=e.createElementVNode("span",null,"Exporting...",-1)),e.createElementVNode("span",qk,e.toDisplayString(x.exportProgress??0)+"%",1)]),e.createVNode(e.unref(G.IonProgressBar),{value:(x.exportProgress??0)/100},null,8,["value"]),e.createElementVNode("div",Jk,[e.createElementVNode("span",null,e.toDisplayString(P(p.value))+" elapsed",1),e.createElementVNode("span",null,e.toDisplayString(P(f.value))+" remaining",1)])])):e.createCommentVNode("",!0),e.createElementVNode("div",Yk,[e.createElementVNode("button",{class:"control-button secondary",onClick:M[2]||(M[2]=E=>x.$emit("save-draft")),disabled:!x.canExport||x.isExporting},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(pl)},null,8,["icon"]),M[10]||(M[10]=e.createTextVNode(" Save Draft ",-1))],8,Qk),e.createElementVNode("button",{class:"control-button secondary",onClick:M[3]||(M[3]=E=>x.$emit("reset")),disabled:x.isExporting},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Uo)},null,8,["icon"]),M[11]||(M[11]=e.createTextVNode(" Reset ",-1))],8,e_),e.createElementVNode("button",{class:"control-button primary",onClick:T,disabled:!x.canExport&&!x.isExporting,"data-testid":"video-export-button"},[e.createVNode(e.unref(G.IonIcon),{icon:x.isExporting?e.unref($o):e.unref(ni)},null,8,["icon"]),e.createTextVNode(" "+e.toDisplayString(x.isExporting?"Cancel":"Export Video"),1)],8,t_)]),e.createElementVNode("div",a_,[e.createVNode(e.unref(G.IonItem),{lines:"none"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonCheckbox),{modelValue:c.value,"onUpdate:modelValue":M[4]||(M[4]=E=>c.value=E)},null,8,["modelValue"]),e.createVNode(e.unref(G.IonLabel),null,{default:e.withCtx(()=>[...M[12]||(M[12]=[e.createTextVNode("Optimize for web streaming",-1)])]),_:1})]),_:1}),e.createVNode(e.unref(G.IonItem),{lines:"none"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonCheckbox),{modelValue:u.value,"onUpdate:modelValue":M[5]||(M[5]=E=>u.value=E)},null,8,["modelValue"]),e.createVNode(e.unref(G.IonLabel),null,{default:e.withCtx(()=>[...M[13]||(M[13]=[e.createTextVNode("Include watermark",-1)])]),_:1})]),_:1})])],2))}}),Zs=Ae(o_,[["__scopeId","data-v-d26ca1bc"]]),i_={class:"thumbnail-picker"},r_={class:"thumbnail-grid"},l_=["onClick"],s_=["src","alt"],d_={key:1,class:"thumbnail-placeholder"},c_={class:"thumbnail-time"},u_={class:"custom-selector"},m_={class:"time-input-group"},p_=["max"],f_={class:"time-value"},h_=["disabled"],v_={class:"picker-actions"},g_=["disabled"],b_=e.defineComponent({__name:"ThumbnailPicker",props:{mediaUuid:{},duration:{},currentTime:{default:0}},emits:["select","cancel"],setup(o,{emit:a}){const t=o,n=a,i=e.ref([]),r=e.ref(-1),l=e.ref(t.currentTime),s=e.ref(!1);function d(){const w=[];if(t.duration<=10)for(let b=0;b<Math.min(9,t.duration);b++)w.push(b);else{const b=t.duration/10;for(let g=1;g<=9;g++)w.push(b*g)}return w}async function c(w){try{const _=document.createElement("video");return _.crossOrigin="anonymous",_.src=await u(),new Promise(b=>{_.addEventListener("loadedmetadata",()=>{_.currentTime=w}),_.addEventListener("seeked",()=>{const g=document.createElement("canvas");g.width=_.videoWidth,g.height=_.videoHeight;const I=g.getContext("2d");I?(I.drawImage(_,0,0),b(g.toDataURL("image/jpeg",.8))):b(null),_.remove()}),_.addEventListener("error",()=>{b(null),_.remove()})})}catch{return null}}async function u(){try{return(await(await fetch(`/api/media/${t.mediaUuid}/playback`)).json()).playback_url}catch{return`/media/${t.mediaUuid}/video`}}async function m(){const w=d();i.value=w.map(b=>({time:b,loading:!0}));const _=3;for(let b=0;b<i.value.length;b+=_){const g=i.value.slice(b,b+_);await Promise.all(g.map(async I=>{const T=await c(I.time);T&&(I.dataUrl=T),I.loading=!1}))}}function p(w){r.value=w,l.value=i.value[w].time}function f(){r.value=-1}async function h(){s.value=!0;try{const w=await c(l.value);if(w){const _=i.value.findIndex(b=>Math.abs(b.time-l.value)<.1);_>=0?(i.value[_].dataUrl=w,r.value=_):(i.value.push({time:l.value,dataUrl:w}),r.value=i.value.length-1,i.value.sort((b,g)=>b.time-g.time),r.value=i.value.findIndex(b=>b.time===l.value))}}finally{s.value=!1}}function v(){const w=r.value>=0?i.value[r.value].time:l.value;n("select",w)}function y(w){const _=Math.floor(w/60),b=Math.floor(w%60),g=Math.floor(w%1*100);return _>0?`${_}:${b.toString().padStart(2,"0")}.${g.toString().padStart(2,"0")}`:`${b}.${g.toString().padStart(2,"0")}s`}return e.onMounted(()=>{m()}),(w,_)=>(e.openBlock(),e.createElementBlock("div",i_,[_[5]||(_[5]=e.createElementVNode("h4",{class:"picker-title"},"Select Video Thumbnail",-1)),e.createElementVNode("div",r_,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,(b,g)=>(e.openBlock(),e.createElementBlock("div",{key:g,class:e.normalizeClass(["thumbnail-item",{selected:r.value===g}]),onClick:I=>p(g)},[b.dataUrl?(e.openBlock(),e.createElementBlock("img",{key:0,src:b.dataUrl,alt:`Frame at ${y(b.time)}`},null,8,s_)):(e.openBlock(),e.createElementBlock("div",d_,[e.createVNode(e.unref(G.IonSpinner),{name:"crescent"})])),e.createElementVNode("div",c_,e.toDisplayString(y(b.time)),1)],10,l_))),128))]),e.createElementVNode("div",u_,[_[3]||(_[3]=e.createElementVNode("label",null,"Custom time:",-1)),e.createElementVNode("div",m_,[e.withDirectives(e.createElementVNode("input",{type:"range","onUpdate:modelValue":_[0]||(_[0]=b=>l.value=b),min:0,max:w.duration,step:.1,onInput:f,class:"time-slider"},null,40,p_),[[e.vModelText,l.value]]),e.createElementVNode("span",f_,e.toDisplayString(y(l.value)),1)]),e.createElementVNode("button",{class:"capture-button",onClick:h,disabled:s.value},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(cv)},null,8,["icon"]),_[2]||(_[2]=e.createTextVNode(" Capture Frame ",-1))],8,h_)]),e.createElementVNode("div",v_,[e.createElementVNode("button",{class:"action-button",onClick:_[1]||(_[1]=b=>w.$emit("cancel"))}," Cancel "),e.createElementVNode("button",{class:"action-button primary",onClick:v,disabled:r.value===-1},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(bm)},null,8,["icon"]),_[4]||(_[4]=e.createTextVNode(" Set Thumbnail ",-1))],8,g_)])]))}}),y_=Ae(b_,[["__scopeId","data-v-336c322c"]]),w_={class:"text-overlay-panel p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},k_={class:"mb-4"},__={class:"space-y-2 max-h-64 overflow-y-auto"},E_={class:"flex items-center justify-between"},S_={class:"flex-1"},C_={class:"font-medium text-gray-900 dark:text-white"},x_={class:"text-sm text-gray-500 dark:text-gray-400"},N_={class:"flex items-center space-x-2"},V_=["onClick"],T_=["onClick"],B_={key:0,class:"text-center py-8 text-gray-500 dark:text-gray-400"},M_={class:"bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-lg mx-4"},I_={class:"text-lg font-semibold text-gray-900 dark:text-white mb-4"},$_={class:"space-y-4"},F_={class:"grid grid-cols-2 gap-4"},D_={class:"grid grid-cols-2 gap-4"},A_={key:0,class:"p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"},R_={class:"grid grid-cols-2 gap-3"},L_={class:"flex justify-end space-x-3 mt-6"},P_=e.defineComponent({__name:"TextOverlayPanel",props:{overlays:{}},emits:["add-overlay","update-overlay","remove-overlay"],setup(o,{emit:a}){const t=a,n=e.ref(!1),i=e.ref(null),r=()=>({id:"",text:"",fontSize:24,color:"#ffffff",position:"center",startTime:0,duration:5,animationType:"",animationDuration:1,animationEasing:"linear"}),l=e.reactive(r());function s(p){Object.assign(l,p),i.value=p}function d(){n.value=!1,i.value=null,Object.assign(l,r())}function c(){const p={text:l.text,fontSize:l.fontSize,color:l.color,position:l.position,startTime:l.startTime,duration:l.duration};if(l.animationType&&(p.animation={type:l.animationType},l.animationDuration!==void 0&&(p.animation.duration=l.animationDuration),l.animationEasing&&(p.animation.easing=l.animationEasing),p.animation))switch(l.animationType){case"rotate":p.animation.rotation={from:0,to:360};break;case"scale":p.animation.scale={from:.5,to:1};break;case"slide":p.animation.translate={fromX:-100,toX:0,fromY:0,toY:0};break}i.value?t("update-overlay",i.value.id,p):t("add-overlay",p),d()}function u(p){confirm("Are you sure you want to remove this text overlay?")&&t("remove-overlay",p)}function m(p){const f=Math.floor(p/60),h=Math.floor(p%60);return`${f}:${h.toString().padStart(2,"0")}`}return(p,f)=>(e.openBlock(),e.createElementBlock("div",w_,[e.createElementVNode("div",k_,[f[11]||(f[11]=e.createElementVNode("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white mb-2"}," Text Overlays ",-1)),e.createElementVNode("button",{onClick:f[0]||(f[0]=h=>n.value=!0),class:"w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"},[...f[10]||(f[10]=[e.createElementVNode("svg",{class:"w-5 h-5 inline-block mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 4v16m8-8H4"})],-1),e.createTextVNode(" Add Text Overlay ",-1)])])]),e.createElementVNode("div",__,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(p.overlays,h=>(e.openBlock(),e.createElementBlock("div",{key:h.id,class:"p-3 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"},[e.createElementVNode("div",E_,[e.createElementVNode("div",S_,[e.createElementVNode("div",C_,e.toDisplayString(h.text.substring(0,30))+e.toDisplayString(h.text.length>30?"...":""),1),e.createElementVNode("div",x_,e.toDisplayString(m(h.startTime??0))+" - "+e.toDisplayString(m((h.startTime||0)+(h.duration||5))),1)]),e.createElementVNode("div",N_,[e.createElementVNode("button",{onClick:v=>s(h),class:"p-1 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 rounded",title:"Edit"},[...f[12]||(f[12]=[e.createElementVNode("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})],-1)])],8,V_),e.createElementVNode("button",{onClick:v=>u(h.id),class:"p-1 text-red-600 hover:bg-red-50 dark:hover:bg-red-900 rounded",title:"Remove"},[...f[13]||(f[13]=[e.createElementVNode("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})],-1)])],8,T_)])])]))),128)),p.overlays.length===0?(e.openBlock(),e.createElementBlock("div",B_," No text overlays added yet ")):e.createCommentVNode("",!0)]),n.value||i.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",onClick:e.withModifiers(d,["self"])},[e.createElementVNode("div",M_,[e.createElementVNode("h4",I_,e.toDisplayString(i.value?"Edit":"Add")+" Text Overlay ",1),e.createElementVNode("div",$_,[e.createElementVNode("div",null,[f[14]||(f[14]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Text ",-1)),e.withDirectives(e.createElementVNode("textarea",{"onUpdate:modelValue":f[1]||(f[1]=h=>l.text=h),rows:"3",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white",placeholder:"Enter your text..."},null,512),[[e.vModelText,l.text]])]),e.createElementVNode("div",F_,[e.createElementVNode("div",null,[f[15]||(f[15]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Font Size ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":f[2]||(f[2]=h=>l.fontSize=h),type:"number",min:"10",max:"200",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,l.fontSize,void 0,{number:!0}]])]),e.createElementVNode("div",null,[f[16]||(f[16]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Color ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":f[3]||(f[3]=h=>l.color=h),type:"color",class:"w-full h-10 border border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer"},null,512),[[e.vModelText,l.color]])])]),e.createElementVNode("div",null,[f[18]||(f[18]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Position ",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":f[4]||(f[4]=h=>l.position=h),class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},[...f[17]||(f[17]=[e.createStaticVNode('<option value="center" data-v-f86e688c>Center</option><option value="top" data-v-f86e688c>Top</option><option value="bottom" data-v-f86e688c>Bottom</option><option value="left" data-v-f86e688c>Left</option><option value="right" data-v-f86e688c>Right</option>',5)])],512),[[e.vModelSelect,l.position]])]),e.createElementVNode("div",D_,[e.createElementVNode("div",null,[f[19]||(f[19]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Start Time (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":f[5]||(f[5]=h=>l.startTime=h),type:"number",min:"0",step:"0.1",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,l.startTime,void 0,{number:!0}]])]),e.createElementVNode("div",null,[f[20]||(f[20]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Duration (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":f[6]||(f[6]=h=>l.duration=h),type:"number",min:"0.1",step:"0.1",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,l.duration,void 0,{number:!0}]])])]),e.createElementVNode("div",null,[f[22]||(f[22]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Animation ",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":f[7]||(f[7]=h=>l.animationType=h),class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},[...f[21]||(f[21]=[e.createStaticVNode('<option value="" data-v-f86e688c>None</option><option value="fade-in" data-v-f86e688c>Fade In</option><option value="fade-out" data-v-f86e688c>Fade Out</option><option value="slide" data-v-f86e688c>Slide</option><option value="scale" data-v-f86e688c>Scale</option><option value="rotate" data-v-f86e688c>Rotate</option><option value="typewriter" data-v-f86e688c>Typewriter</option>',7)])],512),[[e.vModelSelect,l.animationType]])]),l.animationType?(e.openBlock(),e.createElementBlock("div",A_,[f[26]||(f[26]=e.createElementVNode("div",{class:"text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"}," Animation Settings ",-1)),e.createElementVNode("div",R_,[e.createElementVNode("div",null,[f[23]||(f[23]=e.createElementVNode("label",{class:"block text-xs text-gray-600 dark:text-gray-400 mb-1"}," Duration (s) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":f[8]||(f[8]=h=>l.animationDuration=h),type:"number",min:"0.1",step:"0.1",class:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded focus:ring-2 focus:ring-blue-500 dark:bg-gray-600 dark:text-white"},null,512),[[e.vModelText,l.animationDuration,void 0,{number:!0}]])]),e.createElementVNode("div",null,[f[25]||(f[25]=e.createElementVNode("label",{class:"block text-xs text-gray-600 dark:text-gray-400 mb-1"}," Easing ",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":f[9]||(f[9]=h=>l.animationEasing=h),class:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded focus:ring-2 focus:ring-blue-500 dark:bg-gray-600 dark:text-white"},[...f[24]||(f[24]=[e.createElementVNode("option",{value:"linear"},"Linear",-1),e.createElementVNode("option",{value:"easeIn"},"Ease In",-1),e.createElementVNode("option",{value:"easeOut"},"Ease Out",-1),e.createElementVNode("option",{value:"easeInOut"},"Ease In Out",-1)])],512),[[e.vModelSelect,l.animationEasing]])])])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",L_,[e.createElementVNode("button",{onClick:d,class:"px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"}," Cancel "),e.createElementVNode("button",{onClick:c,class:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"},e.toDisplayString(i.value?"Save":"Add"),1)])])])):e.createCommentVNode("",!0)]))}}),Gs=Ae(P_,[["__scopeId","data-v-f86e688c"]]),U_={class:"transition-selector p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},O_={class:"grid grid-cols-3 gap-3 max-h-96 overflow-y-auto"},z_=["onClick"],j_={class:"w-full h-16 bg-gradient-to-r from-gray-300 to-gray-400 dark:from-gray-600 dark:to-gray-700 rounded mb-2 flex items-center justify-center"},W_={key:0,class:"w-8 h-8 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},H_={key:0,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"},Z_={key:1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M14 5l7 7m0 0l-7 7m7-7H3"},G_={key:2,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4"},X_={key:3,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"},K_={key:4,"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 5a1 1 0 011-1h14a1 1 0 011 1v14a1 1 0 01-1 1H5a1 1 0 01-1-1V5z"},q_={class:"text-sm font-medium text-gray-900 dark:text-white text-center"},J_={key:0,class:"mt-4 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"},Y_={class:"space-y-3"},Q_={class:"flex items-center space-x-2"},e2=["disabled"],t2=["disabled"],a2={key:1,class:"mt-4"},n2={class:"space-y-2 max-h-32 overflow-y-auto"},o2={class:"text-sm text-gray-700 dark:text-gray-300"},i2=["onClick"],r2=e.defineComponent({__name:"TransitionSelector",props:{selectedClips:{},appliedTransitions:{}},emits:["apply-transition","remove-transition","preview-transition"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(qi.getAvailableTransitions()),r=e.ref(null),l=e.ref(.5),s=e.ref("linear"),d=e.computed(()=>r.value&&t.selectedClips&&t.selectedClips.length>=2);function c(h){r.value=h}function u(){if(!r.value||!d.value)return;const h={type:r.value.type,duration:l.value,easing:s.value};n("apply-transition",h),r.value=null}function m(){if(!r.value)return;const h={type:r.value.type,duration:l.value,easing:s.value};n("preview-transition",h)}function p(h){n("remove-transition",h)}function f(h){return["fade","wipe","slide","zoom"].some(v=>h.includes(v))}return(h,v)=>(e.openBlock(),e.createElementBlock("div",U_,[v[9]||(v[9]=e.createElementVNode("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white mb-4"}," Transitions ",-1)),e.createElementVNode("div",O_,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,y=>{var w;return e.openBlock(),e.createElementBlock("div",{key:y.type,onClick:_=>c(y),class:e.normalizeClass(["transition-item cursor-pointer rounded-lg p-3 border-2 transition-all",((w=r.value)==null?void 0:w.type)===y.type?"border-blue-500 bg-blue-50 dark:bg-blue-900":"border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600"])},[e.createElementVNode("div",j_,[f(y.type)?(e.openBlock(),e.createElementBlock("svg",W_,[y.type.includes("fade")?(e.openBlock(),e.createElementBlock("path",H_)):y.type.includes("wipe")?(e.openBlock(),e.createElementBlock("path",Z_)):y.type.includes("slide")?(e.openBlock(),e.createElementBlock("path",G_)):y.type.includes("zoom")?(e.openBlock(),e.createElementBlock("path",X_)):(e.openBlock(),e.createElementBlock("path",K_))])):e.createCommentVNode("",!0)]),e.createElementVNode("div",q_,e.toDisplayString(y.name),1)],10,z_)}),128))]),r.value?(e.openBlock(),e.createElementBlock("div",J_,[v[6]||(v[6]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 dark:text-gray-300 mb-3"}," Transition Settings ",-1)),e.createElementVNode("div",Y_,[e.createElementVNode("div",null,[v[3]||(v[3]=e.createElementVNode("label",{class:"block text-xs text-gray-600 dark:text-gray-400 mb-1"}," Duration (seconds) ",-1)),e.createElementVNode("div",Q_,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":v[0]||(v[0]=y=>l.value=y),type:"range",min:"0.1",max:"3",step:"0.1",class:"flex-1"},null,512),[[e.vModelText,l.value,void 0,{number:!0}]]),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":v[1]||(v[1]=y=>l.value=y),type:"number",min:"0.1",max:"3",step:"0.1",class:"w-16 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded focus:ring-2 focus:ring-blue-500 dark:bg-gray-600 dark:text-white"},null,512),[[e.vModelText,l.value,void 0,{number:!0}]])])]),e.createElementVNode("div",null,[v[5]||(v[5]=e.createElementVNode("label",{class:"block text-xs text-gray-600 dark:text-gray-400 mb-1"}," Easing ",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":v[2]||(v[2]=y=>s.value=y),class:"w-full px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded focus:ring-2 focus:ring-blue-500 dark:bg-gray-600 dark:text-white"},[...v[4]||(v[4]=[e.createElementVNode("option",{value:"linear"},"Linear",-1),e.createElementVNode("option",{value:"easeIn"},"Ease In",-1),e.createElementVNode("option",{value:"easeOut"},"Ease Out",-1),e.createElementVNode("option",{value:"easeInOut"},"Ease In Out",-1)])],512),[[e.vModelSelect,s.value]])]),e.createElementVNode("button",{onClick:u,disabled:!d.value,class:e.normalizeClass(["w-full px-3 py-2 rounded-lg font-medium transition-colors",d.value?"bg-blue-600 text-white hover:bg-blue-700":"bg-gray-300 dark:bg-gray-600 text-gray-500 dark:text-gray-400 cursor-not-allowed"])}," Apply Transition ",10,e2),e.createElementVNode("button",{onClick:m,disabled:!r.value,class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors"}," Preview ",8,t2)])])):e.createCommentVNode("",!0),h.appliedTransitions.length>0?(e.openBlock(),e.createElementBlock("div",a2,[v[8]||(v[8]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"}," Applied Transitions ",-1)),e.createElementVNode("div",n2,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(h.appliedTransitions,(y,w)=>(e.openBlock(),e.createElementBlock("div",{key:w,class:"flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-700 rounded"},[e.createElementVNode("div",o2,e.toDisplayString(y.name)+" ("+e.toDisplayString(y.duration)+"s) ",1),e.createElementVNode("button",{onClick:_=>p(w),class:"p-1 text-red-600 hover:bg-red-50 dark:hover:bg-red-900 rounded"},[...v[7]||(v[7]=[e.createElementVNode("svg",{class:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M6 18L18 6M6 6l12 12"})],-1)])],8,i2)]))),128))])])):e.createCommentVNode("",!0),v[10]||(v[10]=e.createElementVNode("div",{class:"mt-4 text-xs text-gray-500 dark:text-gray-400"},[e.createElementVNode("p",null,"Select clips in the timeline, then choose a transition to apply between them.")],-1))]))}}),Xs=Ae(r2,[["__scopeId","data-v-ffcc612d"]]),l2={class:"audio-track-manager p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg"},s2={class:"mb-4"},d2={class:"mb-4 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"},c2={class:"flex items-center justify-between mb-2"},u2={class:"text-sm text-gray-600 dark:text-gray-400"},m2={class:"flex items-center space-x-2"},p2={class:"space-y-3 max-h-64 overflow-y-auto"},f2={class:"flex items-center justify-between mb-2"},h2={class:"font-medium text-gray-900 dark:text-white"},v2={class:"flex items-center space-x-2"},g2=["onClick","title"],b2={key:0,class:"w-5 h-5",fill:"currentColor",viewBox:"0 0 20 20"},y2={key:1,class:"w-5 h-5",fill:"currentColor",viewBox:"0 0 20 20"},w2=["onClick"],k2=["onClick"],_2={class:"flex items-center space-x-2"},E2={class:"text-xs text-gray-500 dark:text-gray-400 w-10"},S2=["value","onInput","disabled"],C2={class:"mt-2 text-xs text-gray-500 dark:text-gray-400"},x2={key:0,class:"ml-2"},N2={key:1,class:"ml-2"},V2={key:0,class:"text-center py-8 text-gray-500 dark:text-gray-400"},T2={class:"bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-lg mx-4"},B2={class:"text-lg font-semibold text-gray-900 dark:text-white mb-4"},M2={class:"space-y-4"},I2={class:"space-y-2"},$2={class:"flex items-center"},F2={class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"},D2={class:"grid grid-cols-2 gap-4"},A2={class:"grid grid-cols-2 gap-4"},R2={class:"flex items-center"},L2={class:"flex justify-end space-x-3 mt-6"},P2=["disabled"],U2=e.defineComponent({__name:"AudioTrackManager",props:{audioLayers:{},masterVolume:{}},emits:["add-track","update-track","remove-track","update-volume","toggle-mute","update-master-volume"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.ref(null),l=e.ref(t.masterVolume),s=()=>({id:"",source:"",sourceUrl:"",name:"Background Music",volume:.7,startTime:0,fadeIn:0,fadeOut:0,loop:!1}),d=e.reactive(s()),c=e.computed(()=>d.sourceUrl||d.sourceFile);function u(b){const g=b.target;g.files&&g.files[0]&&(d.sourceFile=g.files[0],d.name=d.name||g.files[0].name.replace(/\.[^/.]+$/,""))}function m(b){Object.assign(d,b),r.value=b}function p(){i.value=!1,r.value=null,Object.assign(d,s())}function f(){if(!c.value)return;const b={source:d.sourceFile??d.sourceUrl??"",name:d.name,volume:d.volume,startTime:d.startTime,loop:d.loop};d.duration!==void 0&&(b.duration=d.duration),d.fadeIn>0&&(b.fadeIn=d.fadeIn),d.fadeOut>0&&(b.fadeOut=d.fadeOut),r.value?n("update-track",r.value.id,b):n("add-track",b),p()}function h(b){confirm("Are you sure you want to remove this audio track?")&&n("remove-track",b)}function v(b,g){const I=g.target,T=parseFloat(I.value);n("update-volume",b.id,T)}function y(b){n("toggle-mute",b.id,!b.muted)}function w(){n("update-master-volume",l.value)}function _(b){const g=Math.floor(b/60),I=Math.floor(b%60);return`${g}:${I.toString().padStart(2,"0")}`}return(b,g)=>(e.openBlock(),e.createElementBlock("div",l2,[e.createElementVNode("div",s2,[g[11]||(g[11]=e.createElementVNode("h3",{class:"text-lg font-semibold text-gray-900 dark:text-white mb-2"}," Audio Tracks ",-1)),e.createElementVNode("button",{onClick:g[0]||(g[0]=I=>i.value=!0),class:"w-full px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"},[...g[10]||(g[10]=[e.createElementVNode("svg",{class:"w-5 h-5 inline-block mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 4v16m8-8H4"})],-1),e.createTextVNode(" Add Audio Track ",-1)])])]),e.createElementVNode("div",d2,[e.createElementVNode("div",c2,[g[12]||(g[12]=e.createElementVNode("label",{class:"text-sm font-medium text-gray-700 dark:text-gray-300"}," Master Volume ",-1)),e.createElementVNode("span",u2,e.toDisplayString(Math.round(l.value*100))+"% ",1)]),e.createElementVNode("div",m2,[g[13]||(g[13]=e.createElementVNode("svg",{class:"w-4 h-4 text-gray-500",fill:"currentColor",viewBox:"0 0 20 20"},[e.createElementVNode("path",{"fill-rule":"evenodd",d:"M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM12.293 7.293a1 1 0 011.414 0L15 8.586l1.293-1.293a1 1 0 111.414 1.414L16.414 10l1.293 1.293a1 1 0 01-1.414 1.414L15 11.414l-1.293 1.293a1 1 0 01-1.414-1.414L13.586 10l-1.293-1.293a1 1 0 010-1.414z","clip-rule":"evenodd"})],-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[1]||(g[1]=I=>l.value=I),onInput:w,type:"range",min:"0",max:"1",step:"0.01",class:"flex-1"},null,544),[[e.vModelText,l.value,void 0,{number:!0}]]),g[14]||(g[14]=e.createElementVNode("svg",{class:"w-4 h-4 text-gray-500",fill:"currentColor",viewBox:"0 0 20 20"},[e.createElementVNode("path",{"fill-rule":"evenodd",d:"M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM14.657 2.929a1 1 0 011.414 0l3 3a1 1 0 010 1.414l-3 3a1 1 0 01-1.414-1.414L16.586 7l-1.929-1.929a1 1 0 010-1.414z","clip-rule":"evenodd"})],-1))])]),e.createElementVNode("div",p2,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.audioLayers,I=>(e.openBlock(),e.createElementBlock("div",{key:I.id,class:"p-3 border border-gray-200 dark:border-gray-700 rounded-lg"},[e.createElementVNode("div",f2,[e.createElementVNode("div",h2,e.toDisplayString(I.name),1),e.createElementVNode("div",v2,[e.createElementVNode("button",{onClick:T=>y(I),class:e.normalizeClass(["p-1 rounded",I.muted?"text-red-600 bg-red-50 dark:bg-red-900":"text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700"]),title:I.muted?"Unmute":"Mute"},[I.muted?(e.openBlock(),e.createElementBlock("svg",y2,[...g[16]||(g[16]=[e.createElementVNode("path",{"fill-rule":"evenodd",d:"M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM12.293 7.293a1 1 0 011.414 0L15 8.586l1.293-1.293a1 1 0 111.414 1.414L16.414 10l1.293 1.293a1 1 0 01-1.414 1.414L15 11.414l-1.293 1.293a1 1 0 01-1.414-1.414L13.586 10l-1.293-1.293a1 1 0 010-1.414z","clip-rule":"evenodd"},null,-1)])])):(e.openBlock(),e.createElementBlock("svg",b2,[...g[15]||(g[15]=[e.createElementVNode("path",{"fill-rule":"evenodd",d:"M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM14.657 2.929a1 1 0 011.414 0l3 3a1 1 0 010 1.414l-3 3a1 1 0 01-1.414-1.414L16.586 7l-1.929-1.929a1 1 0 010-1.414z","clip-rule":"evenodd"},null,-1)])]))],10,g2),e.createElementVNode("button",{onClick:T=>m(I),class:"p-1 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 rounded",title:"Settings"},[...g[17]||(g[17]=[e.createElementVNode("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})],-1)])],8,w2),e.createElementVNode("button",{onClick:T=>h(I.id),class:"p-1 text-red-600 hover:bg-red-50 dark:hover:bg-red-900 rounded",title:"Remove"},[...g[18]||(g[18]=[e.createElementVNode("svg",{class:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})],-1)])],8,k2)])]),e.createElementVNode("div",_2,[e.createElementVNode("span",E2,e.toDisplayString(Math.round((I.volume||1)*100))+"% ",1),e.createElementVNode("input",{value:I.volume||1,onInput:T=>v(I,T),type:"range",min:"0",max:"1",step:"0.01",class:"flex-1",disabled:I.muted},null,40,S2)]),e.createElementVNode("div",C2,[e.createTextVNode(e.toDisplayString(_(I.startTime||0))+" - "+e.toDisplayString(_((I.startTime||0)+(I.duration||0)))+" ",1),I.fadeIn?(e.openBlock(),e.createElementBlock("span",x2,"Fade In: "+e.toDisplayString(I.fadeIn)+"s",1)):e.createCommentVNode("",!0),I.fadeOut?(e.openBlock(),e.createElementBlock("span",N2,"Fade Out: "+e.toDisplayString(I.fadeOut)+"s",1)):e.createCommentVNode("",!0)])]))),128)),b.audioLayers.length===0?(e.openBlock(),e.createElementBlock("div",V2," No audio tracks added yet ")):e.createCommentVNode("",!0)]),i.value||r.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",onClick:e.withModifiers(p,["self"])},[e.createElementVNode("div",T2,[e.createElementVNode("h4",B2,e.toDisplayString(r.value?"Edit":"Add")+" Audio Track ",1),e.createElementVNode("div",M2,[e.createElementVNode("div",null,[g[20]||(g[20]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Audio Source ",-1)),e.createElementVNode("div",I2,[e.createElementVNode("input",{type:"file",accept:"audio/*",onChange:u,class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,32),e.createElementVNode("div",$2,[g[19]||(g[19]=e.createElementVNode("span",{class:"text-sm text-gray-500 dark:text-gray-400 mr-2"},"or URL:",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[2]||(g[2]=I=>d.sourceUrl=I),type:"url",placeholder:"https://example.com/audio.mp3",class:"flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.sourceUrl]])])])]),e.createElementVNode("div",null,[g[21]||(g[21]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Track Name ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[3]||(g[3]=I=>d.name=I),type:"text",placeholder:"Background Music",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.name]])]),e.createElementVNode("div",null,[e.createElementVNode("label",F2," Volume: "+e.toDisplayString(Math.round(d.volume*100))+"% ",1),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[4]||(g[4]=I=>d.volume=I),type:"range",min:"0",max:"1",step:"0.01",class:"w-full"},null,512),[[e.vModelText,d.volume,void 0,{number:!0}]])]),e.createElementVNode("div",D2,[e.createElementVNode("div",null,[g[22]||(g[22]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Start Time (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[5]||(g[5]=I=>d.startTime=I),type:"number",min:"0",step:"0.1",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.startTime,void 0,{number:!0}]])]),e.createElementVNode("div",null,[g[23]||(g[23]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Duration (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[6]||(g[6]=I=>d.duration=I),type:"number",min:"0.1",step:"0.1",placeholder:"Auto",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.duration,void 0,{number:!0}]])])]),e.createElementVNode("div",A2,[e.createElementVNode("div",null,[g[24]||(g[24]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Fade In (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[7]||(g[7]=I=>d.fadeIn=I),type:"number",min:"0",max:"10",step:"0.1",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.fadeIn,void 0,{number:!0}]])]),e.createElementVNode("div",null,[g[25]||(g[25]=e.createElementVNode("label",{class:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"}," Fade Out (seconds) ",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[8]||(g[8]=I=>d.fadeOut=I),type:"number",min:"0",max:"10",step:"0.1",class:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"},null,512),[[e.vModelText,d.fadeOut,void 0,{number:!0}]])])]),e.createElementVNode("div",R2,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":g[9]||(g[9]=I=>d.loop=I),type:"checkbox",id:"loop-checkbox",class:"mr-2 rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"},null,512),[[e.vModelCheckbox,d.loop]]),g[26]||(g[26]=e.createElementVNode("label",{for:"loop-checkbox",class:"text-sm text-gray-700 dark:text-gray-300"}," Loop audio track ",-1))])]),e.createElementVNode("div",L2,[e.createElementVNode("button",{onClick:p,class:"px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"}," Cancel "),e.createElementVNode("button",{onClick:f,disabled:!c.value,class:e.normalizeClass(["px-4 py-2 rounded-lg transition-colors",c.value?"bg-green-600 text-white hover:bg-green-700":"bg-gray-300 dark:bg-gray-600 text-gray-500 dark:text-gray-400 cursor-not-allowed"])},e.toDisplayString(r.value?"Save":"Add"),11,P2)])])])):e.createCommentVNode("",!0)]))}}),Ks=Ae(U2,[["__scopeId","data-v-593719ac"]]);function xt(o,a={},...t){const n=document.createElement(o);for(const[i,r]of Object.entries(a))r!=null&&(i==="className"?n.className=r:i==="style"&&typeof r=="object"?Object.assign(n.style,r):i.startsWith("on")&&typeof r=="function"?n.addEventListener(i.slice(2).toLowerCase(),r):i==="dataset"&&typeof r=="object"?Object.assign(n.dataset,r):n.setAttribute(i,r));for(const i of t)typeof i=="string"?n.appendChild(document.createTextNode(i)):i instanceof HTMLElement&&n.appendChild(i);return n}function qc(o){return typeof o=="boolean"?o?"On":"Off":typeof o=="number"?Number.isInteger(o)?String(o):o.toFixed(2):String(o??"")}let Jc=!1;function O2(){if(Jc)return;Jc=!0;const o=`
34
+ /* ── MobileVideoFilterPanel — global (not scoped) ── */
35
+ .mvfp {
36
+ display: flex;
37
+ flex-direction: column;
38
+ width: 100%;
39
+ position: relative;
40
+ background: var(--app-surface, var(--ion-background-color, #1a1a1a));
41
+ }
42
+
43
+ /* ── Horizontal scroll rows ── */
44
+ .mvfp-row {
45
+ display: flex;
46
+ gap: 8px;
47
+ padding: 8px 12px;
48
+ overflow-x: auto;
49
+ -webkit-overflow-scrolling: touch;
50
+ scrollbar-width: none;
51
+ flex-shrink: 0;
52
+ }
53
+ .mvfp-row::-webkit-scrollbar { display: none; }
54
+
55
+ /* ── Category chips ── */
56
+ .mvfp-cat {
57
+ display: flex;
58
+ align-items: center;
59
+ gap: 6px;
60
+ min-height: 36px;
61
+ padding: 8px 14px;
62
+ border-radius: 20px;
63
+ border: 1.5px solid var(--app-border, var(--ion-color-step-300, #444));
64
+ background: var(--app-surface-variant, var(--ion-color-step-50, #222));
65
+ color: var(--app-text, var(--ion-text-color, #eee));
66
+ font-size: 13px;
67
+ font-weight: 500;
68
+ white-space: nowrap;
69
+ cursor: pointer;
70
+ flex-shrink: 0;
71
+ transition: all 0.15s;
72
+ -webkit-tap-highlight-color: transparent;
73
+ }
74
+ .mvfp-cat.active {
75
+ background: var(--app-accent, var(--ion-color-primary, #3880ff));
76
+ border-color: var(--app-accent, var(--ion-color-primary, #3880ff));
77
+ color: #fff;
78
+ }
79
+
80
+ /* ── Filter cards ── */
81
+ .mvfp-filter {
82
+ display: flex;
83
+ flex-direction: column;
84
+ align-items: center;
85
+ justify-content: center;
86
+ min-width: 72px;
87
+ max-width: 100px;
88
+ min-height: 48px;
89
+ padding: 10px 12px;
90
+ border-radius: 12px;
91
+ border: 2px solid var(--app-border, var(--ion-color-step-300, #444));
92
+ background: var(--app-surface-variant, var(--ion-color-step-50, #222));
93
+ color: var(--app-text, var(--ion-text-color, #eee));
94
+ font-size: 12px;
95
+ text-align: center;
96
+ line-height: 1.3;
97
+ cursor: pointer;
98
+ flex-shrink: 0;
99
+ position: relative;
100
+ transition: all 0.15s;
101
+ -webkit-tap-highlight-color: transparent;
102
+ }
103
+ .mvfp-filter.active {
104
+ border-color: var(--app-success, var(--ion-color-success, #2dd36f));
105
+ }
106
+ .mvfp-filter.selected {
107
+ background: rgba(var(--ion-color-primary-rgb, 56, 128, 255), 0.15);
108
+ border-color: var(--app-accent, var(--ion-color-primary, #3880ff));
109
+ }
110
+ .mvfp-filter .mvfp-check {
111
+ position: absolute;
112
+ top: -5px;
113
+ right: -5px;
114
+ width: 18px;
115
+ height: 18px;
116
+ border-radius: 50%;
117
+ background: var(--app-success, var(--ion-color-success, #2dd36f));
118
+ color: #fff;
119
+ display: flex;
120
+ align-items: center;
121
+ justify-content: center;
122
+ font-size: 11px;
123
+ cursor: pointer;
124
+ }
125
+
126
+ /* ── Active filter chips ── */
127
+ .mvfp-active-row {
128
+ display: flex;
129
+ gap: 6px;
130
+ padding: 6px 12px;
131
+ overflow-x: auto;
132
+ -webkit-overflow-scrolling: touch;
133
+ scrollbar-width: none;
134
+ flex-shrink: 0;
135
+ }
136
+ .mvfp-active-row::-webkit-scrollbar { display: none; }
137
+
138
+ .mvfp-achip {
139
+ display: flex;
140
+ align-items: center;
141
+ gap: 6px;
142
+ padding: 6px 10px 6px 12px;
143
+ background: rgba(var(--ion-color-primary-rgb, 56, 128, 255), 0.12);
144
+ border: 1px solid var(--app-accent, var(--ion-color-primary, #3880ff));
145
+ border-radius: 20px;
146
+ white-space: nowrap;
147
+ flex-shrink: 0;
148
+ font-size: 12px;
149
+ color: var(--app-text, var(--ion-text-color, #eee));
150
+ cursor: pointer;
151
+ transition: all 0.15s;
152
+ }
153
+ .mvfp-achip.selected {
154
+ background: var(--app-accent, var(--ion-color-primary, #3880ff));
155
+ color: #fff;
156
+ }
157
+ .mvfp-achip-x {
158
+ width: 20px;
159
+ height: 20px;
160
+ border-radius: 50%;
161
+ border: 1.5px solid currentColor;
162
+ background: transparent;
163
+ color: inherit;
164
+ display: flex;
165
+ align-items: center;
166
+ justify-content: center;
167
+ cursor: pointer;
168
+ padding: 0;
169
+ opacity: 0.7;
170
+ flex-shrink: 0;
171
+ }
172
+ .mvfp-achip-x:hover, .mvfp-achip-x:active {
173
+ background: var(--ion-color-danger, #ef4444);
174
+ border-color: var(--ion-color-danger, #ef4444);
175
+ color: #fff;
176
+ opacity: 1;
177
+ }
178
+
179
+ .mvfp-placeholder {
180
+ font-size: 12px;
181
+ color: var(--app-text-secondary, var(--ion-color-medium, #888));
182
+ padding: 6px 12px;
183
+ }
184
+
185
+ /* ── Drawer ── */
186
+ .mvfp-drawer {
187
+ position: absolute;
188
+ bottom: 0;
189
+ left: 0;
190
+ right: 0;
191
+ background: var(--app-surface, var(--ion-background-color, #1a1a1a));
192
+ border-top: 1px solid var(--app-border, var(--ion-color-step-300, #444));
193
+ transform: translateY(100%);
194
+ z-index: 20;
195
+ display: flex;
196
+ flex-direction: column;
197
+ overflow: hidden;
198
+ border-radius: 14px 14px 0 0;
199
+ }
200
+ .mvfp-drawer-hdr {
201
+ display: flex;
202
+ justify-content: space-between;
203
+ align-items: center;
204
+ padding: 8px 14px;
205
+ border-bottom: 1px solid var(--app-border, var(--ion-color-step-200, #333));
206
+ flex-shrink: 0;
207
+ }
208
+ .mvfp-drawer-title {
209
+ font-weight: 600;
210
+ font-size: 14px;
211
+ color: var(--app-text, var(--ion-text-color, #eee));
212
+ }
213
+ .mvfp-drawer-actions {
214
+ display: flex;
215
+ align-items: center;
216
+ gap: 10px;
217
+ }
218
+ .mvfp-drawer-btn {
219
+ background: none;
220
+ border: none;
221
+ font-size: 13px;
222
+ font-weight: 500;
223
+ cursor: pointer;
224
+ padding: 4px 6px;
225
+ color: var(--app-accent, var(--ion-color-primary, #3880ff));
226
+ }
227
+ .mvfp-drawer-btn.danger {
228
+ color: var(--ion-color-danger, #ef4444);
229
+ }
230
+ .mvfp-drawer-close {
231
+ width: 28px;
232
+ height: 28px;
233
+ border: none;
234
+ border-radius: 50%;
235
+ background: var(--app-surface-sunken, var(--ion-color-step-100, #2a2a2a));
236
+ color: var(--app-text-secondary, var(--ion-color-medium, #888));
237
+ display: flex;
238
+ align-items: center;
239
+ justify-content: center;
240
+ cursor: pointer;
241
+ padding: 0;
242
+ }
243
+ .mvfp-drawer-body {
244
+ flex: 1 1 auto;
245
+ overflow-y: auto;
246
+ -webkit-overflow-scrolling: touch;
247
+ padding: 10px 14px 16px;
248
+ }
249
+
250
+ /* ── Drawer slider controls ── */
251
+ .mvfp-ctl {
252
+ margin-bottom: 12px;
253
+ }
254
+ .mvfp-ctl-label {
255
+ display: block;
256
+ font-size: 11px;
257
+ font-weight: 600;
258
+ color: var(--app-text-secondary, var(--ion-color-medium, #888));
259
+ text-transform: uppercase;
260
+ letter-spacing: 0.5px;
261
+ margin-bottom: 4px;
262
+ }
263
+ .mvfp-slider-row {
264
+ display: flex;
265
+ align-items: center;
266
+ gap: 10px;
267
+ }
268
+ .mvfp-range {
269
+ flex: 1;
270
+ height: 6px;
271
+ -webkit-appearance: none;
272
+ appearance: none;
273
+ background: var(--app-border, var(--ion-color-step-200, #333));
274
+ border-radius: 3px;
275
+ outline: none;
276
+ }
277
+ .mvfp-range::-webkit-slider-thumb {
278
+ -webkit-appearance: none;
279
+ width: 22px;
280
+ height: 22px;
281
+ border-radius: 50%;
282
+ background: var(--app-accent, var(--ion-color-primary, #3880ff));
283
+ cursor: pointer;
284
+ border: 2px solid #fff;
285
+ box-shadow: 0 1px 4px rgba(0,0,0,0.3);
286
+ }
287
+ .mvfp-range-val {
288
+ min-width: 3rem;
289
+ text-align: right;
290
+ font-size: 12px;
291
+ font-weight: 500;
292
+ color: var(--app-text-secondary, var(--ion-color-medium, #888));
293
+ }
294
+ .mvfp-toggle-row {
295
+ display: flex;
296
+ align-items: center;
297
+ justify-content: space-between;
298
+ gap: 10px;
299
+ }
300
+ .mvfp-color-row {
301
+ display: flex;
302
+ align-items: center;
303
+ justify-content: space-between;
304
+ gap: 10px;
305
+ }
306
+ .mvfp-color-input {
307
+ width: 36px;
308
+ height: 36px;
309
+ border: 1px solid var(--app-border, var(--ion-color-step-300, #444));
310
+ border-radius: 8px;
311
+ padding: 2px;
312
+ cursor: pointer;
313
+ background: transparent;
314
+ }
315
+ .mvfp-select-row {
316
+ display: flex;
317
+ align-items: center;
318
+ justify-content: space-between;
319
+ gap: 10px;
320
+ }
321
+ .mvfp-select {
322
+ padding: 6px 10px;
323
+ border: 1px solid var(--app-border, var(--ion-color-step-300, #444));
324
+ border-radius: 8px;
325
+ background: var(--app-surface, var(--ion-background-color, #1a1a1a));
326
+ color: var(--app-text, var(--ion-text-color, #eee));
327
+ font-size: 13px;
328
+ }
329
+ .mvfp-no-params {
330
+ text-align: center;
331
+ color: var(--app-text-secondary, var(--ion-color-medium, #888));
332
+ font-style: italic;
333
+ font-size: 13px;
334
+ padding: 12px 0;
335
+ }
336
+ `,a=document.createElement("style");a.textContent=o,document.head.appendChild(a)}class z2{constructor({filters:a=[],callbacks:t={}}){O2(),this._filters=a,this._cb=t,this._selectedCategory="all",this._selectedFilterId=null,this._activeFilters=new Map,this._drawerOpen=!1,this._drawerFilterId=null,this._root=null,this._catRow=null,this._filterRow=null,this._activeRow=null,this._drawer=null,this._drawerTitle=null,this._drawerBody=null}mount(a){return this._root=xt("div",{className:"mvfp"}),this._catRow=xt("div",{className:"mvfp-row"}),this._root.appendChild(this._catRow),this._filterRow=xt("div",{className:"mvfp-row"}),this._root.appendChild(this._filterRow),this._activeRow=xt("div",{className:"mvfp-active-row"}),this._root.appendChild(this._activeRow),this._buildDrawer(),this._root.appendChild(this._drawer),this._renderCategories(),this._renderFilters(),this._renderActiveChips(),a.appendChild(this._root),this._root}setFilters(a){this._filters=a,this._renderCategories(),this._renderFilters()}setActiveFilters(a){this._activeFilters.clear(),a&&a.forEach((t,n)=>{this._activeFilters.set(n,t)}),this._renderFilters(),this._renderActiveChips(),this._drawerOpen&&this._drawerFilterId&&!this._activeFilters.has(this._drawerFilterId)&&this.closeDrawer()}destroy(){var a;this.closeDrawer(),(a=this._root)==null||a.remove(),this._root=null}_getCategories(){const a=new Map;a.set("all","All");for(const t of this._filters){const n=t.category||"other";a.has(n)||a.set(n,n.charAt(0).toUpperCase()+n.slice(1))}return a}_renderCategories(){this._catRow.innerHTML="",this._getCategories().forEach((t,n)=>{const i=xt("div",{className:`mvfp-cat${this._selectedCategory===n?" active":""}`,onClick:()=>{this._selectedCategory=n,this._renderCategories(),this._renderFilters()}},t);this._catRow.appendChild(i)})}_currentFilters(){return this._selectedCategory==="all"?this._filters:this._filters.filter(a=>(a.category||"other")===this._selectedCategory)}_renderFilters(){this._filterRow.innerHTML="";for(const a of this._currentFilters()){const t=this._activeFilters.has(a.id),n=this._selectedFilterId===a.id,i=xt("div",{className:`mvfp-filter${t?" active":""}${n?" selected":""}`,onClick:()=>this._selectFilter(a)});if(t){const r=xt("div",{className:"mvfp-check",onClick:l=>{l.stopPropagation(),this._removeFilter(a.id)}});r.innerHTML="✓",i.appendChild(r)}i.appendChild(xt("span",{},a.name)),this._filterRow.appendChild(i)}}_selectFilter(a){var t,n,i,r;this._selectedFilterId=a.id,this._activeFilters.has(a.id)||(n=(t=this._cb).onApplyFilter)==null||n.call(t,a),(r=(i=this._cb).onPreviewFilter)==null||r.call(i,a),this._renderFilters(),a.params&&a.params.length>0&&this.openDrawer(a.id)}_removeFilter(a){var t,n;(n=(t=this._cb).onRemoveFilter)==null||n.call(t,a),this._selectedFilterId===a&&(this._selectedFilterId=null)}_renderActiveChips(){if(this._activeRow.innerHTML="",this._activeFilters.size===0){this._activeRow.appendChild(xt("div",{className:"mvfp-placeholder"},"No active filters"));return}this._activeFilters.forEach((a,t)=>{const n=this._filters.find(d=>d.id===t);if(!n)return;const i=this._drawerOpen&&this._drawerFilterId===t,r=xt("div",{className:`mvfp-achip${i?" selected":""}`}),l=xt("span",{style:{cursor:"pointer"},onClick:()=>{this._selectedFilterId=t,this._renderFilters(),n.params&&n.params.length>0&&this.openDrawer(t)}},n.name),s=xt("button",{className:"mvfp-achip-x","aria-label":`Remove ${n.name}`,onClick:d=>{d.stopPropagation(),this._removeFilter(t)}});s.innerHTML='<svg width="10" height="10" viewBox="0 0 12 12"><path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',r.appendChild(l),r.appendChild(s),this._activeRow.appendChild(r)})}_buildDrawer(){this._drawer=xt("div",{className:"mvfp-drawer"});const a=xt("div",{className:"mvfp-drawer-hdr"});this._drawerTitle=xt("span",{className:"mvfp-drawer-title"},"Filter");const t=xt("div",{className:"mvfp-drawer-actions"});t.appendChild(xt("button",{className:"mvfp-drawer-btn",onClick:()=>this._resetDrawerFilter()},"Reset")),t.appendChild(xt("button",{className:"mvfp-drawer-btn danger",onClick:()=>{this._drawerFilterId&&(this._removeFilter(this._drawerFilterId),this.closeDrawer())}},"Remove"));const n=xt("button",{className:"mvfp-drawer-close","aria-label":"Close",onClick:()=>this.closeDrawer()});n.innerHTML='<svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 3l8 8M11 3l-8 8" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',t.appendChild(n),a.appendChild(this._drawerTitle),a.appendChild(t),this._drawer.appendChild(a),this._drawerBody=xt("div",{className:"mvfp-drawer-body"}),this._drawer.appendChild(this._drawerBody)}openDrawer(a){const t=this._filters.find(n=>n.id===a);if(t&&(this._drawerFilterId=a,this._drawerTitle.textContent=t.name,this._renderDrawerControls(t),this._renderActiveChips(),!this._drawerOpen)){this._drawerOpen=!0;const n=this._root.offsetHeight;n>0&&(this._drawer.style.height=n+"px"),this._drawer.style.transition="none",this._drawer.style.transform="translateY(100%)",this._drawer.offsetHeight,this._drawer.style.transition="transform 0.25s cubic-bezier(0.33, 1, 0.68, 1)",this._drawer.style.transform="translateY(0)"}}closeDrawer(){this._drawerOpen&&(this._drawerOpen=!1,this._drawerFilterId=null,this._drawer.style.transition="transform 0.2s cubic-bezier(0.32, 0, 0.67, 0)",this._drawer.style.transform="translateY(100%)",this._renderActiveChips())}_renderDrawerControls(a){if(this._drawerBody.innerHTML="",!a.params||a.params.length===0){this._drawerBody.appendChild(xt("div",{className:"mvfp-no-params"},"No adjustable parameters"));return}const t=this._activeFilters.get(a.id),n=(t==null?void 0:t.params)||{};for(const i of a.params){const r=n[i.id]??i.default,l=xt("div",{className:"mvfp-ctl"}),s=xt("label",{className:"mvfp-ctl-label"},i.label||i.id);l.appendChild(s);const d=i.type||"slider";if(d==="slider"||d==="range"){const c=xt("div",{className:"mvfp-slider-row"}),u=xt("span",{className:"mvfp-range-val"},qc(r)),m=xt("input",{type:"range",className:"mvfp-range",min:String(i.min??0),max:String(i.max??1),step:String(i.step??.01),value:String(typeof r=="number"?r:i.default??0),onInput:p=>{var h,v;const f=parseFloat(p.target.value);u.textContent=qc(f),(v=(h=this._cb).onUpdateParam)==null||v.call(h,a.id,i.id,f)}});c.appendChild(m),c.appendChild(u),l.appendChild(c)}else if(d==="toggle"||d==="checkbox"){const c=xt("div",{className:"mvfp-toggle-row"}),u=xt("input",{type:"checkbox",checked:r?"checked":void 0,onChange:m=>{var p,f;return(f=(p=this._cb).onUpdateParam)==null?void 0:f.call(p,a.id,i.id,m.target.checked)}});c.appendChild(u),l.appendChild(c)}else if(d==="color"){const c=xt("div",{className:"mvfp-color-row"}),u=xt("input",{type:"color",className:"mvfp-color-input",value:typeof r=="string"?r:"#000000",onInput:m=>{var p,f;return(f=(p=this._cb).onUpdateParam)==null?void 0:f.call(p,a.id,i.id,m.target.value)}});c.appendChild(u),l.appendChild(c)}else if(d==="select"||d==="dropdown"){const c=xt("div",{className:"mvfp-select-row"}),u=xt("select",{className:"mvfp-select",onChange:m=>{var p,f;return(f=(p=this._cb).onUpdateParam)==null?void 0:f.call(p,a.id,i.id,m.target.value)}});for(const m of i.options||[]){const p=xt("option",{value:m.value},m.label||String(m.value));m.value===r&&(p.selected=!0),u.appendChild(p)}c.appendChild(u),l.appendChild(c)}this._drawerBody.appendChild(l)}}_resetDrawerFilter(){var t,n;if(!this._drawerFilterId)return;const a=this._filters.find(i=>i.id===this._drawerFilterId);if(a!=null&&a.params){for(const i of a.params)(n=(t=this._cb).onUpdateParam)==null||n.call(t,this._drawerFilterId,i.id,i.default);this._renderDrawerControls(a)}}}const j2=[200,500,1e3];function W2(o){return{"360p":[640,360],"480p":[854,480],"720p":[1280,720],"1080p":[1920,1080],"1440p":[2560,1440],"2160p":[3840,2160]}[o??""]??[1920,1080]}function Yc(o){if(!o)return null;const a=o.duration;if(typeof a=="number"&&Number.isFinite(a)&&a>0)return a;if(a&&typeof a=="object"&&"value"in a){const t=a.value;if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t}return null}function H2(o){return new Promise(a=>{window.setTimeout(a,o)})}async function Qc(){return await Promise.resolve().then(()=>require("./PixiFrameExporter-R6iQjzVw.cjs"))}function eu(o,a=0){var r;const t=o.timeline[0],n=t?Math.max(0,t.sourceIn):0,i=(t==null?void 0:t.sourceOut)??((r=o.source)==null?void 0:r.duration)??a;return Math.max(0,i-n)}function lp(o){let a=null;return{canExportClientSide:async()=>{try{const{isWebCodecsSupported:i}=await Qc();return i()}catch{return!1}},renderRecipeWithPixi:async(i,r,l)=>{var f,h,v,y;const s=i.timeline[0],d=s?Math.max(0,s.sourceIn):0,c=s?s.sourceOut:void 0,[u,m]=W2((r==null?void 0:r.quality)??((f=i.output)==null?void 0:f.quality)),p=((h=i.output)==null?void 0:h.fps)||30;o.setPlaying(!1),o.forcePixiPreview.value=!0,await e.nextTick();try{let w=!1;for(const D of j2){await H2(D);const j=o.getPreviewRef();if(!(!j||typeof j.captureFrameAt!="function")){if(typeof j.ensureReadyForCapture=="function"){if(w=await j.ensureReadyForCapture(),w)break;continue}w=!0;break}}const _=o.getPreviewRef();if(!_||typeof _.captureFrameAt!="function")throw new Error("PIXI preview not available for export. Ensure the preview is mounted.");if(!w)throw new Error("PIXI preview not ready for frame capture after retries. The video may still be loading.");const{exportWithPixiFrames:b,isWebCodecsSupported:g}=await Qc();if(!g())throw new Error("WebCodecs is not supported in this browser. Export requires Chrome 94+ or equivalent.");a=new AbortController;const I={width:u,height:m,fps:p,trimStart:d,signal:a.signal};c!==void 0&&(I.trimEnd=c),l&&(I.onProgress=l);const T=o.getSourceUrl();T!==""&&(I.sourceUrl=T);const $=Yc(_)??((v=i.source)==null?void 0:v.duration)??c??0,N=await b({captureFrameAt:D=>{var j;return((j=_.captureFrameAt)==null?void 0:j.call(_,D))??Promise.resolve(null)},duration:{value:$}},I),B=new File([N],`edited-video-${Date.now()}.mp4`,{type:"video/mp4"}),P=Yc(_),x=((y=i.source)==null?void 0:y.duration)??0,E=Math.max(0,(c??P??x)-d);return{file:B,recipe:i,meta:{duration:E,width:u,height:m,format:"mp4",sizeBytes:B.size,size_bytes:B.size}}}finally{o.forcePixiPreview.value=!1,a=null}},cancelClientExport:()=>{a==null||a.abort(),a=null},resetClientExport:()=>{a=null}}}const li="default-video-track",no="default-media-source";function sp(o){var r,l;const a=G2(o),t=X2(o),n=K2(o.timeline,((r=t[0])==null?void 0:r.id)??li,((l=a[0])==null?void 0:l.id)??no),i={version:o.version,source:{...o.source},mediaSources:a,tracks:q2(t,n),clips:n,markers:o.markers?o.markers.map(s=>({...s})):[],transitions:o.transitions?o.transitions.map(up):[],filters:o.filters.map(s=>({...s,params:{...s.params}})),audio:{...o.audio},output:{...o.output}};return typeof o.duration=="number"&&(i.duration=o.duration),o.snapSettings&&(i.snapSettings={...o.snapSettings}),o.textOverlays&&(i.textOverlays=[...o.textOverlays]),o.captionTracks&&(i.captionTracks=o.captionTracks.map(mp)),o.visualLayers&&(i.visualLayers=o.visualLayers.map(pp)),o.audioTracks&&(i.audioTracks=[...o.audioTracks]),o.posterFrame&&(i.posterFrame=o.posterFrame),o.metadata&&(i.metadata={...o.metadata}),i}function Z2(o){const a={version:"1.0",source:{...o.source},timeline:o.clips.map(t=>({...t})),mediaSources:o.mediaSources.map(dp),tracks:o.tracks.map(cp),markers:o.markers.map(t=>({...t})),transitions:o.transitions.map(up),filters:o.filters.map(t=>({...t,params:{...t.params}})),audio:{...o.audio},output:{...o.output}};return typeof o.duration=="number"&&(a.duration=o.duration),o.snapSettings&&(a.snapSettings={...o.snapSettings}),o.textOverlays&&(a.textOverlays=[...o.textOverlays]),o.captionTracks&&(a.captionTracks=o.captionTracks.map(mp)),o.visualLayers&&(a.visualLayers=o.visualLayers.map(pp)),o.audioTracks&&(a.audioTracks=[...o.audioTracks]),o.posterFrame&&(a.posterFrame=o.posterFrame),o.metadata&&(a.metadata={...o.metadata}),a}function G2(o){var t,n;if(o.mediaSources&&o.mediaSources.length>0)return o.mediaSources.map(dp);const a={id:((t=o.timeline.find(i=>i.sourceRefId))==null?void 0:t.sourceRefId)??no,type:"media",mediaUuid:o.source.media_uuid,duration:o.source.duration,width:o.source.original_width,height:o.source.original_height};return(n=o.metadata)!=null&&n.source_url&&(a.url=o.metadata.source_url),[a]}function X2(o){var a;return o.tracks&&o.tracks.length>0?o.tracks.map(cp):[{id:((a=o.timeline.find(t=>t.trackId))==null?void 0:a.trackId)??li,type:"video",name:"Video",order:0}]}function K2(o,a,t){return o.map(n=>{const i={...n,trackId:n.trackId??a,sourceRefId:n.sourceRefId??t};return n.filters&&(i.filters=n.filters.map(r=>({...r,params:{...r.params}}))),n.transform&&(i.transform={...n.transform}),n.keyframes&&(i.keyframes=n.keyframes.map(r=>({...r}))),i})}function q2(o,a){return o.map(t=>{const n=a.filter(i=>i.trackId===t.id).map(i=>i.id);return{...t,clipIds:n}})}function dp(o){const a={...o};return o.metadata&&(a.metadata={...o.metadata}),a}function cp(o){const a={...o};return o.clipIds&&(a.clipIds=[...o.clipIds]),a}function up(o){const a={...o};return o.params&&(a.params={...o.params}),a}function mp(o){return{...o,segments:o.segments.map(t=>{const n={...t};return t.words&&(n.words=t.words.map(i=>({...i}))),n})}}function pp(o){return{...o,transform:{...o.transform,position:{...o.transform.position},anchor:{...o.transform.anchor},scale:{...o.transform.scale}},keyframes:o.keyframes?o.keyframes.map(a=>({...a})):void 0}}const fp="video-project-draft-snapshot:v1",qs="mediables:video-project-drafts",J2=(o,a={})=>{var p,f;const t=Pn(a.now)??Date.now(),n=Pn(a.createdAt)??t,i=Pn(a.updatedAt)??t,r=dE(o),l={id:Ja(a.id)??pE(i),payloadKind:r,createdAt:new Date(n).toISOString(),updatedAt:new Date(i).toISOString(),deviceKind:a.deviceKind??"unknown"},s=Ja(a.projectId),d=Ja(a.sourceMediaUuid)??Ja(o.source.media_uuid),c=Js(a.durationSeconds)??cE(o),u=Ja(a.editorVersion)??Ja((p=o.metadata)==null?void 0:p.editor_version),m=Ja(a.title)??Ja((f=o.metadata)==null?void 0:f.title);return s!==null&&(l.projectId=s),d!==null&&(l.sourceMediaUuid=d),c!==null&&(l.durationSeconds=c),u!==null&&(l.editorVersion=u),m!==null&&(l.title=m),a.saveReason!==void 0&&(l.saveReason=a.saveReason),{schemaVersion:fp,metadata:l,payload:o}},hp=(o,a=qs)=>{const t=Ja(a)??qs,n=iu(o.metadata.projectId??"unsaved-project"),i=iu(o.metadata.id);return`${t}:${n}:${i}`},Y2=o=>JSON.stringify(o),Q2=o=>{if(typeof o!="string"||o.trim().length===0)return null;try{const a=JSON.parse(o);return rE(a)?a:null}catch{return null}},eE=o=>{const a=[];for(const t of o){const n=Ja(t.key),i=Q2(t.value);n===null||i===null||a.push({key:n,snapshot:i})}return ji(a)},tE=(o,a)=>{const t=mE(a.maxCount),n=Pn(a.now)??Date.now(),i=wp(a.maxAgeMs),r=[],l=[];let s=0;for(const d of ji(o)){if(!bp(d,a.projectId)){r.push(d);continue}if(yp(d.snapshot,n,i)||s>=t){l.push(d);continue}r.push(d),s+=1}return{retained:ji(r),removed:ji(l)}},aE=(o,a={})=>{const t={key:hp(o),snapshot:o};if(!bp(t,a.projectId))return!1;const n=Pn(a.now)??Date.now(),i=wp(a.maxAgeMs);if(yp(o,n,i))return!1;const r=a.savedAt===null?null:Pn(a.savedAt);return r===null?!0:al(o)>r},nE=(o,a={})=>ji(o).filter(t=>aE(t.snapshot,a)),oE=(o,a,t={})=>{const n=nE(o,t);if(a==="mobile"){const i=n[0]??null;return i===null?[]:[i]}return n},iE=async(o,a,t=hp(a))=>(await o.setItem(t,Y2(a)),{key:t,snapshot:a}),tu=async(o,a=qs)=>{const t=await o.listKeys(a),n=[];for(const i of t)n.push({key:i,value:await o.getItem(i)});return eE(n)},au=async(o,a)=>{for(const t of a)await o.removeItem(t.key)},rE=o=>!Un(o)||o.schemaVersion!==fp||!lE(o.metadata)?!1:o.metadata.payloadKind==="project"?vp(o.payload):sE(o.payload),lE=o=>Un(o)?Fd(o.id)&&hE(o.payloadKind)&&ou(o.createdAt)&&ou(o.updatedAt)&&vE(o.deviceKind)&&Er(o.projectId)&&Er(o.sourceMediaUuid)&&fE(o.durationSeconds)&&Er(o.editorVersion)&&Er(o.title)&&gE(o.saveReason):!1,sE=o=>Un(o)?o.version==="1.0"&&gp(o.source)&&Array.isArray(o.timeline)&&Array.isArray(o.filters)&&Un(o.audio)&&Un(o.output):!1,vp=o=>Un(o)?o.version==="1.0"&&gp(o.source)&&Array.isArray(o.mediaSources)&&Array.isArray(o.tracks)&&Array.isArray(o.clips)&&Array.isArray(o.markers)&&Array.isArray(o.filters)&&Un(o.audio)&&Un(o.output):!1,gp=o=>Un(o)?Fd(o.media_uuid)&&Wi(o.duration)&&Wi(o.original_width)&&Wi(o.original_height):!1,dE=o=>vp(o)?"project":"recipe",cE=o=>Js(o.duration)??Js(o.source.duration),bp=(o,a)=>{const t=Ja(a);return t===null?!0:o.snapshot.metadata.projectId===t},yp=(o,a,t)=>t===null?!1:a-al(o)>t,ji=o=>[...o].sort(uE),uE=(o,a)=>{const t=al(a.snapshot)-al(o.snapshot);if(t!==0)return t;const n=nu(a.snapshot)-nu(o.snapshot);return n!==0?n:o.snapshot.metadata.id.localeCompare(a.snapshot.metadata.id)},al=o=>Pn(o.metadata.updatedAt)??0,nu=o=>Pn(o.metadata.createdAt)??0,mE=o=>!Number.isFinite(o)||o<0?0:Math.floor(o),wp=o=>o===void 0||!Number.isFinite(o)||o<0?null:Math.floor(o),Pn=o=>{if(o==null)return null;if(o instanceof Date)return Number.isFinite(o.getTime())?o.getTime():null;if(typeof o=="number")return Number.isFinite(o)?o:null;const a=o.trim();if(a.length===0)return null;const t=Date.parse(a);return Number.isFinite(t)?t:null},ou=o=>typeof o=="string"&&Pn(o)!==null,pE=o=>{var t;const a=typeof((t=globalThis.crypto)==null?void 0:t.randomUUID)=="function"?globalThis.crypto.randomUUID():Math.random().toString(36).slice(2,12);return`draft-${o}-${a}`},iu=o=>encodeURIComponent(o.trim()),Ja=o=>{if(typeof o!="string")return null;const a=o.trim();return a.length>0?a:null},Fd=o=>Ja(o)!==null,Er=o=>o===void 0||Fd(o),Js=o=>{if(!Wi(o))return null;const a=Number(o.toFixed(6));return Object.is(a,-0)?0:a},Wi=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0,fE=o=>o===void 0||Wi(o),hE=o=>o==="recipe"||o==="project",vE=o=>o==="desktop"||o==="mobile"||o==="tablet"||o==="unknown",gE=o=>o===void 0||o==="autosave"||o==="manual"||o==="before-export"||o==="before-close",Un=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),bE=1,yE="master",Ji=-60,Ys=12,Dd=0,oo=-90,nl=6,wE=4,kp=8;function _p(){return{mobile:{canAdjustTrackFaders:!0,canAdjustMasterFader:!0,canMuteTracks:!0,canSoloTracks:!0,canAdjustPan:!1,canViewMeters:!0,canEditEffectSlots:!1,canEditRouting:!1,canEditAutomation:!1,meterMode:"basic",maxEffectSlots:0},desktop:{canAdjustTrackFaders:!0,canAdjustMasterFader:!0,canMuteTracks:!0,canSoloTracks:!0,canAdjustPan:!0,canViewMeters:!0,canEditEffectSlots:!0,canEditRouting:!0,canEditAutomation:!0,meterMode:"full",maxEffectSlots:kp}}}function kE(o,a=_p()){return ed(a[o])}function Ep(o){return Number.isNaN(o)?Dd:o<=0||o===Number.NEGATIVE_INFINITY?Ji:Yi(20*Math.log10(o))}function Qs(o){const a=Yi(o);return a<=Ji?0:ro(Math.pow(10,a/20),6)}function Yi(o){return Number.isNaN(o)?Dd:o===Number.NEGATIVE_INFINITY?Ji:o===Number.POSITIVE_INFINITY?Ys:ro(cr(o,Ji,Ys),3)}function Sp(o){return Number.isFinite(o)?ro(cr(o,-1,1),3):0}function _E(o,a=!1){const t=o.some(n=>n.controls.solo);return o.map(n=>{const i=n.controls.muted,r=t&&!n.controls.solo,l=a||i||r,s=l?0:n.controls.fader.linearGain;return{trackId:n.id,soloed:n.controls.solo,mutedByTrack:i,mutedBySolo:r,mutedByMaster:a,effectivelyMuted:l,audible:!l,effectiveGainLinear:s}})}function EE(o,a={}){const t=FE(a.effectSlotCount),n=new Set;return{schemaVersion:bE,capabilities:a.capabilities?LE(a.capabilities):_p(),tracks:o.map((i,r)=>CE(i,r,t,n)),master:xE(a.master,t)}}function Cp(o){const a=Yi(o);return{valueDb:a,minDb:Ji,maxDb:Ys,unityDb:Dd,linearGain:Qs(a)}}function SE(o,a="constant-power"){return{value:Sp(o),mode:a}}function xp(o=oo,a=oo,t=o){const n=ds(o),i=ds(a),r=ds(t);return{peakDb:n,rmsDb:i,peakHoldDb:r,clipping:n>=0||r>=0}}function Np(o){const a=Bp(o);return{id:`empty-effect-slot-${a}`,index:a,kind:"empty",label:"Empty",enabled:!1,bypassed:!0,wetMix:0,parameters:{}}}function CE(o,a,t,n){const i=Tp(o.id),l={id:$E(i??`legacy-audio-track-${a+1}`,n),kind:"legacy-url",name:BE(o.name,a),order:a,source:NE(o.source),controls:{fader:Cp(o.faderDb??Ep(o.volume??1)),pan:SE(o.pan??0),muted:o.muted??!1,solo:o.solo??!1,meter:xp(o.peakDb,o.rmsDb,o.peakHoldDb)},timeline:VE(o),effectSlots:Vp(o.effectSlots,t)};return i!==void 0&&(l.legacyTrackId=i),l}function xE(o,a){return{id:yE,name:ME(o==null?void 0:o.name),fader:Cp((o==null?void 0:o.faderDb)??Ep((o==null?void 0:o.volume)??1)),muted:(o==null?void 0:o.muted)??!1,meter:xp(o==null?void 0:o.peakDb,o==null?void 0:o.rmsDb,o==null?void 0:o.peakHoldDb),effectSlots:Vp(o==null?void 0:o.effectSlots,a)}}function NE(o){const a=o.trim();return a===""?{type:"missing"}:{type:"url",url:a}}function VE(o){const a={startTime:AE(o.startTime??0),loop:o.loop??!1},t=DE(o.duration);t!==void 0&&(a.duration=t);const n=ru(o.fadeIn);n!==void 0&&(a.fadeIn=n);const i=ru(o.fadeOut);return i!==void 0&&(a.fadeOut=i),a}function Vp(o,a){const t=new Map;for(const n of o??[]){const i=TE(n,a);t.set(i.index,i)}return Array.from({length:a},(n,i)=>t.get(i)??Np(i))}function TE(o,a){const t=Bp(o.index),n=a>0?Math.min(t,a-1):0,i=o.kind;return i==="empty"?Np(n):{id:Tp(o.id)??`${i}-effect-slot-${n}`,index:n,kind:i,label:IE(o.label,i),enabled:o.enabled,bypassed:o.bypassed,wetMix:RE(o.wetMix),parameters:{...o.parameters}}}function BE(o,a){const t=o==null?void 0:o.trim();return t&&t!==""?t:`Audio ${a+1}`}function ME(o){const a=o==null?void 0:o.trim();return a&&a!==""?a:"Master"}function IE(o,a){const t=o.trim();return t!==""?t:a}function $E(o,a){if(!a.has(o))return a.add(o),o;let t=2,n=`${o}-${t}`;for(;a.has(n);)t+=1,n=`${o}-${t}`;return a.add(n),n}function Tp(o){const a=o==null?void 0:o.trim();if(!(!a||a===""))return a}function FE(o){return o===void 0||!Number.isFinite(o)?wE:Math.trunc(cr(o,0,kp))}function Bp(o){return!Number.isFinite(o)||o<0?0:Math.trunc(o)}function DE(o){if(!(o===void 0||!Number.isFinite(o)||o<=0))return ro(o,3)}function ru(o){if(!(o===void 0||!Number.isFinite(o)||o<0))return ro(o,3)}function AE(o){return!Number.isFinite(o)||o<0?0:ro(o,3)}function RE(o){return Number.isFinite(o)?ro(cr(o,0,1),3):1}function ds(o){return Number.isNaN(o)||o===Number.NEGATIVE_INFINITY?oo:o===Number.POSITIVE_INFINITY?nl:ro(cr(o,oo,nl),3)}function LE(o){return{mobile:ed(o.mobile),desktop:ed(o.desktop)}}function ed(o){return{...o}}function cr(o,a,t){return Math.min(t,Math.max(a,o))}function ro(o,a){const t=10**a;return Math.round(o*t)/t}const PE=/^(\d{2,}:[0-5]\d:[0-5]\d,\d{3})\s+-->\s+(\d{2,}:[0-5]\d:[0-5]\d,\d{3})$/,UE=/^(\d{2,}):([0-5]\d):([0-5]\d),(\d{3})$/,OE="srt-cue";class io extends Error{constructor(a,t,n={}){super(t),this.name="CaptionSrtError",this.code=a,this.context=n}}function zE(o,a={}){var l,s;const t=jE(a.idPrefix),n=o.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
337
+ `).split(`
338
+ `),i=[];let r=0;for(;r<n.length;){for(;r<n.length&&uu(n[r]);)r+=1;if(r>=n.length)break;const d=r+1,c=WE(((l=n[r])==null?void 0:l.trim())??"",d);if(r+=1,r>=n.length)throw new io("missing-timing",`Cue ${c} is missing its timing line.`,{cueIndex:i.length,cueNumber:c,lineNumber:d});const u=r+1,m=HE(((s=n[r])==null?void 0:s.trim())??"",c,u);r+=1;const p=[];for(;r<n.length&&!uu(n[r]);)p.push(n[r]??""),r+=1;i.push({cueNumber:c,id:`${t}-${i.length+1}`,startTime:m.startTime,endTime:m.endTime,text:p.join(`
339
+ `)})}return Mp(i),i}function lu(o){return Mp(o),o.length===0?"":`${o.map((a,t)=>GE(a,t+1)).join(`
340
+
341
+ `)}
342
+ `}function Mp(o){const a=o.map((t,n)=>{const i=cu(t,n),r=td(t.startTime,"startTime",i),l=td(t.endTime,"endTime",i);if(l<=r)throw new io("invalid-duration",`Caption cue "${t.id}" must end after it starts.`,i);return{cue:t,cueIndex:n,startMilliseconds:r,endMilliseconds:l}}).sort((t,n)=>t.startMilliseconds-n.startMilliseconds||t.cueIndex-n.cueIndex);for(let t=1;t<a.length;t+=1){const n=a[t-1],i=a[t];if(!(n===void 0||i===void 0)&&i.startMilliseconds<n.endMilliseconds)throw new io("overlapping-cues",`Caption cue "${i.cue.id}" overlaps cue "${n.cue.id}".`,cu(i.cue,i.cueIndex))}}function su(o){const a=td(o,"timestamp",{}),t=Math.floor(a/36e5),n=Math.floor(a%36e5/6e4),i=Math.floor(a%6e4/1e3),r=a%1e3;return[t.toString().padStart(2,"0"),n.toString().padStart(2,"0"),i.toString().padStart(2,"0")].join(":")+`,${r.toString().padStart(3,"0")}`}function jE(o){return o===void 0||o.trim()===""?OE:o.trim()}function WE(o,a){if(!/^[1-9]\d*$/.test(o))throw new io("invalid-cue-number",`Invalid SRT cue number at line ${a}.`,{lineNumber:a});return Number.parseInt(o,10)}function HE(o,a,t){const n=PE.exec(o),i=n==null?void 0:n[1],r=n==null?void 0:n[2];if(i===void 0||r===void 0)throw new io("invalid-timing",`Invalid SRT timing line for cue ${a} at line ${t}.`,{cueNumber:a,lineNumber:t});return{startTime:du(i,a,t),endTime:du(r,a,t)}}function du(o,a,t){const n=UE.exec(o),i=n==null?void 0:n[1],r=n==null?void 0:n[2],l=n==null?void 0:n[3],s=n==null?void 0:n[4];if(i===void 0||r===void 0||l===void 0||s===void 0)throw new io("invalid-time",`Invalid SRT timestamp for cue ${a} at line ${t}.`,{cueNumber:a,lineNumber:t});const d=Number.parseInt(i,10),c=Number.parseInt(r,10),u=Number.parseInt(l,10),m=Number.parseInt(s,10);return d*60*60+c*60+u+m/1e3}function td(o,a,t){if(!Number.isFinite(o)||o<0)throw new io("invalid-time",`Caption cue ${a} must be a finite, non-negative number.`,t);return Math.round(o*1e3)}function cu(o,a){const t={cueIndex:a,segmentId:o.id},n=ZE(o);return n!==void 0&&(t.cueNumber=n),t}function ZE(o){if(!(!("cueNumber"in o)||typeof o.cueNumber!="number"))return o.cueNumber}function GE(o,a){return[a.toString(),`${su(o.startTime)} --> ${su(o.endTime)}`,XE(o.text)].join(`
343
+ `)}function XE(o){return o.replace(/\r\n?/g,`
344
+ `)}function uu(o){return o===void 0||o.trim()===""}const KE=["linear","ease-in","ease-out","ease-in-out"];class ol extends Error{constructor(a,t="Invalid keyframe automation."){super(t),this.name="KeyframeAutomationError",this.issues=a}}const qE={opacity:{min:0,max:1},scale:{min:0,max:10},x:{min:0,max:1},y:{min:0,max:1},rotation:{},audioVolume:{min:0,max:1}};function JE(o){return typeof o=="string"&&KE.includes(o)}function YE(o){return o==="mobile"?{platform:o,editingMode:"preset-only",canApplyPresets:!0,canEditKeyframes:!1}:{platform:o,editingMode:"detailed",canApplyPresets:!0,canEditKeyframes:!0}}function QE(o){return[...o].sort((a,t)=>a.target!==t.target?a.target.localeCompare(t.target):a.time!==t.time?a.time-t.time:a.id.localeCompare(t.id))}function Ip(o,a={}){const t=[],n=new Set,i={...qE,...a.ranges};return o.forEach((r,l)=>{if(r.id.trim()===""&&t.push({code:"empty-id",message:"Keyframe id cannot be empty.",index:l,target:r.target,time:r.time}),a.target!==void 0&&r.target!==a.target&&t.push({code:"target-mismatch",message:`Expected ${a.target} keyframe target but received ${r.target}.`,index:l,keyframeId:r.id,target:r.target,time:r.time}),!Number.isFinite(r.time)||r.time<(a.minTime??0))t.push({code:"invalid-time",message:"Keyframe time must be a finite non-negative number.",index:l,keyframeId:r.id,target:r.target,time:r.time});else if(a.maxTime!==void 0&&r.time>a.maxTime)t.push({code:"invalid-time",message:`Keyframe time must be less than or equal to ${a.maxTime}.`,index:l,keyframeId:r.id,target:r.target,time:r.time});else{const s=`${r.target}:${r.time}`;n.has(s)&&t.push({code:"duplicate-time",message:`Keyframe target ${r.target} already has a point at ${r.time}.`,index:l,keyframeId:r.id,target:r.target,time:r.time}),n.add(s)}if(!Number.isFinite(r.value))t.push({code:"invalid-value",message:"Keyframe value must be a finite number.",index:l,keyframeId:r.id,target:r.target,time:r.time});else{const s=i[r.target];s.min!==void 0&&r.value<s.min&&t.push({code:"invalid-value",message:`Keyframe value for ${r.target} must be greater than or equal to ${s.min}.`,index:l,keyframeId:r.id,target:r.target,time:r.time}),s.max!==void 0&&r.value>s.max&&t.push({code:"invalid-value",message:`Keyframe value for ${r.target} must be less than or equal to ${s.max}.`,index:l,keyframeId:r.id,target:r.target,time:r.time})}JE(r.easing)||t.push({code:"invalid-easing",message:`Unsupported keyframe easing "${String(r.easing)}".`,index:l,keyframeId:r.id,target:r.target,time:r.time})}),{valid:t.length===0,issues:t}}function eS(o,a={}){const t=QE(o),n=Ip(t,a);if(!n.valid)throw new ol(n.issues);return t}function tS(o={}){return Ad({id:"fade-in",label:"Fade in",target:"opacity",startValue:o.fromOpacity??0,endValue:o.toOpacity??1,timing:Rd(o,"ease-out")})}function aS(o={}){return Ad({id:"fade-out",label:"Fade out",target:"opacity",startValue:o.fromOpacity??1,endValue:o.toOpacity??0,timing:Rd(o,"ease-in")})}function nS(o={}){return Ad({id:"zoom-in",label:"Zoom in",target:"scale",startValue:o.fromScale??1,endValue:o.toScale??1.1,timing:Rd(o,"ease-out")})}function Ad(o){const a=[{id:`${o.id}:start`,target:o.target,time:o.timing.startTime,value:o.startValue,easing:"linear"},{id:`${o.id}:end`,target:o.target,time:o.timing.endTime,value:o.endValue,easing:o.timing.easing}],t=Ip(a,{target:o.target});if(!t.valid)throw new ol(t.issues);return{id:o.id,label:o.label,target:o.target,editingMode:"preset-only",keyframes:a}}function Rd(o,a){const t=o.startTime??0,n=o.duration??1;if(!Number.isFinite(t)||t<0)throw new ol([{code:"invalid-time",message:"Preset start time must be a finite non-negative number.",time:t}]);if(!Number.isFinite(n)||n<=0)throw new ol([{code:"invalid-time",message:"Preset duration must be a finite number greater than zero."}]);return{startTime:t,endTime:t+n,easing:o.easing??a}}class Do extends Error{constructor(a,t){super(t),this.name="VisualLayerSchemaError",this.code=a}}function oS(o){Pd(o.id,"caption track id");const a={id:o.id,source:o.source,stylePreset:o.stylePreset??"default",animation:o.animation??"none",segments:iS(o.segments)};return o.language!==void 0&&(a.language=o.language),a}function iS(o){const a=o.map(t=>{Pd(t.id,"caption segment id");const n=Ld(t.startTime,"caption segment startTime"),i=$p(t.endTime,"caption segment endTime");if(i<=n)throw new Do("invalid-caption-segment",`Caption segment "${t.id}" must end after it starts.`);const r={id:t.id,startTime:n,endTime:i,text:t.text};return t.words!==void 0&&(r.words=rS(t.id,t.words)),r}).sort((t,n)=>t.startTime-n.startTime);for(let t=1;t<a.length;t+=1){const n=a[t-1],i=a[t];if(!(n===void 0||i===void 0)&&i.startTime<n.endTime)throw new Do("invalid-caption-segment",`Caption segment "${i.id}" overlaps segment "${n.id}".`)}return a}function rS(o,a){return a.map(t=>{Pd(t.id,"caption word id");const n=Ld(t.startTime,"caption word startTime"),i=$p(t.endTime,"caption word endTime");if(i<=n)throw new Do("invalid-caption-segment",`Caption word "${t.id}" in segment "${o}" must end after it starts.`);return{id:t.id,startTime:n,endTime:i,text:t.text}}).sort((t,n)=>t.startTime-n.startTime)}function Ld(o,a){const t=lS(o,a);if(t<0)throw new Do("invalid-time",`${a} must be non-negative.`);return Math.round(t*1e3)/1e3}function $p(o,a){const t=Ld(o,a);if(t<=0)throw new Do("invalid-duration",`${a} must be greater than zero.`);return t}function lS(o,a){if(!sS(o))throw new Do("invalid-time",`${a} must be a finite number.`);return o}function Pd(o,a){if(o.trim()==="")throw new Do("empty-id",`${a} cannot be empty.`)}function sS(o){return Number.isFinite(o)}function mu(o){var m,p,f,h;dS(o);const a=mS(o),t=pS(o),n=((m=a[0])==null?void 0:m.id)??no,i=((p=t[0])==null?void 0:p.id)??li,r=cS(o.clips,i,n),l=fS(t,r),s=[],d=bS(o),c=yS(o),u={version:"1.0",source:{media_uuid:o.mediaUuid,duration:o.originalDuration,original_width:((f=o.media)==null?void 0:f.width)||1920,original_height:((h=o.media)==null?void 0:h.height)||1080},timeline:r,mediaSources:a,tracks:l,filters:s,audio:d,output:c,metadata:{created_at:new Date().toISOString(),editor_version:"2.0.0"}};return o.textOverlays&&(u.textOverlays=o.textOverlays),o.captionTracks&&(u.captionTracks=o.captionTracks.map(v=>({...v,segments:v.segments.map(y=>{const w={...y};return y.words&&(w.words=y.words.map(_=>({..._}))),w})}))),o.visualLayers&&(u.visualLayers=o.visualLayers.map(v=>({...v}))),o.audioTracks&&(u.audioTracks=o.audioTracks.filter(v=>typeof v.source=="string")),o.transitions&&(u.transitions=o.transitions.map(gS)),u}function dS(o){if(!o.mediaUuid)throw new Error("Media UUID is required");if(!o.clips||o.clips.length===0)throw new Error("At least one clip is required");const a=new Map;for(const t of o.clips){const n=uS(t),i=a.get(n)??[];i.push(t),a.set(n,i)}for(const t of a.values()){t.sort((n,i)=>n.timelineStart-i.timelineStart);for(let n=1;n<t.length;n++){const i=t[n],r=t[n-1];if(i.timelineStart<r.timelineEnd)throw new Error(`Clips ${r.id} and ${i.id} overlap on timeline`)}}}function cS(o,a,t){return o.map(n=>{const i=n.speed||1,r=typeof n.sourceIn=="number"&&!Number.isNaN(n.sourceIn),l=typeof n.sourceOut=="number"&&!Number.isNaN(n.sourceOut),s=Math.max(0,n.timelineEnd-n.timelineStart),d=n,c=d.sourceOffset??d.trimStart??0;let u=Number(r?n.sourceIn:c),m=l?Number(n.sourceOut):Number(c)+s/i;m>u||(m=u+Math.max(.033,s/Math.max(1e-6,i)));const p={id:n.id,type:n.type??"clip",trackId:n.trackId??a,sourceRefId:n.sourceRefId??t,timelineStart:n.timelineStart,timelineEnd:n.timelineEnd,sourceIn:u,sourceOut:m,speed:i,filters:n.filters?[...n.filters]:[]};return n.keyframes&&(p.keyframes=n.keyframes.map(f=>({...f}))),p})}function uS(o){return o.trackId??`legacy-track-${o.track??0}`}function mS(o){var t,n,i,r,l,s,d,c;if(o.mediaSources&&o.mediaSources.length>0)return o.mediaSources.map(hS);const a={id:((t=o.clips.find(u=>u.sourceRefId))==null?void 0:t.sourceRefId)??no,type:"media",mediaUuid:o.mediaUuid,duration:o.originalDuration,width:((n=o.media)==null?void 0:n.width)??1920,height:((i=o.media)==null?void 0:i.height)??1080};return(r=o.media)!=null&&r.filename&&(a.filename=o.media.filename),(l=o.media)!=null&&l.mime_type&&(a.mimeType=o.media.mime_type),typeof((s=o.media)==null?void 0:s.frame_rate)=="number"&&(a.frameRate=o.media.frame_rate),typeof((d=o.media)==null?void 0:d.has_audio)=="boolean"&&(a.hasAudio=o.media.has_audio),(c=o.media)!=null&&c.thumbnail_url&&(a.thumbnailUrl=o.media.thumbnail_url),[a]}function pS(o){var a;return o.tracks&&o.tracks.length>0?o.tracks.map(vS):[{id:((a=o.clips.find(t=>t.trackId))==null?void 0:a.trackId)??li,type:"video",name:"Video",order:0}]}function fS(o,a){return o.map(t=>({...t,clipIds:a.filter(n=>n.trackId===t.id).map(n=>n.id)}))}function hS(o){const a={...o};return o.metadata&&(a.metadata={...o.metadata}),a}function vS(o){const a={...o};return o.clipIds&&(a.clipIds=[...o.clipIds]),a}function gS(o){const a={...o};return o.params&&(a.params={...o.params}),a}function bS(o){const a={volume:o.audioVolume,muted:o.audioVolume===0};return o.audioFadeIn>0&&(a.fadeIn=o.audioFadeIn),o.audioFadeOut>0&&(a.fadeOut=o.audioFadeOut),a}function yS(o){var r;const a={"360p":{bitrate:1e6},"480p":{bitrate:25e5},"720p":{bitrate:5e6},"1080p":{bitrate:8e6},"1440p":{bitrate:16e6},"2160p":{bitrate:35e6}},t=a[o.exportQuality]||a["1080p"],n=(r=o.media)==null?void 0:r.frame_rate,i=n&&Number.isFinite(n)&&n>0?n:30;return{format:o.exportFormat||"mp4",codec:"h264",quality:o.exportQuality||"1080p",fps:i,bitrate:t.bitrate}}function fn(o){return arguments.length===0?{ok:!0,value:void 0}:{ok:!0,value:o}}function ta(o,a){return{ok:!1,reason:o,message:a}}const wS={last_clip:"Can't delete the last clip — leave the timeline empty or use Reset.",no_selection:"Select a clip first.",track_locked:"Target track is locked. Unlock it or pick another track.",track_missing:"That track no longer exists.",track_type_mismatch:"Clip can't be placed on that track type.",overlap:"No room on this track. Move neighboring clips or use a different track.",asset_not_ready:"Asset is still uploading or processing.",invariant_violation:"Editor state would be invalid — change rejected.",source_not_found:"Asset source not found.",source_in_use:"This asset is in use on the timeline. Remove its clips before deleting."};function _a(o){return wS[o]}const Hi=1e-6;function cs(o){if(!Number.isFinite(o.desiredDuration)||o.desiredDuration<=0)return{ok:!1};const a=Math.max(0,o.preferredStart),t=[...o.trackClips].filter(i=>i.id!==o.ignoreClipId).sort((i,r)=>i.timelineStart-r.timelineStart);if(t.length===0)return{ok:!0,start:a};if(kS(a,o.desiredDuration,t))return{ok:!0,start:a};let n=a;for(const i of t)if(!(i.timelineEnd<=n+Hi)){if(i.timelineStart-n>=o.desiredDuration-Hi&&n+Hi>=a)return{ok:!0,start:n};n=Math.max(n,i.timelineEnd)}return{ok:!0,start:n}}function kS(o,a,t){const n=o+a;for(const i of t)if(!(i.timelineEnd<=o+Hi)&&!(i.timelineStart>=n-Hi))return!1;return!0}const _S={video:new Set(["clip","video","image"]),image:new Set(["image"]),audio:new Set(["audio"]),text:new Set(["text"]),graphics:new Set(["graphics"]),caption:new Set([])};function pu(o,a){return _S[a].has(o)}function ES(o){const a=new Set;for(const t of o.clips)typeof t.sourceRefId=="string"&&t.sourceRefId!==""&&a.add(t.sourceRefId);return a}function SS(o,a){return ES(o).has(a)}function Sr(o,a=30){const t=typeof o=="number"?o:Number(o);return Number.isFinite(t)&&t>0?t:a}function Fp(o,a,t){var Et,Kt,Ca;const n=typeof o=="string"&&o.trim()!==""?o.trim():`temp-${Date.now()}`,i=e.reactive({mediaUuid:n,clips:[],playheadPosition:0,totalDuration:0,originalDuration:0,filters:[],audioVolume:1,audioFadeIn:0,audioFadeOut:0,exportQuality:"1080p",exportFormat:"mp4",hasChanges:!1,isPlaying:!1,zoomLevel:100}),r=e.ref(null),l=e.ref([]),s=e.ref([]),d=e.ref(void 0);let c=typeof(t==null?void 0:t.duration)=="number"&&t.duration>0&&t.duration!==1;const u=e.ref(!1),m=Sr(((Et=a==null?void 0:a.output)==null?void 0:Et.fps)??(t==null?void 0:t.frame_rate)),p=e.shallowRef(null),f=new tp(m),h=e.ref(m),v=e.ref(!1),y=e.ref(!1);a&&a.timeline&&a.timeline.length>0?(M(a),(Kt=a.output)!=null&&Kt.fps&&(h.value=Sr(a.output.fps,h.value),f.setFps(h.value))):(I(),a&&((Ca=a.output)!=null&&Ca.fps&&(h.value=Sr(a.output.fps,h.value),f.setFps(h.value)),a.audio&&(i.audioVolume=a.audio.volume||1,i.audioFadeIn=a.audio.fadeIn||0,i.audioFadeOut=a.audio.fadeOut||0),a.output&&(i.exportFormat=a.output.format||"mp4",i.exportQuality=a.output.quality||"1080p")));const w=e.ref(1),_=e.computed(()=>i.selectedClipId?i.clips.find(X=>X.id===i.selectedClipId)??null:null);e.watch(_,X=>{w.value=(X==null?void 0:X.speed)??1},{immediate:!0});const b=e.computed(()=>l.value.length>0),g=e.computed(()=>s.value.length>0);function I(){const X=typeof(t==null?void 0:t.duration)=="number"&&t.duration>0?t.duration:1;t&&(i.media=t),i.originalDuration=X,i.totalDuration=X;const Y=It();i.mediaSources=[T(X)],i.tracks=[$([Y])];const fe={id:Y,type:"clip",trackId:li,sourceRefId:no,timelineStart:0,timelineEnd:X,sourceIn:0,sourceOut:X,sourceMinIn:0,sourceMaxOut:X,speed:1};i.clips=[fe],i.selectedClipId=Y,d.value=Y,!(t||n.startsWith("temp-"))&&(async()=>{try{const he=await fetch(`/api/v1/video/${encodeURIComponent(n)}`);if(!he.ok)throw new Error(`Failed to fetch media: ${he.status}`);const Te=await he.json(),Ke=typeof Te=="object"&&Te!==null&&"data"in Te?Te.data:Te;if(!Ke||typeof Ke!="object")throw new Error("Failed to parse media payload");const ct=Ke;i.media=ct,a||(h.value=Sr(ct.frame_rate,h.value),f.setFps(h.value));const tt=typeof ct.duration=="number"&&ct.duration>0?ct.duration:X;if(i.hasChanges||i.clips.length!==1||i.clips[0].id!==Y)return;i.originalDuration=tt,i.totalDuration=tt,i.mediaSources=[T(tt,ct)],i.tracks=[$([Y])];const qe=i.clips[0];qe.timelineStart=0,qe.timelineEnd=tt,qe.sourceIn=0,qe.sourceOut=tt,qe.sourceMinIn=0,qe.sourceMaxOut=tt,Ve(),c=!0}catch{}})()}function T(X,Y=t){const fe={id:no,type:"media",mediaUuid:n,duration:X,width:(Y==null?void 0:Y.width)??1920,height:(Y==null?void 0:Y.height)??1080};return Y!=null&&Y.filename&&(fe.filename=Y.filename),Y!=null&&Y.mime_type&&(fe.mimeType=Y.mime_type),typeof(Y==null?void 0:Y.frame_rate)=="number"&&(fe.frameRate=Y.frame_rate),typeof(Y==null?void 0:Y.has_audio)=="boolean"&&(fe.hasAudio=Y.has_audio),Y!=null&&Y.thumbnail_url&&(fe.thumbnailUrl=Y.thumbnail_url),fe}function $(X){return{id:li,type:"video",name:"Video",order:0,clipIds:X}}function N(X){return`track-${X}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function B(X,Y){const fe=X.charAt(0).toUpperCase()+X.slice(1),he=Y.filter(Te=>Te.type===X).length;return he===0?fe:`${fe} ${he+1}`}function P(X,Y){if(X.originalDuration!==1)return;X.originalDuration=Y,X.totalDuration===1&&(X.totalDuration=Y);const fe=X.clips[0],he=!a&&X.clips.length===1&&fe!==void 0&&fe.timelineStart===0&&fe.timelineEnd===1&&fe.sourceIn===0&&fe.sourceOut===1;for(const Te of X.clips)(Te.sourceMaxOut===1||Te.sourceMaxOut===void 0)&&(Te.sourceMaxOut=Y);if(X.mediaSources)for(const Te of X.mediaSources)Te.id===no&&(Te.duration===1||Te.duration===void 0)&&(Te.duration=Y);he&&fe!==void 0&&(fe.sourceOut=Y,fe.timelineEnd=Y)}function x(X){if(!Number.isFinite(X)||X<=0||c)return;const Y=i.hasChanges;i.originalDuration=X,i.totalDuration=Math.max(i.totalDuration,X),i.media&&(i.media.duration=X);for(const Te of i.clips)Te.sourceMaxOut=X;if(i.mediaSources)for(const Te of i.mediaSources)(Te.id===no||Te.mediaUuid===n)&&(Te.duration=X);const fe=i.clips[0];!a&&i.clips.length===1&&fe!==void 0&&fe.timelineStart===0&&fe.timelineEnd===1&&fe.sourceIn===0&&fe.sourceOut===1&&fe!==void 0&&(fe.sourceOut=X,fe.timelineEnd=fe.timelineStart+(fe.sourceOut-fe.sourceIn)),Ve();for(const Te of l.value)P(Te,X);for(const Te of s.value)P(Te,X);c=!0,e.nextTick(()=>{Y||(i.hasChanges=!1)})}function M(X){const Y=sp(X);i.mediaSources=Y.mediaSources,i.tracks=Y.tracks,i.transitions=Y.transitions,i.clips=Y.clips.map(fe=>({...fe,sourceMinIn:fe.sourceMinIn??0,sourceMaxOut:fe.sourceMaxOut??X.source.duration})),i.filters=[],i.audioVolume=X.audio.volume,i.audioFadeIn=X.audio.fadeIn||0,i.audioFadeOut=X.audio.fadeOut||0,i.exportFormat=X.output.format,i.exportQuality=X.output.quality,i.originalDuration=X.source.duration,i.textOverlays=X.textOverlays?[...X.textOverlays]:[],i.audioTracks=X.audioTracks?[...X.audioTracks]:[],i.captionTracks=X.captionTracks?X.captionTracks.map(oe):[],i.visualLayers=X.visualLayers?X.visualLayers.map(fe=>({...fe})):[],i.clips.length>0?(i.selectedClipId=i.clips[0].id,d.value=i.selectedClipId):(delete i.selectedClipId,d.value=void 0),Ve()}function E(){l.value.push(JSON.parse(JSON.stringify(i))),s.value=[],i.hasChanges=!0}function D(){if(!b.value)return;const X=l.value.pop();s.value.push(JSON.parse(JSON.stringify(i))),Object.assign(i,X)}function j(){if(!g.value)return;const X=s.value.pop();l.value.push(JSON.parse(JSON.stringify(i))),Object.assign(i,X)}function L(X,Y,fe){E();const he=i.clips.find(tt=>tt.id===X);if(!he)return;const Te=1/h.value,Ke=he.sourceMinIn??0,ct=he.sourceMaxOut??i.originalDuration;if(Y==="start"){const tt=he.sourceIn,qe=Math.max(Ke,Math.min(fe,he.sourceOut-Te));he.sourceIn=qe;const vt=qe-tt;he.timelineStart+=vt}else{const tt=Math.max(he.sourceIn+Te,Math.min(fe,ct));he.sourceOut=tt;const qe=he.sourceOut-he.sourceIn;he.timelineEnd=he.timelineStart+qe}Ve(),p.value&&p.value.trimClip(X,he.sourceIn,he.sourceOut)}function z(X){E();const Y=i.clips.find(ct=>X>ct.timelineStart&&X<ct.timelineEnd);if(!Y)return;const fe=X-Y.timelineStart,he=Y.sourceIn+fe,Te={id:It(),type:"clip",timelineStart:X,timelineEnd:Y.timelineEnd,sourceIn:he,sourceOut:Y.sourceOut,speed:Y.speed??1,sourceMinIn:Y.sourceMinIn??0,sourceMaxOut:Y.sourceMaxOut??i.originalDuration,filters:[...Y.filters||[]]};Y.trackId&&(Te.trackId=Y.trackId),Y.sourceRefId&&(Te.sourceRefId=Y.sourceRefId),Y.timelineEnd=X,Y.sourceOut=he;const Ke=i.clips.indexOf(Y);i.clips.splice(Ke+1,0,Te),ue(),i.selectedClipId=Te.id}function C(){z(i.playheadPosition)}function A(X){var fe;const Y=X??i.selectedClipId??d.value??((fe=i.clips[0])==null?void 0:fe.id);Y&&(i.selectedClipId=Y,d.value=Y)}function O(){return i.selectedClipId?K(i.selectedClipId):ta("no_selection",_a("no_selection"))}function K(X){const Y=i.clips.findIndex(fe=>fe.id===X);return Y===-1?ta("source_not_found","Clip not found."):(E(),i.clips.splice(Y,1),ue(),se(Y),Ve(),fn())}function se(X){if(!i.clips.length){delete i.selectedClipId,d.value=void 0;return}const Y=Math.max(0,Math.min(X,i.clips.length-1)),fe=i.clips[Y];fe&&(i.selectedClipId=fe.id,d.value=fe.id)}function xe(X){return X.trackId??`legacy-track-${X.track??0}`}function ue(){const X=i.tracks;if(X)for(const Y of X)Y.clipIds=i.clips.filter(fe=>xe(fe)===Y.id).map(fe=>fe.id)}function le(X="video"){E();const Y=i.tracks??[],fe=Y.reduce((Te,Ke)=>Math.max(Te,Ke.order),-1),he={id:N(X),type:X,name:B(X,Y),order:fe+1,clipIds:[]};return i.tracks=[...Y,he],i.hasChanges=!0,he}function Z(X){if(X.length===0)return;const Y=new Set(X),fe=i.clips.findIndex(he=>Y.has(he.id));i.clips=i.clips.filter(he=>!Y.has(he.id)),i.transitions&&i.transitions.length>0&&(i.transitions=i.transitions.filter(he=>!Y.has(he.fromClipId)&&!Y.has(he.toClipId))),ue(),i.selectedClipId!==void 0&&Y.has(i.selectedClipId)&&se(fe>=0?fe:0),Ve()}function k(X){const Y=i.tracks??[],fe=Y.find(Te=>Te.id===X);if(!fe)return ta("track_missing",_a("track_missing"));if(Y.length<=1)return ta("invariant_violation","Can't delete the last remaining track. Add another track first.");E();const he=i.clips.filter(Te=>xe(Te)===fe.id).map(Te=>Te.id);return Z(he),i.tracks=Y.filter(Te=>Te.id!==fe.id),i.hasChanges=!0,fn()}function F(X,Y){const he=(i.tracks??[]).find(Ke=>Ke.id===X);if(!he)return ta("track_missing",_a("track_missing"));const Te=Y.trim();return Te===""?ta("invariant_violation","Track name cannot be empty."):(he.name===Te||(E(),he.name=Te,i.hasChanges=!0),fn())}function W(X,Y){const fe=i.tracks??[],he=fe.find(vt=>vt.id===X);if(!he)return ta("track_missing",_a("track_missing"));const Te=[...fe].sort((vt,gt)=>vt.order-gt.order),Ke=Te.findIndex(vt=>vt.id===he.id),ct=Y==="up"?Ke+1:Ke-1,tt=Te[ct];if(!tt)return ta("invariant_violation","Track is already at the edge.");E();const qe=he.order;return he.order=tt.order,tt.order=qe,i.hasChanges=!0,fn()}function J(X){let Y=i.tracks??[];if(Y.length===0){const he=$([]);i.tracks=[he],Y=i.tracks}if(X){const he=Y.find(Te=>Te.id===X);return he?he.locked===!0?{ok:!1,reason:"track_locked"}:{ok:!0,track:he}:{ok:!1,reason:"track_missing"}}const fe=Y.find(he=>he.type==="video"&&he.locked!==!0)??Y.find(he=>he.locked!==!0);return fe?{ok:!0,track:fe}:{ok:!1,reason:"no_editable_track"}}function ce(X){const Y=1/h.value;return typeof X.duration=="number"&&Number.isFinite(X.duration)&&X.duration>Y?X.duration:i.originalDuration>Y?i.originalDuration:Math.max(Y,i.totalDuration)}function Ue(X){const Y=i.clips.filter(fe=>xe(fe)===X);return Y.length>0?Y.reduce((fe,he)=>Math.max(fe,he.timelineEnd),0):Math.max(0,Math.min(i.playheadPosition,i.totalDuration))}function be(X){const Y=i.mediaSources??[],fe=Y.find(he=>he.id===X.id);return fe||(i.mediaSources=[...Y,X],i.hasChanges=!0,X)}function _e(X,Y){return Ne(X,"clip",Y)}function ye(X,Y){if(!(i.mediaSources??[]).find(Te=>Te.id===X))return ta("source_not_found",_a("source_not_found"));let he=Y;if(!he){const Te=(i.tracks??[]).find(Ke=>Ke.type==="audio"&&Ke.locked!==!0);he=(Te==null?void 0:Te.id)??le("audio").id}return Ne(X,"audio",he)}function Ne(X,Y,fe){const he=(i.mediaSources??[]).find(Qt=>Qt.id===X);if(!he)return ta("source_not_found",_a("source_not_found"));const Te=J(fe);if(!Te.ok){const Qt=Te.reason==="no_editable_track"?"track_missing":Te.reason;return ta(Qt,_a(Qt))}const Ke=Te.track;if(!pu(Y,Ke.type))return ta("track_type_mismatch",_a("track_type_mismatch"));const ct=i.clips.filter(Qt=>xe(Qt)===Ke.id),tt=ce(he),qe=Ue(Ke.id),vt=cs({trackClips:ct,desiredDuration:tt,preferredStart:qe});if(!vt.ok)return ta("overlap",_a("overlap"));E();const gt=It(),ot={id:gt,type:Y,trackId:Ke.id,sourceRefId:he.id,timelineStart:vt.start,timelineEnd:vt.start+tt,sourceIn:0,sourceOut:tt,sourceMinIn:0,sourceMaxOut:tt,speed:1};return i.clips.push(ot),i.selectedClipId=gt,d.value=gt,ue(),Ve(),fn(ot)}function Se(X){const Y=_.value,fe=(i.mediaSources??[]).find(tt=>tt.id===X);if(!Y||!fe)return!1;E();const he=1/h.value,Te=ce(fe),Ke=Math.max(he,Y.timelineEnd-Y.timelineStart),ct=Math.max(he,Math.min(Ke,Te));return Y.sourceRefId=fe.id,Y.sourceIn=0,Y.sourceOut=ct,Y.sourceMinIn=0,Y.sourceMaxOut=Te,Y.timelineEnd=Y.timelineStart+ct,Ve(),!0}function Re(X){const Y=i.mediaSources??[];return Y.length<=1||SS({clips:i.clips},X)?!1:(E(),i.mediaSources=Y.filter(fe=>fe.id!==X),!0)}function Oe(X,Y){const fe=(i.tracks??[]).find(he=>he.id===X);return fe?(E(),fe[Y]=fe[Y]!==!0,!0):!1}function it(X){return Oe(X,"locked")}function rt(X){return Oe(X,"hidden")}function Pt(X){return Oe(X,"muted")}function bt(X){return Oe(X,"solo")}function Ct(X){if(i.clips.length<=1)return!1;const Y=i.clips.findIndex(Ke=>Ke.id===X),fe=Y===-1?void 0:i.clips[Y];if(!fe)return!1;const he=Math.max(0,fe.timelineEnd-fe.timelineStart),Te=xe(fe);if(E(),i.clips.splice(Y,1),ue(),he>0)for(const Ke of i.clips)xe(Ke)!==Te||Ke.timelineStart<fe.timelineEnd||(Ke.timelineStart=Math.max(0,Ke.timelineStart-he),Ke.timelineEnd=Math.max(Ke.timelineStart,Ke.timelineEnd-he));return i.playheadPosition>=fe.timelineEnd?i.playheadPosition=Math.max(0,i.playheadPosition-he):i.playheadPosition>fe.timelineStart&&(i.playheadPosition=fe.timelineStart),se(Y),Ve(),i.hasChanges=!0,!0}function mt(){return i.selectedClipId?Ct(i.selectedClipId):!1}function pt(){return[...i.clips].sort((X,Y)=>X.timelineStart-Y.timelineStart)}function Nt(X){const Y=i.clips.find(ot=>ot.id===X);if(!Y)return null;const fe=xe(Y),he=pt().filter(ot=>xe(ot)===fe),Te=he.findIndex(ot=>ot.id===X);if(Te===-1)return null;const Ke=he[Te],ct=Ke.timelineEnd-Ke.timelineStart,tt=Te>0?he[Te-1]:null,qe=Te<he.length-1?he[Te+1]:null,vt=tt?tt.timelineEnd:0,gt=qe?qe.timelineStart-ct:Math.max(Ke.timelineStart,i.totalDuration-ct);return{minStart:vt,maxStart:Math.max(vt,gt)}}function Ce(X,Y,fe){const he=i.clips.find(gt=>gt.id===X);if(!he)return ta("source_not_found","Clip not found.");if(fe===void 0||fe===he.trackId){const gt=Nt(X),ot=gt?Math.min(gt.maxStart,Math.max(gt.minStart,Y)):Math.max(0,Y);if(ot===he.timelineStart)return fn();E();const Qt=ot-he.timelineStart;return he.timelineStart=ot,he.timelineEnd+=Qt,Ve(),p.value&&p.value.moveClip(X,ot),fn()}const Ke=(i.tracks??[]).find(gt=>gt.id===fe);if(!Ke)return ta("track_missing",_a("track_missing"));if(Ke.locked===!0)return ta("track_locked",_a("track_locked"));if(!pu(he.type,Ke.type))return ta("track_type_mismatch",_a("track_type_mismatch"));const ct=i.clips.filter(gt=>xe(gt)===Ke.id&&gt.id!==he.id),tt=he.timelineEnd-he.timelineStart,qe=cs({trackClips:ct,desiredDuration:tt,preferredStart:Math.max(0,Y),ignoreClipId:he.id});if(!qe.ok)return ta("overlap",_a("overlap"));E(),he.trackId=Ke.id;const vt=he.timelineStart;return he.timelineStart=qe.start,he.timelineEnd=qe.start+tt,ue(),Ve(),p.value&&vt!==qe.start&&p.value.moveClip(X,qe.start),fn()}function Ve(){if(i.clips.length===0){i.totalDuration=0;return}const X=i.clips.reduce((Y,fe)=>fe.timelineEnd>Y.timelineEnd?fe:Y);i.totalDuration=X.timelineEnd}function Le(){i.zoomLevel=Math.min(200,i.zoomLevel*1.2)}function nt(){i.zoomLevel=Math.max(10,i.zoomLevel/1.2)}function Ge(X){i.zoomLevel=Math.max(10,Math.min(600,Math.round(X)))}function Je(){i.isPlaying=!i.isPlaying}function _t(X){i.isPlaying=X}function ht(X){i.playheadPosition=Math.max(0,Math.min(X,i.totalDuration))}function Wt(){const X=mu(i);try{localStorage.setItem(`video-draft-${n}`,JSON.stringify(X))}catch{}return X}function Pe(){i.hasChanges=!1}function Ht(){return confirm("Are you sure you want to reset all changes?")?(E(),I(),i.hasChanges=!1,!0):!1}function Zt(){return mu(i)}function It(){return`clip-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}async function Ut(X=1920,Y=1080){if(u.value)try{p.value=new ep(X,Y,h.value),await Gt()}catch{p.value=null}}async function Gt(){if(!(!p.value||y.value)){y.value=!0;try{const X=Zt();await p.value.loadFromRecipe(X);const Y=f.secondsToFrames(i.playheadPosition);p.value.seek(Y)}catch{}finally{y.value=!1}}}function sa(X){}function ae(X){return f.secondsToFrames(X)}function ge(X){return f.framesToSeconds(X)}function pe(X){const Y=ge(X);ht(Y),p.value&&p.value.seek(X)}function me(){v.value=!v.value}function Be(){Gt()}function He(X){u.value=!1,p.value=null}e.watch(()=>i.clips,()=>{i.hasChanges=!0,u.value&&p.value&&Gt()},{deep:!0}),e.watch(()=>i.filters,()=>{i.hasChanges=!0,u.value&&p.value&&Gt()},{deep:!0}),e.watch(()=>i.clips.map(X=>X.id),()=>{var Y;if(!i.clips.length){delete i.selectedClipId,d.value=void 0;return}if(!i.clips.some(fe=>fe.id===i.selectedClipId)){const fe=d.value&&((Y=i.clips.find(he=>he.id===d.value))==null?void 0:Y.id);i.selectedClipId=fe??i.clips[0].id,d.value=i.selectedClipId}},{deep:!0});function lt(X){const Y=i.selectedClipId?i.clips.find(fe=>fe.id===i.selectedClipId):i.clips[0];Y&&(Y.filters=[...X],i.hasChanges=!0)}function Vt(X){i.textOverlays=[...X]}function Ot(X){i.audioTracks=[...X]}function $t(X){i.captionTracks=X.map(oe),i.hasChanges=!0}function st(X){i.visualLayers=X.map(Y=>({...Y})),i.hasChanges=!0}function Jt(X){i.transitions=X.map(Y=>{const fe={...Y};return Y.params&&(fe.params={...Y.params}),fe}),i.hasChanges=!0}function q(X,Y){const fe=i.clips.find(he=>he.id===X);fe&&(fe.keyframes=Y.map(he=>({...he})),i.hasChanges=!0)}function ke(X){E(),M(X),i.hasChanges=!0}function oe(X){return{...X,segments:X.segments.map(Y=>{const fe={...Y};return Y.words&&(fe.words=Y.words.map(he=>({...he}))),fe})}}e.watch(u,X=>{X?Ut():p.value&&(p.value.destroy(),p.value=null)}),e.watch(v,()=>{}),e.watch(h,X=>{f.setFps(X)});function $e(){if(!i.selectedClipId)return ta("no_selection",_a("no_selection"));const X=i.clips.find(tt=>tt.id===i.selectedClipId);if(!X)return ta("no_selection",_a("no_selection"));const Y=xe(X),fe=i.clips.filter(tt=>xe(tt)===Y),he=X.timelineEnd-X.timelineStart,Te=cs({trackClips:fe,desiredDuration:he,preferredStart:X.timelineEnd});if(!Te.ok)return ta("overlap",_a("overlap"));E();const Ke={...X,id:It(),timelineStart:Te.start,timelineEnd:Te.start+he,filters:[...X.filters||[]]},ct=i.clips.indexOf(X);return i.clips.splice(ct+1,0,Ke),ue(),i.selectedClipId=Ke.id,i.hasChanges=!0,fn(Ke)}function At(X){const Y=X??800,fe=i.totalDuration;if(fe<=0){i.zoomLevel=50;return}const he=Y*.8/fe;i.zoomLevel=Math.max(10,Math.min(600,Math.round(he)))}function zt(){const X=1/h.value;ht(Math.min(i.playheadPosition+X,i.totalDuration))}function Ft(){const X=1/h.value;ht(Math.max(i.playheadPosition-X,0))}function wt(){ht(0)}function yt(){ht(i.totalDuration)}function Yt(X){if(!Number.isFinite(X)||X<=0)return;const Y=_.value??i.clips[0];if(!Y){w.value=X;return}const fe=Y.speed??1;if(fe===X){w.value=X;return}E();const he=Math.max(1/h.value,Y.sourceOut-Y.sourceIn),Te=he/fe,Ke=he/X,ct=Ke-Te;Y.speed=X,Y.timelineEnd=Y.timelineStart+Ke;const tt=i.clips.findIndex(qe=>qe.id===Y.id);if(tt!==-1&&ct!==0)for(let qe=tt+1;qe<i.clips.length;qe+=1){const vt=i.clips[qe];vt.timelineStart+=ct,vt.timelineEnd+=ct}Ve(),i.playheadPosition=Math.max(0,Math.min(i.playheadPosition,i.totalDuration)),i.hasChanges=!0,w.value=X}return{currentFrame:r,playheadPosition:e.computed(()=>i.playheadPosition),timelineClips:e.computed(()=>i.clips),tracks:e.computed(()=>i.tracks??[]),mediaSources:e.computed(()=>i.mediaSources??[]),transitions:e.computed(()=>i.transitions??[]),totalDuration:e.computed(()=>i.totalDuration),hasChanges:e.computed(()=>i.hasChanges),isPlaying:e.computed(()=>i.isPlaying),selectedClip:_,zoomLevel:e.computed(()=>i.zoomLevel),playbackSpeed:w,useVideoEngine:u,compositionAdapter:e.computed(()=>p.value),fps:h,useFrameMode:v,handleTrim:L,handleSplit:z,handleClipSelect:A,splitAtPlayhead:C,deleteSelectedClip:O,deleteClip:K,rippleDeleteClip:Ct,rippleDeleteSelectedClip:mt,duplicateSelectedClip:$e,addTimelineTrack:le,deleteTimelineTrack:k,renameTimelineTrack:F,reorderTimelineTrack:W,appendMediaSourceToTimeline:_e,appendAudioSourceToTimeline:ye,registerMediaSource:be,replaceSelectedClipSource:Se,removeMediaSource:Re,toggleTrackLock:it,toggleTrackHidden:rt,toggleTrackMuted:Pt,toggleTrackSolo:bt,setFilters:lt,setTextOverlays:Vt,setAudioTracks:Ot,setCaptionTracks:$t,setVisualLayers:st,setTransitions:Jt,setClipKeyframes:q,loadRecipe:ke,moveClip:Ce,saveDraft:Wt,clearHasChanges:Pe,resetChanges:Ht,generateRecipe:Zt,zoomIn:Le,zoomOut:nt,setZoomLevel:Ge,fitToWindow:At,togglePlayback:Je,setPlaying:_t,seekTo:ht,frameForward:zt,frameBackward:Ft,skipToStart:wt,skipToEnd:yt,setPlaybackSpeed:Yt,updateSourceDuration:x,undo:D,redo:j,canUndo:b,canRedo:g,initializeComposition:Ut,syncCompositionWithState:Gt,syncWithComposition:sa,convertToFrames:ae,convertToSeconds:ge,seekToFrame:pe,toggleFrameMode:me,onCompositionReady:Be,onCompositionError:He}}const CS=[{id:"brightness",name:"Brightness",category:"color",ffmpeg:"eq=brightness={value}",pixiFilter:"AdjustmentFilter",defaultParams:{value:0},paramRanges:{value:{min:-1,max:1,step:.05}}},{id:"contrast",name:"Contrast",category:"color",ffmpeg:"eq=contrast={value}",pixiFilter:"AdjustmentFilter",defaultParams:{value:1},paramRanges:{value:{min:.5,max:2,step:.05}}},{id:"saturation",name:"Saturation",category:"color",ffmpeg:"eq=saturation={value}",pixiFilter:"AdjustmentFilter",defaultParams:{value:1},paramRanges:{value:{min:0,max:2,step:.05}}},{id:"hue",name:"Hue Shift",category:"color",ffmpeg:"hue=h={value}",pixiFilter:"HueRotateFilter",defaultParams:{value:0},paramRanges:{value:{min:-180,max:180,step:5}}},{id:"gaussian-blur",name:"Gaussian Blur",category:"blur",ffmpeg:"gblur=sigma={value}",pixiFilter:"BlurFilter",defaultParams:{value:2},paramRanges:{value:{min:0,max:10,step:.5}}},{id:"motion-blur",name:"Motion Blur",category:"blur",ffmpeg:"minterpolate=fps=60:mi_mode=mci:mc_mode=aobmc:me_mode=bidir:me=epzs:vsbmc=1",pixiFilter:"MotionBlurFilter",defaultParams:{velocity:5,angle:0},paramRanges:{velocity:{min:0,max:20,step:1},angle:{min:0,max:360,step:15}}},{id:"vintage",name:"Vintage",category:"stylize",ffmpeg:"curves=preset=vintage",pixiFilter:"ColorMatrixFilter",defaultParams:{preset:"vintage"},paramRanges:{}},{id:"sepia",name:"Sepia",category:"stylize",ffmpeg:"colorchannelmixer=.393:.769:.189:0:.349:.686:.168:0:.272:.534:.131",pixiFilter:"ColorMatrixFilter",defaultParams:{preset:"sepia"},paramRanges:{}},{id:"grayscale",name:"Black & White",category:"stylize",ffmpeg:"colorchannelmixer=0.3:0.59:0.11:0:0.3:0.59:0.11:0:0.3:0.59:0.11",pixiFilter:"ColorMatrixFilter",defaultParams:{preset:"grayscale"},paramRanges:{}},{id:"vignette",name:"Vignette",category:"effects",ffmpeg:"vignette=a={value}",pixiFilter:"VignetteFilter",defaultParams:{value:.3},paramRanges:{value:{min:0,max:1,step:.05}}},{id:"sharpen",name:"Sharpen",category:"effects",ffmpeg:"unsharp=5:5:{value}:5:5:0",pixiFilter:"SharpenFilter",defaultParams:{value:1},paramRanges:{value:{min:0,max:5,step:.25}}},{id:"denoise",name:"Noise Reduction",category:"effects",ffmpeg:"nlmeans=s={value}",pixiFilter:"NoiseFilter",defaultParams:{value:1},paramRanges:{value:{min:.1,max:5,step:.1}}},{id:"motion-blur",name:"Motion Blur",category:"effects",ffmpeg:"minterpolate=fps=30:mi_mode=blend",pixiFilter:"MotionBlurFilter",defaultParams:{velocity:[0,0],kernelSize:5},paramRanges:{velocityX:{min:-100,max:100,step:1},velocityY:{min:-100,max:100,step:1},kernelSize:{min:3,max:15,step:2}}},{id:"radial-blur",name:"Radial Blur",category:"effects",ffmpeg:"boxblur={radius}:{radius}",pixiFilter:"RadialBlurFilter",defaultParams:{radius:.1,angle:0,kernelSize:5},paramRanges:{radius:{min:0,max:1,step:.01},angle:{min:-180,max:180,step:1},kernelSize:{min:3,max:15,step:2}}},{id:"kawase-blur",name:"Kawase Blur",category:"effects",ffmpeg:"gblur=sigma={blur}:steps={quality}",pixiFilter:"KawaseBlurFilter",defaultParams:{blur:4,quality:3},paramRanges:{blur:{min:0,max:20,step:.5},quality:{min:1,max:10,step:1}}},{id:"flip-horizontal",name:"Flip Horizontal",category:"transform",ffmpeg:"hflip",pixiFilter:"FlipFilter",defaultParams:{horizontal:!0},paramRanges:{}},{id:"flip-vertical",name:"Flip Vertical",category:"transform",ffmpeg:"vflip",pixiFilter:"FlipFilter",defaultParams:{vertical:!0},paramRanges:{}},{id:"rotate",name:"Rotate",category:"transform",ffmpeg:"rotate={value}*PI/180",pixiFilter:"RotateFilter",defaultParams:{value:0},paramRanges:{value:{min:-180,max:180,step:15}}}],xS={dropShadow:"drop-shadow",softFocus:"blur",blackAndWhite:"grayscale",gaussianBlur:"blur","gaussian-blur":"blur"};function Bl(o){return typeof o=="object"&&o!==null}function NS(o,a){if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"){const t=Number(o);if(Number.isFinite(t))return t}return a}function Ml(o){if(typeof o=="number"||typeof o=="string"||typeof o=="boolean")return o}function VS(o){const a={id:o.id,type:o.type,label:o.label};o.property!==void 0&&(a.property=o.property),o.min!==void 0&&(a.min=o.min),o.max!==void 0&&(a.max=o.max),o.step!==void 0&&(a.step=o.step);const t=Ml(o.default);return t!==void 0&&(a.default=t),o.options!==void 0&&(a.options=o.options),a}function Dp(o,a,t){const n=la.getFilter(o),i={},r=(n==null?void 0:n.defaultParams)??t;if(r&&Bl(r))for(const[l,s]of Object.entries(r))i[l]=Ml(s)??null;for(const l of a){const s=l.property??l.id;i[s]===void 0&&l.default!==void 0&&(i[s]=l.default)}return i}function Ap(o){const a={};for(const t of o){if(t.type!=="slider")continue;const n=t.property??t.id;a[n]={min:t.min??0,max:t.max??100,step:t.step??1}}return a}function TS(o,a,t,n){const i=n.map(VS);return{id:o,name:a,category:t,controls:i,params:i,defaultParams:Dp(o,i),paramRanges:Ap(i)}}function BS(o){const a=o.paramRanges??{},t=Object.entries(a).map(([n,i])=>{var s;const r={id:n,type:"slider",label:n.replace(/[-_]/g," ").replace(/\b\w/g,d=>d.toUpperCase()),property:n,min:i.min,max:i.max,step:i.step},l=Ml((s=o.defaultParams)==null?void 0:s[n]);return l!==void 0&&(r.default=l),r});return{id:o.id,name:o.name,category:o.category,controls:t,params:t,defaultParams:Dp(o.id,t,o.defaultParams),paramRanges:Ap(t)}}function MS(o,a){return a.toLowerCase()==="unlisted"?!1:la.isFilterCompatibleWithMedia(o,"video")}function us(o){return xS[o]??o}function Fi(o){const a=NS(o,1);return Math.max(0,Math.min(1,a))}function Di(o){if(!Bl(o))return{};const a={};for(const[t,n]of Object.entries(o))a[t]=Ml(n)??null;return a}function IS(o){return!Bl(o)||typeof o.filterId!="string"?null:{filterId:o.filterId,params:Di(o.params),intensity:Fi(o.intensity)}}function $S(o){if(!Bl(o)||typeof o.id!="string"||typeof o.name!="string")return null;const t=(Array.isArray(o.filters)?o.filters:[]).map(i=>IS(i)).filter(i=>i!==null),n=typeof o.created_at=="string"?o.created_at:new Date().toISOString();return{id:o.id,name:o.name,filters:t,created_at:n}}function Rp(){la.initializeFilterRegistry();const o=e.ref([]),a=e.ref(null),t=e.ref(null),n=e.ref([]),i=e.ref(null),r=e.reactive({}),l=e.computed(()=>{const E=new Map,D=la.getRegisteredFilters();for(const j of D)MS(j.id,j.category)&&E.set(j.id,TS(j.id,j.name,j.category,j.controls));for(const j of CS)E.has(j.id)||E.set(j.id,BS(j));return Array.from(E.values())}),s=e.computed(()=>{const E=new Map;for(const D of l.value)E.set(D.id,D);return E}),d=e.computed(()=>o.value.length>0),c=e.computed(()=>{const E={};for(const D of l.value)E[D.category]||(E[D.category]=[]),E[D.category].push(D);return E});function u(E){const D=s.value.get(E);if(D)return D;const j=us(E);return s.value.get(j)??null}function m(E){const D=s.value.get(E);if(D)return D.id;const j=us(E),L=s.value.get(j);return L?L.id:null}function p(E){const D=E?u(E):a.value;if(!D)return;const j=D.defaultParams||{},L={id:B(),filterId:D.id,params:{...j},intensity:1};return o.value.push(L),i.value=L.id,a.value=D,Object.keys(r).forEach(z=>delete r[z]),Object.assign(r,L.params),t.value=null,L}function f(E){const D=u(E);if(!D)return;a.value=D;const j=D.defaultParams||x(E);Object.assign(r,j),t.value={id:"preview",filterId:D.id,params:{...j},intensity:1}}function h(E){if(Object.assign(r,E),t.value&&(t.value.params={...r}),i.value){const D=o.value.find(j=>j.id===i.value);D&&(D.params={...r})}}function v(E){const D=o.value.findIndex(j=>j.id===E);D!==-1&&o.value.splice(D,1)}function y(E,D){if(E<0||E>=o.value.length||D<0||D>=o.value.length)return;const[j]=o.value.splice(E,1);o.value.splice(D,0,j)}function w(E,D){const j=o.value.find(L=>L.id===E);j&&(j.intensity=Math.max(0,Math.min(1,D)))}function _(E){const D=o.value.find(j=>j.id===E);D&&(D.intensity=D.intensity>0?0:1)}function b(){o.value=[],t.value=null,a.value=null,i.value=null,Object.keys(r).forEach(E=>delete r[E])}function g(E){const D={id:P(),name:E,filters:o.value.map(L=>({filterId:L.filterId,params:Di(L.params),intensity:Fi(L.intensity)})),created_at:new Date().toISOString()};n.value.push(D);const j=n.value.map(L=>({...L}));return localStorage.setItem("video-filter-presets",JSON.stringify(j)),D}function I(E){const D=n.value.find(j=>j.id===E);if(D){b();for(const j of D.filters){const L=u(j.filterId);L&&o.value.push({id:B(),filterId:L.id,params:{...j.params},intensity:Fi(j.intensity)})}}}function T(E){const D=n.value.findIndex(j=>j.id===E);D!==-1&&(n.value.splice(D,1),localStorage.setItem("video-filter-presets",JSON.stringify(n.value)))}function $(){try{const E=localStorage.getItem("video-filter-presets");if(!E)return;const D=JSON.parse(E);if(!Array.isArray(D))return;n.value=D.map(j=>$S(j)).filter(j=>j!==null)}catch{}}function N(){if(o.value.length===0)return"No filters applied";const E=o.value.map(D=>{const j=M(D.filterId);return(j==null?void 0:j.name)||D.filterId});return E.length===1?E[0]:E.length===2?`${E[0]} + ${E[1]}`:`${E[0]} + ${E.length-1} more`}function B(){return`filter-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function P(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function x(E){const D=u(E);return D?D.defaultParams||{}:{}}function M(E){return u(E)}return $(),{videoCompatibleFilters:l,activeFilters:o,selectedFilter:a,previewFilter:t,filterPresets:n,filterParams:r,hasActiveFilters:d,filtersByCategory:c,applyFilter:p,previewFilterEffect:f,updateFilterParams:h,removeFilter:v,reorderFilters:y,updateFilterIntensity:w,toggleFilter:_,clearAllFilters:b,saveFilterPreset:g,loadFilterPreset:I,deleteFilterPreset:T,getFilterSummary:N,setActiveFilters(E){var j;const D=[];for(const L of E){const z=m(L.filterId);if(!z){const C=us(L.filterId);D.push({...L,filterId:C,params:Di(L.params),intensity:Fi(L.intensity)});continue}D.push({...L,filterId:z,params:Di(L.params),intensity:Fi(L.intensity)})}o.value=D,i.value=((j=o.value[0])==null?void 0:j.id)??null,Object.keys(r).forEach(L=>delete r[L]),o.value[0]&&Object.assign(r,Di(o.value[0].params))}}}class Lp{constructor(a){this.textClips=new Map,this.overlayConfigs=new Map,this.fonts=new Map,this.nextId=0,this.composition=a,this.initializeDefaultFonts()}initializeDefaultFonts(){try{this.fonts.set("default",new Ea({source:"https://fonts.googleapis.com/css2?family=Inter:wght@400",family:"Inter",weight:"400"})),this.fonts.set("bold",new Ea({source:"https://fonts.googleapis.com/css2?family=Inter:wght@700",family:"Inter",weight:"700"})),this.fonts.set("serif",new Ea({source:"https://fonts.googleapis.com/css2?family=Merriweather:wght@400",family:"Merriweather",weight:"400"}))}catch{}}async loadWebFont(a,t,n,i="400"){const r=new Ea({source:t,family:n,weight:i});this.fonts.set(a,r)}loadLocalFont(a,t,n="400"){const i=new Ea({source:`local('${t}')`,family:t,weight:n});this.fonts.set(a,i)}async addTextOverlay(a){const t=`text-overlay-${this.nextId++}`,n=this.buildTextClipConfig(a),i=new ci(n);return await this.composition.add(i),this.textClips.set(t,i),this.overlayConfigs.set(t,{...a}),t}buildTextClipConfig(a){const t={text:a.text,fontSize:a.fontSize||24,fillStyle:a.color||"#ffffff",textAlign:a.textAlign||"center",textBaseline:a.textBaseline||"middle"},n=a.fontFamily||"default",i=this.fonts.get(n)||this.fonts.get("default");if(i&&(t.font=i),this.applyPosition(t,a.position),a.startTime!==void 0&&(t.start=Ze.fromSeconds(a.startTime)),a.duration!==void 0){const r=a.startTime||0;t.stop=Ze.fromSeconds(r+a.duration)}return a.animation&&this.applyAnimation(t,a.animation,a),t}applyPosition(a,t){if(!t){a.position="center";return}if(typeof t!="string"){a.x=t.x,a.y=t.y;return}switch(t){case"center":a.position="center";break;case"top":a.x="50%",a.y="10%";break;case"bottom":a.x="50%",a.y="90%";break;case"left":a.x="10%",a.y="50%";break;case"right":a.x="90%",a.y="50%";break}}applyAnimation(a,t,n){if(!t)return;const i=n.startTime?Math.round(n.startTime*30):0,r=t.duration||1,l=Math.round(r*30),s=i+l,d=t.easing||"linear";switch(t.type){case"fade-in":a.alpha=new Ye([i,s],[0,1],{easing:d});break;case"fade-out":a.alpha=new Ye([i,s],[1,0],{easing:d});break;case"rotate":t.rotation&&(a.rotation=new Ye([i,s],[t.rotation.from,t.rotation.to],{easing:d}));break;case"scale":t.scale&&(a.scale=new Ye([i,s],[t.scale.from,t.scale.to],{easing:d}));break;case"slide":t.translate&&(a.translate={x:new Ye([i,s],[t.translate.fromX,t.translate.toX],{easing:d}),y:new Ye([i,s],[t.translate.fromY,t.translate.toY],{easing:d})});break;case"typewriter":a.alpha=new Ye([i,s],[0,1],{easing:"linear"});break;case"custom":t.rotation&&(a.rotation=new Ye([i,s],[t.rotation.from,t.rotation.to],{easing:d})),t.scale&&(a.scale=new Ye([i,s],[t.scale.from,t.scale.to],{easing:d})),t.translate&&(a.translate={x:new Ye([i,s],[t.translate.fromX,t.translate.toX],{easing:d}),y:new Ye([i,s],[t.translate.fromY,t.translate.toY],{easing:d})});break}}async updateTextOverlay(a,t){const n=this.textClips.get(a);if(!n)throw new Error(`Text overlay with id ${a} not found`);const i=this.overlayConfigs.get(a);if(!i)throw new Error(`Text overlay with id ${a} is missing config`);const r={...i,...t};n.set(this.buildTextClipConfig(r)),this.overlayConfigs.set(a,r)}async removeTextOverlay(a){const t=this.textClips.get(a);if(!t)throw new Error(`Text overlay with id ${a} not found`);const n=this.composition.tracks;for(const i of n){const r=i.clips.indexOf(t);if(r!==-1){i.clips.splice(r,1);break}}this.textClips.delete(a),this.overlayConfigs.delete(a)}getTextOverlays(){return new Map(this.textClips)}async clearAllTextOverlays(){const a=Array.from(this.textClips.keys());for(const t of a)await this.removeTextOverlay(t)}getOverlays(){return Array.from(this.overlayConfigs.entries()).map(([a,t])=>({id:a,config:{...t}}))}async addCaptions(a,t="classic",n){var d;const r={classic:lr,cascade:Sl,guinea:El,solar:Cl,spotlight:sr,whisper:dr}[t],l=await this.composition.createTrack("caption"),s=new gl({transcript:a});if(await l.add(s),await((d=l.generate)==null?void 0:d.call(l,r)),n&&l.clips.length>0){const c=l.clips[0];c==null||c.set(n)}}}class Pp{constructor(a){this.audioLayers=new Map,this.audioSources=new Map,this.nextId=0,this.masterVolume=1,this.composition=a}async loadAudioSource(a,t){try{const n=await ao.from(a),i=t||`audio-source-${this.nextId++}`;return this.audioSources.set(i,n),n}catch(n){throw n instanceof Error?n:new Error("Failed to load audio source")}}async addBackgroundMusic(a){return this.addAudioTrack({...a,name:a.name||"Background Music"})}async addAudioTrack(a){const t=`audio-track-${this.nextId++}`,n=await this.resolveAudioSource(a.source),i=this.createAudioClipConfig(a,n),r=new Oi(i);let l=this.findAudioTrack();l||(l=await this.composition.createTrack("audio")),await l.add(r);const s={id:t,name:a.name||`Audio Track ${this.audioLayers.size+1}`,clip:r,track:l,config:a};return this.audioLayers.set(t,s),t}async resolveAudioSource(a){try{if(a instanceof ao)return a;if(typeof a=="string"&&a.trim()!=="")return await ao.from(a);if(a instanceof File)return await ao.from(URL.createObjectURL(a));throw new Error("Invalid audio source")}catch(t){throw t instanceof Error?t:new Error("Failed to create audio source")}}createAudioClipConfig(a,t){const n={source:t,volume:(a.volume??1)*this.masterVolume};if(a.startTime!==void 0&&(n.start=Ze.fromSeconds(a.startTime)),a.duration!==void 0){const i=a.startTime||0;n.stop=Ze.fromSeconds(i+a.duration)}return(a.fadeIn||a.fadeOut)&&(n.volume=this.createVolumeKeyframes(a)),n}findAudioTrack(){return this.composition.tracks.find(a=>a.kind==="audio")}removeClipFromTrack(a,t){const n=a.clips.indexOf(t);n!==-1&&a.clips.splice(n,1)}createVolumeKeyframes(a){const t=(a.volume??1)*this.masterVolume,n=a.startTime?Math.round(a.startTime*30):0,i=a.duration,r=[],l=[];if(a.fadeIn){const s=Math.round(a.fadeIn*30);r.push(n,n+s),l.push(0,t)}else r.push(n),l.push(t);if(a.fadeOut&&i){const s=n+Math.round(i*30),d=Math.round(a.fadeOut*30);a.fadeIn||(r.push(s-d),l.push(t)),r.push(s),l.push(0)}return new Ye(r,l,{easing:"linear"})}async updateVolume(a,t){const n=this.audioLayers.get(a);if(!n)throw new Error(`Audio track with id ${a} not found`);const i=Math.max(0,Math.min(1,t));n.config.volume=i,n.clip.set({volume:this.resolveLayerVolume(n.config)})}async updateAudioTrack(a,t){const n=this.audioLayers.get(a);if(!n)throw new Error(`Audio track with id ${a} not found`);const i={...n.config,...t,source:t.source??n.config.source},r=await this.resolveAudioSource(i.source),l=new Oi(this.createAudioClipConfig(i,r));this.removeClipFromTrack(n.track,n.clip),await n.track.add(l),n.clip=l,n.config=i,n.name=i.name||n.name}async applyFadeIn(a,t){const n=this.audioLayers.get(a);if(!n)throw new Error(`Audio track with id ${a} not found`);n.config.fadeIn=t,n.clip.set({volume:this.resolveLayerVolume(n.config)})}async applyFadeOut(a,t){const n=this.audioLayers.get(a);if(!n)throw new Error(`Audio track with id ${a} not found`);n.config.fadeOut=t,n.clip.set({volume:this.resolveLayerVolume(n.config)})}async removeAudioTrack(a){const t=this.audioLayers.get(a);if(!t)throw new Error(`Audio track with id ${a} not found`);this.removeClipFromTrack(t.track,t.clip),this.audioLayers.delete(a)}async muteTrack(a,t){const n=this.audioLayers.get(a);if(!n)throw new Error(`Audio track with id ${a} not found`);t?n.clip.set({volume:0}):n.clip.set({volume:this.resolveLayerVolume(n.config)})}setMasterVolume(a){this.masterVolume=Math.max(0,Math.min(1,a));for(const t of this.audioLayers.values())t.clip.set({volume:this.resolveLayerVolume(t.config)})}resolveLayerVolume(a){return a.fadeIn||a.fadeOut?this.createVolumeKeyframes(a):(a.volume??1)*this.masterVolume}getMasterVolume(){return this.masterVolume}getAudioLayers(){return Array.from(this.audioLayers.values())}getAudioLayer(a){return this.audioLayers.get(a)}async clearAllAudioTracks(){const a=Array.from(this.audioLayers.keys());for(const t of a)await this.removeAudioTrack(t)}async syncWithVideo(a,t){for(const n of this.audioLayers.values()){const i=n.config.startTime||0,r=n.config.duration||t-a;if(i+r>t){n.config.duration=t-i;const l=new Oi(this.createAudioClipConfig(n.config,n.clip.source)),s=n.track.clips.indexOf(n.clip);s!==-1&&(n.track.clips[s]=l,n.clip=l)}}}exportConfiguration(){return Array.from(this.audioLayers.values()).map(a=>({id:a.id,name:a.name,config:{...a.config,source:a.config.source&&typeof a.config.source=="object"&&"type"in a.config.source?"[AudioSource]":a.config.source}}))}async importConfiguration(a){for(const{name:t,config:n}of a)await this.addAudioTrack({...n,name:t})}}function Up(o,a){return function(){return o.apply(a,arguments)}}const{toString:FS}=Object.prototype,{getPrototypeOf:Ud}=Object,{iterator:Il,toStringTag:Op}=Symbol,$l=(o=>a=>{const t=FS.call(a);return o[t]||(o[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),ln=o=>(o=o.toLowerCase(),a=>$l(a)===o),Fl=o=>a=>typeof a===o,{isArray:pi}=Array,Qi=Fl("undefined");function ur(o){return o!==null&&!Qi(o)&&o.constructor!==null&&!Qi(o.constructor)&&$a(o.constructor.isBuffer)&&o.constructor.isBuffer(o)}const zp=ln("ArrayBuffer");function DS(o){let a;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?a=ArrayBuffer.isView(o):a=o&&o.buffer&&zp(o.buffer),a}const AS=Fl("string"),$a=Fl("function"),jp=Fl("number"),mr=o=>o!==null&&typeof o=="object",RS=o=>o===!0||o===!1,zr=o=>{if($l(o)!=="object")return!1;const a=Ud(o);return(a===null||a===Object.prototype||Object.getPrototypeOf(a)===null)&&!(Op in o)&&!(Il in o)},LS=o=>{if(!mr(o)||ur(o))return!1;try{return Object.keys(o).length===0&&Object.getPrototypeOf(o)===Object.prototype}catch{return!1}},PS=ln("Date"),US=ln("File"),OS=ln("Blob"),zS=ln("FileList"),jS=o=>mr(o)&&$a(o.pipe),WS=o=>{let a;return o&&(typeof FormData=="function"&&o instanceof FormData||$a(o.append)&&((a=$l(o))==="formdata"||a==="object"&&$a(o.toString)&&o.toString()==="[object FormData]"))},HS=ln("URLSearchParams"),[ZS,GS,XS,KS]=["ReadableStream","Request","Response","Headers"].map(ln),qS=o=>o.trim?o.trim():o.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function pr(o,a,{allOwnKeys:t=!1}={}){if(o===null||typeof o>"u")return;let n,i;if(typeof o!="object"&&(o=[o]),pi(o))for(n=0,i=o.length;n<i;n++)a.call(null,o[n],n,o);else{if(ur(o))return;const r=t?Object.getOwnPropertyNames(o):Object.keys(o),l=r.length;let s;for(n=0;n<l;n++)s=r[n],a.call(null,o[s],s,o)}}function Wp(o,a){if(ur(o))return null;a=a.toLowerCase();const t=Object.keys(o);let n=t.length,i;for(;n-- >0;)if(i=t[n],a===i.toLowerCase())return i;return null}const Bo=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Hp=o=>!Qi(o)&&o!==Bo;function ad(){const{caseless:o}=Hp(this)&&this||{},a={},t=(n,i)=>{const r=o&&Wp(a,i)||i;zr(a[r])&&zr(n)?a[r]=ad(a[r],n):zr(n)?a[r]=ad({},n):pi(n)?a[r]=n.slice():a[r]=n};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&pr(arguments[n],t);return a}const JS=(o,a,t,{allOwnKeys:n}={})=>(pr(a,(i,r)=>{t&&$a(i)?o[r]=Up(i,t):o[r]=i},{allOwnKeys:n}),o),YS=o=>(o.charCodeAt(0)===65279&&(o=o.slice(1)),o),QS=(o,a,t,n)=>{o.prototype=Object.create(a.prototype,n),o.prototype.constructor=o,Object.defineProperty(o,"super",{value:a.prototype}),t&&Object.assign(o.prototype,t)},eC=(o,a,t,n)=>{let i,r,l;const s={};if(a=a||{},o==null)return a;do{for(i=Object.getOwnPropertyNames(o),r=i.length;r-- >0;)l=i[r],(!n||n(l,o,a))&&!s[l]&&(a[l]=o[l],s[l]=!0);o=t!==!1&&Ud(o)}while(o&&(!t||t(o,a))&&o!==Object.prototype);return a},tC=(o,a,t)=>{o=String(o),(t===void 0||t>o.length)&&(t=o.length),t-=a.length;const n=o.indexOf(a,t);return n!==-1&&n===t},aC=o=>{if(!o)return null;if(pi(o))return o;let a=o.length;if(!jp(a))return null;const t=new Array(a);for(;a-- >0;)t[a]=o[a];return t},nC=(o=>a=>o&&a instanceof o)(typeof Uint8Array<"u"&&Ud(Uint8Array)),oC=(o,a)=>{const n=(o&&o[Il]).call(o);let i;for(;(i=n.next())&&!i.done;){const r=i.value;a.call(o,r[0],r[1])}},iC=(o,a)=>{let t;const n=[];for(;(t=o.exec(a))!==null;)n.push(t);return n},rC=ln("HTMLFormElement"),lC=o=>o.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,i){return n.toUpperCase()+i}),fu=(({hasOwnProperty:o})=>(a,t)=>o.call(a,t))(Object.prototype),sC=ln("RegExp"),Zp=(o,a)=>{const t=Object.getOwnPropertyDescriptors(o),n={};pr(t,(i,r)=>{let l;(l=a(i,r,o))!==!1&&(n[r]=l||i)}),Object.defineProperties(o,n)},dC=o=>{Zp(o,(a,t)=>{if($a(o)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const n=o[t];if($a(n)){if(a.enumerable=!1,"writable"in a){a.writable=!1;return}a.set||(a.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},cC=(o,a)=>{const t={},n=i=>{i.forEach(r=>{t[r]=!0})};return pi(o)?n(o):n(String(o).split(a)),t},uC=()=>{},mC=(o,a)=>o!=null&&Number.isFinite(o=+o)?o:a;function pC(o){return!!(o&&$a(o.append)&&o[Op]==="FormData"&&o[Il])}const fC=o=>{const a=new Array(10),t=(n,i)=>{if(mr(n)){if(a.indexOf(n)>=0)return;if(ur(n))return n;if(!("toJSON"in n)){a[i]=n;const r=pi(n)?[]:{};return pr(n,(l,s)=>{const d=t(l,i+1);!Qi(d)&&(r[s]=d)}),a[i]=void 0,r}}return n};return t(o,0)},hC=ln("AsyncFunction"),vC=o=>o&&(mr(o)||$a(o))&&$a(o.then)&&$a(o.catch),Gp=((o,a)=>o?setImmediate:a?((t,n)=>(Bo.addEventListener("message",({source:i,data:r})=>{i===Bo&&r===t&&n.length&&n.shift()()},!1),i=>{n.push(i),Bo.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",$a(Bo.postMessage)),gC=typeof queueMicrotask<"u"?queueMicrotask.bind(Bo):typeof process<"u"&&process.nextTick||Gp,bC=o=>o!=null&&$a(o[Il]),ve={isArray:pi,isArrayBuffer:zp,isBuffer:ur,isFormData:WS,isArrayBufferView:DS,isString:AS,isNumber:jp,isBoolean:RS,isObject:mr,isPlainObject:zr,isEmptyObject:LS,isReadableStream:ZS,isRequest:GS,isResponse:XS,isHeaders:KS,isUndefined:Qi,isDate:PS,isFile:US,isBlob:OS,isRegExp:sC,isFunction:$a,isStream:jS,isURLSearchParams:HS,isTypedArray:nC,isFileList:zS,forEach:pr,merge:ad,extend:JS,trim:qS,stripBOM:YS,inherits:QS,toFlatObject:eC,kindOf:$l,kindOfTest:ln,endsWith:tC,toArray:aC,forEachEntry:oC,matchAll:iC,isHTMLForm:rC,hasOwnProperty:fu,hasOwnProp:fu,reduceDescriptors:Zp,freezeMethods:dC,toObjectSet:cC,toCamelCase:lC,noop:uC,toFiniteNumber:mC,findKey:Wp,global:Bo,isContextDefined:Hp,isSpecCompliantForm:pC,toJSONObject:fC,isAsyncFn:hC,isThenable:vC,setImmediate:Gp,asap:gC,isIterable:bC};function dt(o,a,t,n,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=o,this.name="AxiosError",a&&(this.code=a),t&&(this.config=t),n&&(this.request=n),i&&(this.response=i,this.status=i.status?i.status:null)}ve.inherits(dt,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ve.toJSONObject(this.config),code:this.code,status:this.status}}});const Xp=dt.prototype,Kp={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(o=>{Kp[o]={value:o}});Object.defineProperties(dt,Kp);Object.defineProperty(Xp,"isAxiosError",{value:!0});dt.from=(o,a,t,n,i,r)=>{const l=Object.create(Xp);return ve.toFlatObject(o,l,function(d){return d!==Error.prototype},s=>s!=="isAxiosError"),dt.call(l,o.message,a,t,n,i),l.cause=o,l.name=o.name,r&&Object.assign(l,r),l};const yC=null;function nd(o){return ve.isPlainObject(o)||ve.isArray(o)}function qp(o){return ve.endsWith(o,"[]")?o.slice(0,-2):o}function hu(o,a,t){return o?o.concat(a).map(function(i,r){return i=qp(i),!t&&r?"["+i+"]":i}).join(t?".":""):a}function wC(o){return ve.isArray(o)&&!o.some(nd)}const kC=ve.toFlatObject(ve,{},null,function(a){return/^is[A-Z]/.test(a)});function Dl(o,a,t){if(!ve.isObject(o))throw new TypeError("target must be an object");a=a||new FormData,t=ve.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(v,y){return!ve.isUndefined(y[v])});const n=t.metaTokens,i=t.visitor||u,r=t.dots,l=t.indexes,d=(t.Blob||typeof Blob<"u"&&Blob)&&ve.isSpecCompliantForm(a);if(!ve.isFunction(i))throw new TypeError("visitor must be a function");function c(h){if(h===null)return"";if(ve.isDate(h))return h.toISOString();if(ve.isBoolean(h))return h.toString();if(!d&&ve.isBlob(h))throw new dt("Blob is not supported. Use a Buffer instead.");return ve.isArrayBuffer(h)||ve.isTypedArray(h)?d&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,v,y){let w=h;if(h&&!y&&typeof h=="object"){if(ve.endsWith(v,"{}"))v=n?v:v.slice(0,-2),h=JSON.stringify(h);else if(ve.isArray(h)&&wC(h)||(ve.isFileList(h)||ve.endsWith(v,"[]"))&&(w=ve.toArray(h)))return v=qp(v),w.forEach(function(b,g){!(ve.isUndefined(b)||b===null)&&a.append(l===!0?hu([v],g,r):l===null?v:v+"[]",c(b))}),!1}return nd(h)?!0:(a.append(hu(y,v,r),c(h)),!1)}const m=[],p=Object.assign(kC,{defaultVisitor:u,convertValue:c,isVisitable:nd});function f(h,v){if(!ve.isUndefined(h)){if(m.indexOf(h)!==-1)throw Error("Circular reference detected in "+v.join("."));m.push(h),ve.forEach(h,function(w,_){(!(ve.isUndefined(w)||w===null)&&i.call(a,w,ve.isString(_)?_.trim():_,v,p))===!0&&f(w,v?v.concat(_):[_])}),m.pop()}}if(!ve.isObject(o))throw new TypeError("data must be an object");return f(o),a}function vu(o){const a={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(o).replace(/[!'()~]|%20|%00/g,function(n){return a[n]})}function Od(o,a){this._pairs=[],o&&Dl(o,this,a)}const Jp=Od.prototype;Jp.append=function(a,t){this._pairs.push([a,t])};Jp.toString=function(a){const t=a?function(n){return a.call(this,n,vu)}:vu;return this._pairs.map(function(i){return t(i[0])+"="+t(i[1])},"").join("&")};function _C(o){return encodeURIComponent(o).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Yp(o,a,t){if(!a)return o;const n=t&&t.encode||_C;ve.isFunction(t)&&(t={serialize:t});const i=t&&t.serialize;let r;if(i?r=i(a,t):r=ve.isURLSearchParams(a)?a.toString():new Od(a,t).toString(n),r){const l=o.indexOf("#");l!==-1&&(o=o.slice(0,l)),o+=(o.indexOf("?")===-1?"?":"&")+r}return o}class gu{constructor(){this.handlers=[]}use(a,t,n){return this.handlers.push({fulfilled:a,rejected:t,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(a){this.handlers[a]&&(this.handlers[a]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(a){ve.forEach(this.handlers,function(n){n!==null&&a(n)})}}const Qp={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},EC=typeof URLSearchParams<"u"?URLSearchParams:Od,SC=typeof FormData<"u"?FormData:null,CC=typeof Blob<"u"?Blob:null,xC={isBrowser:!0,classes:{URLSearchParams:EC,FormData:SC,Blob:CC},protocols:["http","https","file","blob","url","data"]},zd=typeof window<"u"&&typeof document<"u",od=typeof navigator=="object"&&navigator||void 0,NC=zd&&(!od||["ReactNative","NativeScript","NS"].indexOf(od.product)<0),VC=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",TC=zd&&window.location.href||"http://localhost",BC=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:zd,hasStandardBrowserEnv:NC,hasStandardBrowserWebWorkerEnv:VC,navigator:od,origin:TC},Symbol.toStringTag,{value:"Module"})),Sa={...BC,...xC};function MC(o,a){return Dl(o,new Sa.classes.URLSearchParams,{visitor:function(t,n,i,r){return Sa.isNode&&ve.isBuffer(t)?(this.append(n,t.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)},...a})}function IC(o){return ve.matchAll(/\w+|\[(\w*)]/g,o).map(a=>a[0]==="[]"?"":a[1]||a[0])}function $C(o){const a={},t=Object.keys(o);let n;const i=t.length;let r;for(n=0;n<i;n++)r=t[n],a[r]=o[r];return a}function ef(o){function a(t,n,i,r){let l=t[r++];if(l==="__proto__")return!0;const s=Number.isFinite(+l),d=r>=t.length;return l=!l&&ve.isArray(i)?i.length:l,d?(ve.hasOwnProp(i,l)?i[l]=[i[l],n]:i[l]=n,!s):((!i[l]||!ve.isObject(i[l]))&&(i[l]=[]),a(t,n,i[l],r)&&ve.isArray(i[l])&&(i[l]=$C(i[l])),!s)}if(ve.isFormData(o)&&ve.isFunction(o.entries)){const t={};return ve.forEachEntry(o,(n,i)=>{a(IC(n),i,t,0)}),t}return null}function FC(o,a,t){if(ve.isString(o))try{return(a||JSON.parse)(o),ve.trim(o)}catch(n){if(n.name!=="SyntaxError")throw n}return(t||JSON.stringify)(o)}const fr={transitional:Qp,adapter:["xhr","http","fetch"],transformRequest:[function(a,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=ve.isObject(a);if(r&&ve.isHTMLForm(a)&&(a=new FormData(a)),ve.isFormData(a))return i?JSON.stringify(ef(a)):a;if(ve.isArrayBuffer(a)||ve.isBuffer(a)||ve.isStream(a)||ve.isFile(a)||ve.isBlob(a)||ve.isReadableStream(a))return a;if(ve.isArrayBufferView(a))return a.buffer;if(ve.isURLSearchParams(a))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),a.toString();let s;if(r){if(n.indexOf("application/x-www-form-urlencoded")>-1)return MC(a,this.formSerializer).toString();if((s=ve.isFileList(a))||n.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return Dl(s?{"files[]":a}:a,d&&new d,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),FC(a)):a}],transformResponse:[function(a){const t=this.transitional||fr.transitional,n=t&&t.forcedJSONParsing,i=this.responseType==="json";if(ve.isResponse(a)||ve.isReadableStream(a))return a;if(a&&ve.isString(a)&&(n&&!this.responseType||i)){const l=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(a)}catch(s){if(l)throw s.name==="SyntaxError"?dt.from(s,dt.ERR_BAD_RESPONSE,this,null,this.response):s}}return a}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Sa.classes.FormData,Blob:Sa.classes.Blob},validateStatus:function(a){return a>=200&&a<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ve.forEach(["delete","get","head","post","put","patch"],o=>{fr.headers[o]={}});const DC=ve.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),AC=o=>{const a={};let t,n,i;return o&&o.split(`
345
+ `).forEach(function(l){i=l.indexOf(":"),t=l.substring(0,i).trim().toLowerCase(),n=l.substring(i+1).trim(),!(!t||a[t]&&DC[t])&&(t==="set-cookie"?a[t]?a[t].push(n):a[t]=[n]:a[t]=a[t]?a[t]+", "+n:n)}),a},bu=Symbol("internals");function Si(o){return o&&String(o).trim().toLowerCase()}function jr(o){return o===!1||o==null?o:ve.isArray(o)?o.map(jr):String(o)}function RC(o){const a=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=t.exec(o);)a[n[1]]=n[2];return a}const LC=o=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(o.trim());function ms(o,a,t,n,i){if(ve.isFunction(n))return n.call(this,a,t);if(i&&(a=t),!!ve.isString(a)){if(ve.isString(n))return a.indexOf(n)!==-1;if(ve.isRegExp(n))return n.test(a)}}function PC(o){return o.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(a,t,n)=>t.toUpperCase()+n)}function UC(o,a){const t=ve.toCamelCase(" "+a);["get","set","has"].forEach(n=>{Object.defineProperty(o,n+t,{value:function(i,r,l){return this[n].call(this,a,i,r,l)},configurable:!0})})}let Fa=class{constructor(a){a&&this.set(a)}set(a,t,n){const i=this;function r(s,d,c){const u=Si(d);if(!u)throw new Error("header name must be a non-empty string");const m=ve.findKey(i,u);(!m||i[m]===void 0||c===!0||c===void 0&&i[m]!==!1)&&(i[m||d]=jr(s))}const l=(s,d)=>ve.forEach(s,(c,u)=>r(c,u,d));if(ve.isPlainObject(a)||a instanceof this.constructor)l(a,t);else if(ve.isString(a)&&(a=a.trim())&&!LC(a))l(AC(a),t);else if(ve.isObject(a)&&ve.isIterable(a)){let s={},d,c;for(const u of a){if(!ve.isArray(u))throw TypeError("Object iterator must return a key-value pair");s[c=u[0]]=(d=s[c])?ve.isArray(d)?[...d,u[1]]:[d,u[1]]:u[1]}l(s,t)}else a!=null&&r(t,a,n);return this}get(a,t){if(a=Si(a),a){const n=ve.findKey(this,a);if(n){const i=this[n];if(!t)return i;if(t===!0)return RC(i);if(ve.isFunction(t))return t.call(this,i,n);if(ve.isRegExp(t))return t.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(a,t){if(a=Si(a),a){const n=ve.findKey(this,a);return!!(n&&this[n]!==void 0&&(!t||ms(this,this[n],n,t)))}return!1}delete(a,t){const n=this;let i=!1;function r(l){if(l=Si(l),l){const s=ve.findKey(n,l);s&&(!t||ms(n,n[s],s,t))&&(delete n[s],i=!0)}}return ve.isArray(a)?a.forEach(r):r(a),i}clear(a){const t=Object.keys(this);let n=t.length,i=!1;for(;n--;){const r=t[n];(!a||ms(this,this[r],r,a,!0))&&(delete this[r],i=!0)}return i}normalize(a){const t=this,n={};return ve.forEach(this,(i,r)=>{const l=ve.findKey(n,r);if(l){t[l]=jr(i),delete t[r];return}const s=a?PC(r):String(r).trim();s!==r&&delete t[r],t[s]=jr(i),n[s]=!0}),this}concat(...a){return this.constructor.concat(this,...a)}toJSON(a){const t=Object.create(null);return ve.forEach(this,(n,i)=>{n!=null&&n!==!1&&(t[i]=a&&ve.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([a,t])=>a+": "+t).join(`
346
+ `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(a){return a instanceof this?a:new this(a)}static concat(a,...t){const n=new this(a);return t.forEach(i=>n.set(i)),n}static accessor(a){const n=(this[bu]=this[bu]={accessors:{}}).accessors,i=this.prototype;function r(l){const s=Si(l);n[s]||(UC(i,l),n[s]=!0)}return ve.isArray(a)?a.forEach(r):r(a),this}};Fa.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ve.reduceDescriptors(Fa.prototype,({value:o},a)=>{let t=a[0].toUpperCase()+a.slice(1);return{get:()=>o,set(n){this[t]=n}}});ve.freezeMethods(Fa);function ps(o,a){const t=this||fr,n=a||t,i=Fa.from(n.headers);let r=n.data;return ve.forEach(o,function(s){r=s.call(t,r,i.normalize(),a?a.status:void 0)}),i.normalize(),r}function tf(o){return!!(o&&o.__CANCEL__)}function fi(o,a,t){dt.call(this,o??"canceled",dt.ERR_CANCELED,a,t),this.name="CanceledError"}ve.inherits(fi,dt,{__CANCEL__:!0});function af(o,a,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?o(t):a(new dt("Request failed with status code "+t.status,[dt.ERR_BAD_REQUEST,dt.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function OC(o){const a=/^([-+\w]{1,25})(:?\/\/|:)/.exec(o);return a&&a[1]||""}function zC(o,a){o=o||10;const t=new Array(o),n=new Array(o);let i=0,r=0,l;return a=a!==void 0?a:1e3,function(d){const c=Date.now(),u=n[r];l||(l=c),t[i]=d,n[i]=c;let m=r,p=0;for(;m!==i;)p+=t[m++],m=m%o;if(i=(i+1)%o,i===r&&(r=(r+1)%o),c-l<a)return;const f=u&&c-u;return f?Math.round(p*1e3/f):void 0}}function jC(o,a){let t=0,n=1e3/a,i,r;const l=(c,u=Date.now())=>{t=u,i=null,r&&(clearTimeout(r),r=null),o(...c)};return[(...c)=>{const u=Date.now(),m=u-t;m>=n?l(c,u):(i=c,r||(r=setTimeout(()=>{r=null,l(i)},n-m)))},()=>i&&l(i)]}const il=(o,a,t=3)=>{let n=0;const i=zC(50,250);return jC(r=>{const l=r.loaded,s=r.lengthComputable?r.total:void 0,d=l-n,c=i(d),u=l<=s;n=l;const m={loaded:l,total:s,progress:s?l/s:void 0,bytes:d,rate:c||void 0,estimated:c&&s&&u?(s-l)/c:void 0,event:r,lengthComputable:s!=null,[a?"download":"upload"]:!0};o(m)},t)},yu=(o,a)=>{const t=o!=null;return[n=>a[0]({lengthComputable:t,total:o,loaded:n}),a[1]]},wu=o=>(...a)=>ve.asap(()=>o(...a)),WC=Sa.hasStandardBrowserEnv?((o,a)=>t=>(t=new URL(t,Sa.origin),o.protocol===t.protocol&&o.host===t.host&&(a||o.port===t.port)))(new URL(Sa.origin),Sa.navigator&&/(msie|trident)/i.test(Sa.navigator.userAgent)):()=>!0,HC=Sa.hasStandardBrowserEnv?{write(o,a,t,n,i,r){const l=[o+"="+encodeURIComponent(a)];ve.isNumber(t)&&l.push("expires="+new Date(t).toGMTString()),ve.isString(n)&&l.push("path="+n),ve.isString(i)&&l.push("domain="+i),r===!0&&l.push("secure"),document.cookie=l.join("; ")},read(o){const a=document.cookie.match(new RegExp("(^|;\\s*)("+o+")=([^;]*)"));return a?decodeURIComponent(a[3]):null},remove(o){this.write(o,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function ZC(o){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(o)}function GC(o,a){return a?o.replace(/\/?\/$/,"")+"/"+a.replace(/^\/+/,""):o}function nf(o,a,t){let n=!ZC(a);return o&&(n||t==!1)?GC(o,a):a}const ku=o=>o instanceof Fa?{...o}:o;function Ao(o,a){a=a||{};const t={};function n(c,u,m,p){return ve.isPlainObject(c)&&ve.isPlainObject(u)?ve.merge.call({caseless:p},c,u):ve.isPlainObject(u)?ve.merge({},u):ve.isArray(u)?u.slice():u}function i(c,u,m,p){if(ve.isUndefined(u)){if(!ve.isUndefined(c))return n(void 0,c,m,p)}else return n(c,u,m,p)}function r(c,u){if(!ve.isUndefined(u))return n(void 0,u)}function l(c,u){if(ve.isUndefined(u)){if(!ve.isUndefined(c))return n(void 0,c)}else return n(void 0,u)}function s(c,u,m){if(m in a)return n(c,u);if(m in o)return n(void 0,c)}const d={url:r,method:r,data:r,baseURL:l,transformRequest:l,transformResponse:l,paramsSerializer:l,timeout:l,timeoutMessage:l,withCredentials:l,withXSRFToken:l,adapter:l,responseType:l,xsrfCookieName:l,xsrfHeaderName:l,onUploadProgress:l,onDownloadProgress:l,decompress:l,maxContentLength:l,maxBodyLength:l,beforeRedirect:l,transport:l,httpAgent:l,httpsAgent:l,cancelToken:l,socketPath:l,responseEncoding:l,validateStatus:s,headers:(c,u,m)=>i(ku(c),ku(u),m,!0)};return ve.forEach(Object.keys({...o,...a}),function(u){const m=d[u]||i,p=m(o[u],a[u],u);ve.isUndefined(p)&&m!==s||(t[u]=p)}),t}const of=o=>{const a=Ao({},o);let{data:t,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:r,headers:l,auth:s}=a;a.headers=l=Fa.from(l),a.url=Yp(nf(a.baseURL,a.url,a.allowAbsoluteUrls),o.params,o.paramsSerializer),s&&l.set("Authorization","Basic "+btoa((s.username||"")+":"+(s.password?unescape(encodeURIComponent(s.password)):"")));let d;if(ve.isFormData(t)){if(Sa.hasStandardBrowserEnv||Sa.hasStandardBrowserWebWorkerEnv)l.setContentType(void 0);else if((d=l.getContentType())!==!1){const[c,...u]=d?d.split(";").map(m=>m.trim()).filter(Boolean):[];l.setContentType([c||"multipart/form-data",...u].join("; "))}}if(Sa.hasStandardBrowserEnv&&(n&&ve.isFunction(n)&&(n=n(a)),n||n!==!1&&WC(a.url))){const c=i&&r&&HC.read(r);c&&l.set(i,c)}return a},XC=typeof XMLHttpRequest<"u",KC=XC&&function(o){return new Promise(function(t,n){const i=of(o);let r=i.data;const l=Fa.from(i.headers).normalize();let{responseType:s,onUploadProgress:d,onDownloadProgress:c}=i,u,m,p,f,h;function v(){f&&f(),h&&h(),i.cancelToken&&i.cancelToken.unsubscribe(u),i.signal&&i.signal.removeEventListener("abort",u)}let y=new XMLHttpRequest;y.open(i.method.toUpperCase(),i.url,!0),y.timeout=i.timeout;function w(){if(!y)return;const b=Fa.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),I={data:!s||s==="text"||s==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:b,config:o,request:y};af(function($){t($),v()},function($){n($),v()},I),y=null}"onloadend"in y?y.onloadend=w:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(w)},y.onabort=function(){y&&(n(new dt("Request aborted",dt.ECONNABORTED,o,y)),y=null)},y.onerror=function(){n(new dt("Network Error",dt.ERR_NETWORK,o,y)),y=null},y.ontimeout=function(){let g=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const I=i.transitional||Qp;i.timeoutErrorMessage&&(g=i.timeoutErrorMessage),n(new dt(g,I.clarifyTimeoutError?dt.ETIMEDOUT:dt.ECONNABORTED,o,y)),y=null},r===void 0&&l.setContentType(null),"setRequestHeader"in y&&ve.forEach(l.toJSON(),function(g,I){y.setRequestHeader(I,g)}),ve.isUndefined(i.withCredentials)||(y.withCredentials=!!i.withCredentials),s&&s!=="json"&&(y.responseType=i.responseType),c&&([p,h]=il(c,!0),y.addEventListener("progress",p)),d&&y.upload&&([m,f]=il(d),y.upload.addEventListener("progress",m),y.upload.addEventListener("loadend",f)),(i.cancelToken||i.signal)&&(u=b=>{y&&(n(!b||b.type?new fi(null,o,y):b),y.abort(),y=null)},i.cancelToken&&i.cancelToken.subscribe(u),i.signal&&(i.signal.aborted?u():i.signal.addEventListener("abort",u)));const _=OC(i.url);if(_&&Sa.protocols.indexOf(_)===-1){n(new dt("Unsupported protocol "+_+":",dt.ERR_BAD_REQUEST,o));return}y.send(r||null)})},qC=(o,a)=>{const{length:t}=o=o?o.filter(Boolean):[];if(a||t){let n=new AbortController,i;const r=function(c){if(!i){i=!0,s();const u=c instanceof Error?c:this.reason;n.abort(u instanceof dt?u:new fi(u instanceof Error?u.message:u))}};let l=a&&setTimeout(()=>{l=null,r(new dt(`timeout ${a} of ms exceeded`,dt.ETIMEDOUT))},a);const s=()=>{o&&(l&&clearTimeout(l),l=null,o.forEach(c=>{c.unsubscribe?c.unsubscribe(r):c.removeEventListener("abort",r)}),o=null)};o.forEach(c=>c.addEventListener("abort",r));const{signal:d}=n;return d.unsubscribe=()=>ve.asap(s),d}},JC=function*(o,a){let t=o.byteLength;if(t<a){yield o;return}let n=0,i;for(;n<t;)i=n+a,yield o.slice(n,i),n=i},YC=async function*(o,a){for await(const t of QC(o))yield*JC(t,a)},QC=async function*(o){if(o[Symbol.asyncIterator]){yield*o;return}const a=o.getReader();try{for(;;){const{done:t,value:n}=await a.read();if(t)break;yield n}}finally{await a.cancel()}},_u=(o,a,t,n)=>{const i=YC(o,a);let r=0,l,s=d=>{l||(l=!0,n&&n(d))};return new ReadableStream({async pull(d){try{const{done:c,value:u}=await i.next();if(c){s(),d.close();return}let m=u.byteLength;if(t){let p=r+=m;t(p)}d.enqueue(new Uint8Array(u))}catch(c){throw s(c),c}},cancel(d){return s(d),i.return()}},{highWaterMark:2})},Al=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",rf=Al&&typeof ReadableStream=="function",ex=Al&&(typeof TextEncoder=="function"?(o=>a=>o.encode(a))(new TextEncoder):async o=>new Uint8Array(await new Response(o).arrayBuffer())),lf=(o,...a)=>{try{return!!o(...a)}catch{return!1}},tx=rf&&lf(()=>{let o=!1;const a=new Request(Sa.origin,{body:new ReadableStream,method:"POST",get duplex(){return o=!0,"half"}}).headers.has("Content-Type");return o&&!a}),Eu=64*1024,id=rf&&lf(()=>ve.isReadableStream(new Response("").body)),rl={stream:id&&(o=>o.body)};Al&&(o=>{["text","arrayBuffer","blob","formData","stream"].forEach(a=>{!rl[a]&&(rl[a]=ve.isFunction(o[a])?t=>t[a]():(t,n)=>{throw new dt(`Response type '${a}' is not supported`,dt.ERR_NOT_SUPPORT,n)})})})(new Response);const ax=async o=>{if(o==null)return 0;if(ve.isBlob(o))return o.size;if(ve.isSpecCompliantForm(o))return(await new Request(Sa.origin,{method:"POST",body:o}).arrayBuffer()).byteLength;if(ve.isArrayBufferView(o)||ve.isArrayBuffer(o))return o.byteLength;if(ve.isURLSearchParams(o)&&(o=o+""),ve.isString(o))return(await ex(o)).byteLength},nx=async(o,a)=>{const t=ve.toFiniteNumber(o.getContentLength());return t??ax(a)},ox=Al&&(async o=>{let{url:a,method:t,data:n,signal:i,cancelToken:r,timeout:l,onDownloadProgress:s,onUploadProgress:d,responseType:c,headers:u,withCredentials:m="same-origin",fetchOptions:p}=of(o);c=c?(c+"").toLowerCase():"text";let f=qC([i,r&&r.toAbortSignal()],l),h;const v=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let y;try{if(d&&tx&&t!=="get"&&t!=="head"&&(y=await nx(u,n))!==0){let I=new Request(a,{method:"POST",body:n,duplex:"half"}),T;if(ve.isFormData(n)&&(T=I.headers.get("content-type"))&&u.setContentType(T),I.body){const[$,N]=yu(y,il(wu(d)));n=_u(I.body,Eu,$,N)}}ve.isString(m)||(m=m?"include":"omit");const w="credentials"in Request.prototype;h=new Request(a,{...p,signal:f,method:t.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:w?m:void 0});let _=await fetch(h,p);const b=id&&(c==="stream"||c==="response");if(id&&(s||b&&v)){const I={};["status","statusText","headers"].forEach(B=>{I[B]=_[B]});const T=ve.toFiniteNumber(_.headers.get("content-length")),[$,N]=s&&yu(T,il(wu(s),!0))||[];_=new Response(_u(_.body,Eu,$,()=>{N&&N(),v&&v()}),I)}c=c||"text";let g=await rl[ve.findKey(rl,c)||"text"](_,o);return!b&&v&&v(),await new Promise((I,T)=>{af(I,T,{data:g,headers:Fa.from(_.headers),status:_.status,statusText:_.statusText,config:o,request:h})})}catch(w){throw v&&v(),w&&w.name==="TypeError"&&/Load failed|fetch/i.test(w.message)?Object.assign(new dt("Network Error",dt.ERR_NETWORK,o,h),{cause:w.cause||w}):dt.from(w,w&&w.code,o,h)}}),rd={http:yC,xhr:KC,fetch:ox};ve.forEach(rd,(o,a)=>{if(o){try{Object.defineProperty(o,"name",{value:a})}catch{}Object.defineProperty(o,"adapterName",{value:a})}});const Su=o=>`- ${o}`,ix=o=>ve.isFunction(o)||o===null||o===!1,sf={getAdapter:o=>{o=ve.isArray(o)?o:[o];const{length:a}=o;let t,n;const i={};for(let r=0;r<a;r++){t=o[r];let l;if(n=t,!ix(t)&&(n=rd[(l=String(t)).toLowerCase()],n===void 0))throw new dt(`Unknown adapter '${l}'`);if(n)break;i[l||"#"+r]=n}if(!n){const r=Object.entries(i).map(([s,d])=>`adapter ${s} `+(d===!1?"is not supported by the environment":"is not available in the build"));let l=a?r.length>1?`since :
347
+ `+r.map(Su).join(`
348
+ `):" "+Su(r[0]):"as no adapter specified";throw new dt("There is no suitable adapter to dispatch the request "+l,"ERR_NOT_SUPPORT")}return n},adapters:rd};function fs(o){if(o.cancelToken&&o.cancelToken.throwIfRequested(),o.signal&&o.signal.aborted)throw new fi(null,o)}function Cu(o){return fs(o),o.headers=Fa.from(o.headers),o.data=ps.call(o,o.transformRequest),["post","put","patch"].indexOf(o.method)!==-1&&o.headers.setContentType("application/x-www-form-urlencoded",!1),sf.getAdapter(o.adapter||fr.adapter)(o).then(function(n){return fs(o),n.data=ps.call(o,o.transformResponse,n),n.headers=Fa.from(n.headers),n},function(n){return tf(n)||(fs(o),n&&n.response&&(n.response.data=ps.call(o,o.transformResponse,n.response),n.response.headers=Fa.from(n.response.headers))),Promise.reject(n)})}const df="1.11.0",Rl={};["object","boolean","number","function","string","symbol"].forEach((o,a)=>{Rl[o]=function(n){return typeof n===o||"a"+(a<1?"n ":" ")+o}});const xu={};Rl.transitional=function(a,t,n){function i(r,l){return"[Axios v"+df+"] Transitional option '"+r+"'"+l+(n?". "+n:"")}return(r,l,s)=>{if(a===!1)throw new dt(i(l," has been removed"+(t?" in "+t:"")),dt.ERR_DEPRECATED);return t&&!xu[l]&&(xu[l]=!0),a?a(r,l,s):!0}};Rl.spelling=function(a){return(t,n)=>!0};function rx(o,a,t){if(typeof o!="object")throw new dt("options must be an object",dt.ERR_BAD_OPTION_VALUE);const n=Object.keys(o);let i=n.length;for(;i-- >0;){const r=n[i],l=a[r];if(l){const s=o[r],d=s===void 0||l(s,r,o);if(d!==!0)throw new dt("option "+r+" must be "+d,dt.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new dt("Unknown option "+r,dt.ERR_BAD_OPTION)}}const Wr={assertOptions:rx,validators:Rl},hn=Wr.validators;let Io=class{constructor(a){this.defaults=a||{},this.interceptors={request:new gu,response:new gu}}async request(a,t){try{return await this._request(a,t)}catch(n){if(n instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const r=i.stack?i.stack.replace(/^.+\n/,""):"";try{n.stack?r&&!String(n.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(n.stack+=`
349
+ `+r):n.stack=r}catch{}}throw n}}_request(a,t){typeof a=="string"?(t=t||{},t.url=a):t=a||{},t=Ao(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;n!==void 0&&Wr.assertOptions(n,{silentJSONParsing:hn.transitional(hn.boolean),forcedJSONParsing:hn.transitional(hn.boolean),clarifyTimeoutError:hn.transitional(hn.boolean)},!1),i!=null&&(ve.isFunction(i)?t.paramsSerializer={serialize:i}:Wr.assertOptions(i,{encode:hn.function,serialize:hn.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Wr.assertOptions(t,{baseUrl:hn.spelling("baseURL"),withXsrfToken:hn.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let l=r&&ve.merge(r.common,r[t.method]);r&&ve.forEach(["delete","get","head","post","put","patch","common"],h=>{delete r[h]}),t.headers=Fa.concat(l,r);const s=[];let d=!0;this.interceptors.request.forEach(function(v){typeof v.runWhen=="function"&&v.runWhen(t)===!1||(d=d&&v.synchronous,s.unshift(v.fulfilled,v.rejected))});const c=[];this.interceptors.response.forEach(function(v){c.push(v.fulfilled,v.rejected)});let u,m=0,p;if(!d){const h=[Cu.bind(this),void 0];for(h.unshift(...s),h.push(...c),p=h.length,u=Promise.resolve(t);m<p;)u=u.then(h[m++],h[m++]);return u}p=s.length;let f=t;for(m=0;m<p;){const h=s[m++],v=s[m++];try{f=h(f)}catch(y){v.call(this,y);break}}try{u=Cu.call(this,f)}catch(h){return Promise.reject(h)}for(m=0,p=c.length;m<p;)u=u.then(c[m++],c[m++]);return u}getUri(a){a=Ao(this.defaults,a);const t=nf(a.baseURL,a.url,a.allowAbsoluteUrls);return Yp(t,a.params,a.paramsSerializer)}};ve.forEach(["delete","get","head","options"],function(a){Io.prototype[a]=function(t,n){return this.request(Ao(n||{},{method:a,url:t,data:(n||{}).data}))}});ve.forEach(["post","put","patch"],function(a){function t(n){return function(r,l,s){return this.request(Ao(s||{},{method:a,headers:n?{"Content-Type":"multipart/form-data"}:{},url:r,data:l}))}}Io.prototype[a]=t(),Io.prototype[a+"Form"]=t(!0)});let lx=class cf{constructor(a){if(typeof a!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(r){t=r});const n=this;this.promise.then(i=>{if(!n._listeners)return;let r=n._listeners.length;for(;r-- >0;)n._listeners[r](i);n._listeners=null}),this.promise.then=i=>{let r;const l=new Promise(s=>{n.subscribe(s),r=s}).then(i);return l.cancel=function(){n.unsubscribe(r)},l},a(function(r,l,s){n.reason||(n.reason=new fi(r,l,s),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(a){if(this.reason){a(this.reason);return}this._listeners?this._listeners.push(a):this._listeners=[a]}unsubscribe(a){if(!this._listeners)return;const t=this._listeners.indexOf(a);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const a=new AbortController,t=n=>{a.abort(n)};return this.subscribe(t),a.signal.unsubscribe=()=>this.unsubscribe(t),a.signal}static source(){let a;return{token:new cf(function(i){a=i}),cancel:a}}};function sx(o){return function(t){return o.apply(null,t)}}function dx(o){return ve.isObject(o)&&o.isAxiosError===!0}const ld={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ld).forEach(([o,a])=>{ld[a]=o});function uf(o){const a=new Io(o),t=Up(Io.prototype.request,a);return ve.extend(t,Io.prototype,a,{allOwnKeys:!0}),ve.extend(t,a,null,{allOwnKeys:!0}),t.create=function(i){return uf(Ao(o,i))},t}const aa=uf(fr);aa.Axios=Io;aa.CanceledError=fi;aa.CancelToken=lx;aa.isCancel=tf;aa.VERSION=df;aa.toFormData=Dl;aa.AxiosError=dt;aa.Cancel=aa.CanceledError;aa.all=function(a){return Promise.all(a)};aa.spread=sx;aa.isAxiosError=dx;aa.mergeConfig=Ao;aa.AxiosHeaders=Fa;aa.formToJSON=o=>ef(ve.isHTMLForm(o)?new FormData(o):o);aa.getAdapter=sf.getAdapter;aa.HttpStatusCode=ld;aa.default=aa;const{Axios:LO,AxiosError:PO,CanceledError:UO,isCancel:OO,CancelToken:zO,VERSION:jO,all:WO,Cancel:HO,isAxiosError:ZO,spread:GO,toFormData:XO,AxiosHeaders:KO,HttpStatusCode:qO,formToJSON:JO,getAdapter:YO,mergeConfig:QO}=aa;class Ll{constructor(a="/api/v1"){this.eventSource=null,this.progressCallbacks=new Map,this.api=aa.create({baseURL:a,headers:{"Content-Type":"application/json",Accept:"application/json"}}),this.api.interceptors.request.use(t=>{const n=this.getAuthToken();return n&&(t.headers.Authorization=`Bearer ${n}`),t}),this.api.interceptors.response.use(t=>t,t=>{var n;return(n=t.response)==null||n.status,Promise.reject(t)})}async createJob(a){try{const t=await this.api.post("/video/jobs",a);return this.normalizeJob(t.data.data)}catch(t){throw t}}async createRenderJob(a){try{const t=await this.api.post("/video/jobs/render",a);return this.normalizeJob(t.data.data)}catch(t){throw t}}async pollRenderJob(a,t,n=3e3,i=6e5){const r=Date.now();return new Promise((l,s)=>{const d=setInterval(async()=>{try{const c=await this.getJob(a);t==null||t(c.progress,c.status),c.status==="completed"?(clearInterval(d),l(c)):c.status==="failed"?(clearInterval(d),s(new Error(c.error_message??"Render job failed"))):c.status==="cancelled"?(clearInterval(d),s(new Error("Render job cancelled"))):Date.now()-r>i&&(clearInterval(d),s(new Error("Render job timed out")))}catch(c){clearInterval(d),s(c)}},n)})}async getJob(a){try{const t=await this.api.get(`/video/jobs/${a}`);return this.normalizeJob(t.data.data)}catch(t){throw t}}async listJobs(a){try{return(await this.api.get("/video/jobs",{params:a})).data}catch(t){throw t}}async cancelJob(a){try{const t=await this.api.delete(`/video/jobs/${a}`);return this.unsubscribeFromProgress(a),this.normalizeJob(t.data.data)}catch(t){throw t}}async retryJob(a){try{const t=await this.api.post(`/video/jobs/${a}/retry`);return this.normalizeJob(t.data.data)}catch(t){throw t}}subscribeToProgress(a,t){this.progressCallbacks.set(a,t),this.eventSource||this.initializeEventSource(),this.eventSource||this.pollProgress(a)}unsubscribeFromProgress(a){this.progressCallbacks.delete(a),this.progressCallbacks.size===0&&this.eventSource&&(this.eventSource.close(),this.eventSource=null)}initializeEventSource(){try{const a=this.getAuthToken(),t=`/api/v1/video/jobs/events${a?`?token=${a}`:""}`;this.eventSource=new EventSource(t),this.eventSource.addEventListener("progress",n=>{const i=JSON.parse(n.data),r=this.progressCallbacks.get(i.jobId);r&&r(i.progress)}),this.eventSource.addEventListener("complete",n=>{const i=JSON.parse(n.data),r=this.progressCallbacks.get(i.jobId);r&&(r(100),this.unsubscribeFromProgress(i.jobId))}),this.eventSource.addEventListener("error",n=>{this.progressCallbacks.forEach((i,r)=>{this.pollProgress(r)})})}catch{}}async pollProgress(a){const t=setInterval(async()=>{try{const n=await this.getJob(a),i=this.progressCallbacks.get(a);i&&i(n.progress),(n.status==="completed"||n.status==="failed"||n.status==="cancelled")&&(clearInterval(t),this.unsubscribeFromProgress(a))}catch{clearInterval(t)}},2e3)}getAuthToken(){const a=localStorage.getItem("auth_token");if(a)return a;const t=document.cookie.split(";");for(const n of t){const[i,r]=n.trim().split("=");if(i==="auth_token")return decodeURIComponent(r)}return null}async downloadVideo(a){try{return(await this.api.get(`/video/jobs/${a}/download`,{responseType:"blob"})).data}catch(t){throw t}}async getThumbnail(a,t=0){try{const n=await this.api.get(`/video/jobs/${a}/thumbnail`,{params:{time:t},responseType:"blob"});return URL.createObjectURL(n.data)}catch(n){throw n}}normalizeJob(a){const t=a,n={...t,user_id:t.user_id??t.userId??"",source_media_id:t.source_media_id??t.sourceMediaId??"",created_at:t.created_at??t.createdAt??"",updated_at:t.updated_at??t.updatedAt??""},i=t.output_media_id??t.outputMediaId;typeof i=="string"&&i!==""&&(n.output_media_id=i);const r=t.error_message??t.errorMessage;typeof r=="string"&&r!==""&&(n.error_message=r);const l=t.progress_message??t.progressMessage;typeof l=="string"&&l!==""&&(n.progress_message=l);const s=t.progress_detail??t.progressDetail;s&&typeof s=="object"&&(n.progress_detail=s);const d=t.started_at??t.startedAt;typeof d=="string"&&d!==""&&(n.started_at=d);const c=t.completed_at??t.completedAt;typeof c=="string"&&c!==""&&(n.completed_at=c);const u=t.cancelled_at??t.cancelledAt;return typeof u=="string"&&u!==""&&(n.cancelled_at=u),n}}new Ll;const cx={key:0,class:"mobile-layout"},ux={class:"mobile-toolbar"},mx={class:"mobile-toolbar-left"},px=["aria-label"],fx={class:"mobile-toolbar-right"},hx=["disabled"],vx=["disabled"],gx={class:"preview-section"},bx={key:0,class:"mobile-export-overlay"},yx={class:"mobile-export-progress"},wx={class:"mobile-export-bar"},kx={class:"mobile-timeline-zoom"},_x={class:"mobile-edit-strip"},Ex={class:"mobile-selection-summary"},Sx={class:"mobile-selection-title"},Cx={class:"mobile-selection-meta"},xx={class:"mobile-readout-row"},Nx=["disabled"],Vx={class:"mobile-readout-grid"},Tx={class:"mobile-readout-chip","data-testid":"mobile-playhead-readout"},Bx={class:"mobile-readout-chip","data-testid":"mobile-clip-in-readout"},Mx={class:"mobile-readout-chip","data-testid":"mobile-clip-out-readout"},Ix={class:"mobile-readout-chip","data-testid":"mobile-duration-readout"},$x=["disabled"],Fx={class:"mobile-speed-strip"},Dx={class:"mobile-speed-chips"},Ax=["data-testid","onClick"],Rx={class:"mobile-edit-actions"},Lx=["disabled"],Px=["disabled"],Ux=["disabled"],Ox=["disabled"],zx=["disabled"],jx={class:"mobile-action-sheet-header"},Wx={class:"mobile-action-sheet-title"},Hx={class:"mobile-action-sheet-subtitle"},Zx={class:"mobile-action-sheet-actions"},Gx=["disabled"],Xx=["disabled"],Kx=["disabled"],qx=["disabled"],Jx=["disabled"],Yx={key:1,class:"desktop-layout"},Qx={class:"desktop-main-row"},eN={class:"preview-panel"},tN={class:"fit-toggle"},aN={class:"editor-content"},nN={class:"editor-tabs"},oN={class:"tab-header"},iN=["onClick"],rN={class:"tab-content-area"},lN={class:"filter-controls"},sN={class:"text-controls"},dN={class:"transition-controls"},cN={class:"audio-controls"},uN={class:"adjustments-controls"},mN={key:1,class:"no-filter-selected"},pN={class:"export-controls"},fN={key:0,"data-testid":"video-export-status-completed"},hN={key:1,"data-testid":"video-export-status-message",class:"export-status-message"},vN={class:"desktop-timeline-row"},gN={class:"timeline-zoom"},bN=["value"],yN={class:"zoom-readout"},wN={key:0,class:"dev-editor-controls","data-testid":"video-editor-dev-controls"},kN={class:"dev-editor-row"},_N={class:"dev-editor-field"},EN={class:"dev-editor-field"},SN=["disabled"],CN=["disabled"],xN=["disabled"],NN={class:"dev-editor-row"},VN={class:"dev-editor-field dev-editor-field--wide"},TN=["value"],BN=["disabled"],MN=["disabled"],IN=["disabled"],$N=["disabled"],FN=e.defineComponent({__name:"VideoEditor",props:{mediaUuid:{},initialRecipe:{},media:{},showThumbnailPicker:{type:Boolean,default:!1},workflowMode:{default:"full"},featureFlags:{},clientExportThreshold:{default:20},maxDuration:{default:300},serverRenderEndpoint:{default:null}},emits:["recipe-generated","export-started","draft-saved","video-exported","thumbnail-selected","server-render-started","server-render-progress","server-render-completed","server-render-failed","close"],setup(o,{expose:a,emit:t}){const n=o,i=t,r=e.computed(()=>{if(!n.media||typeof n.media!="object")return;const V=n.media.uuid??n.media.id;return typeof V=="string"&&V.trim()!==""?V.trim():void 0}),l=e.computed(()=>{const V=typeof n.mediaUuid=="string"?n.mediaUuid.trim():"";return V!==""?V:r.value??`temp-${Date.now()}`}),s=e.ref(typeof window<"u"?window.innerWidth<768:!1),d=e.ref("filters"),c=e.ref("filters"),u=e.computed(()=>{const V=n.workflowMode==="uploader"?{filters:!0,adjustments:!0,text:!1,transitions:!1,audio:!1,export:!1}:{filters:!0,adjustments:!0,text:!0,transitions:!0,audio:!0,export:!0},U=n.featureFlags;return U?{filters:typeof U.filters=="boolean"?U.filters:V.filters,adjustments:typeof U.adjustments=="boolean"?U.adjustments:V.adjustments,text:typeof U.text=="boolean"?U.text:V.text,transitions:typeof U.transitions=="boolean"?U.transitions:V.transitions,audio:typeof U.audio=="boolean"?U.audio:V.audio,export:typeof U.export=="boolean"?U.export:V.export}:V}),m=e.computed(()=>s.value?d.value:c.value),p=e.computed(()=>m.value==="filters"||y.value),f=e.computed(()=>m.value!=="filters"&&!y.value),h=e.ref(null),v=e.ref(null),y=e.ref(!1),w=e.computed(()=>s.value?h.value:v.value);function _(V){return V==="contain"||V==="cover"||V==="none"}function b(V){if(!(V!=null&&V.metadata))return null;const U=V.metadata.fit_mode;return _(U)?U:null}const g=e.shallowRef(null),I=e.ref(null),T=e.ref(b(n.initialRecipe)??"contain"),$=e.ref(null),N=e.ref(null),B=e.ref(null),P=e.ref(!1),x=new Map,M=e.ref([]),E=e.ref([]),D=e.ref([]),j=e.ref([]),L=e.ref(1),z=()=>{s.value=window.innerWidth<768},C=[{id:"filters",label:"Filters",icon:to},{id:"adjustments",label:"Adjust",icon:Ev},{id:"text",label:"Text",icon:"text-outline"},{id:"transitions",label:"Transitions",icon:"swap-horizontal-outline"},{id:"audio",label:"Audio",icon:"musical-notes-outline"},{id:"export",label:"Export",icon:ni}],A=[{id:"filters",label:"Filters"},{id:"adjustments",label:"Adjustments"},{id:"text",label:"Text"},{id:"transitions",label:"Transitions"},{id:"audio",label:"Audio"},{id:"export",label:"Export"}],O=e.computed(()=>C.filter(V=>u.value[V.id])),K=e.computed(()=>A.filter(V=>u.value[V.id])),se=e.computed(()=>{var V,U;return((V=K.value[0])==null?void 0:V.id)??((U=O.value[0])==null?void 0:U.id)??"filters"});e.watch(u,V=>{V[d.value]||(d.value=se.value),V[c.value]||(c.value=se.value)},{immediate:!0,deep:!0}),e.watch(se,V=>{u.value[d.value]||(d.value=V),u.value[c.value]||(c.value=V)},{immediate:!0}),e.watch(u,V=>{V.export||(d.value==="export"&&(d.value=se.value),c.value==="export"&&(c.value=se.value))},{immediate:!0,deep:!0});const xe=e.computed(()=>typeof window>"u"?!1:window.__MEDIABLES_EDITOR_DEV__===!0),ue=Em(),{currentFrame:le,playheadPosition:Z,timelineClips:k,totalDuration:F,hasChanges:W,isPlaying:J,selectedClip:ce,zoomLevel:Ue,playbackSpeed:be,fps:_e,handleTrim:ye,handleSplit:Ne,handleClipSelect:Se,splitAtPlayhead:Re,deleteSelectedClip:Oe,duplicateSelectedClip:it,setZoomLevel:rt,moveClip:Pt,setFilters:bt,setTextOverlays:Ct,setAudioTracks:mt,saveDraft:pt,clearHasChanges:Nt,resetChanges:Ce,generateRecipe:Ve,zoomIn:Le,zoomOut:nt,fitToWindow:Ge,togglePlayback:Je,setPlaying:_t,seekTo:ht,frameForward:Wt,frameBackward:Pe,skipToStart:Ht,skipToEnd:Zt,setPlaybackSpeed:It,updateSourceDuration:Ut,undo:Gt,redo:sa,canUndo:ae,canRedo:ge}=Fp(l.value,n.initialRecipe,n.media),{videoCompatibleFilters:pe,activeFilters:me,selectedFilter:Be,previewFilter:He,previewFilterEffect:lt,applyFilter:Vt,updateFilterParams:Ot,removeFilter:$t,clearAllFilters:st,setActiveFilters:Jt}=Rp();function q(V){var re,Ee;const U=((re=ce.value)==null?void 0:re.id)??((Ee=k.value[0])==null?void 0:Ee.id);U&&(P.value=!0,typeof V=="object"&&V.id?Vt(V.id):typeof V=="string"&&Vt(V),bt(me.value),g.value?g.value.setClipFilters(U,me.value):x.set(U,[...me.value]),Se(U),P.value=!1,pn())}function ke(){var U,re;const V=((U=ce.value)==null?void 0:U.id)??((re=k.value[0])==null?void 0:re.id);V&&Se(V)}function oe(V){const U=me.value.find(re=>re.filterId===V);U&&$t(U.id)}const $e=e.computed(()=>pe.value.map(U=>{var Ee;const re=[];if(U.controls&&U.controls.length>0)for(const De of U.controls){const Me=De.type;if(Me==="button"||Me==="text"||Me==="range")continue;const Ie={id:De.property||De.id,label:De.label||De.id,type:Me,default:De.default??(Me==="toggle"?!1:Me==="color"?"#ffffff":0)};Me==="slider"&&(Ie.min=De.min??0,Ie.max=De.max??1,Ie.step=De.step??.01),Me==="select"&&De.options&&(Ie.options=De.options),re.push(Ie)}else if(U.paramRanges){const De=Object.entries(U.paramRanges);for(const[Me,Ie]of De){const Lt=Me.replace(/[-_]/g," ").replace(/\b\w/g,wo=>wo.toUpperCase()),Oa=(Ee=U.defaultParams)==null?void 0:Ee[Me],Ho=(Ie.min+Ie.max)/2;re.push({id:Me,label:Lt,min:Ie.min,max:Ie.max,step:Ie.step??.01,default:typeof Oa=="number"?Oa:Ho})}}return{id:U.id,name:U.name,category:U.category,params:re}})),At=e.ref("0.00"),zt=e.ref("0.00"),Ft=e.ref("");e.watch($e,V=>{if(V.length===0){Ft.value="";return}V.some(re=>re.id===Ft.value)||(Ft.value=V[0].id)},{immediate:!0});const wt=e.ref(!1),yt=e.ref(0),Yt=e.ref(!1),Et=e.ref(null),Kt=e.ref(null);let Ca=null,X=!1;const Y=e.computed(()=>{const V=new Map;return me.value.forEach(U=>V.set(U.filterId,U)),V}),fe=e.computed(()=>{var V,U;return le.value?le.value:((V=n.media)==null?void 0:V.thumbnail_url)||((U=n.media)==null?void 0:U.url)}),he=e.ref("");e.watch(()=>{var V,U;return{file:(V=n.media)==null?void 0:V.file,url:(U=n.media)==null?void 0:U.url}},(V,U,re)=>{var De,Me;const Ee=he.value;re(()=>{Ee&&Ee.startsWith("blob:")&&URL.revokeObjectURL(Ee)}),(De=n.media)!=null&&De.file?he.value=URL.createObjectURL(n.media.file):(Me=n.media)!=null&&Me.url?he.value=n.media.url:he.value=""},{immediate:!0}),e.onUnmounted(()=>{he.value&&he.value.startsWith("blob:")&&URL.revokeObjectURL(he.value)});const Te=e.computed(()=>he.value),Ke=lp({forcePixiPreview:y,getPreviewRef:()=>w.value,getSourceUrl:()=>he.value,setPlaying:_t}),ct=e.computed(()=>{if(!n.media)return null;const{file:V,...U}=n.media;return{...U,url:he.value}}),tt=e.computed(()=>{var U;const V=(U=n.media)==null?void 0:U.url;return!!(V&&/^https?:/i.test(V))}),qe=e.computed(()=>me.value),vt=e.computed(()=>Z.value),gt=e.computed(()=>!!ce.value&&Z.value>0),ot=e.computed(()=>!!ce.value&&k.value.length>1),Qt=e.computed(()=>!!ce.value),Rt=e.ref(!0),Za=[.5,1,1.5,2],ha=e.computed(()=>{const V=new Set([0,ba.value]);for(const U of k.value)V.add(U.timelineStart),V.add(U.timelineEnd);return Array.from(V).filter(U=>Number.isFinite(U)).sort((U,re)=>U-re)}),Cn=e.computed(()=>ha.value.some(V=>V<Z.value-.001)),Ta=e.computed(()=>ha.value.some(V=>V>Z.value+.001)),xa=e.ref(!1),Aa=e.ref(null);function va(V){if(!Number.isFinite(V)||V<0)return"0:00";const U=Math.floor(V/60),re=Math.floor(V%60);return`${U}:${re.toString().padStart(2,"0")}`}const Qa=e.computed(()=>{var re;const V=ce.value??k.value[0];if(!V)return"No clip selected";const U=(re=V.label)==null?void 0:re.trim();return U&&U.length>0?U:`Clip ${V.id.slice(-4)}`}),On=e.computed(()=>{const V=ce.value??k.value[0];if(!V)return"Tap a clip to start editing";const U=Math.max(0,V.timelineEnd-V.timelineStart);return`${va(V.timelineStart)} - ${va(V.timelineEnd)} • ${U.toFixed(1)}s`});function Ga(V){return!Number.isFinite(V)||V<0?"0.0s":V<60?`${V.toFixed(1)}s`:va(V)}const zn=e.computed(()=>va(Z.value)),ga=e.computed(()=>{const V=ce.value??k.value[0];return V?va(V.sourceIn):"0:00"}),Ra=e.computed(()=>{const V=ce.value??k.value[0];return V?va(V.sourceOut):"0:00"}),Wo=e.computed(()=>{const V=ce.value??k.value[0];return V?Ga(V.timelineEnd-V.timelineStart):"0.0s"}),lo=e.computed(()=>Aa.value===null?ce.value??k.value[0]??null:k.value.find(V=>V.id===Aa.value)??null),hi=e.computed(()=>{var re;const V=lo.value;if(!V)return"Clip actions";const U=(re=V.label)==null?void 0:re.trim();return U&&U.length>0?U:`Clip ${V.id.slice(-4)}`}),vi=e.computed(()=>{const V=lo.value;return V?`${va(V.timelineStart)} - ${va(V.timelineEnd)} • ${Ga(V.timelineEnd-V.timelineStart)}`:"Choose an action"}),xn=e.ref(0),ba=e.computed(()=>{try{const V=F.value??F;return V&&typeof V=="number"&&V>0?V:xn.value}catch{return xn.value}}),sn=e.ref(),so=e.ref(),jn=e.ref(),en=e.ref(),Wn=e.ref(0),Xa=e.ref(!1);let da=null,Ba=null;e.watch(ba,V=>{var re;if(Xa.value||!V||V<=0)return;const U=Wn.value||((re=sn.value)==null?void 0:re.clientWidth)||0;U>0&&(Xa.value=!0,Ge(U))}),e.watch(Wn,V=>{if(Xa.value||!V||V<=0)return;ba.value>0&&(Xa.value=!0,Ge(V))}),e.watch(s,V=>{V||Pa()}),e.watch(()=>{var V;return(V=lo.value)==null?void 0:V.id},V=>{xa.value&&!V&&Pa()});function tn(V){return Number.isFinite(V)?V.toFixed(2):"0.00"}function co(V){const U=Number(V);return Number.isFinite(U)?U:null}function H(V){V&&(At.value=tn(V.sourceIn),zt.value=tn(V.sourceOut))}e.watch(()=>{var V,U,re;return[(V=ce.value)==null?void 0:V.id,(U=ce.value)==null?void 0:U.sourceIn,(re=ce.value)==null?void 0:re.sourceOut]},()=>{H(ce.value)},{immediate:!0});function Q(V){const U=ce.value;if(!U)return;const re=1/30,Ee=U.sourceMinIn??0,De=U.sourceMaxOut??ba.value,Me=U.sourceIn+(Z.value-U.timelineStart);if(V==="start"){const Lt=Math.max(Ee,Math.min(Me,U.sourceOut-re));At.value=tn(Lt);return}const Ie=Math.max(U.sourceIn+re,Math.min(Me,De));zt.value=tn(Ie)}function Fe(){const V=ce.value;if(!V)return;const U=co(At.value),re=co(zt.value);if(U===null||re===null)return;const Ee=1/30,De=V.sourceMinIn??0,Me=V.sourceMaxOut??ba.value,Ie=Math.max(De,Math.min(U,Me-Ee)),Lt=Math.max(Ie+Ee,Math.min(re,Me));ye(V.id,"start",Ie),ye(V.id,"end",Lt),At.value=tn(Ie),zt.value=tn(Lt),ce.value&&ht(ce.value.timelineStart)}function ne(){Ft.value.trim()!==""&&q(Ft.value)}function Qe(){var V;st(),bt(me.value),(V=ce.value)!=null&&V.id&&(g.value?g.value.setClipFilters(ce.value.id,me.value):x.set(ce.value.id,[...me.value])),pn()}function Tt(V,U,re){var De,Me;const Ee=me.value.find(Ie=>Ie.filterId===V);Ee?(Ee.params={...Ee.params,[U]:re},bt(me.value),g.value&&((De=ce.value)!=null&&De.id)?g.value.setClipFilters(ce.value.id,me.value):(Me=ce.value)!=null&&Me.id&&x.set(ce.value.id,[...me.value]),pn(),ke()):He.value&&He.value.filterId===V&&(He.value.params={...He.value.params||{},[U]:re})}function dn(V){ht(V)}function La(V){!V||!Number.isFinite(V.timestamp)||ht(V.timestamp)}function Hn(V){_t(V)}function Nn(V){!Number.isFinite(V)||V<=0||(xn.value=V,Ut(V))}function Pa(){xa.value=!1,Aa.value=null}function ya(V){s.value&&(Aa.value=V,xa.value=!0)}function Zn(V){var Ee,De,Me,Ie;const U=((Ee=ce.value)==null?void 0:Ee.id)??((De=k.value[0])==null?void 0:De.id)??null;Se(V),(((Me=ce.value)==null?void 0:Me.id)??((Ie=k.value[0])==null?void 0:Ie.id)??null)!==U&&ue.selection()}function uo(V){Zn(V),ya(V)}function cn(V){V&&ue.selection()}function Vn(){Rt.value=!Rt.value,ue.selection()}function Ua(){const V=ha.value.filter(re=>re<Z.value-.001),U=V.length>0?V[V.length-1]:0;ht(U)}function mo(){const V=ha.value.find(U=>U>Z.value+.001);ht(V??ba.value)}function Tn(){Gt()}function Bn(){sa()}function an(){const V=k.value.length;Re(),k.value.length>V&&(ue.success(),Pa())}function Gn(V){const U=k.value.length;Ne(V),k.value.length>U&&ue.success()}function un(){const V=k.value.length;it(),k.value.length>V&&(ue.selection(),Pa())}function Mn(){const V=k.value.length;Oe(),k.value.length<V&&(ue.error(),Pa())}function mn(V){const U=be.value;It(V),be.value!==U&&ue.selection()}function In(V){return V instanceof HTMLElement?V.closest('input, textarea, select, button, [contenteditable="true"]')!==null:!1}function nn(V){if(s.value||In(V.target))return;const U=V.key.toLowerCase(),re=V.metaKey||V.ctrlKey;if(V.code==="Space"){V.preventDefault(),Je();return}if(!re&&U==="s"){V.preventDefault(),an();return}if(U==="arrowleft"){V.preventDefault(),Pe();return}if(U==="arrowright"){V.preventDefault(),Wt();return}if(U==="home"){V.preventDefault(),Ht();return}if(U==="end"){V.preventDefault(),Zt();return}if(!re&&U==="["){V.preventDefault(),Ua();return}if(!re&&U==="]"){V.preventDefault(),mo();return}if(re&&U==="z"&&V.shiftKey){V.preventDefault(),Bn();return}re&&U==="z"&&(V.preventDefault(),Tn())}function po(){var U;const V=Wn.value||((U=sn.value)==null?void 0:U.clientWidth)||800;Ge(V)}function Xn(V){Xa.value=!0,rt(V)}function gi(){Xa.value=!0,Le()}function bi(){Xa.value=!0,nt()}function $n(V){const U=V.target,re=Number(U.value);Xn(re)}function Kn(V){const U=Math.min(600,Math.max(10,Ue.value+V));Xn(U)}function qn(){Ba==null||Ba(),Ba=null;const V=jn.value,U=en.value;if(!s.value||!V||!U)return;const re=()=>{Kn(-20)},Ee=()=>{Kn(20)};V.addEventListener("click",re),U.addEventListener("click",Ee),Ba=()=>{V.removeEventListener("click",re),U.removeEventListener("click",Ee)}}e.watch([s,jn,en],()=>{qn()},{flush:"post"});function fo(V){var U;g.value=V,(U=g.value)!=null&&U.composition&&($.value=new Lp(g.value.composition),N.value=new qi(g.value.composition),B.value=new Pp(g.value.composition));try{x.size&&(x.forEach((re,Ee)=>{g.value.setClipFilters(Ee,re)}),x.clear(),g.value.composition.computeFrame())}catch{}}function ho(V){V!=null&&V.id&&lt(V.id)}function vo(V){Ot(V),pn()}async function go(V){if(!$.value)return;const U=await $.value.addTextOverlay(V);M.value.push({id:U,...V})}async function bo(V,U){if(!$.value)return;await $.value.updateTextOverlay(V,U);const re=M.value.findIndex(Ee=>Ee.id===V);re!==-1&&(M.value[re]={...M.value[re],...U})}async function S(V){$.value&&(await $.value.removeTextOverlay(V),M.value=M.value.filter(U=>U.id!==V))}async function R(V){if(!N.value||j.value.length<2)return;const[U,re]=j.value,Ee=await N.value.applyTransition(U,re,V);E.value.push({id:Ee,...V,name:V.type})}function te(V){if(!N.value)return;const U=E.value[V];U&&(N.value.removeTransition(U.id),E.value.splice(V,1))}function we(V){}async function ze(V){if(!B.value)return;const U=await B.value.addAudioTrack(V);D.value.push({id:U,...V})}async function je(V,U){if(!B.value)return;const re=D.value.findIndex(Ee=>Ee.id===V);re!==-1&&(D.value[re]={...D.value[re],...U})}async function ut(V){B.value&&(await B.value.removeAudioTrack(V),D.value=D.value.filter(U=>U.id!==V))}async function Bt(V,U){if(!B.value)return;await B.value.updateVolume(V,U);const re=D.value.find(Ee=>Ee.id===V);re&&(re.volume=U)}async function qt(V,U){if(!B.value)return;await B.value.muteTrack(V,U);const re=D.value.find(Ee=>Ee.id===V);re&&(re.muted=U)}function ca(V){B.value&&(B.value.setMasterVolume(V),L.value=V)}function Na(V){i("thumbnail-selected",V)}function Jn(){Ca!==null&&(clearInterval(Ca),Ca=null)}function ih(V,U){return U?{...V,output:{...V.output,format:U.format,quality:U.quality}}:V}function yi(V){var U;return V.metadata||(V.metadata={created_at:new Date().toISOString(),editor_version:"2.0.0"}),V.metadata.fit_mode=T.value,(U=n.media)!=null&&U.url&&/^https?:/i.test(n.media.url)?V.metadata.source_url=n.media.url:delete V.metadata.source_url,V}function ea(V,U,re){return Math.min(re,Math.max(U,V))}function Zl(V,U){if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){const re=Number(V);if(Number.isFinite(re))return re}return U}function wa(V,U,re){for(const Ee of U)if(Ee in V)return Zl(V[Ee],re);return re}function rh(V){const U=typeof V.params=="object"&&V.params!==null?V.params:{};switch(V.filterId.trim().toLowerCase()){case"brightness":return[{type:"brightness",value:ea(wa(U,["value","brightness"],0),-1,1)}];case"contrast":return[{type:"contrast",value:ea(wa(U,["value","contrast"],1),.1,3)}];case"saturation":return[{type:"saturation",value:ea(wa(U,["value","saturation"],1),0,3)}];case"blur":case"gaussian-blur":case"kawase-blur":case"radial-blur":return[{type:"blur",value:ea(wa(U,["value","blur","radius"],0),0,25)}];case"sharpen":return[{type:"sharpen",value:ea(wa(U,["value","amount"],1),0,5)}];case"sepia":return[{type:"sepia",value:1}];case"grayscale":return[{type:"grayscale",value:1}];case"adjustment":{const Ee=ea(wa(U,["brightness"],1)-1,-1,1),De=ea(wa(U,["contrast"],1),.1,3),Me=ea(wa(U,["saturation"],1),0,3);return[{type:"brightness",value:Ee},{type:"contrast",value:De},{type:"saturation",value:Me}]}default:return[]}}function lh(V){const U=V.timeline[0],re=Array.isArray(U==null?void 0:U.filters)?U.filters:[],Ee=[];for(const Me of re)if(Ee.push(...rh(Me)),Ee.length>=12)break;const De={...V,filters:Ee.slice(0,12)};if(V.timeline.length===1&&U){const Me=Math.max(0,Zl(U.sourceIn,0)),Ie=Zl(U.sourceOut,Me);Ie>Me&&(De.trim={start:Me,end:Ie})}return De}async function rc(V,U,re){return Ke.renderRecipeWithPixi(V,U,re)}async function sh(V,U){var wi;Jn(),X=!1,Ke.resetClientExport(),Kt.value=null,Et.value=null,Yt.value=!1,yt.value=0;const re=yi(V??Ve()),Ee=pc(re),De=Array.isArray(Ee.filters)&&Ee.filters.length>0,Me=Kl(Ee);if(!(W.value||De||Me))return Nt(),i("video-exported",null),null;const Lt=Ee.timeline[0],Oa=Lt?Math.max(0,Lt.sourceIn):0,wo=((Lt==null?void 0:Lt.sourceOut)??((wi=Ee.source)==null?void 0:wi.duration)??ba.value)-Oa,Yl=n.serverRenderEndpoint!=null&&n.clientExportThreshold>0&&wo>n.clientExportThreshold;if(Yl){wt.value=!0;try{return await dh(Ee),null}catch(ka){const za=ka instanceof Error?ka.message:"Server render failed";throw Et.value=za,i("server-render-failed",za),ka}finally{wt.value=!1}}if(n.maxDuration>0&&wo>n.maxDuration&&!Yl){const ka=`This video is too long for in-browser export (${Math.round(wo)}s). Server rendering is not available. Try a shorter clip.`;return Et.value=ka,i("video-exported",null),null}wt.value=!0;try{const ka=await rc(Ee,U,za=>{X||(yt.value=za)});return X?(Et.value="Export canceled.",yt.value=0,i("video-exported",null),null):(Nt(),i("recipe-generated",Ee),i("video-exported",ka),yt.value=100,Yt.value=!0,ka)}catch(ka){if(X)return Et.value="Export canceled.",yt.value=0,i("video-exported",null),null;const za=ka instanceof Error?ka.message:"Local WebGL export failed.";throw Et.value=za,new Error(`Video export failed: ${za}`)}finally{wt.value=!1}}function hr(){return new Ll(n.serverRenderEndpoint??"/api/v1")}async function dh(V){const U=hr();Et.value="Starting server render...",yt.value=0;const re=await U.createRenderJob({source_media_uuid:l.value,recipe:V});Kt.value=re.id,i("server-render-started",re.id),i("export-started",re.id),Et.value="Rendering on server...";const Ee=await U.pollRenderJob(re.id,(Me,Ie)=>{yt.value=Me,Ie==="processing"&&(Et.value=`Server rendering: ${Me}%`)},3e3,(n.maxDuration>0?n.maxDuration*3:1800)*1e3);yt.value=100,Yt.value=!0,Et.value="Server render complete!",Nt(),i("recipe-generated",V);const De={id:Ee.id};typeof Ee.output_media_id=="string"&&Ee.output_media_id!==""&&(De.output_media_id=Ee.output_media_id),i("server-render-completed",De)}async function lc(){if(!wt.value)return;X=!0,y.value=!1,Ke.cancelClientExport(),Jn();const V=Kt.value;if(V)try{await hr().cancelJob(V)}catch(U){const re=U instanceof Error?U.message:"Failed to cancel export";Et.value=re,wt.value=!1,Kt.value=null;return}wt.value=!1,yt.value=0,Yt.value=!1,Kt.value=null,Et.value="Export canceled."}async function sc(V){Jn(),X=!1,Ke.resetClientExport(),Kt.value=null,Et.value=null,Yt.value=!1,wt.value=!0,yt.value=0;try{const U=yi(ih(Ve(),V));i("recipe-generated",U);const re=l.value.startsWith("temp-"),Ee=U.timeline[0],De=Array.isArray(Ee==null?void 0:Ee.filters)?Ee.filters:[],Me=!0,Ie=typeof window<"u"&&window.MEDIABLES_ALLOW_SERVER_EXPORT_FALLBACK===1||typeof localStorage<"u"&&localStorage.getItem("mediables.export.allowServerFallback")==="1";if(Me)try{const za=await rc(U,V,_h=>{X||(yt.value=_h)});if(X){Et.value="Export canceled.",wt.value=!1,yt.value=0;return}i("video-exported",za);const hc=URL.createObjectURL(za.file),Ql=document.createElement("a");Ql.href=hc,Ql.download=`edited-video-${Date.now()}.mp4`,Ql.click(),setTimeout(()=>URL.revokeObjectURL(hc),100),wt.value=!1,yt.value=100,Yt.value=!0;return}catch(za){if(X){Et.value="Export canceled.",wt.value=!1,yt.value=0;return}if(re||!Ie)throw za;yt.value=0,Et.value="Local filter export failed, falling back to server render."}const Lt={"360p":"low","480p":"low","720p":"medium","1080p":"high","1440p":"ultra","2160p":"ultra"},Oa=(V==null?void 0:V.quality)??U.output.quality,Ho=Lt[Oa]??"high",wo={...lh(U),export:{format:(V==null?void 0:V.format)??U.output.format,quality:Ho,resolution:Oa,framerate:U.output.fps}},wi=await hr().createJob({source_media_id:l.value,recipe:wo}),ka=typeof wi.id=="string"?wi.id:null;if(!ka)throw new Error("Export failed: missing job id");Kt.value=ka,i("export-started",ka),wh(ka)}catch(U){if(y.value=!1,Ke.resetClientExport(),X){Et.value="Export canceled.",wt.value=!1,yt.value=0,Kt.value=null;return}try{const re=yi(Ve()),Ee=new Blob([JSON.stringify(re,null,2)],{type:"application/json"}),De=URL.createObjectURL(Ee),Me=document.createElement("a");Me.href=De,Me.download=`video-recipe-${Date.now()}.json`,Me.click(),setTimeout(()=>URL.revokeObjectURL(De),100)}finally{wt.value=!1,yt.value=0,Kt.value=null,Et.value=U instanceof Error?U.message:"Export failed"}}}const Gl=async V=>{await new Promise(U=>{window.setTimeout(U,V)})},Xl=V=>{if(!V||V.width<=0||V.height<=0)return null;try{return V.toDataURL("image/jpeg",.85)}catch{return null}},ch=V=>{if(!V||typeof V!="object")return null;const re=V.pixiCanvas;if(re&&typeof re=="object"&&"value"in re){const Ee=re.value;return Ee instanceof HTMLCanvasElement?Ee:null}return re instanceof HTMLCanvasElement?re:null},uh=V=>{if(!V||typeof V!="object")return null;const U=V.duration;if(typeof U=="number"&&Number.isFinite(U))return U;if(U&&typeof U=="object"&&"value"in U){const re=U.value;if(typeof re=="number"&&Number.isFinite(re))return re}return null},mh=V=>{if(!V||typeof V!="object")return null;const re=V.videoElement;if(re&&typeof re=="object"&&"value"in re){const Ee=re.value;return Ee instanceof HTMLVideoElement?Ee:null}return re instanceof HTMLVideoElement?re:null},dc=V=>typeof V.params=="object"&&V.params!==null?V.params:{},ph=V=>{const U=[];for(const re of V){const Ee=dc(re),De=re.filterId.trim().toLowerCase();if(De==="brightness"){const Ie=(ea(wa(Ee,["value","brightness"],0),-1,1)+1)*100;U.push(`brightness(${Ie.toFixed(2)}%)`);continue}if(De==="contrast"){const Me=ea(wa(Ee,["value","contrast"],1),.1,4);U.push(`contrast(${(Me*100).toFixed(2)}%)`);continue}if(De==="saturation"||De==="saturate"){const Me=ea(wa(Ee,["value","saturation"],1),0,4);U.push(`saturate(${(Me*100).toFixed(2)}%)`);continue}if(De==="grayscale"){U.push("grayscale(100%)");continue}if(De==="sepia"){U.push("sepia(100%)");continue}if(De==="blur"||De==="gaussian-blur"||De==="kawase-blur"){const Me=ea(wa(Ee,["value","blur","radius"],0),0,30);Me>.01&&U.push(`blur(${Me.toFixed(2)}px)`);continue}if(De==="adjustment"){const Me=wa(Ee,["brightness"],1),Ie=wa(Ee,["contrast"],1),Lt=wa(Ee,["saturation"],1);Math.abs(Me-1)>.01&&U.push(`brightness(${(ea(Me,0,5)*100).toFixed(2)}%)`),Math.abs(Ie-1)>.01&&U.push(`contrast(${(ea(Ie,.1,5)*100).toFixed(2)}%)`),Math.abs(Lt-1)>.01&&U.push(`saturate(${(ea(Lt,0,5)*100).toFixed(2)}%)`);continue}if(De==="cinematic"){U.push("contrast(120%) brightness(95%) saturate(85%)");continue}if(De==="dramatic"){U.push("contrast(140%) brightness(90%) saturate(110%) sepia(10%)");continue}if(De==="dreamy"){U.push("blur(0.5px) brightness(105%) saturate(90%) contrast(95%)");continue}}return U.join(" ")},fh=V=>{const U=V.find(De=>De.filterId.trim().toLowerCase()==="noise");if(!U)return 0;const re=dc(U),Ee=wa(re,["noise","value","amount","intensity"],.2);return Ee<=1?ea(Ee,0,1):ea(Ee/100,0,1)},hh=(V,U,re,Ee)=>{if(Ee<=0)return;const De=V.getImageData(0,0,U,re),Me=255*Ee;for(let Ie=0;Ie<De.data.length;Ie+=4){const Lt=(Math.random()*2-1)*Me;De.data[Ie]=ea(De.data[Ie]+Lt,0,255),De.data[Ie+1]=ea(De.data[Ie+1]+Lt,0,255),De.data[Ie+2]=ea(De.data[Ie+2]+Lt,0,255)}V.putImageData(De,0,0)},cc=async V=>{V.readyState>=2&&V.videoWidth>0&&V.videoHeight>0||await new Promise(U=>{let re=!1,Ee=0;const De=()=>{re||(re=!0,V.removeEventListener("loadedmetadata",Me),V.removeEventListener("loadeddata",Me),V.removeEventListener("canplay",Me),window.clearTimeout(Ee),U())},Me=()=>{De()};V.addEventListener("loadedmetadata",Me),V.addEventListener("loadeddata",Me),V.addEventListener("canplay",Me),Ee=window.setTimeout(()=>De(),800),V.play().catch(()=>{})})},vh=async(V,U)=>{await new Promise(re=>{let Ee=!1,De=0;const Me=()=>{Ee||(Ee=!0,V.removeEventListener("seeked",Ie),window.clearTimeout(De),re())},Ie=()=>{Me()};if(Math.abs(V.currentTime-U)<.016){requestAnimationFrame(()=>Me());return}V.addEventListener("seeked",Ie),De=window.setTimeout(()=>Me(),700),V.currentTime=U})},uc=async(V,U)=>{await cc(V);const re=Math.floor(V.videoWidth),Ee=Math.floor(V.videoHeight);if(re<=0||Ee<=0)return null;const De=Number.isFinite(V.duration)&&V.duration>0?V.duration:0,Me=De>0?ea(U,0,De):0;await vh(V,Me);const Ie=document.createElement("canvas");Ie.width=re,Ie.height=Ee;const Lt=Ie.getContext("2d");if(!Lt)return null;const Oa=ph(me.value);Oa!==""&&(Lt.filter=Oa);try{Lt.drawImage(V,0,0,re,Ee)}catch{return null}const Ho=fh(me.value);return hh(Lt,re,Ee,Ho),Xl(Ie)},gh=async(V,U)=>{const re=document.createElement("video");re.src=V,re.muted=!0,re.playsInline=!0,re.preload="auto",V.startsWith("blob:")||(re.crossOrigin="anonymous");try{return await cc(re),await uc(re,U)}catch{return null}finally{re.pause(),re.removeAttribute("src"),re.load()}},bh=async V=>{const U=w.value,re=Xl(ch(U));if(re)return re;if(U!=null&&U.captureFrameAt)for(let Me=0;Me<4;Me+=1){const Ie=uh(U);if(Ie!==null&&Ie<=0&&Me<2){await Gl(80);continue}const Lt=await Promise.race([U.captureFrameAt(V),Gl(450).then(()=>null)]),Oa=Xl(Lt);if(Oa)return Oa;await Gl(80)}const Ee=mh(U);if(Ee){const Me=await uc(Ee,V);if(Me)return Me}const De=Te.value.trim();if(De!==""){const Me=await gh(De,V);if(Me)return Me}return null},mc=V=>V.map(U=>({...U,params:U.params&&typeof U.params=="object"?{...U.params}:U.params}));function pc(V){const U=mc(me.value);if(!Kl(V)&&U.length>0&&Array.isArray(V.timeline)&&V.timeline.length>0){const Ee=V.timeline[0];Ee&&(V.timeline=[{...Ee,filters:U},...V.timeline.slice(1)])}return V}const Kl=V=>Array.isArray(V.timeline)?V.timeline.some(U=>Array.isArray(U.filters)&&U.filters.length>0):!1,yh=V=>{if(!V||typeof V!="object")return null;const U=V.posterFrame;if(typeof U!="string")return null;const re=U.trim();return re!==""?re:null};async function ql(){const V=yi(pc(pt())),U=mc(me.value),re=Kl(V)||U.length>0,Ee=yh(n.initialRecipe);if(re){const De=Z.value>0?Z.value:.1;try{const Me=await bh(De);Me?V.posterFrame=Me:Ee&&(V.posterFrame=Ee)}catch{Ee&&(V.posterFrame=Ee)}}else delete V.posterFrame;return Nt(),i("draft-saved",V),V}function fc(){Ce()&&(st(),pn())}async function wh(V){Jn();const U=hr();Ca=window.setInterval(async()=>{try{if(X){Jn();return}const re=await U.getJob(V),Ee=Number(re.progress??0);if(yt.value=Number.isFinite(Ee)?Ee:0,re.status==="completed"||re.status==="failed"||re.status==="cancelled")if(Jn(),wt.value=!1,Kt.value=null,re.status==="completed")yt.value=100,Yt.value=!0,Et.value=null;else{const De=re.status==="cancelled"||typeof re.error_message=="string"&&/cancel/i.test(re.error_message);Et.value=De?"Export canceled.":typeof re.error_message=="string"&&re.error_message.trim()!==""?re.error_message:"Export failed"}}catch(re){Jn(),wt.value=!1,Kt.value=null,Et.value=re instanceof Error?re.message:"Failed to check export progress"}},2e3)}function Jl(){const V=yi(Ve());try{const U=V.timeline??[]}catch{}I.value=V}let yo=null;function pn(){yo&&clearTimeout(yo),yo=setTimeout(()=>{Jl(),yo=null},200)}e.watch(()=>k.value,pn,{deep:!0}),e.watch(()=>ce.value,V=>{if(P.value||!V)return;const U=(V==null?void 0:V.filters)??[];Jt(U)},{immediate:!0}),e.watch(()=>me.value,V=>{bt(V),pn()},{deep:!0}),e.watch(()=>M.value,V=>{Ct(V),pn()},{deep:!0}),e.watch(()=>D.value,V=>{const U=V.map(re=>({...re,source:typeof re.source=="string"?re.source:void 0}));mt(U),pn()},{deep:!0}),e.watch(()=>Z.value,pn),a({saveDraft:ql,exportForUpload:sh}),Jl(),e.onUnmounted(()=>{Jn(),X=!0,Ke.cancelClientExport(),yo&&(clearTimeout(yo),yo=null),g.value&&(g.value.destroy(),g.value=null),$.value=null,N.value=null,B.value=null});function kh(){da||!so.value||(da=new z2({filters:$e.value,callbacks:{onApplyFilter:V=>{q(V.id)},onRemoveFilter:V=>{oe(V)},onUpdateParam:(V,U,re)=>{Tt(V,U,re)},onPreviewFilter:V=>{lt(V.id)}}}),da.mount(so.value),da.setActiveFilters(Y.value))}e.watch(Y,V=>{da==null||da.setActiveFilters(V)},{deep:!0}),e.watch($e,V=>{da==null||da.setFilters(V)});let Yn=null;return e.onMounted(()=>{window.addEventListener("resize",z),window.addEventListener("keydown",nn);const V=()=>{!sn.value||Yn||(Yn=new ResizeObserver(U=>{U[0]&&(Wn.value=Math.round(U[0].contentRect.width))}),Yn.observe(sn.value))};V(),Yn||e.nextTick(V),s.value&&(qn(),Ba||e.nextTick(qn)),n.media&&Jl(),s.value&&e.nextTick(()=>{kh()}),e.nextTick(()=>{const U=document.querySelector(".video-editor");U&&U.getBoundingClientRect();const re=document.querySelector(".mobile-layout");re&&re.getBoundingClientRect()})}),e.onUnmounted(()=>{window.removeEventListener("resize",z),window.removeEventListener("keydown",nn),Yn==null||Yn.disconnect(),Yn=null,Ba==null||Ba(),Ba=null,da==null||da.destroy(),da=null}),(V,U)=>{var re,Ee,De,Me;return e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-editor",{mobile:s.value}])},[s.value?(e.openBlock(),e.createElementBlock("div",cx,[e.createElementVNode("div",ux,[e.createElementVNode("div",mx,[e.createElementVNode("button",{class:e.normalizeClass(["mobile-toolbar-btn",{active:e.unref(J)}]),onClick:U[0]||(U[0]=(...Ie)=>e.unref(Je)&&e.unref(Je)(...Ie)),"aria-label":e.unref(J)?"Pause":"Play","data-testid":"btn-mobile-play"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(J)?e.unref(fd):e.unref(hd)},null,8,["icon"])],10,px),e.createElementVNode("button",{class:"mobile-toolbar-btn",onClick:fc,"aria-label":"Reset all changes","data-testid":"btn-mobile-reset"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Uo)},null,8,["icon"])])]),e.createElementVNode("div",fx,[e.createElementVNode("button",{class:"mobile-toolbar-btn mobile-toolbar-save",onClick:ql,"aria-label":"Save","data-testid":"btn-mobile-save",disabled:!e.unref(W)},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(pl)},null,8,["icon"]),U[13]||(U[13]=e.createElementVNode("span",null,"Save",-1))],8,hx),e.createElementVNode("button",{class:"mobile-toolbar-btn",onClick:U[1]||(U[1]=Ie=>sc()),"aria-label":"Export","data-testid":"btn-mobile-export",disabled:wt.value||!e.unref(W)},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(ni)},null,8,["icon"])],8,vx),e.createElementVNode("button",{class:"mobile-toolbar-btn",onClick:U[2]||(U[2]=Ie=>i("close")),"aria-label":"Close","data-testid":"btn-mobile-close"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref($o)},null,8,["icon"])])])]),e.createElementVNode("div",gx,[e.withDirectives(e.createVNode(Cs,{ref_key:"pixiPreviewMobileRef",ref:h,"aria-hidden":!p.value,class:"preview-host-child",source:Te.value,"fallback-duration":ba.value,filters:qe.value,playhead:vt.value,"is-playing":e.unref(J),"fit-mode":T.value,active:p.value,onPlayPause:e.unref(Je),onFrameUpdate:La,onDurationChange:Nn},null,8,["aria-hidden","source","fallback-duration","filters","playhead","is-playing","fit-mode","active","onPlayPause"]),[[e.vShow,p.value]]),e.withDirectives(e.createVNode(Os,{"aria-hidden":!f.value,class:"preview-host-child","media-uuid":l.value,recipe:I.value,media:ct.value,"enable-engine":f.value&&tt.value,"fit-mode":T.value,onTimeUpdate:dn,onPlayStateChange:Hn,onDurationChange:Nn,onEngineReady:fo},null,8,["aria-hidden","media-uuid","recipe","media","enable-engine","fit-mode"]),[[e.vShow,f.value]]),wt.value?(e.openBlock(),e.createElementBlock("div",bx,[e.createElementVNode("div",yx,[e.createElementVNode("span",null,"Exporting "+e.toDisplayString(yt.value)+"%",1),e.createElementVNode("div",wx,[e.createElementVNode("div",{class:"mobile-export-bar-fill",style:e.normalizeStyle({width:yt.value+"%"})},null,4)]),e.createElementVNode("button",{class:"mobile-export-cancel",onClick:lc},"Cancel")])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",{ref_key:"timelineContainerRef",ref:sn,class:"timeline-section"},[e.createElementVNode("div",kx,[e.createElementVNode("button",{ref_key:"mobileZoomOutButtonRef",ref:jn,type:"button",class:"mobile-zoom-btn","aria-label":"Zoom out timeline","data-testid":"btn-timeline-zoom-out"},[...U[14]||(U[14]=[e.createElementVNode("svg",{width:"16",height:"16",viewBox:"0 0 16 16"},[e.createElementVNode("path",{d:"M4 8h8",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"})],-1)])],512),e.createElementVNode("button",{ref_key:"mobileZoomInButtonRef",ref:en,type:"button",class:"mobile-zoom-btn","aria-label":"Zoom in timeline","data-testid":"btn-timeline-zoom-in"},[...U[15]||(U[15]=[e.createElementVNode("svg",{width:"16",height:"16",viewBox:"0 0 16 16"},[e.createElementVNode("path",{d:"M4 8h8M8 4v8",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"})],-1)])],512)]),e.createVNode(zs,{playhead:e.unref(Z),clips:e.unref(k),"selected-clip-id":((re=e.unref(ce))==null?void 0:re.id)??((Ee=e.unref(k)[0])==null?void 0:Ee.id)??null,duration:ba.value,fps:e.unref(_e),"zoom-level":e.unref(Ue),"snap-enabled":Rt.value,sensitivity:.25,"is-mobile":!0,"onUpdate:playhead":e.unref(ht),onTrim:e.unref(ye),onSplit:Gn,onClipSelect:Zn,onClipMove:e.unref(Pt),onClipLongPress:uo,onSnapStateChange:cn},null,8,["playhead","clips","selected-clip-id","duration","fps","zoom-level","snap-enabled","onUpdate:playhead","onTrim","onClipMove"])],512),e.createElementVNode("div",_x,[e.createElementVNode("div",Ex,[e.createElementVNode("span",Sx,e.toDisplayString(Qa.value),1),e.createElementVNode("span",Cx,e.toDisplayString(On.value),1)]),e.createElementVNode("div",xx,[e.createElementVNode("button",{type:"button",class:"mobile-cut-nav-btn","data-testid":"btn-mobile-prev-cut","aria-label":"Jump to previous cut",disabled:!Cn.value,onClick:Ua}," Prev Cut ",8,Nx),e.createElementVNode("div",Vx,[e.createElementVNode("span",Tx,"Playhead "+e.toDisplayString(zn.value),1),e.createElementVNode("span",Bx,"In "+e.toDisplayString(ga.value),1),e.createElementVNode("span",Mx,"Out "+e.toDisplayString(Ra.value),1),e.createElementVNode("span",Ix,"Duration "+e.toDisplayString(Wo.value),1)]),e.createElementVNode("button",{type:"button",class:"mobile-cut-nav-btn","data-testid":"btn-mobile-next-cut","aria-label":"Jump to next cut",disabled:!Ta.value,onClick:mo}," Next Cut ",8,$x)]),e.createElementVNode("div",Fx,[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["mobile-snap-toggle",{active:Rt.value}]),"data-testid":"btn-mobile-snap-toggle",onClick:Vn},e.toDisplayString(Rt.value?"Snap On":"Snap Off"),3),e.createElementVNode("div",Dx,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(Za,Ie=>e.createElementVNode("button",{key:Ie,type:"button",class:e.normalizeClass(["mobile-speed-chip",{active:e.unref(be)===Ie}]),"data-testid":`btn-mobile-speed-${String(Ie).replace(".","-")}`,onClick:Lt=>mn(Ie)},e.toDisplayString(Ie)+"x ",11,Ax)),64))])]),e.createElementVNode("div",Rx,[e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-undo","aria-label":"Undo",disabled:!e.unref(ae),onClick:Tn}," Undo ",8,Lx),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-redo","aria-label":"Redo",disabled:!e.unref(ge),onClick:Bn}," Redo ",8,Px),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-split","aria-label":"Split at playhead",disabled:!gt.value,onClick:an}," Split ",8,Ux),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn","data-testid":"btn-mobile-duplicate","aria-label":"Duplicate selected clip",disabled:!Qt.value,onClick:un}," Duplicate ",8,Ox),e.createElementVNode("button",{type:"button",class:"mobile-edit-btn mobile-edit-btn--danger","data-testid":"btn-mobile-delete","aria-label":"Delete selected clip",disabled:!ot.value,onClick:Mn}," Delete ",8,zx)])]),e.createElementVNode("div",{ref_key:"mobileControlsRef",ref:so,class:"controls-section mobile-controls"},null,512),xa.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"mobile-action-sheet-backdrop","data-testid":"video-mobile-action-sheet",onClick:Pa},[e.createElementVNode("div",{class:"mobile-action-sheet",onClick:U[3]||(U[3]=e.withModifiers(()=>{},["stop"]))},[U[16]||(U[16]=e.createElementVNode("div",{class:"mobile-action-sheet-handle"},null,-1)),e.createElementVNode("div",jx,[e.createElementVNode("span",Wx,e.toDisplayString(hi.value),1),e.createElementVNode("span",Hx,e.toDisplayString(vi.value),1)]),e.createElementVNode("div",Zx,[e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-undo",disabled:!e.unref(ae),onClick:Tn},"Undo",8,Gx),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-redo",disabled:!e.unref(ge),onClick:Bn},"Redo",8,Xx),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-split",disabled:!gt.value,onClick:an},"Split",8,Kx),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-duplicate",disabled:!Qt.value,onClick:un},"Duplicate",8,qx),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn mobile-action-sheet-btn--danger","data-testid":"btn-mobile-sheet-delete",disabled:!ot.value,onClick:Mn},"Delete",8,Jx),e.createElementVNode("button",{type:"button",class:"mobile-action-sheet-btn","data-testid":"btn-mobile-sheet-close",onClick:Pa},"Close")])])])):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("div",Yx,[e.createElementVNode("div",Qx,[e.createElementVNode("div",eN,[e.createElementVNode("div",tN,[e.createElementVNode("label",null,[e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":U[4]||(U[4]=Ie=>T.value=Ie),"aria-label":"Fit mode","data-testid":"select-video-fit-mode"},[...U[17]||(U[17]=[e.createElementVNode("option",{value:"contain"},"Contain",-1),e.createElementVNode("option",{value:"cover"},"Cover",-1),e.createElementVNode("option",{value:"none"},"None",-1)])],512),[[e.vModelSelect,T.value]])])]),e.withDirectives(e.createVNode(Cs,{ref_key:"pixiPreviewDesktopRef",ref:v,"aria-hidden":!p.value,class:"preview-host-child",source:Te.value,"fallback-duration":ba.value,filters:qe.value,playhead:vt.value,"is-playing":e.unref(J),"fit-mode":T.value,active:p.value,onPlayPause:e.unref(Je),onFrameUpdate:La,onDurationChange:Nn},null,8,["aria-hidden","source","fallback-duration","filters","playhead","is-playing","fit-mode","active","onPlayPause"]),[[e.vShow,p.value]]),e.withDirectives(e.createVNode(Os,{"aria-hidden":!f.value,class:"preview-host-child","media-uuid":l.value,recipe:I.value,media:ct.value,"enable-engine":f.value&&tt.value,"fit-mode":T.value,onTimeUpdate:dn,onPlayStateChange:Hn,onDurationChange:Nn,onEngineReady:fo},null,8,["aria-hidden","media-uuid","recipe","media","enable-engine","fit-mode"]),[[e.vShow,f.value]]),V.showThumbnailPicker?(e.openBlock(),e.createBlock(y_,{key:0,"media-uuid":l.value,duration:ba.value,onSelect:Na},null,8,["media-uuid","duration"])):e.createCommentVNode("",!0)]),e.createElementVNode("div",aN,[e.createElementVNode("div",nN,[e.createElementVNode("div",oN,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(K.value,Ie=>(e.openBlock(),e.createElementBlock("button",{key:Ie.id,class:e.normalizeClass(["tab-btn",{active:c.value===Ie.id}]),onClick:Lt=>c.value=Ie.id},e.toDisplayString(Ie.label),11,iN))),128))]),e.createElementVNode("div",rN,[e.withDirectives(e.createElementVNode("div",lN,[e.createVNode(Ws,{filters:$e.value,"active-filters":Y.value,"thumbnail-url":fe.value,onApplyFilter:q,onRemoveFilter:oe,onUpdateParam:Tt,onPreviewFilter:ho},null,8,["filters","active-filters","thumbnail-url"])],512),[[e.vShow,c.value==="filters"]]),e.withDirectives(e.createElementVNode("div",sN,[e.createVNode(Gs,{overlays:M.value,onAddOverlay:go,onUpdateOverlay:bo,onRemoveOverlay:S},null,8,["overlays"])],512),[[e.vShow,c.value==="text"]]),e.withDirectives(e.createElementVNode("div",dN,[e.createVNode(Xs,{"selected-clips":j.value,"applied-transitions":E.value,onApplyTransition:R,onRemoveTransition:te,onPreviewTransition:we},null,8,["selected-clips","applied-transitions"])],512),[[e.vShow,c.value==="transitions"]]),e.withDirectives(e.createElementVNode("div",cN,[e.createVNode(Ks,{"audio-layers":D.value,"master-volume":L.value,onAddTrack:ze,onUpdateTrack:je,onRemoveTrack:ut,onUpdateVolume:Bt,onToggleMute:qt,onUpdateMasterVolume:ca},null,8,["audio-layers","master-volume"])],512),[[e.vShow,c.value==="audio"]]),e.withDirectives(e.createElementVNode("div",uN,[e.unref(Be)?(e.openBlock(),e.createBlock(Hs,{key:0,filter:e.unref(Be),"current-frame":e.unref(le),onUpdateParams:vo},null,8,["filter","current-frame"])):(e.openBlock(),e.createElementBlock("div",mN,[...U[18]||(U[18]=[e.createElementVNode("p",null,"Select a filter from the Filters tab to adjust its parameters",-1)])]))],512),[[e.vShow,c.value==="adjustments"]]),e.withDirectives(e.createElementVNode("div",pN,[e.createVNode(Zs,{"can-export":e.unref(W),"is-exporting":wt.value,"export-progress":yt.value,onExport:sc,onCancelExport:lc,onSaveDraft:ql,onReset:fc},null,8,["can-export","is-exporting","export-progress"]),Yt.value?(e.openBlock(),e.createElementBlock("div",fN," Export complete ")):e.createCommentVNode("",!0),Et.value&&!Yt.value?(e.openBlock(),e.createElementBlock("div",hN,e.toDisplayString(Et.value),1)):e.createCommentVNode("",!0)],512),[[e.vShow,c.value==="export"]])])])])]),e.createElementVNode("div",vN,[e.createElementVNode("div",{ref_key:"timelineContainerRef",ref:sn,class:"timeline-container"},[e.createElementVNode("div",gN,[e.createElementVNode("label",null,[U[19]||(U[19]=e.createTextVNode(" Zoom ",-1)),e.createElementVNode("input",{type:"range",min:"10",max:"600",value:e.unref(Ue),onInput:U[5]||(U[5]=Ie=>$n(Ie))},null,40,bN)]),e.createElementVNode("span",yN,e.toDisplayString(Math.round(e.unref(Ue)))+" px/s",1),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["desktop-snap-toggle",{active:Rt.value}]),"data-testid":"btn-desktop-snap-toggle",onClick:Vn},e.toDisplayString(Rt.value?"Snap On":"Snap Off"),3)]),e.createVNode(zs,{playhead:e.unref(Z),clips:e.unref(k),"selected-clip-id":((De=e.unref(ce))==null?void 0:De.id)??((Me=e.unref(k)[0])==null?void 0:Me.id)??null,duration:ba.value,fps:e.unref(_e),"zoom-level":e.unref(Ue),"snap-enabled":Rt.value,sensitivity:.25,"onUpdate:playhead":e.unref(ht),onTrim:e.unref(ye),onSplit:Gn,onClipSelect:Zn,onClipMove:e.unref(Pt),onClipLongPress:uo,onSnapStateChange:cn},null,8,["playhead","clips","selected-clip-id","duration","fps","zoom-level","snap-enabled","onUpdate:playhead","onTrim","onClipMove"]),e.createVNode(js,{"selected-clip":e.unref(ce),"can-split":gt.value,"can-delete":ot.value,"is-playing":e.unref(J),"zoom-level":e.unref(Ue),"playback-speed":e.unref(be),onSplit:an,onDelete:Mn,onDuplicate:un,onZoomIn:gi,onZoomOut:bi,onZoomChange:Xn,onFitToWindow:po,onPlayPause:e.unref(Je),onFrameForward:e.unref(Wt),onFrameBackward:e.unref(Pe),onSkipToStart:e.unref(Ht),onSkipToEnd:e.unref(Zt),onSpeedChange:e.unref(It)},null,8,["selected-clip","can-split","can-delete","is-playing","zoom-level","playback-speed","onPlayPause","onFrameForward","onFrameBackward","onSkipToStart","onSkipToEnd","onSpeedChange"]),xe.value?(e.openBlock(),e.createElementBlock("div",wN,[e.createElementVNode("div",kN,[e.createElementVNode("label",_N,[U[20]||(U[20]=e.createElementVNode("span",null,"Trim start (s)",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":U[6]||(U[6]=Ie=>At.value=Ie),type:"number",step:"0.01",min:"0",inputmode:"decimal","data-testid":"video-dev-trim-start"},null,512),[[e.vModelText,At.value]])]),e.createElementVNode("label",EN,[U[21]||(U[21]=e.createElementVNode("span",null,"Trim end (s)",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":U[7]||(U[7]=Ie=>zt.value=Ie),type:"number",step:"0.01",min:"0",inputmode:"decimal","data-testid":"video-dev-trim-end"},null,512),[[e.vModelText,zt.value]])]),e.createElementVNode("button",{class:"dev-editor-button",type:"button","data-testid":"video-dev-trim-start-playhead",disabled:!e.unref(ce),onClick:U[8]||(U[8]=Ie=>Q("start"))}," Start = Playhead ",8,SN),e.createElementVNode("button",{class:"dev-editor-button",type:"button","data-testid":"video-dev-trim-end-playhead",disabled:!e.unref(ce),onClick:U[9]||(U[9]=Ie=>Q("end"))}," End = Playhead ",8,CN),e.createElementVNode("button",{class:"dev-editor-button dev-editor-button--primary",type:"button","data-testid":"video-dev-apply-trim",disabled:!e.unref(ce),onClick:Fe}," Apply Trim ",8,xN)]),e.createElementVNode("div",NN,[e.createElementVNode("label",VN,[U[22]||(U[22]=e.createElementVNode("span",null,"Quick filter",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":U[10]||(U[10]=Ie=>Ft.value=Ie),"data-testid":"video-dev-filter-select"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList($e.value,Ie=>(e.openBlock(),e.createElementBlock("option",{key:Ie.id,value:Ie.id},e.toDisplayString(Ie.name),9,TN))),128))],512),[[e.vModelSelect,Ft.value]])]),e.createElementVNode("button",{class:"dev-editor-button dev-editor-button--primary",type:"button","data-testid":"video-dev-apply-filter",disabled:!e.unref(ce)||Ft.value==="",onClick:ne}," Apply Filter ",8,BN),e.createElementVNode("button",{class:"dev-editor-button",type:"button","data-testid":"video-dev-clear-filters",disabled:e.unref(me).length===0,onClick:Qe}," Clear Filters ",8,MN),e.createElementVNode("button",{class:"dev-editor-button dev-editor-button--primary",type:"button","data-testid":"btn-apply-noise-filter","aria-label":"Apply noise filter for QA testing",disabled:!e.unref(ce),onClick:U[11]||(U[11]=Ie=>q("noise"))}," QA: Noise ",8,IN),e.createElementVNode("button",{class:"dev-editor-button dev-editor-button--primary",type:"button","data-testid":"btn-apply-grayscale-filter","aria-label":"Apply grayscale filter for QA testing",disabled:!e.unref(ce),onClick:U[12]||(U[12]=Ie=>q("grayscale"))}," QA: Grayscale ",8,$N)])])):e.createCommentVNode("",!0)],512)])]))],2)}}}),mf=Ae(FN,[["__scopeId","data-v-1bb4247b"]]),DN={key:0,class:"video-editor-v2-toolbar"},AN={class:"video-editor-v2-body"},RN={key:0,class:"video-editor-v2-assets","data-testid":"v2-assets-panel"},LN={class:"video-editor-v2-main"},PN={class:"video-editor-v2-canvas"},UN={key:1,class:"video-editor-v2-timeline"},ON=["aria-expanded"],zN=["aria-hidden","inert"],jN="(max-width: 900px)",WN=e.defineComponent({__name:"SplitPanelLayout",setup(o,{expose:a}){const t=e.ref(!1),n=e.ref(!1);let i=null,r=null;const l=c=>{t.value=c,c&&(n.value=!1)},s=()=>{n.value=!0},d=()=>{n.value=!1};return e.onMounted(()=>{typeof window>"u"||!window.matchMedia||(i=window.matchMedia(jN),l(i.matches),r=c=>l(c.matches),i.addEventListener?i.addEventListener("change",r):"addListener"in i&&i.addListener(r))}),e.onBeforeUnmount(()=>{!i||!r||(i.removeEventListener?i.removeEventListener("change",r):"removeListener"in i&&i.removeListener(r),i=null,r=null)}),a({isMobile:t}),(c,u)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-editor-v2",{"is-mobile":t.value,"is-desktop":!t.value}]),"data-testid":"video-editor-v2-shell"},[c.$slots.toolbar?(e.openBlock(),e.createElementBlock("div",DN,[e.renderSlot(c.$slots,"toolbar",{},void 0,!0)])):e.createCommentVNode("",!0),e.createElementVNode("div",AN,[!t.value&&c.$slots.assets?(e.openBlock(),e.createElementBlock("aside",RN,[e.renderSlot(c.$slots,"assets",{},void 0,!0)])):e.createCommentVNode("",!0),e.createElementVNode("div",LN,[e.createElementVNode("div",PN,[e.renderSlot(c.$slots,"canvas",{},void 0,!0)])])]),c.$slots.timeline?(e.openBlock(),e.createElementBlock("div",UN,[e.renderSlot(c.$slots,"timeline",{isMobile:t.value},void 0,!0)])):e.createCommentVNode("",!0),!t.value&&c.$slots.inspector?(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[n.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:0,class:"video-editor-v2-tools-tab",type:"button","data-testid":"v2-tools-drawer-open","aria-label":"Open editor tools","aria-controls":"v2-editor-tools-drawer","aria-expanded":n.value?"true":"false",onClick:s}," Tools ",8,ON)),n.value?(e.openBlock(),e.createElementBlock("div",{key:1,class:"video-editor-v2-drawer-backdrop","data-testid":"v2-tools-drawer-backdrop",onClick:d})):e.createCommentVNode("",!0),e.createElementVNode("aside",{id:"v2-editor-tools-drawer",class:e.normalizeClass(["video-editor-v2-side",{"is-open":n.value}]),"data-testid":"v2-side-panel","aria-hidden":n.value?"false":"true",inert:!n.value},[e.createElementVNode("div",{class:"video-editor-v2-side-header"},[u[0]||(u[0]=e.createElementVNode("span",null,"Tools",-1)),e.createElementVNode("button",{class:"video-editor-v2-side-close",type:"button","data-testid":"v2-tools-drawer-close","aria-label":"Close editor tools",onClick:d}," x ")]),e.renderSlot(c.$slots,"inspector",{},void 0,!0)],10,zN)],64)):e.createCommentVNode("",!0),t.value?e.renderSlot(c.$slots,"drawer",{key:3},void 0,!0):e.createCommentVNode("",!0)],2))}}),HN=Ae(WN,[["__scopeId","data-v-ed83bde0"]]),ZN=["aria-selected"],GN={class:"asset-rail-item__main"},XN={class:"asset-rail-item__type","data-testid":"asset-rail-item-type"},KN={class:"asset-rail-item__label","data-testid":"asset-rail-item-label"},qN={key:0,class:"asset-rail-item__details","data-testid":"asset-rail-item-details"},JN={class:"asset-rail-item__actions","aria-label":"Asset actions"},YN=e.defineComponent({__name:"AssetRailItem",props:{source:{},selected:{type:Boolean}},emits:["add","replaceSelected","remove"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>t.source.label??t.source.name??t.source.filename??t.source.id),r=e.computed(()=>{if(typeof t.source.duration!="number"||!Number.isFinite(t.source.duration))return null;const c=Math.max(0,Math.round(t.source.duration)),u=Math.floor(c/60),m=c%60;return`${u}:${m.toString().padStart(2,"0")}`}),l=e.computed(()=>typeof t.source.width!="number"||typeof t.source.height!="number"||!Number.isFinite(t.source.width)||!Number.isFinite(t.source.height)?null:`${Math.round(t.source.width)}x${Math.round(t.source.height)}`),s=e.computed(()=>[r.value,l.value].filter(c=>c!==null)),d=c=>{if(c==="add"){n("add",t.source.id);return}if(c==="replaceSelected"){n("replaceSelected",t.source.id);return}n("remove",t.source.id)};return(c,u)=>(e.openBlock(),e.createElementBlock("article",{class:e.normalizeClass(["asset-rail-item",{"is-selected":c.selected}]),"aria-selected":c.selected?"true":"false","data-testid":"asset-rail-item"},[e.createElementVNode("div",GN,[e.createElementVNode("span",XN,e.toDisplayString(c.source.type),1),e.createElementVNode("span",KN,e.toDisplayString(i.value),1),s.value.length>0?(e.openBlock(),e.createElementBlock("span",qN,e.toDisplayString(s.value.join(" / ")),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",JN,[e.createElementVNode("button",{class:"asset-rail-item__action",type:"button",title:"Add to timeline","aria-label":"Add to timeline","data-testid":"asset-rail-item-add",onClick:u[0]||(u[0]=m=>d("add"))}," + "),e.createElementVNode("button",{class:"asset-rail-item__action",type:"button",title:"Replace selected","aria-label":"Replace selected","data-testid":"asset-rail-item-replace",onClick:u[1]||(u[1]=m=>d("replaceSelected"))}," R "),e.createElementVNode("button",{class:"asset-rail-item__action asset-rail-item__action--danger",type:"button",title:"Remove asset","aria-label":"Remove asset","data-testid":"asset-rail-item-remove",onClick:u[2]||(u[2]=m=>d("remove"))}," - ")])],10,ZN))}}),QN=Ae(YN,[["__scopeId","data-v-3ba2fd25"]]),eV={class:"asset-rail__header"},tV={key:0,class:"asset-rail__list","data-testid":"asset-rail-list"},aV={key:1,class:"asset-rail__empty","data-testid":"asset-rail-empty"},nV=e.defineComponent({__name:"AssetRail",props:{sources:{},selectedSourceId:{},uploadsEnabled:{type:Boolean}},emits:["add","replaceSelected","remove","importFiles"],setup(o,{emit:a}){const t=a,n=e.ref(null),i=e.ref(!1),r=(m,p)=>{if(m==="add"){t("add",p);return}if(m==="replaceSelected"){t("replaceSelected",p);return}t("remove",p)},l=()=>{var m;(m=n.value)==null||m.click()},s=m=>{const p=m.target;if(!(p!=null&&p.files)||p.files.length===0)return;const f=Array.from(p.files);t("importFiles",f),p.value=""},d=m=>{m.preventDefault(),m.dataTransfer&&(m.dataTransfer.dropEffect="copy"),i.value=!0},c=()=>{i.value=!1},u=m=>{var f;m.preventDefault(),i.value=!1;const p=Array.from(((f=m.dataTransfer)==null?void 0:f.files)??[]);p.length!==0&&t("importFiles",p)};return(m,p)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["asset-rail",{"asset-rail--drag-over":i.value&&m.uploadsEnabled}]),"aria-label":"Assets","data-testid":"asset-rail",onDragover:d,onDragleave:c,onDrop:u},[e.createElementVNode("div",eV,[p[3]||(p[3]=e.createElementVNode("h2",{class:"asset-rail__title"},"Assets",-1)),m.uploadsEnabled?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"asset-rail__upload","data-testid":"asset-rail-upload","aria-label":"Upload media files",onClick:l}," Upload ")):e.createCommentVNode("",!0),m.uploadsEnabled?(e.openBlock(),e.createElementBlock("input",{key:1,ref_key:"fileInput",ref:n,class:"asset-rail__file-input",type:"file",accept:"video/mp4,video/webm,video/quicktime,image/png,image/jpeg,image/webp,audio/mpeg,audio/aac,audio/wav",multiple:"","data-testid":"asset-rail-file-input",onChange:s},null,544)):e.createCommentVNode("",!0)]),m.sources.length>0?(e.openBlock(),e.createElementBlock("div",tV,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(m.sources,f=>(e.openBlock(),e.createBlock(QN,{key:f.id,source:f,selected:f.id===m.selectedSourceId,onAdd:p[0]||(p[0]=h=>r("add",h)),onReplaceSelected:p[1]||(p[1]=h=>r("replaceSelected",h)),onRemove:p[2]||(p[2]=h=>r("remove",h))},null,8,["source","selected"]))),128))])):(e.openBlock(),e.createElementBlock("p",aV,e.toDisplayString(m.uploadsEnabled?"Drop files here or click Upload to add media.":"No assets"),1))],34))}}),oV=Ae(nV,[["__scopeId","data-v-3db665c6"]]),iV={class:"audio-mixer-panel__tracks","data-testid":"audio-mixer-tracks"},rV={key:0,class:"audio-mixer-panel__empty","data-testid":"audio-mixer-empty"},lV=["data-testid"],sV={class:"audio-mixer-strip__header"},dV={class:"audio-mixer-strip__identity"},cV={class:"audio-mixer-strip__kind"},uV=["data-testid"],mV=["data-testid"],pV=["data-testid"],fV={class:"audio-mixer-meter__rail","aria-hidden":"true"},hV={class:"audio-mixer-meter__value"},vV={class:"audio-mixer-strip__controls"},gV=["for"],bV=["id","min","max","value","data-testid","onInput"],yV={class:"audio-mixer-control__value"},wV={class:"audio-mixer-buttons"},kV=["aria-pressed","aria-label","data-testid","onClick"],_V=["aria-pressed","aria-label","data-testid","onClick"],EV=["for"],SV=["id","value","data-testid","onInput"],CV={class:"audio-mixer-control__value"},xV=["data-testid"],NV={key:0},VV={key:1},TV=["data-testid"],BV=["data-testid"],MV=["data-testid"],IV={class:"audio-mixer-routing__target"},$V={class:"audio-mixer-strip__header"},FV={class:"audio-mixer-strip__identity"},DV={class:"audio-mixer-strip__name","data-testid":"audio-mixer-master-name"},AV={class:"audio-mixer-meter__rail","aria-hidden":"true"},RV={class:"audio-mixer-meter__value"},LV={class:"audio-mixer-strip__controls"},PV={key:0,class:"audio-mixer-control audio-mixer-control--fader",for:"audio-mixer-master-fader"},UV=["min","max","value"],OV={class:"audio-mixer-control__value"},zV={class:"audio-mixer-buttons"},jV=["aria-pressed","aria-label"],WV={key:1,class:"audio-mixer-effects","data-testid":"audio-mixer-master-effects"},HV=["data-testid"],ZV=e.defineComponent({__name:"AudioMixerPanel",props:{state:{},deviceClass:{}},emits:["update"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>kE(t.deviceClass,t.state.capabilities)),r=e.computed(()=>t.deviceClass==="desktop"),l=e.computed(()=>[...t.state.tracks].sort((L,z)=>L.order-z.order)),s=e.computed(()=>{const L=new Map(_E(l.value,t.state.master.muted).map(z=>[z.trackId,z]));return l.value.map(z=>({track:z,effectiveState:L.get(z.id)??null}))}),d=e.computed(()=>i.value.canAdjustTrackFaders),c=e.computed(()=>i.value.canAdjustMasterFader),u=e.computed(()=>i.value.canMuteTracks),m=e.computed(()=>r.value&&i.value.canSoloTracks),p=e.computed(()=>r.value&&i.value.canAdjustPan),f=e.computed(()=>i.value.canViewMeters&&i.value.meterMode!=="off"),h=e.computed(()=>r.value&&i.value.canEditEffectSlots&&i.value.maxEffectSlots>0),v=e.computed(()=>r.value&&i.value.canEditRouting),y=L=>{if(!(L.target instanceof HTMLInputElement))return null;const z=Number(L.target.value);return Number.isFinite(z)?z:null},w=(L,z)=>{if(!d.value)return;const C=y(z);C!==null&&n("update",{type:"track-fader-db",trackId:L.id,valueDb:Yi(C)})},_=L=>{u.value&&n("update",{type:"track-mute",trackId:L.id,muted:!L.controls.muted})},b=L=>{m.value&&n("update",{type:"track-solo",trackId:L.id,solo:!L.controls.solo})},g=(L,z)=>{if(!p.value)return;const C=y(z);C!==null&&n("update",{type:"track-pan",trackId:L.id,pan:Sp(C)})},I=L=>{if(!c.value)return;const z=y(L);z!==null&&n("update",{type:"master-fader-db",valueDb:Yi(z)})},T=L=>{u.value&&n("update",{type:"master-mute",muted:!L.muted})},$=L=>{const z=Math.round(L*10)/10;return z>0?`+${z.toFixed(z%1===0?0:1)} dB`:`${z.toFixed(z%1===0?0:1)} dB`},N=L=>L===0?"C":`${L<0?"L":"R"} ${Math.round(Math.abs(L)*100)}`,B=L=>{if(L===void 0)return"";const z=Math.round(L*10)/10;return`${z.toFixed(z%1===0?0:1)}s`},P=L=>$(L),x=L=>{if(!Number.isFinite(L))return 0;const z=Math.min(nl,Math.max(oo,L)),C=nl-oo;return Math.round((z-oo)/C*100)},M=L=>L.slice(0,i.value.maxEffectSlots),E=L=>h.value&&M(L).length>0,D=L=>L.timeline.fadeIn!==void 0||L.timeline.fadeOut!==void 0,j=L=>L===null?"Unknown":L.mutedByMaster?"Master muted":L.mutedByTrack?"Muted":L.mutedBySolo?"Muted by solo":L.soloed?"Solo active":"Audible";return(L,z)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["audio-mixer-panel",`audio-mixer-panel--${L.deviceClass}`]),"data-testid":"audio-mixer-panel","aria-label":"Audio mixer"},[e.createElementVNode("div",iV,[s.value.length===0?(e.openBlock(),e.createElementBlock("p",rV," No audio tracks ")):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(s.value,({track:C,effectiveState:A})=>(e.openBlock(),e.createElementBlock("article",{key:C.id,class:e.normalizeClass(["audio-mixer-strip",{"is-muted":(A==null?void 0:A.effectivelyMuted)===!0,"is-soloed":C.controls.solo}]),"data-testid":`audio-mixer-track-${C.id}`},[e.createElementVNode("header",sV,[e.createElementVNode("div",dV,[e.createElementVNode("span",cV,e.toDisplayString(C.kind),1),e.createElementVNode("h3",{class:"audio-mixer-strip__name","data-testid":`audio-mixer-track-name-${C.id}`},e.toDisplayString(C.name),9,uV)]),e.createElementVNode("span",{class:e.normalizeClass(["audio-mixer-strip__status",{"is-active":(A==null?void 0:A.audible)===!0}]),"data-testid":`audio-mixer-track-status-${C.id}`},e.toDisplayString(j(A)),11,mV)]),f.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:e.normalizeClass(["audio-mixer-meter",{"is-clipping":C.controls.meter.clipping}]),"data-testid":`audio-mixer-track-meter-${C.id}`,"aria-label":"Track meter"},[e.createElementVNode("span",fV,[e.createElementVNode("span",{class:"audio-mixer-meter__fill",style:e.normalizeStyle({width:`${x(C.controls.meter.peakDb)}%`})},null,4)]),e.createElementVNode("span",hV,e.toDisplayString(P(C.controls.meter.peakDb)),1)],10,pV)):e.createCommentVNode("",!0),e.createElementVNode("div",vV,[d.value?(e.openBlock(),e.createElementBlock("label",{key:0,class:"audio-mixer-control audio-mixer-control--fader",for:`audio-mixer-track-fader-${C.id}`},[z[2]||(z[2]=e.createElementVNode("span",{class:"audio-mixer-control__label"},"Level",-1)),e.createElementVNode("input",{id:`audio-mixer-track-fader-${C.id}`,type:"range",class:"audio-mixer-control__range",min:C.controls.fader.minDb,max:C.controls.fader.maxDb,value:C.controls.fader.valueDb,step:"0.5","data-testid":`audio-mixer-track-fader-${C.id}`,onInput:O=>w(C,O)},null,40,bV),e.createElementVNode("span",yV,e.toDisplayString($(C.controls.fader.valueDb)),1)],8,gV)):e.createCommentVNode("",!0),e.createElementVNode("div",wV,[u.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:e.normalizeClass(["audio-mixer-button",{"is-active":C.controls.muted}]),"aria-pressed":C.controls.muted?"true":"false","aria-label":C.controls.muted?`Unmute ${C.name}`:`Mute ${C.name}`,"data-testid":`audio-mixer-track-mute-${C.id}`,onClick:O=>_(C)}," M ",10,kV)):e.createCommentVNode("",!0),m.value?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",class:e.normalizeClass(["audio-mixer-button audio-mixer-button--solo",{"is-active":C.controls.solo}]),"aria-pressed":C.controls.solo?"true":"false","aria-label":C.controls.solo?`Clear solo on ${C.name}`:`Solo ${C.name}`,"data-testid":`audio-mixer-track-solo-${C.id}`,onClick:O=>b(C)}," S ",10,_V)):e.createCommentVNode("",!0)])]),p.value?(e.openBlock(),e.createElementBlock("label",{key:1,class:"audio-mixer-control audio-mixer-control--pan",for:`audio-mixer-track-pan-${C.id}`},[z[3]||(z[3]=e.createElementVNode("span",{class:"audio-mixer-control__label"},"Pan",-1)),e.createElementVNode("input",{id:`audio-mixer-track-pan-${C.id}`,type:"range",class:"audio-mixer-control__range",min:"-1",max:"1",step:"0.01",value:C.controls.pan.value,"data-testid":`audio-mixer-track-pan-${C.id}`,onInput:O=>g(C,O)},null,40,SV),e.createElementVNode("span",CV,e.toDisplayString(N(C.controls.pan.value)),1)],8,EV)):e.createCommentVNode("",!0),D(C)?(e.openBlock(),e.createElementBlock("div",{key:2,class:"audio-mixer-strip__fades","data-testid":`audio-mixer-track-fades-${C.id}`},[C.timeline.fadeIn!==void 0?(e.openBlock(),e.createElementBlock("span",NV," In "+e.toDisplayString(B(C.timeline.fadeIn)),1)):e.createCommentVNode("",!0),C.timeline.fadeOut!==void 0?(e.openBlock(),e.createElementBlock("span",VV," Out "+e.toDisplayString(B(C.timeline.fadeOut)),1)):e.createCommentVNode("",!0)],8,xV)):e.createCommentVNode("",!0),E(C.effectSlots)?(e.openBlock(),e.createElementBlock("div",{key:3,class:"audio-mixer-effects","data-testid":`audio-mixer-track-effects-${C.id}`},[z[4]||(z[4]=e.createElementVNode("span",{class:"audio-mixer-effects__label"},"FX",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(M(C.effectSlots),O=>(e.openBlock(),e.createElementBlock("span",{key:O.id,class:e.normalizeClass(["audio-mixer-effect",{"is-empty":O.kind==="empty","is-bypassed":O.bypassed,"is-enabled":O.enabled&&!O.bypassed}]),"data-testid":`audio-mixer-track-effect-${C.id}-${O.index}`},e.toDisplayString(O.label),11,BV))),128))],8,TV)):e.createCommentVNode("",!0),v.value?(e.openBlock(),e.createElementBlock("div",{key:4,class:"audio-mixer-routing","data-testid":`audio-mixer-track-routing-${C.id}`},[z[5]||(z[5]=e.createElementVNode("span",{class:"audio-mixer-routing__label"},"Route",-1)),e.createElementVNode("span",IV,e.toDisplayString(L.state.master.name),1)],8,MV)):e.createCommentVNode("",!0)],10,lV))),128))]),e.createElementVNode("article",{class:e.normalizeClass(["audio-mixer-strip audio-mixer-strip--master",{"is-muted":L.state.master.muted}]),"data-testid":"audio-mixer-master-strip"},[e.createElementVNode("header",$V,[e.createElementVNode("div",FV,[z[6]||(z[6]=e.createElementVNode("span",{class:"audio-mixer-strip__kind"},"master",-1)),e.createElementVNode("h3",DV,e.toDisplayString(L.state.master.name),1)]),e.createElementVNode("span",{class:e.normalizeClass(["audio-mixer-strip__status",{"is-active":!L.state.master.muted}]),"data-testid":"audio-mixer-master-status"},e.toDisplayString(L.state.master.muted?"Muted":"Active"),3)]),f.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:e.normalizeClass(["audio-mixer-meter",{"is-clipping":L.state.master.meter.clipping}]),"data-testid":"audio-mixer-master-meter","aria-label":"Master meter"},[e.createElementVNode("span",AV,[e.createElementVNode("span",{class:"audio-mixer-meter__fill",style:e.normalizeStyle({width:`${x(L.state.master.meter.peakDb)}%`})},null,4)]),e.createElementVNode("span",RV,e.toDisplayString(P(L.state.master.meter.peakDb)),1)],2)):e.createCommentVNode("",!0),e.createElementVNode("div",LV,[c.value?(e.openBlock(),e.createElementBlock("label",PV,[z[7]||(z[7]=e.createElementVNode("span",{class:"audio-mixer-control__label"},"Level",-1)),e.createElementVNode("input",{id:"audio-mixer-master-fader",type:"range",class:"audio-mixer-control__range",min:L.state.master.fader.minDb,max:L.state.master.fader.maxDb,value:L.state.master.fader.valueDb,step:"0.5","data-testid":"audio-mixer-master-fader",onInput:z[0]||(z[0]=C=>I(C))},null,40,UV),e.createElementVNode("span",OV,e.toDisplayString($(L.state.master.fader.valueDb)),1)])):e.createCommentVNode("",!0),e.createElementVNode("div",zV,[u.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:e.normalizeClass(["audio-mixer-button",{"is-active":L.state.master.muted}]),"aria-pressed":L.state.master.muted?"true":"false","aria-label":L.state.master.muted?`Unmute ${L.state.master.name}`:`Mute ${L.state.master.name}`,"data-testid":"audio-mixer-master-mute",onClick:z[1]||(z[1]=C=>T(L.state.master))}," M ",10,jV)):e.createCommentVNode("",!0)])]),E(L.state.master.effectSlots)?(e.openBlock(),e.createElementBlock("div",WV,[z[8]||(z[8]=e.createElementVNode("span",{class:"audio-mixer-effects__label"},"FX",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(M(L.state.master.effectSlots),C=>(e.openBlock(),e.createElementBlock("span",{key:C.id,class:e.normalizeClass(["audio-mixer-effect",{"is-empty":C.kind==="empty","is-bypassed":C.bypassed,"is-enabled":C.enabled&&!C.bypassed}]),"data-testid":`audio-mixer-master-effect-${C.index}`},e.toDisplayString(C.label),11,HV))),128))])):e.createCommentVNode("",!0)],2)],2))}}),Nu=Ae(ZV,[["__scopeId","data-v-e5c785e8"]]),GV={class:"caption-srt-panel__header"},XV={class:"caption-srt-panel__title-group"},KV={class:"caption-srt-panel__title"},qV=["id"],JV={key:0,class:"caption-srt-panel__stats","data-testid":"caption-srt-desktop-stats"},YV={key:0,class:"caption-srt-panel__desktop-controls","data-testid":"caption-srt-desktop-controls"},QV={class:"caption-srt-panel__field"},eT={class:"caption-srt-panel__field"},tT=["for"],aT=["id","aria-describedby","aria-invalid"],nT=["id"],oT=["id"],iT={key:3,class:"caption-srt-panel__cue-summary","data-testid":"caption-srt-cue-summary","aria-label":"Current caption cue summary"},rT={key:0,class:"caption-srt-panel__cue-list"},lT={class:"caption-srt-panel__cue-time"},sT={class:"caption-srt-panel__cue-text"},dT={key:1,class:"caption-srt-panel__empty"},cT=e.defineComponent({__name:"CaptionSrtPanel",props:{captionTrack:{default:null},segments:{default:null},layout:{default:"desktop"},trackId:{default:"caption-track-srt"},idPrefix:{default:"srt-cue"},panelId:{default:"caption-srt-panel"},title:{default:"Caption SRT"},textareaLabel:{default:"SRT caption text"}},emits:["import","update:captionTrack","update:segments","export","clear"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(""),r=e.ref(null),l=e.ref(null),s=e.ref(""),d=e.ref(""),c=e.ref(!1),u=e.computed(()=>t.layout==="mobile"),m=e.computed(()=>`${t.panelId}-textarea`),p=e.computed(()=>`${t.panelId}-helper`),f=e.computed(()=>`${t.panelId}-error`),h=e.computed(()=>`${t.panelId}-status`),v=e.computed(()=>{const E=[p.value,h.value];return r.value!==null&&E.push(f.value),E.join(" ")}),y=e.computed(()=>t.captionTrack!==null?t.captionTrack.segments:t.segments??[]),w=e.computed(()=>{try{return{text:lu(y.value),errorMessage:null}}catch(E){return{text:"",errorMessage:P(E)}}}),_=e.computed(()=>y.value.length),b=e.computed(()=>y.value.reduce((E,D)=>Math.max(E,D.endTime),0)),g=e.computed(()=>y.value.slice(0,5));e.watch(()=>{var E,D;return[(E=t.captionTrack)==null?void 0:E.id,(D=t.captionTrack)==null?void 0:D.language,t.trackId]},([E,D,j])=>{s.value=E??j,d.value=D??""},{immediate:!0}),e.watch(w,E=>{if(E.errorMessage!==null){r.value=E.errorMessage;return}c.value||(i.value=E.text)},{immediate:!0});const I=()=>{c.value=!0,l.value=null,r.value!==null&&(r.value=null)},T=()=>{const E=i.value;if(r.value=null,l.value=null,E.trim()===""){r.value="Paste SRT text before importing captions.";return}try{const D=zE(E,{idPrefix:t.idPrefix}),j=oS(B(D)),L=lu(j.segments);i.value=L,c.value=!1,l.value=`Imported ${x(j.segments.length)}.`,n("update:captionTrack",j),n("update:segments",j.segments),n("import",{track:j,segments:j.segments,sourceText:E})}catch(D){r.value=P(D)}},$=()=>{const E=w.value;if(r.value=E.errorMessage,E.errorMessage!==null){l.value=null;return}i.value=E.text,c.value=!1,l.value=E.text===""?"No captions to export.":`Exported ${x(_.value)}.`,n("export",E.text)},N=()=>{i.value="",c.value=!0,r.value=null,l.value="SRT text cleared.",n("clear")};function B(E){var L,z;const D={id:s.value.trim(),source:"srt-import",stylePreset:((L=t.captionTrack)==null?void 0:L.stylePreset)??"default",animation:((z=t.captionTrack)==null?void 0:z.animation)??"none",segments:E},j=d.value.trim();return j!==""&&(D.language=j),D}function P(E){return E instanceof io||E instanceof Error?E.message:"Unable to process SRT captions."}function x(E){return E===1?"1 cue":`${E} cues`}function M(E){const D=Math.floor(E/60),j=Math.floor(E%60);return`${D}:${j.toString().padStart(2,"0")}`}return(E,D)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["caption-srt-panel",{"caption-srt-panel--mobile":u.value}]),"data-testid":"caption-srt-panel","aria-label":"SRT caption import and export"},[e.createElementVNode("header",GV,[e.createElementVNode("div",XV,[e.createElementVNode("h2",KV,e.toDisplayString(E.title),1),e.createElementVNode("p",{id:p.value,class:"caption-srt-panel__helper"}," Paste SRT, import it as captions, or export the current caption track. ",8,qV)]),u.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",JV,[e.createElementVNode("span",null,e.toDisplayString(x(_.value)),1),e.createElementVNode("span",null,e.toDisplayString(M(b.value)),1)]))]),u.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",YV,[e.createElementVNode("label",QV,[D[3]||(D[3]=e.createElementVNode("span",null,"Track ID",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":D[0]||(D[0]=j=>s.value=j),class:"caption-srt-panel__input",type:"text",autocomplete:"off","data-testid":"caption-srt-track-id"},null,512),[[e.vModelText,s.value]])]),e.createElementVNode("label",eT,[D[4]||(D[4]=e.createElementVNode("span",null,"Language",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":D[1]||(D[1]=j=>d.value=j),class:"caption-srt-panel__input",type:"text",autocomplete:"off",placeholder:"en","data-testid":"caption-srt-language"},null,512),[[e.vModelText,d.value]])])])),e.createElementVNode("label",{class:"caption-srt-panel__textarea-label",for:m.value},e.toDisplayString(E.textareaLabel),9,tT),e.withDirectives(e.createElementVNode("textarea",{id:m.value,"onUpdate:modelValue":D[2]||(D[2]=j=>i.value=j),class:e.normalizeClass(["caption-srt-panel__textarea",{"has-error":r.value!==null}]),spellcheck:"false","aria-describedby":v.value,"aria-invalid":r.value!==null?"true":"false","data-testid":"caption-srt-textarea",onInput:I},null,42,aT),[[e.vModelText,i.value]]),r.value!==null?(e.openBlock(),e.createElementBlock("p",{key:1,id:f.value,class:"caption-srt-panel__error",role:"alert","data-testid":"caption-srt-error"},e.toDisplayString(r.value),9,nT)):(e.openBlock(),e.createElementBlock("p",{key:2,id:h.value,class:"caption-srt-panel__status","aria-live":"polite","data-testid":"caption-srt-status"},e.toDisplayString(l.value??"Ready for caption import or export."),9,oT)),e.createElementVNode("div",{class:"caption-srt-panel__actions","aria-label":"SRT caption actions"},[e.createElementVNode("button",{type:"button",class:"caption-srt-panel__button caption-srt-panel__button--primary","data-testid":"caption-srt-import",onClick:T}," Import "),e.createElementVNode("button",{type:"button",class:"caption-srt-panel__button","data-testid":"caption-srt-export",onClick:$}," Export "),e.createElementVNode("button",{type:"button",class:"caption-srt-panel__button","data-testid":"caption-srt-clear",onClick:N}," Clear ")]),u.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",iT,[D[5]||(D[5]=e.createElementVNode("p",{class:"caption-srt-panel__cue-summary-title"},"Cue summary",-1)),g.value.length>0?(e.openBlock(),e.createElementBlock("ol",rT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.value,j=>(e.openBlock(),e.createElementBlock("li",{key:j.id,class:"caption-srt-panel__cue"},[e.createElementVNode("span",lT,e.toDisplayString(M(j.startTime))+"-"+e.toDisplayString(M(j.endTime)),1),e.createElementVNode("span",sT,e.toDisplayString(j.text),1)]))),128))])):(e.openBlock(),e.createElementBlock("p",dT," No captions loaded. "))]))],2))}}),Vu=Ae(cT,[["__scopeId","data-v-1d5fdb3b"]]),uT=["aria-label"],mT={class:"draft-recovery-banner__header"},pT={class:"draft-recovery-banner__heading"},fT={class:"draft-recovery-banner__title"},hT={class:"draft-recovery-banner__summary","data-testid":"draft-recovery-summary"},vT={key:0,class:"draft-recovery-banner__list","data-testid":"draft-recovery-list"},gT={class:"draft-recovery-banner__record-copy"},bT={class:"draft-recovery-banner__record-title","data-testid":"draft-recovery-record-title"},yT={class:"draft-recovery-banner__record-meta"},wT={"data-testid":"draft-recovery-record-updated"},kT={"data-testid":"draft-recovery-record-reason"},_T={class:"draft-recovery-banner__actions"},ET=["onClick"],ST=["onClick"],CT={key:1,class:"draft-recovery-banner__mobile-prompt","data-testid":"draft-recovery-mobile-prompt"},xT={class:"draft-recovery-banner__record-copy"},NT={class:"draft-recovery-banner__record-title","data-testid":"draft-recovery-record-title"},VT={class:"draft-recovery-banner__record-meta"},TT={"data-testid":"draft-recovery-record-updated"},BT={"data-testid":"draft-recovery-record-reason"},MT={class:"draft-recovery-banner__actions draft-recovery-banner__actions--mobile"},IT={key:2,class:"draft-recovery-banner__empty","data-testid":"draft-recovery-empty"},$T=e.defineComponent({__name:"DraftRecoveryBanner",props:{records:{},surface:{},projectId:{},savedAt:{},maxAgeMs:{},now:{},maxDesktopItems:{default:3}},emits:["restore","dismiss"],setup(o,{emit:a}){const t=o,n=a,i={autosave:"Autosaved",manual:"Manual save","before-export":"Before export","before-close":"Before close"},r=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),l=e.computed(()=>{const T={};return t.projectId!==void 0&&(T.projectId=t.projectId),t.savedAt!==void 0&&(T.savedAt=t.savedAt),t.maxAgeMs!==void 0&&(T.maxAgeMs=t.maxAgeMs),t.now!==void 0&&(T.now=t.now),T}),s=e.computed(()=>{const T=t.maxDesktopItems;return!Number.isFinite(T)||T<1?1:Math.floor(T)}),d=e.computed(()=>oE(t.records,t.surface,l.value)),c=e.computed(()=>t.surface==="mobile"?d.value:d.value.slice(0,s.value)),u=e.computed(()=>t.surface==="mobile"),m=e.computed(()=>c.value.length>0),p=e.computed(()=>u.value?c.value[0]??null:null),f=e.computed(()=>u.value?"Unsaved video draft":"Unsaved video drafts"),h=e.computed(()=>m.value?u.value?"A newer draft is available on this device.":`${c.value.length} recoverable draft${c.value.length===1?"":"s"} found.`:"No recoverable video drafts"),v=T=>{var $;return(($=T.snapshot.metadata.title)==null?void 0:$.trim())||"Untitled video draft"},y=T=>{const $=T.snapshot.metadata.saveReason;return $===void 0?"Saved draft":i[$]},w=T=>{const $=new Date(T.snapshot.metadata.updatedAt);return Number.isFinite($.getTime())?r.format($):"Updated time unavailable"},_=T=>{n("restore",T)},b=T=>{T.length!==0&&n("dismiss",T)},g=T=>{b([T])},I=()=>{b(c.value)};return(T,$)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["draft-recovery-banner",{"draft-recovery-banner--mobile":u.value,"draft-recovery-banner--empty":!m.value}]),"data-testid":"draft-recovery-banner","aria-live":"polite","aria-label":f.value},[e.createElementVNode("header",mT,[e.createElementVNode("div",pT,[$[2]||($[2]=e.createElementVNode("p",{class:"draft-recovery-banner__eyebrow"},"Draft recovery",-1)),e.createElementVNode("h2",fT,e.toDisplayString(f.value),1),e.createElementVNode("p",hT,e.toDisplayString(h.value),1)]),!u.value&&c.value.length>1?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"draft-recovery-banner__ghost-action","data-testid":"draft-recovery-dismiss-all",onClick:I}," Dismiss all ")):e.createCommentVNode("",!0)]),!u.value&&m.value?(e.openBlock(),e.createElementBlock("ul",vT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,N=>(e.openBlock(),e.createElementBlock("li",{key:N.key,class:"draft-recovery-banner__record","data-testid":"draft-recovery-record"},[e.createElementVNode("div",gT,[e.createElementVNode("h3",bT,e.toDisplayString(v(N)),1),e.createElementVNode("p",yT,[e.createElementVNode("span",wT,"Updated "+e.toDisplayString(w(N)),1),$[3]||($[3]=e.createElementVNode("span",{"aria-hidden":"true"},"·",-1)),e.createElementVNode("span",kT,e.toDisplayString(y(N)),1)])]),e.createElementVNode("div",_T,[e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__primary-action","data-testid":"draft-recovery-restore",onClick:B=>_(N)}," Restore ",8,ET),e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__secondary-action","data-testid":"draft-recovery-dismiss",onClick:B=>g(N)}," Dismiss ",8,ST)])]))),128))])):p.value?(e.openBlock(),e.createElementBlock("article",CT,[e.createElementVNode("div",xT,[e.createElementVNode("h3",NT,e.toDisplayString(v(p.value)),1),e.createElementVNode("p",VT,[e.createElementVNode("span",TT,"Updated "+e.toDisplayString(w(p.value)),1),$[4]||($[4]=e.createElementVNode("span",{"aria-hidden":"true"},"·",-1)),e.createElementVNode("span",BT,e.toDisplayString(y(p.value)),1)])]),e.createElementVNode("div",MT,[e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__primary-action","data-testid":"draft-recovery-restore",onClick:$[0]||($[0]=N=>_(p.value))}," Restore "),e.createElementVNode("button",{type:"button",class:"draft-recovery-banner__secondary-action","data-testid":"draft-recovery-dismiss",onClick:$[1]||($[1]=N=>g(p.value))}," Dismiss ")])])):(e.openBlock(),e.createElementBlock("p",IT," No recoverable drafts "))],10,uT))}}),Tu=Ae($T,[["__scopeId","data-v-3ed3c273"]]),FT={class:"inspector-tabs",role:"tablist","aria-label":"Editor tools"},DT=["aria-selected","data-testid","onClick"],AT=["aria-labelledby"],RT={class:"inspector-placeholder","data-testid":"v2-inspector-placeholder"},LT=e.defineComponent({__name:"InspectorPanel",props:{activeTab:{},tabs:{},compact:{type:Boolean,default:!1}},emits:["update:activeTab"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>t.tabs.filter(l=>l.enabled)),r=l=>{l!==t.activeTab&&n("update:activeTab",l)};return(l,s)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["inspector-panel",{"inspector-panel--compact":l.compact}]),"data-testid":"v2-inspector-panel"},[e.createElementVNode("nav",FT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,d=>(e.openBlock(),e.createElementBlock("button",{key:d.id,type:"button",role:"tab",class:e.normalizeClass(["inspector-tab",{"is-active":l.activeTab===d.id}]),"aria-selected":l.activeTab===d.id?"true":"false","data-testid":`v2-inspector-tab-${d.id}`,onClick:c=>r(d.id)},e.toDisplayString(d.label),11,DT))),128))]),e.createElementVNode("div",{class:"inspector-body",role:"tabpanel","aria-labelledby":`v2-inspector-tab-${l.activeTab}`},[e.renderSlot(l.$slots,l.activeTab,{},()=>[e.createElementVNode("div",RT,[e.createElementVNode("p",null,e.toDisplayString(l.activeTab)+" controls — coming soon",1)])],!0)],8,AT)],2))}}),PT=Ae(LT,[["__scopeId","data-v-7f5b0e50"]]),UT={class:"keyframe-preset-panel__header"},OT={class:"keyframe-preset-panel__target","data-testid":"keyframe-preset-target"},zT={key:0,class:"keyframe-preset-panel__notice","data-testid":"keyframe-preset-invalid-duration"},jT={class:"keyframe-preset-panel__grid","data-testid":"keyframe-preset-buttons"},WT=["disabled","aria-disabled","data-testid","onClick"],HT={class:"keyframe-preset-panel__preset-label"},ZT={class:"keyframe-preset-panel__preset-summary"},GT={key:1,class:"keyframe-preset-panel__compact-summary","data-testid":"keyframe-preset-mobile-summary"},XT={key:2,class:"keyframe-preset-panel__desktop-summary","data-testid":"keyframe-preset-desktop-summary"},KT={class:"keyframe-preset-panel__summary-list"},qT=["data-testid"],JT={key:0,class:"keyframe-preset-panel__summary-empty","data-testid":"keyframe-preset-summary-empty"},YT=e.defineComponent({__name:"KeyframePresetPanel",props:{duration:{},target:{},deviceClass:{}},emits:["apply-preset"],setup(o,{emit:a}){const t=o,n=a,i={all:"All targets",opacity:"Opacity",scale:"Scale",x:"Pan X",y:"Pan Y",rotation:"Rotation",audioVolume:"Audio"},r=[{id:"fade-in",label:"Fade in",target:"opacity",summary:"Opacity 0 -> 100%",create:T=>{const $=tS({duration:I(T)});return w("fade-in","Fade in",$,T)}},{id:"fade-out",label:"Fade out",target:"opacity",summary:"Opacity 100 -> 0%",create:T=>{const $=I(T),N=aS({startTime:T-$,duration:$});return w("fade-out","Fade out",N,T)}},{id:"push-in",label:"Push in",target:"scale",summary:"Scale 100 -> 108%",create:T=>{const $=nS({duration:T,fromScale:1,toScale:1.08,easing:"ease-out"});return w("push-in","Push in",$,T)}},{id:"push-out",label:"Push out",target:"scale",summary:"Scale 108 -> 100%",create:T=>b({id:"push-out",label:"Push out",target:"scale",duration:T,startValue:1.08,endValue:1,easing:"ease-in"})},{id:"pan-x-left",label:"Pan left",target:"x",summary:"X 55 -> 45%",create:T=>b({id:"pan-x-left",label:"Pan left",target:"x",duration:T,startValue:.55,endValue:.45,easing:"ease-in-out"})},{id:"pan-x-right",label:"Pan right",target:"x",summary:"X 45 -> 55%",create:T=>b({id:"pan-x-right",label:"Pan right",target:"x",duration:T,startValue:.45,endValue:.55,easing:"ease-in-out"})},{id:"pan-y-up",label:"Pan up",target:"y",summary:"Y 55 -> 45%",create:T=>b({id:"pan-y-up",label:"Pan up",target:"y",duration:T,startValue:.55,endValue:.45,easing:"ease-in-out"})},{id:"pan-y-down",label:"Pan down",target:"y",summary:"Y 45 -> 55%",create:T=>b({id:"pan-y-down",label:"Pan down",target:"y",duration:T,startValue:.45,endValue:.55,easing:"ease-in-out"})},{id:"audio-fade-in",label:"Audio fade in",target:"audioVolume",summary:"Volume 0 -> 100%",create:T=>b({id:"audio-fade-in",label:"Audio fade in",target:"audioVolume",duration:I(T),startValue:0,endValue:1,easing:"ease-out"})},{id:"audio-fade-out",label:"Audio fade out",target:"audioVolume",summary:"Volume 100 -> 0%",create:T=>{const $=I(T);return b({id:"audio-fade-out",label:"Audio fade out",target:"audioVolume",duration:$,startTime:T-$,startValue:1,endValue:0,easing:"ease-in"})}}],l=e.computed(()=>YE(t.deviceClass)),s=e.computed(()=>l.value.platform==="mobile"),d=e.computed(()=>Number.isFinite(t.duration)&&t.duration>0),c=e.computed(()=>t.target==="all"?r:r.filter(T=>T.target===t.target)),u=e.computed(()=>d.value?c.value.map(T=>({definition:T,automation:T.create(t.duration)})):[]),m=e.computed(()=>i[t.target]),p=e.computed(()=>{const T=c.value.length,$=T===1?"preset":"presets";return d.value?`${T} ${$} - ${h(t.duration)} clip.`:`${T} ${$} available when duration is set.`}),f=T=>{if(!d.value)return;const $=T.create(t.duration);n("apply-preset",{presetId:$.id,target:$.target,keyframes:$.keyframes,automation:$})},h=T=>{const $=Math.round(T*100)/100;return`${$.toFixed($%1===0?0:2)}s`},v=(T,$)=>T==="opacity"||T==="audioVolume"?`${Math.round($*100)}%`:T==="scale"?`${Math.round($*100)}%`:T==="x"||T==="y"?`${Math.round($*100)}%`:`${Math.round($*100)/100}`,y=T=>{const[$,N]=T.keyframes;return`${h($.time)} ${v(T.target,$.value)} -> ${h(N.time)} ${v(T.target,N.value)}`};function w(T,$,N,B){return _({id:T,label:$,target:N.target,duration:B,keyframes:N.keyframes})}function _(T){const $=eS(T.keyframes,{target:T.target,minTime:0,maxTime:T.duration}),N=$[0],B=$[1];if($.length!==2||N===void 0||B===void 0)throw new Error("Keyframe preset panel presets must generate exactly two keyframes.");return{id:T.id,label:T.label,target:T.target,editingMode:"preset-only",keyframes:[N,B]}}function b(T){const $=T.startTime??0,N=[g(`${T.id}:start`,T.target,$,T.startValue,"linear"),g(`${T.id}:end`,T.target,$+T.duration,T.endValue,T.easing)];return _({id:T.id,label:T.label,target:T.target,duration:$+T.duration,keyframes:N})}function g(T,$,N,B,P){return{id:T,target:$,time:N,value:B,easing:P}}function I(T){return Math.min(T,1)}return(T,$)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["keyframe-preset-panel",{"keyframe-preset-panel--mobile":s.value}]),"data-testid":"keyframe-preset-panel","aria-label":"Keyframe presets"},[e.createElementVNode("header",UT,[$[0]||($[0]=e.createElementVNode("div",{class:"keyframe-preset-panel__heading"},[e.createElementVNode("p",{class:"keyframe-preset-panel__eyebrow"},"Presets"),e.createElementVNode("h3",{class:"keyframe-preset-panel__title"},"Keyframe automation")],-1)),e.createElementVNode("span",OT,e.toDisplayString(m.value),1)]),d.value?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("p",zT," Set a valid clip duration to apply automation presets. ")),e.createElementVNode("div",jT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,N=>(e.openBlock(),e.createElementBlock("button",{key:N.id,type:"button",class:"keyframe-preset-panel__preset",disabled:!d.value,"aria-disabled":d.value?void 0:"true","data-testid":`keyframe-preset-button-${N.id}`,onClick:B=>f(N)},[e.createElementVNode("span",HT,e.toDisplayString(N.label),1),e.createElementVNode("span",ZT,e.toDisplayString(N.summary),1)],8,WT))),128))]),s.value?(e.openBlock(),e.createElementBlock("p",GT,e.toDisplayString(p.value),1)):(e.openBlock(),e.createElementBlock("div",XT,[$[1]||($[1]=e.createElementVNode("p",{class:"keyframe-preset-panel__summary-title"},"Generated keyframes",-1)),e.createElementVNode("ul",KT,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(u.value,N=>(e.openBlock(),e.createElementBlock("li",{key:N.definition.id,class:"keyframe-preset-panel__summary-row","data-testid":`keyframe-preset-summary-${N.definition.id}`},[e.createElementVNode("span",null,e.toDisplayString(N.definition.label),1),e.createElementVNode("span",null,e.toDisplayString(y(N.automation)),1)],8,qT))),128))]),u.value.length===0?(e.openBlock(),e.createElementBlock("p",JT," No generated keyframes until duration is valid. ")):e.createCommentVNode("",!0)]))],2))}}),Bu=Ae(YT,[["__scopeId","data-v-79615683"]]),QT={class:"mobile-clip-summary__main"},eB={class:"mobile-clip-summary__title","data-testid":"v2-mobile-clip-label"},tB={class:"mobile-clip-summary__stats","aria-label":"Selected clip timing"},aB={class:"mobile-clip-summary__stat"},nB={"data-testid":"v2-mobile-clip-start"},oB={class:"mobile-clip-summary__stat"},iB={"data-testid":"v2-mobile-clip-end"},rB={class:"mobile-clip-summary__stat"},lB={"data-testid":"v2-mobile-clip-duration"},sB={key:1,class:"mobile-clip-summary__empty","data-testid":"v2-mobile-no-clip"},dB=e.defineComponent({__name:"MobileClipSummary",props:{selectedClip:{}},emits:["open-actions"],setup(o,{emit:a}){const t=o,n=a,i=m=>m===void 0||!Number.isFinite(m)?null:m,r=e.computed(()=>{var m,p,f;return((p=(m=t.selectedClip)==null?void 0:m.label)==null?void 0:p.trim())||((f=t.selectedClip)==null?void 0:f.id)||""}),l=e.computed(()=>t.selectedClip?i(t.selectedClip.timelineStart)??i(t.selectedClip.startTime):null),s=e.computed(()=>t.selectedClip?i(t.selectedClip.timelineEnd)??i(t.selectedClip.endTime):null),d=e.computed(()=>{const m=l.value,p=s.value;return m!==null&&p!==null?Math.max(0,p-m):t.selectedClip?i(t.selectedClip.duration):null}),c=m=>{if(m===null)return"--";const p=Math.round(m*100)/100;return`${p.toFixed(p%1===0?0:2)}s`},u=()=>{t.selectedClip&&n("open-actions",t.selectedClip.id)};return(m,p)=>(e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["mobile-clip-summary",{"mobile-clip-summary--empty":!m.selectedClip}]),"data-testid":"v2-mobile-clip-summary","aria-live":"polite"},[m.selectedClip?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("div",QT,[p[0]||(p[0]=e.createElementVNode("p",{class:"mobile-clip-summary__eyebrow"},"Selected clip",-1)),e.createElementVNode("h2",eB,e.toDisplayString(r.value),1)]),e.createElementVNode("dl",tB,[e.createElementVNode("div",aB,[p[1]||(p[1]=e.createElementVNode("dt",null,"Start",-1)),e.createElementVNode("dd",nB,e.toDisplayString(c(l.value)),1)]),e.createElementVNode("div",oB,[p[2]||(p[2]=e.createElementVNode("dt",null,"End",-1)),e.createElementVNode("dd",iB,e.toDisplayString(c(s.value)),1)]),e.createElementVNode("div",rB,[p[3]||(p[3]=e.createElementVNode("dt",null,"Duration",-1)),e.createElementVNode("dd",lB,e.toDisplayString(c(d.value)),1)])]),e.createElementVNode("button",{type:"button",class:"mobile-clip-summary__actions","aria-label":"Open selected clip actions","data-testid":"v2-mobile-clip-actions",onClick:u}," Actions ")],64)):(e.openBlock(),e.createElementBlock("p",sB," No clip selected "))],2))}}),cB=Ae(dB,[["__scopeId","data-v-433c7812"]]),uB=["aria-label"],mB=["aria-pressed","data-testid","onClick"],pB={class:"mobile-tool-picker__label"},fB=e.defineComponent({__name:"MobileToolPicker",props:{modelValue:{},ariaLabel:{default:"Mobile editor tools"}},emits:["update:modelValue"],setup(o,{emit:a}){const t=[{id:"look",label:"Look"},{id:"trim",label:"Trim"},{id:"text",label:"Text"},{id:"audio",label:"Audio"},{id:"export",label:"Export"},{id:"more",label:"More"}],n=o,i=a,r=l=>{l!==n.modelValue&&i("update:modelValue",l)};return(l,s)=>(e.openBlock(),e.createElementBlock("div",{class:"mobile-tool-picker",role:"group","aria-label":l.ariaLabel,"data-testid":"v2-mobile-tool-picker"},[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(t,d=>e.createElementVNode("button",{key:d.id,type:"button",class:e.normalizeClass(["mobile-tool-picker__button",{"is-active":l.modelValue===d.id}]),"aria-pressed":l.modelValue===d.id?"true":"false","data-testid":`v2-mobile-tool-${d.id}`,onClick:c=>r(d.id)},[e.createElementVNode("span",pB,e.toDisplayString(d.label),1)],10,mB)),64))],8,uB))}}),hB=Ae(fB,[["__scopeId","data-v-ec597c70"]]),vB=["aria-label","data-snap"],gB=["aria-expanded"],bB={class:"drawer-header"},yB={class:"drawer-body"},wB=e.defineComponent({__name:"VideoBottomDrawer",props:{initialSnap:{default:"half"},ariaLabel:{default:"Editor controls drawer"},containerHeight:{default:0}},emits:["snap-change"],setup(o,{expose:a,emit:t}){const n=["collapsed","half","full"],i=o,r=t,l=e.ref(null),s=e.ref(null),d=e.ref(i.initialSnap);let c=!1,u=!1,m=null,p=0,f=0,h=0;const v=B=>{const P=h||(typeof window<"u"?window.innerHeight:600);switch(B){case"collapsed":return 80;case"half":return Math.round(P*.45);case"full":return Math.round(P*.85)}},y=(B,{animate:P=!0}={})=>{var E;if(!l.value)return;const x=d.value;d.value=B;const M=typeof window<"u"&&((E=window.matchMedia)==null?void 0:E.call(window,"(prefers-reduced-motion: reduce)").matches);l.value.style.transition=P&&!M?"height 0.25s cubic-bezier(0.33, 1, 0.68, 1)":"none",l.value.style.height=`${v(B)}px`,B!==x&&r("snap-change",B,x)},w=B=>{let P=n[0],x=1/0;for(const M of n){const E=Math.abs(v(M)-B);E<x&&(x=E,P=M)}return P},_=()=>{const B=n.indexOf(d.value);y(n[(B+1)%n.length])},b=B=>{if(u){u=!1,B.preventDefault();return}_()},g=B=>{var P,x,M;if(B.button===0){c=!0,u=!1,m=B.pointerId,p=B.clientY,f=((P=l.value)==null?void 0:P.offsetHeight)??0;try{(M=(x=s.value)==null?void 0:x.setPointerCapture)==null||M.call(x,B.pointerId)}catch{}l.value&&(l.value.style.transition="none")}},I=B=>{if(!c||B.pointerId!==m)return;const P=B.clientY-p,x=f-P,M=v("collapsed"),E=v("full"),D=Math.max(M,Math.min(E,x));l.value&&(l.value.style.height=`${D}px`),Math.abs(P)>4&&(u=!0),B.preventDefault()},T=B=>{var x,M,E;if(!c)return;c=!1;try{(M=(x=s.value)==null?void 0:x.releasePointerCapture)==null||M.call(x,B.pointerId)}catch{}m=null;const P=((E=l.value)==null?void 0:E.offsetHeight)??0;y(w(P))},$=(B,P={})=>{n.includes(B)&&y(B,{animate:P.animate!==!1})},N=B=>{h=Math.max(0,Number(B)||0),y(d.value,{animate:!1})};return e.watch(()=>i.containerHeight,B=>{B>0&&N(B)}),e.onMounted(()=>{i.containerHeight>0&&(h=i.containerHeight),y(d.value,{animate:!1})}),e.onBeforeUnmount(()=>{c=!1,m=null}),a({snapTo:$,updateContainerHeight:N,snap:d}),(B,P)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"rootEl",ref:l,class:"video-editor-v2-drawer",role:"dialog","aria-label":B.ariaLabel,"data-snap":d.value,"data-testid":"v2-video-bottom-drawer"},[e.createElementVNode("button",{ref_key:"handleEl",ref:s,type:"button",class:"drawer-handle","aria-label":"Drag to resize editor drawer","aria-expanded":d.value==="full"?"true":"false","data-testid":"v2-video-drawer-handle",onClick:b,onPointerdown:g,onPointermove:I,onPointerup:T,onPointercancel:T},[...P[0]||(P[0]=[e.createElementVNode("span",{class:"drawer-handle-grip","aria-hidden":"true"},null,-1)])],40,gB),e.createElementVNode("div",bB,[e.renderSlot(B.$slots,"header",{},void 0,!0)]),e.createElementVNode("div",yB,[e.renderSlot(B.$slots,"default",{},void 0,!0)])],8,vB))}}),kB=Ae(wB,[["__scopeId","data-v-4ebedbf7"]]),_B=new Set(["INPUT","TEXTAREA","SELECT"]);function EB(o){return o instanceof HTMLElement?!!(_B.has(o.tagName)||o.isContentEditable):!1}function SB(o,a={}){const t=n=>{var s,d,c,u,m,p,f,h,v,y,w,_,b,g,I,T,$;if(a.enabled&&a.enabled()===!1||EB(n.target))return;const i=n.ctrlKey||n.metaKey,r=n.shiftKey,l=n.key;if(i&&(l==="z"||l==="Z")){r?(s=o.redo)==null||s.call(o):(d=o.undo)==null||d.call(o),n.preventDefault();return}if(i&&(l==="s"||l==="S")){(c=o.save)==null||c.call(o),n.preventDefault();return}if(i&&(l==="e"||l==="E")){(u=o.exportNow)==null||u.call(o),n.preventDefault();return}switch(l){case" ":case"Spacebar":(m=o.playPause)==null||m.call(o),n.preventDefault();return;case"ArrowLeft":r?(p=o.secondBackward)==null||p.call(o):(f=o.frameBackward)==null||f.call(o),n.preventDefault();return;case"ArrowRight":r?(h=o.secondForward)==null||h.call(o):(v=o.frameForward)==null||v.call(o),n.preventDefault();return;case"Home":(y=o.skipToStart)==null||y.call(o),n.preventDefault();return;case"End":(w=o.skipToEnd)==null||w.call(o),n.preventDefault();return;case"[":(_=o.prevClip)==null||_.call(o),n.preventDefault();return;case"]":(b=o.nextClip)==null||b.call(o),n.preventDefault();return;case"s":case"S":i||((g=o.splitAtPlayhead)==null||g.call(o),n.preventDefault());return;case"Delete":case"Backspace":r?(I=o.rippleDeleteSelected)==null||I.call(o):(T=o.deleteSelected)==null||T.call(o),n.preventDefault();return;case"?":($=o.showShortcutsOverlay)==null||$.call(o),n.preventDefault();return}};e.onMounted(()=>{window.addEventListener("keydown",t)}),e.onBeforeUnmount(()=>{window.removeEventListener("keydown",t)})}const pf=["video/mp4","video/webm","video/quicktime"],ff=["image/png","image/jpeg","image/jpg","image/webp"],CB=["audio/mpeg","audio/mp3","audio/aac","audio/wav","audio/x-wav","audio/wave"],xB=new Set([...pf,...ff,...CB]),NB=2*1024*1024*1024,VB=60*60;function Mu(o,a){const t=o.type.toLowerCase();return xB.has(t)?o.size>NB?{ok:!1,reason:"oversize",message:`File is too large (${(o.size/(1024*1024*1024)).toFixed(2)} GiB). Limit is 2 GiB.`}:typeof a=="number"&&Number.isFinite(a)&&a>VB?{ok:!1,reason:"duration_exceeded",message:`Clip is too long (${Math.round(a)}s). Limit is 1 hour.`}:{ok:!0,kind:pf.includes(t)?"video":ff.includes(t)?"image":"audio"}:{ok:!1,reason:"unsupported_mime",message:`Unsupported file type: ${t||"unknown"}.`}}const TB="mediables-asset-blobs",vn="blobs",BB=1;class MB{constructor(){this.dbPromise=null}openDb(){return this.dbPromise?this.dbPromise:(this.dbPromise=new Promise((a,t)=>{if(typeof indexedDB>"u"){t(new Error("IndexedDB is not available in this environment."));return}const n=indexedDB.open(TB,BB);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(vn)||i.createObjectStore(vn)},n.onsuccess=()=>{a(n.result)},n.onerror=()=>{t(n.error??new Error("Failed to open IndexedDB."))}}),this.dbPromise)}async put(a,t){const n=await this.openDb();await new Promise((i,r)=>{const d=n.transaction(vn,"readwrite").objectStore(vn).put(t,a);d.onsuccess=()=>{i()},d.onerror=()=>{r(d.error??new Error("Failed to write blob."))}})}async get(a){const t=await this.openDb();return new Promise((n,i)=>{const s=t.transaction(vn,"readonly").objectStore(vn).get(a);s.onsuccess=()=>{const d=s.result;d==null?n(null):d instanceof Blob?n(d):n(null)},s.onerror=()=>{i(s.error??new Error("Failed to read blob."))}})}async delete(a){const t=await this.openDb();await new Promise((n,i)=>{const s=t.transaction(vn,"readwrite").objectStore(vn).delete(a);s.onsuccess=()=>{n()},s.onerror=()=>{i(s.error??new Error("Failed to delete blob."))}})}async clear(){const a=await this.openDb();await new Promise((t,n)=>{const l=a.transaction(vn,"readwrite").objectStore(vn).clear();l.onsuccess=()=>{t()},l.onerror=()=>{n(l.error??new Error("Failed to clear cache."))}})}}let hs=null;function IB(){return hs===null&&(hs=new MB),hs}class $B{constructor(){this.store=new Map}async put(a,t){this.store.set(a,t)}async get(a){return this.store.get(a)??null}async delete(a){this.store.delete(a)}async clear(){this.store.clear()}}function FB(){return`asset-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function DB(o,a){if(a<=0)return{};if(typeof URL>"u"||typeof document>"u")return{};const t=URL.createObjectURL(o),n=async()=>o.type.startsWith("video/")?new Promise(i=>{const r=document.createElement("video");r.preload="metadata",r.src=t,r.onloadedmetadata=()=>{i({durationSeconds:r.duration,width:r.videoWidth,height:r.videoHeight})},r.onerror=()=>{i({})}}):o.type.startsWith("audio/")?new Promise(i=>{const r=document.createElement("audio");r.preload="metadata",r.src=t,r.onloadedmetadata=()=>{i({durationSeconds:r.duration})},r.onerror=()=>{i({})}}):o.type.startsWith("image/")?new Promise(i=>{const r=new Image;r.src=t,r.onload=()=>{i({width:r.naturalWidth,height:r.naturalHeight})},r.onerror=()=>{i({})}}):{};try{return await Promise.race([n(),new Promise(i=>{setTimeout(()=>i({}),a)})])}finally{URL.revokeObjectURL(t)}}function AB(o){const a=e.reactive(new Map),t=o.blobCache??RB();async function n(u,m){try{await t.put(u,m)}catch{}}async function i(u){try{await t.delete(u)}catch{}}async function r(u,m,p){var f,h,v;try{m.status="uploading",m.uploadProgress=0,a.set(m.assetId,m);const y=await o.uploader.upload({file:u},({assetId:w,progress:_,status:b})=>{if(w!==m.assetId)return;const g=a.get(w);g&&(g.uploadProgress=_,g.status=b,a.set(w,g))});return a.set(m.assetId,y),y.status==="ready"?(i(m.assetId),(f=o.onReady)==null||f.call(o,y)):y.status==="failed"&&((h=o.onFailure)==null||h.call(o,y)),{ok:!0,record:y}}catch(y){const w=y instanceof Error?y.message:"Upload failed.",_={...m,status:"failed",failureMessage:w};return a.set(m.assetId,_),(v=o.onFailure)==null||v.call(o,_),{ok:!1,reason:"upload",message:w}}}const l=o.probeTimeoutMs??1500;async function s(u){const m=await DB(u,l),p=Mu(u,m.durationSeconds);if(!p.ok)return{ok:!1,reason:"preflight",message:p.message};const f=FB(),h={assetId:f,filename:u.name,mime:u.type,sizeBytes:u.size,status:"local-selected"};return m.durationSeconds!==void 0&&(h.durationSeconds=m.durationSeconds),m.width!==void 0&&(h.width=m.width),m.height!==void 0&&(h.height=m.height),a.set(f,h),await n(f,u),r(u,h)}async function d(u){const m=a.get(u);if(!m)return{ok:!1,reason:"unknown",message:"Unknown asset."};const p=await t.get(u);if(!p)return{ok:!1,reason:"unknown",message:"Original file is no longer cached."};const f=p instanceof File?p:new File([p],m.filename,{type:m.mime}),h=Mu(f,m.durationSeconds);return h.ok?r(f,m):{ok:!1,reason:"preflight",message:h.message}}async function c(u){a.delete(u),await i(u)}return{records:e.readonly(a),importFile:s,retry:d,remove:c}}function RB(){return typeof indexedDB<"u"?IB():new $B}const LB={class:"v2-toolbar-group"},PB=["aria-label"],UB=["disabled"],OB={class:"v2-toolbar-group"},zB={class:"v2-toolbar-fit"},jB=["disabled"],WB=["aria-label","title","disabled"],HB={class:"v2-assets"},ZB={key:0,class:"v2-asset-rail-status","data-testid":"v2-asset-rail-status",role:"status"},GB={class:"v2-preview-host"},XB={class:"v2-timeline-topbar"},KB={class:"v2-timeline-heading"},qB={class:"v2-timeline-meta","data-testid":"v2-timeline-meta"},JB={class:"v2-timeline-zoom"},YB=["value"],QB={class:"v2-timeline-zoom-readout"},e4={key:0,class:"v2-timeline-track-actions"},t4={key:0,class:"v2-timeline-track-target"},a4=["value"],n4=["value"],o4=["aria-pressed"],i4={key:0,class:"v2-editor-status","data-testid":"v2-editor-status",role:"status","aria-live":"polite"},r4={key:1,class:"v2-timeline-empty","data-testid":"v2-timeline-empty"},l4={key:1,class:"v2-empty-state"},s4={key:0,"data-testid":"v2-export-status-completed",class:"v2-export-status"},d4={key:1,class:"v2-export-status","data-testid":"v2-export-status-message"},c4={key:1,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-look"},u4={class:"v2-mobile-panel-section"},m4={class:"v2-mobile-panel-section v2-mobile-panel-section--compact"},p4={key:1,class:"v2-empty-state"},f4={key:2,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-trim"},h4={key:3,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-text"},v4={key:4,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-audio"},g4={key:5,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-export"},b4={key:0,class:"v2-export-status"},y4={key:1,class:"v2-export-status"},w4={key:6,class:"v2-mobile-tool-panel","data-testid":"v2-mobile-panel-more"},k4={class:"v2-mobile-secondary-controls"},_4={class:"v2-mobile-secondary-field"},E4=["aria-pressed"],S4=["disabled"],C4=["disabled"],x4={key:0,class:"v2-mobile-secondary-details","data-testid":"v2-mobile-transitions"},N4={class:"v2-mobile-secondary-details","data-testid":"v2-mobile-keyframes"},V4={class:"v2-shortcuts-overlay__panel"},T4={class:"v2-shortcuts-overlay__header"},B4=e.defineComponent({__name:"VideoEditorV2",props:{mediaUuid:{},initialRecipe:{},media:{},showThumbnailPicker:{type:Boolean,default:!1},workflowMode:{default:"full"},featureFlags:{},clientExportThreshold:{default:20},maxDuration:{default:300},serverRenderEndpoint:{default:null},assetUploader:{default:null}},emits:["recipe-generated","export-started","draft-saved","video-exported","thumbnail-selected","server-render-started","server-render-progress","server-render-completed","server-render-failed","close"],setup(o,{expose:a,emit:t}){var ho,vo,go,bo;const n=o,i=t,r=e.computed(()=>{var te;const S=typeof n.mediaUuid=="string"?n.mediaUuid.trim():"";if(S!=="")return S;const R=(te=n.media)==null?void 0:te.uuid;return typeof R=="string"&&R.trim()!==""?R.trim():`temp-${Date.now()}`}),l=Fp(r.value,n.initialRecipe,n.media),s=Rp(),d=e.ref("filters"),c=e.ref("look"),u=e.ref(null),m=e.computed(()=>n.workflowMode==="uploader"?{filters:!0,adjustments:!0,text:!1,transitions:!1,audio:!1,export:!1}:{filters:!0,adjustments:!0,text:!0,transitions:!0,audio:!0,export:!0}),p=e.computed(()=>{const S=n.featureFlags??{},R=["filters","adjustments","text","transitions","audio","export"],te={filters:"Filters",adjustments:"Adjust",text:"Text",transitions:"Transitions",audio:"Audio",export:"Export"};return R.map(we=>({id:we,label:te[we],enabled:typeof S[we]=="boolean"?S[we]:m.value[we]}))}),f=S=>p.value.some(R=>R.id===S&&R.enabled),h={look:"filters",text:"text",audio:"audio",export:"export"},v=e.computed(()=>{var S;return((S=n.featureFlags)==null?void 0:S.transitions)===!0});e.watch(c,S=>{var R,te;if(S!=="trim"&&S!=="more"){const we=h[S];f(we)&&(d.value=we)}(te=(R=u.value)==null?void 0:R.snapTo)==null||te.call(R,"full"),e.nextTick(()=>{var je;if(typeof document>"u")return;const we=document.querySelector(`[data-testid="v2-mobile-panel-${S}"]`);if(!we||!(we instanceof HTMLElement))return;const ze=typeof window<"u"&&((je=window.matchMedia)==null?void 0:je.call(window,"(prefers-reduced-motion: reduce)").matches);we.scrollIntoView({block:"start",behavior:ze?"auto":"smooth"})})});const y=e.ref(!1),w=e.computed(()=>d.value),_=e.computed(()=>w.value==="filters"||y.value),b=e.computed(()=>w.value!=="filters"&&!y.value),g=e.ref(null),I=e.computed(()=>g.value),T=["contain","cover","none"],$=S=>typeof S=="string"&&T.includes(S),N=S=>{var te;const R=(te=S==null?void 0:S.metadata)==null?void 0:te.fit_mode;return $(R)?R:null},B=e.ref(N(n.initialRecipe)??"contain"),P=e.ref("");e.watch(()=>{var S,R;return{file:(S=n.media)==null?void 0:S.file,url:(R=n.media)==null?void 0:R.url}},(S,R,te)=>{var ze,je;const we=P.value;te(()=>{we&&we.startsWith("blob:")&&URL.revokeObjectURL(we)}),(ze=n.media)!=null&&ze.file?P.value=URL.createObjectURL(n.media.file):(je=n.media)!=null&&je.url?P.value=n.media.url:P.value=""},{immediate:!0});const x=e.computed(()=>P.value),M=e.computed(()=>s.activeFilters.value),E=e.computed(()=>l.playheadPosition.value),D=lp({forcePixiPreview:y,getPreviewRef:()=>I.value,getSourceUrl:()=>P.value,setPlaying:l.setPlaying}),j=e.computed(()=>{if(!n.media)return null;const{file:S,...R}=n.media;return{...R,url:P.value}}),L=e.computed(()=>{var R;const S=(R=n.media)==null?void 0:R.url;return!!(S&&/^https?:/i.test(S))}),z=e.ref(0),C=e.computed(()=>{var R;if(l.totalDuration.value>0)return l.totalDuration.value;if(z.value>0)return z.value;const S=Number((R=n.media)==null?void 0:R.duration);return Number.isFinite(S)&&S>0?S:0}),A=S=>{!Number.isFinite(S)||S<=0||(z.value=S,l.updateSourceDuration(S))},O=S=>{S&&typeof S.time=="number"&&Number.isFinite(S.time)&&l.seekTo(S.time)},K=S=>{Number.isFinite(S)&&l.seekTo(S)},se=S=>{l.setPlaying(S)},xe=e.computed(()=>s.videoCompatibleFilters.value.map(R=>{var we;const te=[];if(R.controls&&R.controls.length>0)for(const ze of R.controls){const je=ze.type;if(je==="button"||je==="text"||je==="range")continue;const ut={id:ze.property||ze.id,label:ze.label||ze.id,type:je,default:ze.default??(je==="toggle"?!1:je==="color"?"#ffffff":0)};je==="slider"&&(ut.min=ze.min??0,ut.max=ze.max??1,ut.step=ze.step??.01),je==="select"&&ze.options&&(ut.options=ze.options),te.push(ut)}else if(R.paramRanges){const ze=Object.entries(R.paramRanges);for(const[je,ut]of ze){const Bt=je.replace(/[-_]/g," ").replace(/\b\w/g,Na=>Na.toUpperCase()),qt=(we=R.defaultParams)==null?void 0:we[je],ca=(ut.min+ut.max)/2;te.push({id:je,label:Bt,min:ut.min,max:ut.max,step:ut.step??.01,default:typeof qt=="number"?qt:ca})}}return{id:R.id,name:R.name,category:R.category,params:te}})),ue=e.computed(()=>{const S=new Map;return s.activeFilters.value.forEach(R=>S.set(R.filterId,R)),S}),le=e.computed(()=>{if(l.currentFrame.value)return l.currentFrame.value;const S=n.media;return(S==null?void 0:S.thumbnail_url)??(S==null?void 0:S.url)}),Z=e.shallowRef(null),k=e.ref(null),F=e.ref(null),W=e.ref(null),J=e.ref(!1),ce=new Map,Ue=(S,R)=>{const te={id:S.id??`text-overlay-recipe-${R}`,text:S.content};return S.fontFamily!==void 0&&(te.fontFamily=S.fontFamily),S.fontSize!==void 0&&(te.fontSize=S.fontSize),S.fontWeight!==void 0&&(te.fontWeight=S.fontWeight),S.color!==void 0&&(te.color=S.color),S.position!==void 0&&(te.position=S.position),S.startTime!==void 0&&(te.startTime=S.startTime),S.duration!==void 0&&(te.duration=S.duration),S.animation!==void 0&&(te.animation=S.animation),S.textAlign!==void 0&&(te.textAlign=S.textAlign),S.textBaseline!==void 0&&(te.textBaseline=S.textBaseline),te},be=S=>{const R={id:S.id,content:S.text};return S.fontFamily!==void 0&&(R.fontFamily=S.fontFamily),S.fontSize!==void 0&&(R.fontSize=S.fontSize),S.fontWeight!==void 0&&(R.fontWeight=S.fontWeight),S.color!==void 0&&(R.color=S.color),S.position!==void 0&&(R.position=S.position),S.startTime!==void 0&&(R.startTime=S.startTime),S.duration!==void 0&&(R.duration=S.duration),S.animation!==void 0&&(R.animation=S.animation),S.textAlign!==void 0&&(R.textAlign=S.textAlign),S.textBaseline!==void 0&&(R.textBaseline=S.textBaseline),R},_e=(S,R)=>{const te={id:S.id??`audio-track-recipe-${R}`,source:S.source};return S.volume!==void 0&&(te.volume=S.volume),S.startTime!==void 0&&(te.startTime=S.startTime),S.duration!==void 0&&(te.duration=S.duration),S.fadeIn!==void 0&&(te.fadeIn=S.fadeIn),S.fadeOut!==void 0&&(te.fadeOut=S.fadeOut),S.loop!==void 0&&(te.loop=S.loop),S.name!==void 0&&(te.name=S.name),te},ye=S=>{if(typeof S.source!="string")return null;const R={id:S.id,source:S.source};return S.volume!==void 0&&(R.volume=S.volume),S.startTime!==void 0&&(R.startTime=S.startTime),S.duration!==void 0&&(R.duration=S.duration),S.fadeIn!==void 0&&(R.fadeIn=S.fadeIn),S.fadeOut!==void 0&&(R.fadeOut=S.fadeOut),S.loop!==void 0&&(R.loop=S.loop),S.name!==void 0&&(R.name=S.name),R},Ne=S=>{const R={id:S.id,source:typeof S.source=="string"?S.source:""};return S.volume!==void 0&&(R.volume=S.volume),S.startTime!==void 0&&(R.startTime=S.startTime),S.duration!==void 0&&(R.duration=S.duration),S.fadeIn!==void 0&&(R.fadeIn=S.fadeIn),S.fadeOut!==void 0&&(R.fadeOut=S.fadeOut),S.loop!==void 0&&(R.loop=S.loop),S.name!==void 0&&(R.name=S.name),S.muted!==void 0&&(R.muted=S.muted),S.solo!==void 0&&(R.solo=S.solo),S.pan!==void 0&&(R.pan=S.pan),S.faderDb!==void 0&&(R.faderDb=S.faderDb),R},Se=S=>({...S,segments:S.segments.map(R=>{const te={...R};return R.words&&(te.words=R.words.map(we=>({...we}))),te})}),Re=e.ref((((ho=n.initialRecipe)==null?void 0:ho.textOverlays)??[]).map(Ue)),Oe=S=>{switch(S){case"crossfade":return"cross-fade";case"zoom":return"zoom-in";case"cut":return"fade";default:return S}},it=S=>{switch(S){case"ease-in":return"easeIn";case"ease-out":return"easeOut";case"ease-in-out":return"easeInOut";case"linear":return"linear"}},rt=S=>{switch(S){case"cross-fade":case"dissolve":return"crossfade";case"zoom-in":case"zoom-out":return"zoom";case"dip-to-white":return"fade";case"wipe-up":case"wipe-down":return"wipe-left";case"slide-up":case"slide-down":return"slide-left";default:return S}},Pt=S=>{switch(S){case"easeIn":return"ease-in";case"easeOut":return"ease-out";case"easeInOut":return"ease-in-out";case"linear":default:return"linear"}},bt=S=>({id:S.id,type:Oe(S.type),duration:S.duration,easing:it(S.easing),name:S.type,fromClipId:S.fromClipId,toClipId:S.toClipId,cutTime:S.cutTime??0}),Ct=S=>({id:S.id,type:rt(S.type),fromClipId:S.fromClipId,toClipId:S.toClipId,duration:S.duration,easing:Pt(S.easing),cutTime:S.cutTime}),mt=e.ref((((vo=n.initialRecipe)==null?void 0:vo.transitions)??[]).map(bt)),pt=e.ref((((go=n.initialRecipe)==null?void 0:go.audioTracks)??[]).map(_e)),Nt=e.ref(1),Ce=e.ref(!1),Ve=e.ref((((bo=n.initialRecipe)==null?void 0:bo.captionTracks)??[]).map(Se)),Le=e.ref([]),nt=e.ref(null),Ge=e.computed(()=>r.value),Je=e.computed(()=>Le.value),_t=e.computed(()=>Ve.value[0]??null),ht=e.computed(()=>{const S=l.selectedClip.value??l.timelineClips.value[0];return S?Math.max(0,S.timelineEnd-S.timelineStart):C.value}),Wt=e.computed(()=>EE(pt.value.map(Ne),{master:{volume:Nt.value,muted:Ce.value}})),Pe=e.computed(()=>{const S=[...l.timelineClips.value].sort((ut,Bt)=>ut.timelineStart-Bt.timelineStart),R=l.selectedClip.value??S[0];if(!R)return[];const te=S.findIndex(ut=>ut.id===R.id);if(te===-1)return[];const we=ut=>(ut.trackId??null)===(R.trackId??null),ze=S.slice(te+1).find(we);if(ze)return[R,ze];const je=[...S.slice(0,te)].reverse().find(we);return je?[je,R]:[]}),Ht=S=>{Z.value=S,S!=null&&S.composition&&(F.value=new Lp(S.composition),W.value=new Pp(S.composition));try{ce.size&&Z.value&&(ce.forEach((R,te)=>{Z.value.setClipFilters(te,R)}),ce.clear(),Z.value.composition.computeFrame())}catch{}},Zt=S=>{Z.value?Z.value.setClipFilters(S,s.activeFilters.value):ce.set(S,[...s.activeFilters.value])},It=S=>{var te,we;const R=((te=l.selectedClip.value)==null?void 0:te.id)??((we=l.timelineClips.value[0])==null?void 0:we.id);R&&(J.value=!0,typeof S=="object"&&S!==null&&"id"in S?s.applyFilter(S.id):typeof S=="string"&&s.applyFilter(S),l.setFilters(s.activeFilters.value),Zt(R),l.handleClipSelect(R),J.value=!1,qe())},Ut=S=>{var we,ze;const R=s.activeFilters.value.find(je=>je.filterId===S);R&&s.removeFilter(R.id),l.setFilters(s.activeFilters.value);const te=((we=l.selectedClip.value)==null?void 0:we.id)??((ze=l.timelineClips.value[0])==null?void 0:ze.id);te&&Zt(te),qe()},Gt=(S,R,te)=>{var je,ut;const we=s.activeFilters.value.find(Bt=>Bt.filterId===S);if(we){we.params={...we.params??{},[R]:te},l.setFilters(s.activeFilters.value);const Bt=((je=l.selectedClip.value)==null?void 0:je.id)??((ut=l.timelineClips.value[0])==null?void 0:ut.id);Bt&&Zt(Bt),qe();return}const ze=s.previewFilter.value;ze&&ze.filterId===S&&(ze.params={...ze.params??{},[R]:te})},sa=S=>{S&&typeof S.id=="string"&&S.id!==""&&s.previewFilterEffect(S.id)},ae=S=>{s.updateFilterParams(S),l.setFilters(s.activeFilters.value),qe()},ge=async S=>{if(!F.value)return;const R=await F.value.addTextOverlay(S);Re.value.push({id:R,...S})},pe=async(S,R)=>{if(!F.value)return;await F.value.updateTextOverlay(S,R);const te=Re.value.findIndex(we=>we.id===S);te!==-1&&(Re.value[te]={...Re.value[te],...R})},me=async S=>{F.value&&(await F.value.removeTextOverlay(S),Re.value=Re.value.filter(R=>R.id!==S))},Be=async S=>{const[R,te]=Pe.value;if(!R||!te)return;const we={id:`transition-${R.id}-${te.id}-${Date.now()}`,...S,name:S.type,fromClipId:R.id,toClipId:te.id,cutTime:R.timelineEnd};mt.value.push(we),l.setTransitions(mt.value.map(Ct)),qe()},He=S=>{mt.value[S]&&(mt.value.splice(S,1),l.setTransitions(mt.value.map(Ct)),qe())},lt=S=>{},Vt=async S=>{if(!W.value)return;const R=await W.value.addAudioTrack(S);pt.value.push({id:R,...S});const te=typeof S.source=="string"?S.source:S.source instanceof File?URL.createObjectURL(S.source):null;if(!te)return;const we={id:`audio-source-${R}`,type:"url",url:te,duration:typeof S.duration=="number"&&S.duration>0?S.duration:0,width:0,height:0};typeof S.name=="string"&&(we.filename=S.name),l.registerMediaSource(we);const ze=l.appendAudioSourceToTimeline(we.id);if(!ze.ok){ot.value=ze.message;return}ot.value=`Audio added to ${ze.value.trackId??"timeline"}.`,qe()},Ot=async(S,R)=>{if(!W.value)return;await W.value.updateAudioTrack(S,R);const te=pt.value.findIndex(we=>we.id===S);te!==-1&&(pt.value[te]={...pt.value[te],...R})},$t=async S=>{W.value&&(await W.value.removeAudioTrack(S),pt.value=pt.value.filter(R=>R.id!==S))},st=async(S,R)=>{if(!W.value)return;await W.value.updateVolume(S,R);const te=pt.value.find(we=>we.id===S);te&&(te.volume=R)},Jt=async(S,R)=>{if(!W.value)return;await W.value.muteTrack(S,R);const te=pt.value.find(we=>we.id===S);te&&(te.muted=R)},q=S=>{W.value&&(W.value.setMasterVolume(S),Nt.value=S)},ke=(S,R)=>{const te=pt.value.findIndex(ze=>ze.id===S);if(te===-1)return null;const we={...pt.value[te],...R};return pt.value[te]=we,we},oe=S=>{switch(S.type){case"track-fader-db":{const R=Qs(S.valueDb);ke(S.trackId,{faderDb:S.valueDb,volume:R}),W.value&&W.value.updateVolume(S.trackId,R);break}case"track-mute":ke(S.trackId,{muted:S.muted}),W.value&&W.value.muteTrack(S.trackId,S.muted);break;case"track-solo":ke(S.trackId,{solo:S.solo});break;case"track-pan":ke(S.trackId,{pan:S.pan});break;case"master-fader-db":{Nt.value=Qs(S.valueDb),W.value&&W.value.setMasterVolume(Ce.value?0:Nt.value);break}case"master-mute":Ce.value=S.muted,W.value&&W.value.setMasterVolume(Ce.value?0:Nt.value);break}},$e=S=>{Ve.value=[Se(S.track)],l.setCaptionTracks(Ve.value),qe()},At=S=>{Ve.value=[Se(S)],l.setCaptionTracks(Ve.value),qe()},zt=()=>{Ve.value=[],l.setCaptionTracks([]),qe()},Ft=S=>{const R=l.selectedClip.value??l.timelineClips.value[0];if(!R)return;const we=[...(R.keyframes??[]).filter(ze=>ze.target!==S.target),...S.keyframes].sort((ze,je)=>{const ut=ze.time-je.time;return ut===0?ze.id.localeCompare(je.id):ut});l.setClipKeyframes(R.id,we),qe()},wt=S=>{var R;return S.metadata||(S.metadata={created_at:new Date().toISOString(),editor_version:"2.0.0"}),S.metadata.fit_mode=B.value,(R=n.media)!=null&&R.url&&/^https?:/i.test(n.media.url)?S.metadata.source_url=n.media.url:delete S.metadata.source_url,S.captionTracks=Ve.value.map(Se),S},yt=(S,R)=>R?{...S,output:{...S.output,format:R.format,quality:R.quality,codec:R.codec??S.output.codec,fps:R.fps??S.output.fps,...typeof R.bitrate=="number"?{bitrate:R.bitrate}:{}}}:S,Yt=S=>S.map(R=>({...R,params:R.params&&typeof R.params=="object"?{...R.params}:R.params})),Et=S=>S.timeline.some(R=>Array.isArray(R.filters)&&R.filters.length>0),Kt=S=>{const R=Yt(s.activeFilters.value);if(!Et(S)&&R.length>0&&S.timeline.length>0){const we=S.timeline[0];we&&(S.timeline=[{...we,filters:R},...S.timeline.slice(1)])}return S},Ca=()=>{const S=Kt(wt(l.saveDraft()));try{localStorage.setItem(`video-draft-${r.value}`,JSON.stringify(S))}catch{}return fe(S,"manual",!0),S},X=()=>typeof localStorage>"u"?null:{getItem:S=>localStorage.getItem(S),setItem:(S,R)=>{localStorage.setItem(S,R)},removeItem:S=>{localStorage.removeItem(S)},listKeys:S=>{const R=[];for(let te=0;te<localStorage.length;te+=1){const we=localStorage.key(te);we!=null&&we.startsWith(S)&&R.push(we)}return R}},Y=async()=>{const S=X();if(S===null){Le.value=[];return}Le.value=await tu(S)},fe=async(S,R,te)=>{var ca,Na;const we=X();if(we===null)return;const ze=new Date().toISOString(),je={projectId:Ge.value,sourceMediaUuid:r.value,durationSeconds:C.value,editorVersion:((ca=S.metadata)==null?void 0:ca.editor_version)??"2.0.0",saveReason:R,now:ze};((Na=S.metadata)==null?void 0:Na.title)!==void 0&&(je.title=S.metadata.title);const ut=J2(sp(S),je);await iE(we,ut);const Bt=await tu(we),qt=tE(Bt,{maxCount:5,projectId:Ge.value,now:ze});await au(we,qt.removed),Le.value=[...qt.retained],te&&(nt.value=ze)},he=S=>S.snapshot.metadata.payloadKind==="project"?Z2(S.snapshot.payload):S.snapshot.payload,Te=S=>{const R=he(S);l.loadRecipe(R),Re.value=(R.textOverlays??[]).map(Ue),pt.value=(R.audioTracks??[]).map(_e),Ve.value=(R.captionTracks??[]).map(Se),mt.value=(R.transitions??[]).map(bt);const te=N(R);te!==null&&(B.value=te),ct()},Ke=S=>{const R=X();Le.value=Le.value.filter(te=>!S.some(we=>we.key===te.key)),R!==null&&au(R,S)},ct=()=>{k.value=wt(l.generateRecipe())};let tt=null;const qe=()=>{tt&&clearTimeout(tt),tt=setTimeout(()=>{ct(),tt=null},200)};if(e.watch(()=>l.timelineClips.value,qe,{deep:!0}),e.watch(()=>l.selectedClip.value,S=>{if(J.value||!S)return;const R=(S==null?void 0:S.filters)??[];s.setActiveFilters(R)},{immediate:!0}),e.watch(()=>s.activeFilters.value,S=>{l.setFilters(S),qe()},{deep:!0}),e.watch(()=>Re.value,S=>{l.setTextOverlays(S.map(be)),qe()},{deep:!0}),e.watch(()=>pt.value,S=>{const R=S.map(ye).filter(te=>te!==null);l.setAudioTracks(R),qe()},{deep:!0}),e.watch(()=>Ve.value,S=>{l.setCaptionTracks(S.map(Se)),qe()},{deep:!0}),Re.value.length>0&&l.setTextOverlays(Re.value.map(be)),pt.value.length>0){const S=pt.value.map(ye).filter(R=>R!==null);l.setAudioTracks(S)}Ve.value.length>0&&l.setCaptionTracks(Ve.value.map(Se)),e.watch(()=>l.playheadPosition.value,qe),ct();const vt=e.ref(!0),gt=e.ref(null),ot=e.ref(null);let Qt=null;e.watch(ot,S=>{Qt!==null&&(clearTimeout(Qt),Qt=null),!(S===null||S==="")&&(Qt=setTimeout(()=>{ot.value=null},4e3))});const Rt=e.ref(null),Za=e.computed(()=>l.tracks.value),ha=e.computed(()=>l.mediaSources.value),Cn=e.computed(()=>{var S,R;return((S=l.selectedClip.value)==null?void 0:S.sourceRefId)??((R=ha.value[0])==null?void 0:R.id)}),Ta=e.computed(()=>Za.value.filter(S=>S.locked!==!0&&S.type==="video")),xa=e.computed(()=>Rt.value?Za.value.find(S=>S.id===Rt.value)??null:null),Aa=e.computed(()=>!!l.selectedClip.value&&l.playheadPosition.value>0),va=e.computed(()=>!!l.selectedClip.value),Qa=e.computed(()=>l.timelineClips.value.length>0&&l.hasChanges.value),On=e.computed(()=>l.selectedClip.value??l.timelineClips.value[0]??null),Ga=S=>{const R=Number.isFinite(S)&&S>0?Math.round(S):0,te=Math.floor(R/60),we=R%60;return`${te}:${we.toString().padStart(2,"0")}`},zn=e.computed(()=>{const S=l.timelineClips.value.length,R=Za.value.length,te=S===1?"1 clip":`${S} clips`,we=R===1?"1 track":`${R} tracks`;return`${te} / ${we} / ${Ga(C.value)}`});e.watch(()=>Za.value.map(S=>`${S.id}:${S.locked===!0?"locked":"open"}`).join("|"),()=>{var S;Rt.value&&Ta.value.some(R=>R.id===Rt.value)||(Rt.value=((S=Ta.value[0])==null?void 0:S.id)??null)},{immediate:!0}),e.watch(()=>{var S;return(S=l.selectedClip.value)==null?void 0:S.trackId},S=>{S&&Ta.value.some(R=>R.id===S)&&(Rt.value=S)},{immediate:!0});const ga=S=>{const R=ha.value.find(te=>te.id===S);return R?R.filename??R.mediaUuid??R.url??R.id:"Asset"},Ra=n.assetUploader?AB({uploader:n.assetUploader,onReady:S=>{if(!S.mediaUrl&&!S.mediaUuid)return;const R={id:`imported-${S.assetId}`,type:S.mediaUuid?"media":"url",filename:S.filename,mimeType:S.mime,duration:S.durationSeconds??0,width:S.width??0,height:S.height??0};S.mediaUuid!==void 0&&(R.mediaUuid=S.mediaUuid),S.mediaUrl!==void 0&&(R.url=S.mediaUrl),l.registerMediaSource(R),ot.value=`${S.filename} ready.`},onFailure:S=>{ot.value=S.failureMessage??`Upload of ${S.filename} failed.`}}):null,Wo=async S=>{if(!Ra){ot.value="Asset import is not configured for this editor host.";return}for(const R of S){const te=await Ra.importFile(R);te.ok||(ot.value=te.message)}},lo=S=>{var ze;const R=l.appendMediaSourceToTimeline(S,Rt.value);if(!R.ok){gt.value=R.message;return}const te=R.value;te.trackId&&(Rt.value=te.trackId),l.handleClipSelect(te.id);const we=((ze=xa.value)==null?void 0:ze.name)??"timeline";gt.value=`${ga(S)} added to ${we}.`,qe()},hi=S=>{if(!l.replaceSelectedClipSource(S)){gt.value="Select a clip before replacing its source.";return}gt.value=`${ga(S)} replaced the selected clip.`,qe()},vi=S=>{const R=ga(S);if(!l.removeMediaSource(S)){gt.value="Remove timeline clips before deleting this asset.";return}gt.value=`${R} removed.`,qe()},xn=(S="video")=>{const R=l.addTimelineTrack(S);Rt.value=R.id,gt.value=`${R.name} added. New assets will be placed on that track.`,qe()},ba=S=>{const R=S.target;R&&(Rt.value=R.value||null)},sn=S=>{var te;l.handleClipSelect(S);const R=(te=l.selectedClip.value)==null?void 0:te.trackId;R&&Ta.value.some(we=>we.id===R)&&(Rt.value=R)},so=(S,R,te)=>{const we=l.moveClip(S,R,te);if(!we.ok){ot.value=we.message;return}qe()},jn=S=>{const R=l.deleteClip(S);if(!R.ok){ot.value=R.message;return}ot.value="Clip deleted.",qe()},en=(S,R)=>{R(S)&&qe()},Wn=(S,R)=>{const te=l.renameTimelineTrack(S,R);if(!te.ok){ot.value=te.message;return}ot.value=`Track renamed to "${R}".`,qe()},Xa=S=>{const R=l.deleteTimelineTrack(S);if(!R.ok){ot.value=R.message;return}Rt.value===S&&(Rt.value=null),ot.value="Track deleted.",qe()},da=(S,R)=>{const te=l.reorderTimelineTrack(S,R);if(!te.ok){ot.value=te.message;return}ot.value=`Track moved ${R}.`,qe()},Ba=S=>{vt.value=S},tn=()=>{vt.value=!vt.value},co=S=>{const R=S.target;if(!R)return;const te=Number(R.value);Number.isFinite(te)&&l.setZoomLevel(te)},H=e.ref(!1),Q=e.ref(0),Fe=e.ref(!1),ne=e.ref(null),Qe=e.ref(null),Tt=e.ref("preparing");let dn=null,La=!1;const Hn={preparing:"Preparing export...",rendering:"Rendering frames...","encoding-video":"Encoding video...","encoding-audio":"Encoding audio...",muxing:"Muxing output...",storing:"Storing export...",complete:"Export complete"},Nn=S=>typeof S=="string"&&S in Hn,Pa=(S,R)=>{Tt.value=S,ne.value=typeof R=="string"&&R.trim()!==""?R.trim():Hn[S]},ya=(S,R,te)=>{const we=Number.isFinite(S)?Math.max(0,Math.min(100,S)):0;Q.value=we,R&&Pa(R,te)},Zn=S=>{if(Nn(S.phase))return S.phase;switch(S.status){case"pending":return"preparing";case"processing":return"rendering";case"completed":return"complete";default:return Tt.value}},uo=S=>typeof S.progress_message=="string"&&S.progress_message.trim()!==""?S.progress_message.trim():void 0,cn=(S,R,te={allowClient:!0})=>{if(!Number.isFinite(R)||R<=0||S.timeline.length===0)return{route:"unsupported",exportDuration:R,message:"Export unavailable: the recipe has no renderable duration."};if(n.maxDuration>0&&R>n.maxDuration)return{route:"unsupported",exportDuration:R,message:`Export unavailable: duration exceeds the ${n.maxDuration}s limit.`};if(te.allowClient&&n.clientExportThreshold>0&&R<=n.clientExportThreshold)return{route:"client",exportDuration:R};const ze=!!n.serverRenderEndpoint,je=r.value.startsWith("temp-");return ze&&!je?{route:"server-render",exportDuration:R}:{route:"recipe-download",exportDuration:R,message:je?"Local media — downloaded recipe.json. Client-side PIXI export is unavailable on this device.":"No server render endpoint configured — downloaded recipe.json."}},Vn=()=>new Ll(n.serverRenderEndpoint??"/api/v1"),Ua=()=>{dn!==null&&(clearInterval(dn),dn=null)},mo=S=>{Ua();const R=Vn();dn=setInterval(async()=>{if(La){Ua();return}try{const te=await R.getJob(S),we=Number(te.progress??0);if(ya(we,Zn(te),uo(te)),i("server-render-progress",Q.value),te.status==="completed"||te.status==="failed"||te.status==="cancelled")if(Ua(),H.value=!1,Qe.value=null,te.status==="completed"){ya(100,"complete"),Fe.value=!0,ne.value=null;const ze=typeof te.output_media_id=="string"?te.output_media_id:void 0,je={id:S};ze!==void 0&&(je.output_media_id=ze),i("server-render-completed",je)}else{const ze=te.status==="cancelled"||typeof te.error_message=="string"&&/cancel/i.test(te.error_message),je=ze?"Export canceled.":typeof te.error_message=="string"&&te.error_message.trim()!==""?te.error_message:"Export failed";ne.value=je,ze||i("server-render-failed",je)}}catch(te){Ua(),H.value=!1,Qe.value=null;const we=te instanceof Error?te.message:"Failed to check export progress";ne.value=we,i("server-render-failed",we)}},2e3)},Tn=S=>{const R=new Blob([JSON.stringify(S,null,2)],{type:"application/json"}),te=URL.createObjectURL(R),we=document.createElement("a");we.href=te,we.download=`video-recipe-${Date.now()}.json`,we.click(),setTimeout(()=>URL.revokeObjectURL(te),100)},Bn=()=>{Ua(),La=!1,D.resetClientExport(),Qe.value=null,ne.value=null,Fe.value=!1,Q.value=0,Tt.value="preparing"},an=async S=>{ya(0,"preparing");const te=await Vn().createRenderJob({source_media_uuid:r.value,recipe:S}),we=typeof te.id=="string"?te.id:null;if(!we)throw new Error("Export failed: missing job id");Qe.value=we,i("export-started",we),i("server-render-started",we),ya(1,"rendering"),mo(we)},Gn=async(S,R)=>{if(!await D.canExportClientSide())return null;const te=await D.renderRecipeWithPixi(S,R,we=>{La||ya(we,"rendering")});return La?(ne.value="Export canceled.",ya(0),i("video-exported",null),null):(l.clearHasChanges(),i("recipe-generated",S),i("video-exported",te),ya(100,"complete"),Fe.value=!0,te)},un=async S=>{Bn(),H.value=!0,Pa("preparing");try{const R=wt(Kt(yt(l.generateRecipe(),S)));fe(R,"before-export",!1),i("recipe-generated",R);const te=eu(R,C.value),we=cn(R,te);if(we.route==="unsupported"){H.value=!1,ne.value=we.message??"Export unavailable.",i("server-render-failed",ne.value);return}if(we.route==="client"){const je=await Gn(R,S);if(je!==null){const ut=URL.createObjectURL(je.file),Bt=document.createElement("a");Bt.href=ut,Bt.download=`edited-video-${Date.now()}.mp4`,Bt.click(),setTimeout(()=>URL.revokeObjectURL(ut),100),H.value=!1;return}}const ze=we.route==="client"?cn(R,te,{allowClient:!1}):we;if(ze.route==="unsupported"){H.value=!1,ne.value=ze.message??"Export unavailable.",i("server-render-failed",ne.value);return}if(ze.route==="recipe-download"){Tn(R),H.value=!1,ya(100,"complete"),Fe.value=!0,ne.value=ze.message??"Downloaded recipe.json.";return}await an(R)}catch(R){const te=wt(l.generateRecipe());Tn(te);const we=R instanceof Error?R.message:"Export failed";H.value=!1,ya(0),Qe.value=null,ne.value=we,i("server-render-failed",we)}},Mn=async()=>{La=!0,y.value=!1,D.cancelClientExport();const S=Qe.value;if(Ua(),H.value=!1,ya(0),ne.value="Export canceled.",Qe.value=null,S&&n.serverRenderEndpoint)try{await Vn().cancelJob(S)}catch{}},mn=()=>{l.togglePlayback()},In=()=>{l.resetChanges()},nn=()=>{const S=Ca();i("draft-saved",S)},po=()=>{un()},Xn=()=>{i("close")};a({saveDraft:async()=>{const S=Ca();return i("draft-saved",S),S},exportForUpload:async S=>{Bn();const R=wt(S??l.generateRecipe()),te=Kt(R),we=Array.isArray(te.filters)&&te.filters.length>0,ze=Et(te);if(!(l.hasChanges.value||we||ze))return l.clearHasChanges(),i("video-exported",null),null;const ut=eu(te,C.value),Bt=cn(te,ut);if(Bt.route==="unsupported"){const qt=Bt.message??"Export unavailable.";throw ne.value=qt,new Error(`Video export failed: ${qt}`)}if(Bt.route==="server-render")return H.value=!0,await an(te),null;H.value=!0;try{if(Bt.route==="client"){const ca=await Gn(te);if(ca!==null)return ca}const qt=Bt.route==="client"?cn(te,ut,{allowClient:!1}):Bt;if(qt.route==="server-render")return await an(te),null;if(qt.route==="unsupported"){const ca=qt.message??"Export unavailable.";throw ne.value=ca,new Error(`Video export failed: ${ca}`)}return ne.value=qt.message??"Export unavailable for upload.",i("video-exported",null),null}catch(qt){if(La)return ne.value="Export canceled.",ya(0),i("video-exported",null),null;const ca=qt instanceof Error?qt.message:"Local WebGL export failed.";throw ne.value=ca,new Error(`Video export failed: ${ca}`)}finally{H.value=!1}}});const $n=e.ref(!1),Kn=S=>{var je,ut;const R=[...l.timelineClips.value].sort((Bt,qt)=>Bt.timelineStart-qt.timelineStart);if(R.length===0)return;const te=l.selectedClip.value;if(!te){l.handleClipSelect(((je=R[0])==null?void 0:je.id)??null);return}const we=R.findIndex(Bt=>Bt.id===te.id);if(we===-1){l.handleClipSelect(((ut=R[0])==null?void 0:ut.id)??null);return}const ze=S==="next"?R[Math.min(we+1,R.length-1)]:R[Math.max(we-1,0)];ze&&l.handleClipSelect(ze.id)},qn=()=>{l.seekTo(Math.min(l.totalDuration.value,l.playheadPosition.value+1))},fo=()=>{l.seekTo(Math.max(0,l.playheadPosition.value-1))};return SB({playPause:mn,frameForward:l.frameForward,frameBackward:l.frameBackward,secondForward:qn,secondBackward:fo,skipToStart:l.skipToStart,skipToEnd:l.skipToEnd,prevClip:()=>Kn("prev"),nextClip:()=>Kn("next"),splitAtPlayhead:l.splitAtPlayhead,deleteSelected:()=>{const S=l.deleteSelectedClip();S.ok?ot.value="Clip deleted.":ot.value=S.message},rippleDeleteSelected:()=>{l.rippleDeleteSelectedClip()?ot.value="Clip removed and gap closed.":ot.value="Nothing to ripple-delete."},undo:l.undo,redo:l.redo,save:nn,exportNow:()=>{if(l.timelineClips.value.length===0){ot.value="Add media to export.";return}po()},showShortcutsOverlay:()=>{$n.value=!0}}),e.onMounted(()=>{document.documentElement.setAttribute("data-video-editor-version","v2"),Y()}),e.onBeforeUnmount(()=>{document.documentElement.getAttribute("data-video-editor-version")==="v2"&&document.documentElement.removeAttribute("data-video-editor-version")}),e.onUnmounted(()=>{Ua(),La=!0,D.cancelClientExport(),tt&&(clearTimeout(tt),tt=null),Z.value&&(Z.value.destroy(),Z.value=null),F.value=null,W.value=null}),(S,R)=>(e.openBlock(),e.createElementBlock(e.Fragment,null,[e.createVNode(HN,{"data-testid":"video-editor-v2"},{toolbar:e.withCtx(()=>[e.createElementVNode("div",LB,[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["v2-toolbar-btn",{"is-active":e.unref(l).isPlaying.value}]),"data-testid":"v2-btn-play","aria-label":e.unref(l).isPlaying.value?"Pause":"Play",onClick:mn},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(l).isPlaying.value?e.unref(fd):e.unref(hd),"aria-hidden":"true"},null,8,["icon"])],10,PB),e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn","data-testid":"v2-btn-reset","aria-label":"Reset all changes",disabled:!e.unref(l).hasChanges.value,onClick:In},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Uo),"aria-hidden":"true"},null,8,["icon"])],8,UB)]),R[20]||(R[20]=e.createElementVNode("div",{class:"v2-toolbar-title","aria-live":"polite"},[e.createElementVNode("span",{class:"v2-toolbar-badge"},"V2"),e.createTextVNode(" Video Editor ")],-1)),e.createElementVNode("div",OB,[e.createElementVNode("label",zB,[R[18]||(R[18]=e.createElementVNode("span",{class:"sr-only"},"Fit mode",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":R[0]||(R[0]=te=>B.value=te),"aria-label":"Fit mode","data-testid":"v2-select-fit-mode"},[...R[17]||(R[17]=[e.createElementVNode("option",{value:"contain"},"Contain",-1),e.createElementVNode("option",{value:"cover"},"Cover",-1),e.createElementVNode("option",{value:"none"},"None",-1)])],512),[[e.vModelSelect,B.value]])]),e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn","data-testid":"v2-btn-save","aria-label":"Save draft",disabled:!e.unref(l).hasChanges.value,onClick:nn},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(pl),"aria-hidden":"true"},null,8,["icon"]),R[19]||(R[19]=e.createElementVNode("span",{class:"v2-toolbar-btn-label"},"Save",-1))],8,jB),e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn","data-testid":"v2-btn-export","aria-label":e.unref(l).timelineClips.value.length===0?"Export disabled — add media first":"Export",title:e.unref(l).timelineClips.value.length===0?"Add media to export":void 0,disabled:H.value||e.unref(l).timelineClips.value.length===0,onClick:po},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(ni),"aria-hidden":"true"},null,8,["icon"])],8,WB),e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn","data-testid":"v2-btn-close","aria-label":"Close editor",onClick:Xn},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref($o),"aria-hidden":"true"},null,8,["icon"])])])]),assets:e.withCtx(()=>[e.createElementVNode("div",HB,[e.createVNode(oV,{sources:ha.value,"selected-source-id":Cn.value,"uploads-enabled":!!S.assetUploader,onAdd:lo,onReplaceSelected:hi,onRemove:vi,onImportFiles:Wo},null,8,["sources","selected-source-id","uploads-enabled"]),gt.value?(e.openBlock(),e.createElementBlock("p",ZB,e.toDisplayString(gt.value),1)):e.createCommentVNode("",!0)])]),canvas:e.withCtx(()=>[e.createElementVNode("div",GB,[e.withDirectives(e.createVNode(Cs,{ref_key:"pixiPreviewRef",ref:g,class:"v2-preview-child","aria-hidden":!_.value,source:x.value,"fallback-duration":C.value,filters:M.value,playhead:E.value,"is-playing":e.unref(l).isPlaying.value,"fit-mode":B.value,active:_.value,onPlayPause:mn,onFrameUpdate:O,onDurationChange:A},null,8,["aria-hidden","source","fallback-duration","filters","playhead","is-playing","fit-mode","active"]),[[e.vShow,_.value]]),e.withDirectives(e.createVNode(Os,{class:"v2-preview-child","aria-hidden":!b.value,"media-uuid":r.value,recipe:k.value,media:j.value,"enable-engine":b.value&&L.value,"fit-mode":B.value,onTimeUpdate:K,onPlayStateChange:se,onDurationChange:A,onEngineReady:Ht},null,8,["aria-hidden","media-uuid","recipe","media","enable-engine","fit-mode"]),[[e.vShow,b.value]])])]),timeline:e.withCtx(({isMobile:te})=>{var we,ze;return[e.createElementVNode("div",{class:e.normalizeClass(["v2-timeline",{"is-mobile":!!te}])},[e.createElementVNode("div",XB,[e.createElementVNode("div",KB,[R[21]||(R[21]=e.createElementVNode("span",{class:"v2-timeline-title","data-testid":"v2-timeline-title"},"Timeline",-1)),e.createElementVNode("span",qB,e.toDisplayString(zn.value),1)]),e.createElementVNode("label",JB,[R[22]||(R[22]=e.createElementVNode("span",null,"Zoom",-1)),e.createElementVNode("input",{type:"range",min:"10",max:"600",value:e.unref(l).zoomLevel.value,"aria-label":"Timeline zoom","data-testid":"v2-timeline-zoom",onInput:co},null,40,YB),e.createElementVNode("span",QB,e.toDisplayString(Math.round(e.unref(l).zoomLevel.value))+" px/s",1)]),te?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",e4,[e.createElementVNode("button",{type:"button",class:"v2-toolbar-btn v2-toolbar-btn--ghost","data-testid":"v2-btn-add-track",onClick:R[1]||(R[1]=je=>xn("video"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Fr)},null,8,["icon"]),R[23]||(R[23]=e.createTextVNode(" Add Track ",-1))]),Ta.value.length>0?(e.openBlock(),e.createElementBlock("label",t4,[R[24]||(R[24]=e.createElementVNode("span",null,"Place clips in",-1)),e.createElementVNode("select",{value:Rt.value??"","data-testid":"v2-select-target-track","aria-label":"Target track for added assets",onChange:ba},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Ta.value,je=>(e.openBlock(),e.createElementBlock("option",{key:je.id,value:je.id},e.toDisplayString(je.name),9,n4))),128))],40,a4)])):e.createCommentVNode("",!0)])),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["v2-toolbar-btn v2-toolbar-btn--ghost",{"is-active":vt.value}]),"data-testid":"v2-btn-snap-toggle","aria-pressed":vt.value?"true":"false",onClick:tn},e.toDisplayString(vt.value?"Snap On":"Snap Off"),11,o4)]),ot.value?(e.openBlock(),e.createElementBlock("p",i4,e.toDisplayString(ot.value),1)):e.createCommentVNode("",!0),e.unref(l).timelineClips.value.length===0?(e.openBlock(),e.createElementBlock("div",r4,[...R[25]||(R[25]=[e.createElementVNode("p",{class:"v2-timeline-empty-title"},"Your timeline is empty",-1),e.createElementVNode("p",{class:"v2-timeline-empty-hint"}," Add a clip from the Assets panel or upload media to get started. Export is disabled until the timeline has at least one clip. ",-1)])])):(e.openBlock(),e.createBlock(zs,{key:2,playhead:e.unref(l).playheadPosition.value,clips:e.unref(l).timelineClips.value,tracks:Za.value,"selected-clip-id":((we=e.unref(l).selectedClip.value)==null?void 0:we.id)??((ze=e.unref(l).timelineClips.value[0])==null?void 0:ze.id)??null,duration:C.value,fps:e.unref(l).fps.value,"is-mobile":!!te,"zoom-level":e.unref(l).zoomLevel.value,"snap-enabled":vt.value,sensitivity:.25,"onUpdate:playhead":R[2]||(R[2]=je=>e.unref(l).seekTo(je)),onTrim:R[3]||(R[3]=(je,ut,Bt)=>e.unref(l).handleTrim(je,ut,Bt)),onSplit:R[4]||(R[4]=je=>e.unref(l).handleSplit(je)),onClipSelect:sn,onClipDelete:jn,onClipMove:so,onSnapStateChange:Ba,onToggleLock:R[5]||(R[5]=je=>en(je,e.unref(l).toggleTrackLock)),onToggleHidden:R[6]||(R[6]=je=>en(je,e.unref(l).toggleTrackHidden)),onToggleMuted:R[7]||(R[7]=je=>en(je,e.unref(l).toggleTrackMuted)),onToggleSolo:R[8]||(R[8]=je=>en(je,e.unref(l).toggleTrackSolo)),onRenameTrack:Wn,onDeleteTrack:Xa,onReorderTrack:da},null,8,["playhead","clips","tracks","selected-clip-id","duration","fps","is-mobile","zoom-level","snap-enabled"])),e.createVNode(js,{"selected-clip":e.unref(l).selectedClip.value,"can-split":Aa.value,"can-delete":va.value,"can-undo":e.unref(l).canUndo.value,"can-redo":e.unref(l).canRedo.value,"is-playing":e.unref(l).isPlaying.value,"zoom-level":e.unref(l).zoomLevel.value,"playback-speed":e.unref(l).playbackSpeed.value,"is-mobile":!!te,"show-add-track":!!te,onSplit:e.unref(l).splitAtPlayhead,onDelete:e.unref(l).deleteSelectedClip,onAddTrack:R[9]||(R[9]=je=>xn("video")),onDuplicate:e.unref(l).duplicateSelectedClip,onUndo:e.unref(l).undo,onRedo:e.unref(l).redo,onZoomIn:e.unref(l).zoomIn,onZoomOut:e.unref(l).zoomOut,onZoomChange:e.unref(l).setZoomLevel,onFitToWindow:e.unref(l).fitToWindow,onPlayPause:mn,onFrameForward:e.unref(l).frameForward,onFrameBackward:e.unref(l).frameBackward,onSkipToStart:e.unref(l).skipToStart,onSkipToEnd:e.unref(l).skipToEnd,onSpeedChange:e.unref(l).setPlaybackSpeed},null,8,["selected-clip","can-split","can-delete","can-undo","can-redo","is-playing","zoom-level","playback-speed","is-mobile","show-add-track","onSplit","onDelete","onDuplicate","onUndo","onRedo","onZoomIn","onZoomOut","onZoomChange","onFitToWindow","onFrameForward","onFrameBackward","onSkipToStart","onSkipToEnd","onSpeedChange"])],2)]}),inspector:e.withCtx(()=>[Je.value.length>0?(e.openBlock(),e.createBlock(Tu,{key:0,class:"v2-draft-recovery",records:Je.value,surface:"desktop","project-id":Ge.value,"saved-at":nt.value,onRestore:Te,onDismiss:Ke},null,8,["records","project-id","saved-at"])):e.createCommentVNode("",!0),e.createVNode(PT,{"active-tab":d.value,"onUpdate:activeTab":R[10]||(R[10]=te=>d.value=te),tabs:p.value},{filters:e.withCtx(()=>[e.createVNode(Ws,{filters:xe.value,"active-filters":ue.value,"thumbnail-url":le.value,onApplyFilter:It,onRemoveFilter:Ut,onUpdateParam:Gt,onPreviewFilter:sa},null,8,["filters","active-filters","thumbnail-url"])]),adjustments:e.withCtx(()=>[e.unref(s).selectedFilter.value?(e.openBlock(),e.createBlock(Hs,{key:0,filter:e.unref(s).selectedFilter.value,"current-frame":e.unref(l).currentFrame.value,onUpdateParams:ae},null,8,["filter","current-frame"])):(e.openBlock(),e.createElementBlock("div",l4,[...R[26]||(R[26]=[e.createElementVNode("p",null,"Select a filter from the Filters tab to adjust its parameters.",-1)])])),e.createVNode(Bu,{class:"v2-keyframe-panel",duration:ht.value,target:"all","device-class":"desktop",onApplyPreset:Ft},null,8,["duration"])]),text:e.withCtx(()=>[e.createVNode(Gs,{overlays:Re.value,onAddOverlay:ge,onUpdateOverlay:pe,onRemoveOverlay:me},null,8,["overlays"]),e.createVNode(Vu,{class:"v2-caption-panel","caption-track":_t.value,layout:"desktop",onImport:$e,"onUpdate:captionTrack":At,onClear:zt},null,8,["caption-track"])]),transitions:e.withCtx(()=>[e.createVNode(Xs,{"selected-clips":Pe.value,"applied-transitions":mt.value,onApplyTransition:Be,onRemoveTransition:He,onPreviewTransition:lt},null,8,["selected-clips","applied-transitions"])]),audio:e.withCtx(()=>[e.createVNode(Ks,{"audio-layers":pt.value,"master-volume":Nt.value,onAddTrack:Vt,onUpdateTrack:Ot,onRemoveTrack:$t,onUpdateVolume:st,onToggleMute:Jt,onUpdateMasterVolume:q},null,8,["audio-layers","master-volume"]),e.createVNode(Nu,{class:"v2-audio-mixer",state:Wt.value,"device-class":"desktop",onUpdate:oe},null,8,["state"])]),export:e.withCtx(()=>[e.createVNode(Zs,{"can-export":Qa.value,"is-exporting":H.value,"export-progress":Q.value,onExport:un,onCancelExport:Mn,onSaveDraft:nn,onReset:In},null,8,["can-export","is-exporting","export-progress"]),Fe.value?(e.openBlock(),e.createElementBlock("div",s4," Export complete ")):e.createCommentVNode("",!0),ne.value&&!Fe.value?(e.openBlock(),e.createElementBlock("div",d4,e.toDisplayString(ne.value),1)):e.createCommentVNode("",!0)]),_:1},8,["active-tab","tabs"])]),drawer:e.withCtx(()=>[e.createVNode(kB,{ref_key:"mobileDrawerRef",ref:u,"initial-snap":"half","aria-label":"Video editor controls"},{default:e.withCtx(()=>[Je.value.length>0?(e.openBlock(),e.createBlock(Tu,{key:0,class:"v2-draft-recovery",records:Je.value,surface:"mobile","project-id":Ge.value,"saved-at":nt.value,onRestore:Te,onDismiss:Ke},null,8,["records","project-id","saved-at"])):e.createCommentVNode("",!0),e.createVNode(cB,{"selected-clip":On.value,onOpenActions:R[11]||(R[11]=te=>c.value="trim")},null,8,["selected-clip"]),e.createVNode(hB,{modelValue:c.value,"onUpdate:modelValue":R[12]||(R[12]=te=>c.value=te)},null,8,["modelValue"]),c.value==="look"?(e.openBlock(),e.createElementBlock("section",c4,[e.createElementVNode("div",u4,[e.createVNode(Ws,{filters:xe.value,"active-filters":ue.value,"thumbnail-url":le.value,onApplyFilter:It,onRemoveFilter:Ut,onUpdateParam:Gt,onPreviewFilter:sa},null,8,["filters","active-filters","thumbnail-url"])]),e.createElementVNode("div",m4,[e.unref(s).selectedFilter.value?(e.openBlock(),e.createBlock(Hs,{key:0,filter:e.unref(s).selectedFilter.value,"current-frame":e.unref(l).currentFrame.value,onUpdateParams:ae},null,8,["filter","current-frame"])):(e.openBlock(),e.createElementBlock("div",p4,[...R[27]||(R[27]=[e.createElementVNode("p",null,"Select a filter from the Filters tab to adjust its parameters.",-1)])]))])])):c.value==="trim"?(e.openBlock(),e.createElementBlock("section",f4,[e.createVNode(js,{"selected-clip":e.unref(l).selectedClip.value,"can-split":Aa.value,"can-delete":va.value,"can-undo":e.unref(l).canUndo.value,"can-redo":e.unref(l).canRedo.value,"is-playing":e.unref(l).isPlaying.value,"zoom-level":e.unref(l).zoomLevel.value,"playback-speed":e.unref(l).playbackSpeed.value,"is-mobile":"","show-add-track":"",onSplit:e.unref(l).splitAtPlayhead,onDelete:e.unref(l).deleteSelectedClip,onAddTrack:R[13]||(R[13]=te=>xn("video")),onDuplicate:e.unref(l).duplicateSelectedClip,onUndo:e.unref(l).undo,onRedo:e.unref(l).redo,onZoomIn:e.unref(l).zoomIn,onZoomOut:e.unref(l).zoomOut,onZoomChange:e.unref(l).setZoomLevel,onFitToWindow:e.unref(l).fitToWindow,onPlayPause:mn,onFrameForward:e.unref(l).frameForward,onFrameBackward:e.unref(l).frameBackward,onSkipToStart:e.unref(l).skipToStart,onSkipToEnd:e.unref(l).skipToEnd,onSpeedChange:e.unref(l).setPlaybackSpeed},null,8,["selected-clip","can-split","can-delete","can-undo","can-redo","is-playing","zoom-level","playback-speed","onSplit","onDelete","onDuplicate","onUndo","onRedo","onZoomIn","onZoomOut","onZoomChange","onFitToWindow","onFrameForward","onFrameBackward","onSkipToStart","onSkipToEnd","onSpeedChange"])])):c.value==="text"?(e.openBlock(),e.createElementBlock("section",h4,[e.createVNode(Gs,{overlays:Re.value,onAddOverlay:ge,onUpdateOverlay:pe,onRemoveOverlay:me},null,8,["overlays"]),e.createVNode(Vu,{"caption-track":_t.value,layout:"mobile",onImport:$e,"onUpdate:captionTrack":At,onClear:zt},null,8,["caption-track"])])):c.value==="audio"?(e.openBlock(),e.createElementBlock("section",v4,[e.createVNode(Ks,{"audio-layers":pt.value,"master-volume":Nt.value,onAddTrack:Vt,onUpdateTrack:Ot,onRemoveTrack:$t,onUpdateVolume:st,onToggleMute:Jt,onUpdateMasterVolume:q},null,8,["audio-layers","master-volume"]),e.createVNode(Nu,{state:Wt.value,"device-class":"mobile",onUpdate:oe},null,8,["state"])])):c.value==="export"?(e.openBlock(),e.createElementBlock("section",g4,[e.createVNode(Zs,{"can-export":Qa.value,"is-exporting":H.value,"export-progress":Q.value,"is-mobile":"",onExport:un,onCancelExport:Mn,onSaveDraft:nn,onReset:In},null,8,["can-export","is-exporting","export-progress"]),Fe.value?(e.openBlock(),e.createElementBlock("div",b4,"Export complete")):e.createCommentVNode("",!0),ne.value&&!Fe.value?(e.openBlock(),e.createElementBlock("div",y4,e.toDisplayString(ne.value),1)):e.createCommentVNode("",!0)])):(e.openBlock(),e.createElementBlock("section",w4,[e.createElementVNode("div",k4,[e.createElementVNode("label",_4,[R[29]||(R[29]=e.createElementVNode("span",null,"Fit",-1)),e.withDirectives(e.createElementVNode("select",{"onUpdate:modelValue":R[14]||(R[14]=te=>B.value=te),"aria-label":"Mobile fit mode"},[...R[28]||(R[28]=[e.createElementVNode("option",{value:"contain"},"Contain",-1),e.createElementVNode("option",{value:"cover"},"Cover",-1),e.createElementVNode("option",{value:"none"},"None",-1)])],512),[[e.vModelSelect,B.value]])]),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["v2-mobile-secondary-button",{"is-active":vt.value}]),"aria-pressed":vt.value?"true":"false","data-testid":"v2-mobile-btn-snap-toggle",onClick:tn},e.toDisplayString(vt.value?"Snap On":"Snap Off"),11,E4),e.createElementVNode("button",{type:"button",class:"v2-mobile-secondary-button","data-testid":"v2-mobile-btn-reset",disabled:!e.unref(l).hasChanges.value,onClick:In}," Reset ",8,S4),e.createElementVNode("button",{type:"button",class:"v2-mobile-secondary-button","data-testid":"v2-mobile-btn-save",disabled:!e.unref(l).hasChanges.value,onClick:nn}," Save ",8,C4)]),v.value?(e.openBlock(),e.createElementBlock("details",x4,[R[30]||(R[30]=e.createElementVNode("summary",null,"Transitions",-1)),e.createVNode(Xs,{"selected-clips":Pe.value,"applied-transitions":mt.value,onApplyTransition:Be,onRemoveTransition:He,onPreviewTransition:lt},null,8,["selected-clips","applied-transitions"])])):e.createCommentVNode("",!0),e.createElementVNode("details",N4,[R[31]||(R[31]=e.createElementVNode("summary",null,"Keyframe presets",-1)),e.createVNode(Bu,{duration:ht.value,target:"all","device-class":"mobile",onApplyPreset:Ft},null,8,["duration"])])]))]),_:1},512)]),_:1}),$n.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"v2-shortcuts-overlay",role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts","data-testid":"v2-shortcuts-overlay",onClick:R[16]||(R[16]=e.withModifiers(te=>$n.value=!1,["self"]))},[e.createElementVNode("div",V4,[e.createElementVNode("div",T4,[R[32]||(R[32]=e.createElementVNode("h2",null,"Keyboard shortcuts",-1)),e.createElementVNode("button",{type:"button",class:"v2-shortcuts-overlay__close","aria-label":"Close shortcuts overlay","data-testid":"v2-shortcuts-overlay-close",onClick:R[15]||(R[15]=te=>$n.value=!1)},"×")]),R[33]||(R[33]=e.createStaticVNode('<dl class="v2-shortcuts-overlay__list" data-v-aa4426a6><div data-v-aa4426a6><dt data-v-aa4426a6>Space</dt><dd data-v-aa4426a6>Play / pause</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>← / →</dt><dd data-v-aa4426a6>Frame back / forward</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Shift + ← / →</dt><dd data-v-aa4426a6>1 second back / forward</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Home / End</dt><dd data-v-aa4426a6>Skip to start / end</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>[ / ]</dt><dd data-v-aa4426a6>Previous / next clip</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>S</dt><dd data-v-aa4426a6>Split at playhead</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Delete</dt><dd data-v-aa4426a6>Delete selected clip</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Shift + Delete</dt><dd data-v-aa4426a6>Ripple delete (closes the gap)</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Cmd / Ctrl + Z</dt><dd data-v-aa4426a6>Undo</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Cmd / Ctrl + Shift + Z</dt><dd data-v-aa4426a6>Redo</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Cmd / Ctrl + S</dt><dd data-v-aa4426a6>Save draft</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>Cmd / Ctrl + E</dt><dd data-v-aa4426a6>Export</dd></div><div data-v-aa4426a6><dt data-v-aa4426a6>?</dt><dd data-v-aa4426a6>This overlay</dd></div></dl>',1))])])):e.createCommentVNode("",!0)],64))}}),M4=Ae(B4,[["__scopeId","data-v-aa4426a6"]]),rn=o=>o===null||typeof o!="object"||Array.isArray(o)?null:o,Mt=o=>{if(typeof o=="number"&&Number.isFinite(o))return o;if(typeof o=="string"){const a=Number(o);return Number.isFinite(a)?a:null}return null},I4=(o,a)=>{if(a===null)return;const t=rn(o.source)??{},n=Mt(t.duration);if(!(n!==null&&n>0&&n<=1&&a>n))return;t.duration=a,o.source=t;const r=Array.isArray(o.timeline)?o.timeline:[];if(r.length===1){const d=rn(r[0]);if(d!==null){const c=Mt(d.sourceIn)??0,u=Mt(d.sourceOut)??Mt(d.end)??Mt(d.timelineEnd);if(c===0&&u!==null&&u>0&&u<=1){d.sourceOut=a;const p=Mt(d.end);p!==null&&p>0&&p<=1&&(d.end=a);const f=Mt(d.timelineEnd);f!==null&&f>0&&f<=1&&(d.timelineEnd=a)}}}const l=Mt(o.trimEnd)??Mt(o.trim_end);l!==null&&l>0&&l<=1&&(o.trimEnd=a);const s=rn(o.trim);if(s!==null){const d=Mt(s.end);d!==null&&d>0&&d<=1&&(s.end=a,o.trim=s)}},$4=(o,a)=>{if(!o)return!1;const t=rn(o);if(t===null)return!1;const n=rn(t.trim),i=rn(t.source),l=Mt(i==null?void 0:i.duration)??a,s=Array.isArray(o.filters)&&o.filters.length>0;let d=!1;if(Array.isArray(o.timeline)&&o.timeline.length===1){const f=o.timeline[0];f&&Array.isArray(f.filters)&&f.filters.length>0&&(d=!0)}let c=!1;const u=Mt(t.trimStart)??Mt(t.trim_start)??Mt(n==null?void 0:n.start),m=Mt(t.trimEnd)??Mt(t.trim_end)??Mt(n==null?void 0:n.end);if(u!==null&&u>0&&(c=!0),m!==null&&l!==void 0&&m<l&&(c=!0),!c&&Array.isArray(o.timeline)&&o.timeline.length===1){const f=o.timeline[0];if(f){const h=Mt(f.sourceIn),v=Mt(f.sourceOut);h!==null&&h>0&&(c=!0),v!==null&&l!==void 0&&v<l&&(c=!0)}}let p=!1;if(Array.isArray(o.timeline)&&o.timeline.length===1){const f=o.timeline[0];if(f){const h=Mt(f.speed);p=h!==null&&h!==1}}return s||d||c||p},hf=o=>{if(!o)return!1;const a=rn(o);return a===null?!1:!!(Array.isArray(a.textOverlays)&&a.textOverlays.length>0||Array.isArray(a.transitions)&&a.transitions.length>0||Array.isArray(o.timeline)&&o.timeline.length>1)},F4=(o,a={})=>{var p,f;const t=JSON.parse(JSON.stringify(o)),n=Array.isArray(t.timeline)?t.timeline:[],i=n.length>0?rn(n[0]):null,r=Array.isArray(i==null?void 0:i.filters)?i.filters:[],l=Array.isArray(t.filters)?t.filters:[];if(l.length>0?t.filters=l:t.filters=r,n.length===1&&i!==null){const h=Mt(i.sourceIn),v=Mt(i.sourceOut);h!==null&&t.trimStart===void 0&&(t.trimStart=h),v!==null&&t.trimEnd===void 0&&(t.trimEnd=v)}const s=rn(t.trim);if(t.trimStart===void 0){const h=Mt(s==null?void 0:s.start);h!==null&&(t.trimStart=h)}if(t.trimEnd===void 0){const h=Mt(s==null?void 0:s.end);h!==null&&(t.trimEnd=h)}const d=rn(t.source),c=Mt(t.width)??Mt(d==null?void 0:d.original_width)??Mt((p=a.exportMeta)==null?void 0:p.width);c!==null&&(t.width=c);const u=Mt(t.height)??Mt(d==null?void 0:d.original_height)??Mt((f=a.exportMeta)==null?void 0:f.height);u!==null&&(t.height=u);const m=rn(t.output);return t.fps=Mt(t.fps)??Mt(m==null?void 0:m.fps)??30,I4(t,a.mediaDuration??null),t},D4={key:0},A4=["data-testid"],R4={class:"ve-mobile-header"},L4=["data-testid"],P4={class:"ve-mobile-title"},U4=["data-testid","disabled"],O4={key:1,class:"ve-mobile-spacer","aria-hidden":"true"},z4={class:"ve-body"},j4=["data-testid"],W4=["aria-label"],H4={class:"ve-header"},Z4={class:"ve-title"},G4=["data-testid"],X4={class:"ve-body"},K4={class:"ve-footer"},q4=["data-testid"],J4=["data-testid","disabled"],Y4=e.defineComponent({__name:"VideoEditorDialog",props:{open:{type:Boolean,default:!0},mediaUuid:{},initialRecipe:{},media:{},showThumbnailPicker:{type:Boolean,default:!1},title:{default:"Edit Video"},workflowMode:{default:"full"},featureFlags:{},clientExportThreshold:{default:20},maxDuration:{default:300},serverRenderEndpoint:{default:null},saveImmediate:{type:Boolean,default:!0},confirmText:{default:"Save"},savingText:{default:"Rendering..."},closeText:{default:"Cancel"},dataTestId:{default:"video-editor-dialog"},editorVersion:{}},emits:["update:open","close","recipe-generated","export-started","draft-saved","thumbnail-selected","video-exported","save-recipe","save-started","save-complete","save-error"],setup(o,{expose:a,emit:t}){const n=o,i=t,r=e.computed(()=>n.dataTestId),l=e.computed(()=>n.open),s=e.computed(()=>n.saveImmediate===!1),d=e.computed(()=>n.closeText),c=e.computed(()=>m.value?n.savingText:n.confirmText),u=e.ref(typeof window<"u"?window.innerWidth<768:!1),m=e.ref(!1),p=e.ref(!1),f=e.ref(null),h=`temp-${Date.now()}`,v=e.computed(()=>{var C;const z=(C=n.featureFlags)==null?void 0:C.export;return typeof z=="boolean"?z:n.workflowMode==="full"}),y=e.computed(()=>{if(n.editorVersion==="v1"||n.editorVersion==="v2")return n.editorVersion;if(typeof window>"u")return"v2";try{const z=new URLSearchParams(window.location.search),C=z.get("editor")??z.get("video-editor");if(C==="v1")return"v1";if(C==="v2")return"v2"}catch{}return"v2"}),w=e.computed(()=>y.value==="v2"?M4:mf),_=e.computed(()=>typeof n.mediaUuid=="string"&&n.mediaUuid.trim()!==""?n.mediaUuid.trim():n.media&&n.media.uuid.trim()!==""?n.media.uuid.trim():h),b=e.computed(()=>{const z={showThumbnailPicker:n.showThumbnailPicker,workflowMode:n.workflowMode,clientExportThreshold:n.clientExportThreshold,maxDuration:n.maxDuration,serverRenderEndpoint:n.serverRenderEndpoint};return n.featureFlags!==void 0&&(z.featureFlags=n.featureFlags),n.initialRecipe!==void 0&&(z.initialRecipe=n.initialRecipe),n.media!==void 0&&(z.media=n.media),z}),g=()=>{u.value=window.innerWidth<768};e.onMounted(()=>{window.addEventListener("resize",g)}),e.onUnmounted(()=>{window.removeEventListener("resize",g)}),e.onErrorCaptured(()=>(p.value=!0,!1));const I=z=>{const C=Array.isArray(z.timeline)?z.timeline:[];if(C.length===0)return 0;let A=0;for(const O of C){const K=Number(O.sourceIn),se=Number(O.sourceOut),xe=Number(O.speed??1),ue=Number.isFinite(xe)&&xe>0?xe:1;if(Number.isFinite(K)&&Number.isFinite(se)&&se>K){A+=(se-K)/ue;continue}const le=Number(O.timelineStart),Z=Number(O.timelineEnd);Number.isFinite(le)&&Number.isFinite(Z)&&Z>le&&(A+=Z-le)}return A},T=(z,C,A)=>{let O=null;const K=new Promise((se,xe)=>{O=setTimeout(()=>xe(new Error(`${A} timed out after ${C}ms`)),C)});return Promise.race([z,K]).finally(()=>{O!==null&&clearTimeout(O)})},$=()=>{var K;const A=(K=n.media)==null?void 0:K.duration;if(typeof A!="number"||!Number.isFinite(A)||A<=0)return 12e3;const O=Math.round(A*1e3);return Math.min(45e3,Math.max(12e3,O))},N=()=>{i("close"),i("update:open",!1)},B=()=>{m.value=!1,N()},P=z=>{i("recipe-generated",z)},x=z=>{i("export-started",z),i("save-started",z)},M=z=>{i("video-exported",z)},E=z=>{i("thumbnail-selected",z)},D=(z,C,A)=>{i("save-recipe",z);const O={recipe:z,exportPayload:C};A!==void 0&&(O.toastDescription=A),i("save-complete",O),N()},j=z=>{m.value||(i("draft-saved",z),D(z,null))},L=async()=>{var z;if(!m.value){if(p.value||f.value===null){i("save-error",{code:"save-failed",message:"Unable to save video edits. Please try again."}),N();return}m.value=!0;try{const C=await T(f.value.saveDraft(),$(),"saveDraft");let A=null,O=!1,K;const se=I(C),xe=se>0?se:((z=n.media)==null?void 0:z.duration)??0;if(v.value&&xe>0&&xe<=n.clientExportThreshold&&typeof f.value.exportForUpload=="function"){O=!0;const le=Math.min(9e4,Math.max(15e3,n.clientExportThreshold*2e3));try{A=await T(f.value.exportForUpload(C),le,"exportForUpload")}catch{A=null}}if(hf(C)&&A===null){i("save-error",{code:"unsupported-client-export-required",message:"These edits require in-browser export. Shorten the clip or remove text overlays, transitions, or extra clips and try again."});return}O&&A===null&&(K="Video edits saved. Final render will happen when you share."),D(C,A,K)}catch{i("save-error",{code:"save-failed",message:"Unable to save video edits. Please try again."}),N()}finally{m.value=!1}}};return a({saveDraft:L}),(z,C)=>(e.openBlock(),e.createBlock(e.Teleport,{to:"body"},[l.value?(e.openBlock(),e.createElementBlock("div",D4,[u.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"ve-fullscreen","data-testid":r.value},[e.createElementVNode("header",R4,[e.createElementVNode("button",{class:"ve-mobile-action",type:"button","data-testid":`${r.value}-close-button`,onClick:B},e.toDisplayString(d.value),9,L4),e.createElementVNode("h2",P4,e.toDisplayString(z.title),1),s.value?(e.openBlock(),e.createElementBlock("button",{key:0,class:"ve-mobile-action ve-mobile-action--primary",type:"button","data-testid":`${r.value}-confirm-button`,disabled:m.value,onClick:L},e.toDisplayString(c.value),9,U4)):(e.openBlock(),e.createElementBlock("span",O4))]),e.createElementVNode("section",z4,[(e.openBlock(),e.createBlock(e.resolveDynamicComponent(w.value),e.mergeProps({ref_key:"videoEditorRef",ref:f,"media-uuid":_.value,"data-editor-version":y.value},b.value,{onClose:B,onDraftSaved:j,onExportStarted:x,onRecipeGenerated:P,onThumbnailSelected:E,onVideoExported:M}),null,16,["media-uuid","data-editor-version"]))])],8,A4)):(e.openBlock(),e.createElementBlock("div",{key:1,class:"ve-overlay","data-testid":r.value,onClick:e.withModifiers(B,["self"])},[e.createElementVNode("div",{class:"ve-dialog",role:"dialog","aria-label":z.title,"aria-modal":"true"},[e.createElementVNode("header",H4,[e.createElementVNode("h2",Z4,e.toDisplayString(z.title),1),e.createElementVNode("button",{class:"ve-close",type:"button","data-testid":`${r.value}-close-button`,"aria-label":"Close",onClick:B}," ✕ ",8,G4)]),e.createElementVNode("section",X4,[(e.openBlock(),e.createBlock(e.resolveDynamicComponent(w.value),e.mergeProps({ref_key:"videoEditorRef",ref:f,"media-uuid":_.value,"data-editor-version":y.value},b.value,{onClose:B,onDraftSaved:j,onExportStarted:x,onRecipeGenerated:P,onThumbnailSelected:E,onVideoExported:M}),null,16,["media-uuid","data-editor-version"]))]),e.createElementVNode("footer",K4,[e.renderSlot(z.$slots,"footer",{close:B,isSaving:m.value,save:L},()=>[e.createElementVNode("button",{class:"ve-btn",type:"button","data-testid":`${r.value}-cancel-button`,onClick:B},e.toDisplayString(d.value),9,q4),s.value?(e.openBlock(),e.createElementBlock("button",{key:0,class:"ve-btn ve-btn--primary",type:"button","data-testid":`${r.value}-confirm-button`,disabled:m.value,onClick:L},e.toDisplayString(c.value),9,J4)):e.createCommentVNode("",!0)],!0)])],8,W4)],8,j4))])):e.createCommentVNode("",!0)]))}}),Q4=Ae(Y4,[["__scopeId","data-v-3cc6e078"]]),eM={class:"video-editor-modal"},tM={class:"video-preview-container"},aM=["src"],nM={class:"video-overlay-controls"},oM=["aria-label"],iM={class:"time-display"},rM={class:"timeline-container"},lM={class:"clip-name"},sM={class:"timeline-time-labels"},dM={class:"tool-tabs"},cM=["onClick"],uM={class:"tool-panel"},mM={key:0,class:"trim-panel"},pM={class:"trim-controls"},fM={key:1,class:"filters-panel"},hM={class:"filter-grid"},vM=["onClick"],gM={key:2,class:"text-panel"},bM={key:3,class:"transitions-panel"},yM={class:"transition-grid"},wM=["onClick"],kM={class:"action-buttons"},_M=e.defineComponent({__name:"VideoEditorSimple",props:{media:{}},emits:["save","cancel"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(),r=e.ref(""),l=e.ref(!1),s=e.ref(0),d=e.ref(0),c=e.ref("video-1"),u=e.ref(0),m=e.ref(0),p=e.ref(null),f=e.ref("trim"),h=e.ref(null),v=e.ref(""),y=[{id:"trim",label:"Trim",icon:Gr},{id:"filters",label:"Filters",icon:pv},{id:"text",label:"Text",icon:km},{id:"transitions",label:"Transitions",icon:kv}],w=[{id:"none",name:"None"},{id:"grayscale",name:"Grayscale"},{id:"sepia",name:"Sepia"},{id:"blur",name:"Blur"},{id:"brightness",name:"Brightness"},{id:"contrast",name:"Contrast"}],_=[{id:"fade",name:"Fade"},{id:"slide",name:"Slide"},{id:"zoom",name:"Zoom"},{id:"wipe",name:"Wipe"}],b=e.ref();e.onMounted(()=>{var C,A;(C=t.media)!=null&&C.url?r.value=t.media.url:(A=t.media)!=null&&A.file&&(r.value=URL.createObjectURL(t.media.file))}),e.onUnmounted(()=>{var C;(C=t.media)!=null&&C.file&&r.value&&URL.revokeObjectURL(r.value)});function g(){i.value&&(d.value=i.value.duration,m.value=d.value)}function I(){i.value&&(s.value=i.value.currentTime)}function T(){l.value=!1}function $(){i.value&&(l.value?(i.value.pause(),l.value=!1):(i.value.play(),l.value=!0))}function N(C){if(!C||isNaN(C))return"00:00";const A=Math.floor(C/60),O=Math.floor(C%60);return`${A.toString().padStart(2,"0")}:${O.toString().padStart(2,"0")}`}function B(C){if(!i.value||!b.value)return;const A=b.value.getBoundingClientRect(),se=(C.clientX-A.left)/A.width*d.value;i.value.currentTime=Math.max(0,Math.min(se,d.value))}function P(){u.value=s.value}function x(){m.value=s.value}function M(){u.value=0,m.value=d.value}function E(C){p.value=C;const A=K=>{if(!p.value||!b.value)return;const se=b.value.getBoundingClientRect(),le=(K.clientX-se.left)/se.width*d.value;p.value==="start"?u.value=Math.max(0,Math.min(le,m.value-1)):m.value=Math.max(u.value+1,Math.min(le,d.value))},O=()=>{p.value=null,document.removeEventListener("mousemove",A),document.removeEventListener("mouseup",O)};document.addEventListener("mousemove",A),document.addEventListener("mouseup",O)}function D(C){if(h.value=C,!i.value)return;const A={none:"none",grayscale:"grayscale(100%)",sepia:"sepia(100%)",blur:"blur(5px)",brightness:"brightness(150%)",contrast:"contrast(150%)"};i.value.style.filter=A[C]||"none"}function j(){}function L(C){}function z(){const C={timeline:[{id:c.value,url:r.value,startTime:0,endTime:d.value,sourceIn:u.value,sourceOut:m.value,track:0}],filters:h.value?[{type:h.value}]:[],textOverlays:v.value?[{content:v.value}]:[],duration:m.value-u.value};n("save",C)}return(C,A)=>(e.openBlock(),e.createElementBlock("div",eM,[e.createElementVNode("div",tM,[e.createElementVNode("video",{ref_key:"videoElement",ref:i,class:"video-preview",src:r.value,onLoadedmetadata:g,onTimeupdate:I,onEnded:T,controls:""},null,40,aM),e.createElementVNode("div",nM,[e.createElementVNode("button",{class:"play-pause-btn",onClick:$,"aria-label":l.value?"Pause":"Play"},[e.createVNode(e.unref(G.IonIcon),{icon:l.value?e.unref(Cv):e.unref(Tv)},null,8,["icon"])],8,oM),e.createElementVNode("div",iM,e.toDisplayString(N(s.value))+" / "+e.toDisplayString(N(d.value)),1)])]),e.createElementVNode("div",rM,[e.createElementVNode("div",{class:"timeline-track",onClick:B,ref_key:"timelineTrack",ref:b},[e.createElementVNode("div",{class:"timeline-clip",style:e.normalizeStyle({left:`${u.value/d.value*100}%`,right:`${100-m.value/d.value*100}%`})},[e.createElementVNode("span",lM,e.toDisplayString(c.value),1)],4),e.createElementVNode("div",{class:"timeline-playhead",style:e.normalizeStyle({left:`${s.value/d.value*100}%`})},null,4),f.value==="trim"?(e.openBlock(),e.createElementBlock("div",{key:0,class:"trim-handle trim-start",style:e.normalizeStyle({left:`${u.value/d.value*100}%`}),onMousedown:A[0]||(A[0]=O=>E("start"))},null,36)):e.createCommentVNode("",!0),f.value==="trim"?(e.openBlock(),e.createElementBlock("div",{key:1,class:"trim-handle trim-end",style:e.normalizeStyle({left:`${m.value/d.value*100}%`}),onMousedown:A[1]||(A[1]=O=>E("end"))},null,36)):e.createCommentVNode("",!0)],512),e.createElementVNode("div",sM,[e.createElementVNode("span",null,e.toDisplayString(N(0)),1),e.createElementVNode("span",null,e.toDisplayString(N(d.value)),1)])]),e.createElementVNode("div",dM,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(y,O=>e.createElementVNode("button",{key:O.id,class:e.normalizeClass(["tool-tab",{active:f.value===O.id}]),onClick:K=>f.value=O.id},[e.createVNode(e.unref(G.IonIcon),{icon:O.icon},null,8,["icon"]),e.createTextVNode(" "+e.toDisplayString(O.label),1)],10,cM)),64))]),e.createElementVNode("div",uM,[f.value==="trim"?(e.openBlock(),e.createElementBlock("div",mM,[A[7]||(A[7]=e.createElementVNode("h3",null,"Trim Video",-1)),A[8]||(A[8]=e.createElementVNode("p",null,"Click and drag on the timeline to set trim points",-1)),e.createElementVNode("div",pM,[e.createElementVNode("button",{class:"btn-trim",onClick:P},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Ec)},null,8,["icon"]),A[4]||(A[4]=e.createTextVNode(" Set Start ",-1))]),e.createElementVNode("button",{class:"btn-trim",onClick:x},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Ec)},null,8,["icon"]),A[5]||(A[5]=e.createTextVNode(" Set End ",-1))]),e.createElementVNode("button",{class:"btn-trim",onClick:M},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref($o)},null,8,["icon"]),A[6]||(A[6]=e.createTextVNode(" Clear ",-1))])])])):f.value==="filters"?(e.openBlock(),e.createElementBlock("div",fM,[A[9]||(A[9]=e.createElementVNode("h3",null,"Filters",-1)),e.createElementVNode("div",hM,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(w,O=>e.createElementVNode("button",{key:O.id,class:e.normalizeClass(["filter-option",{active:h.value===O.id}]),onClick:K=>D(O.id)},e.toDisplayString(O.name),11,vM)),64))])])):f.value==="text"?(e.openBlock(),e.createElementBlock("div",gM,[A[10]||(A[10]=e.createElementVNode("h3",null,"Text Overlay",-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":A[2]||(A[2]=O=>v.value=O),type:"text",placeholder:"Enter text...",class:"text-input"},null,512),[[e.vModelText,v.value]]),e.createElementVNode("button",{class:"btn-add-text",onClick:j},"Add Text")])):f.value==="transitions"?(e.openBlock(),e.createElementBlock("div",bM,[A[11]||(A[11]=e.createElementVNode("h3",null,"Transitions",-1)),e.createElementVNode("div",yM,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(_,O=>e.createElementVNode("button",{key:O.id,class:"transition-option",onClick:K=>(O.id,void 0)},e.toDisplayString(O.name),9,wM)),64))])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",kM,[e.createElementVNode("button",{class:"btn-cancel",onClick:A[3]||(A[3]=O=>C.$emit("cancel"))},"CANCEL"),e.createElementVNode("button",{class:"btn-save",onClick:z},"SAVE")])]))}}),EM=Ae(_M,[["__scopeId","data-v-b933f33b"]]),SM={class:"time-label"},CM=e.defineComponent({__name:"TimeRuler",props:{duration:{},zoom:{}},setup(o){const a=o,t=e.computed(()=>({width:`${a.duration*a.zoom*100}px`})),n=e.computed(()=>{const l=[],s=i(a.duration,a.zoom);for(let d=0;d<=a.duration;d+=s){const c=`${d/a.duration*100}%`,u=r(d),m=d%(s*5)===0;l.push({time:d,position:c,label:u,major:m})}return l});function i(l,s){const d=l/(10*s);return d<=1?1:d<=5?5:d<=10?10:d<=30?30:d<=60?60:Math.ceil(d/60)*60}function r(l){const s=Math.floor(l/60),d=Math.floor(l%60);return s===0?`${d}s`:d===0?`${s}m`:`${s}:${d.toString().padStart(2,"0")}`}return(l,s)=>(e.openBlock(),e.createElementBlock("div",{class:"time-ruler",style:e.normalizeStyle(t.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,d=>(e.openBlock(),e.createElementBlock("div",{key:d.time,class:"time-mark",style:e.normalizeStyle({left:d.position})},[e.createElementVNode("span",SM,e.toDisplayString(d.label),1),e.createElementVNode("div",{class:e.normalizeClass(["time-tick",{major:d.major}])},null,2)],4))),128))],4))}}),xM=Ae(CM,[["__scopeId","data-v-0ef9c910"]]),NM=["data-track-index"],VM={class:"track-header"},TM={class:"track-label"},BM={class:"track-controls"},MM=["data-testid","aria-label"],IM=["data-testid","onMousedown","onClick"],$M={class:"clip-content"},FM={class:"clip-name"},DM={key:0,class:"clip-thumbnail"},AM=["src","alt"],RM=["onMousedown","aria-label"],LM=["onMousedown","aria-label"],PM=e.defineComponent({__name:"VideoTrack",props:{clips:{},trackIndex:{},zoom:{},duration:{}},emits:["clip-move","clip-trim","clip-select"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null),r=e.ref(!1),l=e.ref(!1),s=e.ref(null),d=e.computed(()=>({width:`${t.duration*t.zoom*100}px`}));function c(y){const w=y.timelineEnd-y.timelineStart,_=y.timelineStart/t.duration*100,b=w/t.duration*100;return{left:`${_}%`,width:`${b}%`,backgroundColor:u(y)}}function u(y){const w=["#4A90E2","#7ED321","#F5A623","#BD10E0","#9013FE","#50E3C2","#B8E986","#F8E71C"],_=parseInt(y.id.replace(/\D/g,""))%w.length;return w[_]}function m(y){return y.label?y.label:y.url?(y.url.split("/").pop()||"Clip").split(".")[0]:`Clip ${y.id.slice(-4)}`}function p(y){i.value=y.id,n("clip-select",y.id)}function f(){r.value=!r.value}function h(y,w){if(s.value)return;l.value=!0;const _=w.clientX,b=y.timelineStart,g=T=>{if(!l.value)return;const $=T.clientX-_,N=parseFloat(d.value.width),B=$/(t.zoom*100)*(t.duration/N),P=Math.max(0,b+B);n("clip-move",y.id,P)},I=()=>{l.value=!1,document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",I)};document.addEventListener("mousemove",g),document.addEventListener("mouseup",I)}function v(y,w,_){s.value=w;const b=_.clientX,g=y.sourceIn,I=y.sourceOut,T=N=>{if(!s.value)return;const B=N.clientX-b,P=parseFloat(d.value.width),x=B/(t.zoom*100)*(t.duration/P);if(s.value==="start"){const M=Math.max(0,g+x);n("clip-trim",y.id,M,I)}else{const M=Math.max(g+1,I+x);n("clip-trim",y.id,g,M)}},$=()=>{s.value=null,document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",$)};document.addEventListener("mousemove",T),document.addEventListener("mouseup",$)}return(y,w)=>(e.openBlock(),e.createElementBlock("div",{class:"video-track","data-track-index":y.trackIndex},[e.createElementVNode("div",VM,[e.createElementVNode("span",TM,"Track "+e.toDisplayString(y.trackIndex+1),1),e.createElementVNode("div",BM,[y.clips.length>0?(e.openBlock(),e.createElementBlock("button",{key:0,class:"track-btn","data-testid":`btn-mute-track-${y.trackIndex}`,"aria-label":`${r.value?"Unmute":"Mute"} track ${y.trackIndex+1}`,onClick:f},[e.createVNode(e.unref(G.IonIcon),{icon:r.value?e.unref(jv):e.unref(Ov)},null,8,["icon"])],8,MM)):e.createCommentVNode("",!0)])]),e.createElementVNode("div",{class:"track-timeline",style:e.normalizeStyle(d.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(y.clips,_=>(e.openBlock(),e.createElementBlock("div",{key:_.id,class:e.normalizeClass(["timeline-clip",{selected:_.id===i.value}]),style:e.normalizeStyle(c(_)),"data-testid":`clip-${_.id}`,onMousedown:b=>h(_,b),onClick:b=>p(_)},[e.createElementVNode("div",$M,[e.createElementVNode("span",FM,e.toDisplayString(m(_)),1),_.thumbnail?(e.openBlock(),e.createElementBlock("div",DM,[e.createElementVNode("img",{src:_.thumbnail,alt:m(_)},null,8,AM)])):e.createCommentVNode("",!0)]),e.createElementVNode("div",{class:"trim-handle trim-start",onMousedown:e.withModifiers(b=>v(_,"start",b),["stop"]),"aria-label":`Trim start of ${m(_)}`},null,40,RM),e.createElementVNode("div",{class:"trim-handle trim-end",onMousedown:e.withModifiers(b=>v(_,"end",b),["stop"]),"aria-label":`Trim end of ${m(_)}`},null,40,LM)],46,IM))),128))],4)],8,NM))}}),UM=Ae(PM,[["__scopeId","data-v-48e480d2"]]),OM={class:"video-timeline"},zM={class:"timeline-tracks"},jM=["aria-label","aria-valuenow","aria-valuemax"],WM={class:"timeline-controls"},HM={class:"zoom-level"},ZM=e.defineComponent({__name:"VideoTimeline",props:{clips:{},duration:{},currentTime:{}},emits:["update:clips","seek","clip-move","clip-trim"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(1),r=e.ref(null),l=e.ref(!1),s=e.ref(),d=e.computed(()=>{const b=Math.max(0,...t.clips.map(g=>g.track||0));return Array(b+1).fill(null)}),c=e.computed(()=>`${t.currentTime/t.duration*100}%`);function u(b){return t.clips.filter(g=>(g.track||0)===b)}function m(b){const g=Math.floor(b/60),I=Math.floor(b%60);return`${g}:${I.toString().padStart(2,"0")}`}function p(b,g){n("clip-move",b,g)}function f(b,g,I){n("clip-trim",b,g,I)}function h(b){r.value=b}function v(){i.value=Math.min(i.value*1.2,5)}function y(){i.value=Math.max(i.value/1.2,.5)}function w(){l.value=!0;const b=I=>{if(!l.value||!s.value)return;const T=s.value.getBoundingClientRect(),B=Math.max(0,Math.min(I.clientX-T.left,T.width))/T.width*t.duration;n("seek",B)},g=()=>{l.value=!1,document.removeEventListener("mousemove",b),document.removeEventListener("mouseup",g)};document.addEventListener("mousemove",b),document.addEventListener("mouseup",g)}function _(b){let g=t.currentTime;switch(b.key){case"ArrowLeft":g=Math.max(0,t.currentTime-1);break;case"ArrowRight":g=Math.min(t.duration,t.currentTime+1);break;case"Home":g=0;break;case"End":g=t.duration;break;default:return}b.preventDefault(),n("seek",g)}return e.onMounted(()=>{s.value=document.querySelector(".video-timeline")}),e.onUnmounted(()=>{}),(b,g)=>(e.openBlock(),e.createElementBlock("div",OM,[e.createVNode(xM,{duration:b.duration,zoom:i.value},null,8,["duration","zoom"]),e.createElementVNode("div",zM,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(d.value,(I,T)=>(e.openBlock(),e.createBlock(UM,{key:`track-${T}`,"data-testid":`track-${T}`,clips:u(T),"track-index":T,zoom:i.value,duration:b.duration,onClipMove:p,onClipTrim:f,onClipSelect:h},null,8,["data-testid","clips","track-index","zoom","duration"]))),128))]),e.createElementVNode("div",{class:"timeline-playhead",style:e.normalizeStyle({left:c.value}),onMousedown:w,"data-testid":"playhead","aria-label":`Playhead at ${m(b.currentTime)}`,role:"slider","aria-valuenow":b.currentTime,"aria-valuemax":b.duration,tabindex:"0",onKeydown:_},null,44,jM),e.createElementVNode("div",WM,[e.createElementVNode("button",{"data-testid":"btn-zoom-in","aria-label":"Zoom in",onClick:v},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(md)},null,8,["icon"])]),e.createElementVNode("span",HM,e.toDisplayString(Math.round(i.value*100))+"%",1),e.createElementVNode("button",{"data-testid":"btn-zoom-out","aria-label":"Zoom out",onClick:y},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Dv)},null,8,["icon"])])])]))}}),GM=Ae(ZM,[["__scopeId","data-v-001df415"]]),XM={class:"video-filters-panel"},KM={class:"filter-controls"},qM=["for"],JM={class:"filter-slider-group"},YM=["id","onUpdate:modelValue","min","max","step","data-testid","aria-label","aria-valuenow","aria-valuemin","aria-valuemax","onInput"],QM={class:"filter-value"},eI={class:"filter-actions"},tI={key:0,class:"filter-presets"},aI={class:"preset-list"},nI=["data-testid","aria-label","onClick"],oI=e.defineComponent({__name:"VideoFiltersPanel",emits:["filter-change"],setup(o,{emit:a}){const t=a,n=[{type:"brightness",label:"Brightness",min:0,max:200,step:1,default:100},{type:"contrast",label:"Contrast",min:0,max:200,step:1,default:100},{type:"saturation",label:"Saturation",min:0,max:200,step:1,default:100},{type:"hue",label:"Hue",min:-180,max:180,step:1,default:0},{type:"blur",label:"Blur",min:0,max:10,step:.5,default:0},{type:"sharpen",label:"Sharpen",min:0,max:10,step:.5,default:0},{type:"sepia",label:"Sepia",min:0,max:100,step:1,default:0},{type:"grayscale",label:"Grayscale",min:0,max:100,step:1,default:0}],i=e.reactive(n.reduce((p,f)=>(p[f.type]=f.default,p),{})),r=e.ref([{id:"vintage",name:"Vintage",values:{brightness:110,contrast:120,saturation:80,sepia:30}},{id:"noir",name:"Film Noir",values:{brightness:90,contrast:130,grayscale:100}},{id:"vibrant",name:"Vibrant",values:{brightness:110,contrast:110,saturation:140}},{id:"dreamy",name:"Dreamy",values:{brightness:120,blur:2,saturation:90}}]);function l(p,f){switch(p){case"brightness":case"contrast":case"saturation":case"sepia":case"grayscale":return`${f}%`;case"hue":return`${f}°`;case"blur":case"sharpen":return f.toFixed(1);default:return f.toString()}}function s(p){return["brightness","contrast","saturation","hue","blur","sharpen","sepia","grayscale"].includes(p)}function d(p){if(!s(p))return;const f={id:`filter-${p}`,filterId:p,params:{value:i[p]},intensity:1};t("filter-change",f)}function c(){n.forEach(p=>{i[p.type]=p.default,d(p.type)})}function u(){const p=prompt("Enter preset name:");if(!p)return;const f={id:`custom-${Date.now()}`,name:p,values:{...i}};r.value.push(f)}function m(p){Object.entries(p.values).forEach(([f,h])=>{i[f]=h,d(f)})}return(p,f)=>(e.openBlock(),e.createElementBlock("div",XM,[f[3]||(f[3]=e.createElementVNode("h3",null,"Video Filters",-1)),e.createElementVNode("div",KM,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(n,h=>e.createElementVNode("div",{key:h.type,class:"filter-control"},[e.createElementVNode("label",{for:`filter-${h.type}`},e.toDisplayString(h.label),9,qM),e.createElementVNode("div",JM,[e.withDirectives(e.createElementVNode("input",{id:`filter-${h.type}`,"onUpdate:modelValue":v=>i[h.type]=v,type:"range",min:h.min,max:h.max,step:h.step,class:"filter-slider","data-testid":`filter-${h.type}`,"aria-label":`${h.label} filter`,"aria-valuenow":i[h.type],"aria-valuemin":h.min,"aria-valuemax":h.max,onInput:v=>d(h.type)},null,40,YM),[[e.vModelText,i[h.type],void 0,{number:!0}]]),e.createElementVNode("span",QM,e.toDisplayString(l(h.type,i[h.type])),1)])])),64))]),e.createElementVNode("div",eI,[e.createElementVNode("button",{class:"reset-filters-btn","data-testid":"btn-reset-filters","aria-label":"Reset all filters to default",onClick:c},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Uo)},null,8,["icon"]),f[0]||(f[0]=e.createTextVNode(" Reset All Filters ",-1))]),e.createElementVNode("button",{class:"save-preset-btn","data-testid":"btn-save-preset","aria-label":"Save current filter settings as preset",onClick:u},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(pl)},null,8,["icon"]),f[1]||(f[1]=e.createTextVNode(" Save as Preset ",-1))])]),r.value.length>0?(e.openBlock(),e.createElementBlock("div",tI,[f[2]||(f[2]=e.createElementVNode("h4",null,"Presets",-1)),e.createElementVNode("div",aI,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.value,h=>(e.openBlock(),e.createElementBlock("button",{key:h.id,class:"preset-btn","data-testid":`preset-${h.id}`,"aria-label":`Apply ${h.name} preset`,onClick:v=>m(h)},e.toDisplayString(h.name),9,nI))),128))])])):e.createCommentVNode("",!0)]))}}),iI=Ae(oI,[["__scopeId","data-v-5ad2ac63"]]),rI={class:"video-text-panel"},lI={class:"text-input-group"},sI={class:"text-options"},dI={class:"option-row"},cI={class:"option-row"},uI={class:"option-row"},mI={class:"option-row"},pI={class:"checkbox-label"},fI={class:"option-row"},hI={class:"text-overlay-list"},vI={key:0,class:"empty-state"},gI=["data-testid"],bI={class:"overlay-preview"},yI={class:"overlay-controls"},wI=["data-testid","aria-label","onClick"],kI=["data-testid","aria-label","onClick"],_I=["data-testid","aria-label","onClick"],EI=e.defineComponent({__name:"VideoTextPanel",emits:["text-add","text-remove","text-update"],setup(o,{emit:a}){const t=a,n=e.ref([]),i=e.reactive({text:"",fontFamily:"Arial",fontSize:32,color:"#FFFFFF",backgroundColor:"#000000",hasBackground:!0,animation:"fade-in"});function r(){if(!i.text.trim())return;const c={id:`text-${Date.now()}`,text:i.text,x:50,y:50,fontSize:i.fontSize,fontFamily:i.fontFamily,color:i.color,startTime:0,opacity:1};i.hasBackground&&(c.backgroundColor=i.backgroundColor),i.animation!=="none"&&(c.animation=i.animation),n.value.push(c),t("text-add",c),i.text=""}function l(c){const u=n.value.findIndex(m=>m.id===c);u!==-1&&(n.value.splice(u,1),t("text-remove",c))}function s(c){i.text=c.text,i.fontFamily=c.fontFamily||"Arial",i.fontSize=c.fontSize,i.color=c.color,i.backgroundColor=c.backgroundColor||"#000000",i.hasBackground=!!c.backgroundColor,i.animation=c.animation||"none",l(c.id)}function d(c){const u={...c,id:`text-${Date.now()}`,x:c.x+10,y:c.y+10};n.value.push(u),t("text-add",u)}return(c,u)=>(e.openBlock(),e.createElementBlock("div",rI,[u[17]||(u[17]=e.createElementVNode("h3",null,"Text Overlays",-1)),e.createElementVNode("div",lI,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":u[0]||(u[0]=m=>i.text=m),type:"text",placeholder:"Enter text...",class:"text-input","data-testid":"input-text","aria-label":"Text overlay content",onKeyup:e.withKeys(r,["enter"])},null,544),[[e.vModelText,i.text]]),e.createElementVNode("button",{class:"add-text-btn","data-testid":"btn-add-text","aria-label":"Add text overlay",onClick:r},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(md)},null,8,["icon"]),u[7]||(u[7]=e.createTextVNode(" Add ",-1))])]),e.createElementVNode("div",sI,[e.createElementVNode("div",dI,[u[9]||(u[9]=e.createElementVNode("label",{for:"font-family"},"Font:",-1)),e.withDirectives(e.createElementVNode("select",{id:"font-family","onUpdate:modelValue":u[1]||(u[1]=m=>i.fontFamily=m),"data-testid":"select-font"},[...u[8]||(u[8]=[e.createStaticVNode('<option value="Arial" data-v-4d240e1e>Arial</option><option value="Helvetica" data-v-4d240e1e>Helvetica</option><option value="Times New Roman" data-v-4d240e1e>Times New Roman</option><option value="Georgia" data-v-4d240e1e>Georgia</option><option value="Courier New" data-v-4d240e1e>Courier New</option><option value="Impact" data-v-4d240e1e>Impact</option><option value="Comic Sans MS" data-v-4d240e1e>Comic Sans MS</option>',7)])],512),[[e.vModelSelect,i.fontFamily]])]),e.createElementVNode("div",cI,[u[10]||(u[10]=e.createElementVNode("label",{for:"font-size"},"Size:",-1)),e.withDirectives(e.createElementVNode("input",{id:"font-size","onUpdate:modelValue":u[2]||(u[2]=m=>i.fontSize=m),type:"number",min:"10",max:"200","data-testid":"input-font-size"},null,512),[[e.vModelText,i.fontSize,void 0,{number:!0}]])]),e.createElementVNode("div",uI,[u[11]||(u[11]=e.createElementVNode("label",{for:"text-color"},"Color:",-1)),e.withDirectives(e.createElementVNode("input",{id:"text-color","onUpdate:modelValue":u[3]||(u[3]=m=>i.color=m),type:"color","data-testid":"input-text-color"},null,512),[[e.vModelText,i.color]])]),e.createElementVNode("div",mI,[u[13]||(u[13]=e.createElementVNode("label",{for:"bg-color"},"Background:",-1)),e.withDirectives(e.createElementVNode("input",{id:"bg-color","onUpdate:modelValue":u[4]||(u[4]=m=>i.backgroundColor=m),type:"color","data-testid":"input-bg-color"},null,512),[[e.vModelText,i.backgroundColor]]),e.createElementVNode("label",pI,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":u[5]||(u[5]=m=>i.hasBackground=m),type:"checkbox","data-testid":"checkbox-bg"},null,512),[[e.vModelCheckbox,i.hasBackground]]),u[12]||(u[12]=e.createTextVNode(" Enable ",-1))])]),e.createElementVNode("div",fI,[u[15]||(u[15]=e.createElementVNode("label",{for:"text-animation"},"Animation:",-1)),e.withDirectives(e.createElementVNode("select",{id:"text-animation","onUpdate:modelValue":u[6]||(u[6]=m=>i.animation=m),"data-testid":"select-animation"},[...u[14]||(u[14]=[e.createStaticVNode('<option value="none" data-v-4d240e1e>None</option><option value="fade-in" data-v-4d240e1e>Fade In</option><option value="slide-left" data-v-4d240e1e>Slide from Left</option><option value="slide-right" data-v-4d240e1e>Slide from Right</option><option value="slide-up" data-v-4d240e1e>Slide from Bottom</option><option value="slide-down" data-v-4d240e1e>Slide from Top</option><option value="typewriter" data-v-4d240e1e>Typewriter</option><option value="bounce" data-v-4d240e1e>Bounce</option>',8)])],512),[[e.vModelSelect,i.animation]])])]),e.createElementVNode("div",hI,[u[16]||(u[16]=e.createElementVNode("h4",null,"Active Overlays",-1)),n.value.length===0?(e.openBlock(),e.createElementBlock("div",vI," No text overlays added yet ")):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,(m,p)=>(e.openBlock(),e.createElementBlock("div",{key:m.id,class:"text-overlay-item","data-testid":`overlay-${p}`},[e.createElementVNode("div",bI,[e.createElementVNode("span",{style:e.normalizeStyle({fontFamily:m.fontFamily,fontSize:`${Math.min(m.fontSize/4,16)}px`,color:m.color})},e.toDisplayString(m.text),5)]),e.createElementVNode("div",yI,[e.createElementVNode("button",{class:"edit-btn","data-testid":`btn-edit-${p}`,"aria-label":`Edit overlay: ${m.text}`,onClick:f=>s(m)},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(hv)},null,8,["icon"])],8,wI),e.createElementVNode("button",{class:"duplicate-btn","data-testid":`btn-duplicate-${p}`,"aria-label":`Duplicate overlay: ${m.text}`,onClick:f=>d(m)},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Ss)},null,8,["icon"])],8,kI),e.createElementVNode("button",{class:"remove-btn","data-testid":`btn-remove-${p}`,"aria-label":`Remove overlay: ${m.text}`,onClick:f=>l(m.id)},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Xr)},null,8,["icon"])],8,_I)])],8,gI))),128))])]))}}),SI=Ae(EI,[["__scopeId","data-v-4d240e1e"]]),CI={class:"video-tools-panel"},xI={class:"tool-tabs"},NI=["data-testid","aria-label","aria-selected","onClick"],VI={class:"tool-content"},TI={key:0,class:"trim-panel",role:"tabpanel","aria-label":"Trim controls"},BI={class:"trim-actions"},MI={key:3,class:"transitions-panel",role:"tabpanel","aria-label":"Transition controls"},II={class:"transition-types"},$I=["data-testid","aria-label","onClick"],FI={class:"transition-preview"},DI=e.defineComponent({__name:"VideoToolsPanel",props:{activeTool:{}},emits:["tool-change","filter-change","text-add","transition-add","trim-set-start","trim-set-end","trim-clear"],setup(o){const a=[{id:"trim",name:"Trim",icon:Gr},{id:"filters",name:"Filters",icon:to},{id:"text",name:"Text",icon:km},{id:"transitions",name:"Transitions",icon:xc}],t=[{id:"fade",name:"Fade",icon:as},{id:"slide-left",name:"Slide Left",icon:sv},{id:"slide-right",name:"Slide Right",icon:dv},{id:"dissolve",name:"Dissolve",icon:as},{id:"wipe",name:"Wipe",icon:xc},{id:"zoom",name:"Zoom",icon:as}];return(n,i)=>(e.openBlock(),e.createElementBlock("div",CI,[e.createElementVNode("div",xI,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(a,r=>e.createElementVNode("button",{key:r.id,class:e.normalizeClass(["tool-tab",{active:n.activeTool===r.id}]),"data-testid":`tab-${r.id}`,"aria-label":`${r.name} tool`,"aria-selected":n.activeTool===r.id,role:"tab",onClick:l=>n.$emit("tool-change",r.id)},[e.createVNode(e.unref(G.IonIcon),{icon:r.icon},null,8,["icon"]),e.createTextVNode(" "+e.toDisplayString(r.name),1)],10,NI)),64))]),e.createElementVNode("div",VI,[n.activeTool==="trim"?(e.openBlock(),e.createElementBlock("div",TI,[i[8]||(i[8]=e.createElementVNode("h3",null,"Trim Video",-1)),i[9]||(i[9]=e.createElementVNode("p",null,"Click and drag on the timeline to set trim points",-1)),e.createElementVNode("div",BI,[e.createElementVNode("button",{class:"action-btn","data-testid":"btn-set-start","aria-label":"Set trim start at current position",onClick:i[0]||(i[0]=r=>n.$emit("trim-set-start"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Sc)},null,8,["icon"]),i[5]||(i[5]=e.createTextVNode(" Set Start ",-1))]),e.createElementVNode("button",{class:"action-btn","data-testid":"btn-set-end","aria-label":"Set trim end at current position",onClick:i[1]||(i[1]=r=>n.$emit("trim-set-end"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Sc)},null,8,["icon"]),i[6]||(i[6]=e.createTextVNode(" Set End ",-1))]),e.createElementVNode("button",{class:"action-btn","data-testid":"btn-clear-trim","aria-label":"Clear trim points",onClick:i[2]||(i[2]=r=>n.$emit("trim-clear"))},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref($o)},null,8,["icon"]),i[7]||(i[7]=e.createTextVNode(" Clear ",-1))])])])):e.createCommentVNode("",!0),n.activeTool==="filters"?(e.openBlock(),e.createBlock(iI,{key:1,onFilterChange:i[3]||(i[3]=r=>n.$emit("filter-change",r))})):e.createCommentVNode("",!0),n.activeTool==="text"?(e.openBlock(),e.createBlock(SI,{key:2,onTextAdd:i[4]||(i[4]=r=>n.$emit("text-add",r))})):e.createCommentVNode("",!0),n.activeTool==="transitions"?(e.openBlock(),e.createElementBlock("div",MI,[i[10]||(i[10]=e.createElementVNode("h3",null,"Transitions",-1)),e.createElementVNode("div",II,[(e.openBlock(),e.createElementBlock(e.Fragment,null,e.renderList(t,r=>e.createElementVNode("button",{key:r.id,class:"transition-btn","data-testid":`transition-${r.id}`,"aria-label":`Add ${r.name} transition`,onClick:l=>n.$emit("transition-add",r.id)},[e.createElementVNode("div",FI,[e.createVNode(e.unref(G.IonIcon),{icon:r.icon},null,8,["icon"])]),e.createElementVNode("span",null,e.toDisplayString(r.name),1)],8,$I)),64))])])):e.createCommentVNode("",!0)])]))}}),AI=Ae(DI,[["__scopeId","data-v-fc135306"]]),RI={class:"video-export-panel"},LI={class:"export-presets"},PI=["value"],UI={key:0,class:"preset-details"},OI={class:"detail-row"},zI={class:"detail-row"},jI={class:"detail-row"},WI={class:"advanced-options"},HI={class:"options-content"},ZI={class:"option-group"},GI={class:"option-group"},XI={class:"option-group"},KI=["disabled"],qI={key:1,class:"export-progress"},JI={class:"progress-message"},YI={class:"progress-bar"},QI=["aria-valuenow"],e3={class:"progress-percentage"},t3=e.defineComponent({__name:"VideoExportPanel",props:{presets:{},isExporting:{type:Boolean},exportProgress:{}},emits:["export"],setup(o,{emit:a}){const t=o,n=a,i=e.ref("instagram-reel"),r=e.reactive({quality:"medium",bitrate:5,includeAudio:!0}),l=e.computed(()=>t.presets.find(c=>c.id===i.value)),s=e.computed(()=>t.exportProgress<10?"Initializing export...":t.exportProgress<30?"Processing video tracks...":t.exportProgress<50?"Applying filters and effects...":t.exportProgress<70?"Rendering frames...":t.exportProgress<90?"Encoding video...":t.exportProgress<100?"Finalizing export...":"Export complete!");function d(){l.value&&n("export",{...l.value,options:{...r}})}return(c,u)=>(e.openBlock(),e.createElementBlock("div",RI,[u[14]||(u[14]=e.createElementVNode("h3",null,"Export Video",-1)),e.createElementVNode("div",LI,[u[4]||(u[4]=e.createElementVNode("label",{for:"preset-select"},"Export Preset:",-1)),e.withDirectives(e.createElementVNode("select",{id:"preset-select","onUpdate:modelValue":u[0]||(u[0]=m=>i.value=m),"data-testid":"preset-select","aria-label":"Select export preset"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.presets,m=>(e.openBlock(),e.createElementBlock("option",{key:m.id,value:m.id},e.toDisplayString(m.name),9,PI))),128))],512),[[e.vModelSelect,i.value]])]),l.value?(e.openBlock(),e.createElementBlock("div",UI,[e.createElementVNode("div",OI,[u[5]||(u[5]=e.createElementVNode("span",null,"Resolution:",-1)),e.createElementVNode("span",null,e.toDisplayString(l.value.width)+"x"+e.toDisplayString(l.value.height),1)]),e.createElementVNode("div",zI,[u[6]||(u[6]=e.createElementVNode("span",null,"Frame Rate:",-1)),e.createElementVNode("span",null,e.toDisplayString(l.value.fps)+" fps",1)]),e.createElementVNode("div",jI,[u[7]||(u[7]=e.createElementVNode("span",null,"Format:",-1)),e.createElementVNode("span",null,e.toDisplayString(l.value.format.toUpperCase()),1)])])):e.createCommentVNode("",!0),e.createElementVNode("details",WI,[u[12]||(u[12]=e.createElementVNode("summary",null,"Advanced Options",-1)),e.createElementVNode("div",HI,[e.createElementVNode("div",ZI,[u[9]||(u[9]=e.createElementVNode("label",{for:"quality-select"},"Quality:",-1)),e.withDirectives(e.createElementVNode("select",{id:"quality-select","onUpdate:modelValue":u[1]||(u[1]=m=>r.quality=m),"data-testid":"quality-select"},[...u[8]||(u[8]=[e.createElementVNode("option",{value:"low"},"Low (smaller file)",-1),e.createElementVNode("option",{value:"medium"},"Medium (balanced)",-1),e.createElementVNode("option",{value:"high"},"High (best quality)",-1)])],512),[[e.vModelSelect,r.quality]])]),e.createElementVNode("div",GI,[u[10]||(u[10]=e.createElementVNode("label",{for:"bitrate-input"},"Bitrate (Mbps):",-1)),e.withDirectives(e.createElementVNode("input",{id:"bitrate-input","onUpdate:modelValue":u[2]||(u[2]=m=>r.bitrate=m),type:"number",min:"1",max:"50","data-testid":"bitrate-input"},null,512),[[e.vModelText,r.bitrate,void 0,{number:!0}]])]),e.createElementVNode("div",XI,[e.createElementVNode("label",null,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":u[3]||(u[3]=m=>r.includeAudio=m),type:"checkbox","data-testid":"include-audio"},null,512),[[e.vModelCheckbox,r.includeAudio]]),u[11]||(u[11]=e.createTextVNode(" Include Audio ",-1))])])])]),e.createElementVNode("button",{class:"btn-export",disabled:c.isExporting||!l.value,"data-testid":"btn-start-export","aria-label":"Start video export",onClick:d},[c.isExporting?(e.openBlock(),e.createBlock(e.unref(G.IonSpinner),{key:0,name:"crescent"})):(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(ni)},null,8,["icon"]),u[13]||(u[13]=e.createTextVNode(" Export Video ",-1))],64))],8,KI),c.isExporting?(e.openBlock(),e.createElementBlock("div",qI,[e.createElementVNode("div",JI,e.toDisplayString(s.value),1),e.createElementVNode("div",YI,[e.createElementVNode("div",{class:"progress-fill",style:e.normalizeStyle({width:`${c.exportProgress}%`}),role:"progressbar","aria-valuenow":c.exportProgress,"aria-valuemin":"0","aria-valuemax":"100"},null,12,QI)]),e.createElementVNode("div",e3,e.toDisplayString(c.exportProgress)+"% ",1)])):e.createCommentVNode("",!0)]))}}),a3=Ae(t3,[["__scopeId","data-v-5caf8fe6"]]),n3=["data-testid"],o3={class:"progress-header"},i3={class:"file-info"},r3={class:"file-details"},l3={class:"file-name"},s3={class:"file-meta"},d3={class:"file-size"},c3={key:0,class:"separator"},u3={key:1,class:"upload-speed"},m3={key:2,class:"separator"},p3={key:3,class:"time-remaining"},f3={class:"progress-actions"},h3={key:0,class:"status-icon completed","data-testid":"video-upload-status-completed"},v3={key:1,class:"status-icon error","data-testid":"video-upload-status-error"},g3={key:2,class:"status-icon processing","data-testid":"video-upload-status-processing",role:"status","aria-label":"Processing video"},b3=["aria-valuenow","aria-label"],y3={class:"progress-bar"},w3={class:"progress-percent"},k3={key:1,class:"error-message","data-testid":"video-upload-error"},_3={key:2,class:"thumbnail-preview","data-testid":"video-upload-thumbnail"},E3=["src","alt"],S3={key:0,class:"video-duration"},C3=e.defineComponent({__name:"VideoUploadProgress",props:{upload:{}},emits:["cancel","retry","remove"],setup(o){const a=o,t=e.computed(()=>({"is-uploading":a.upload.status==="uploading","is-processing":a.upload.status==="processing","is-completed":a.upload.status==="completed","is-error":a.upload.status==="error","is-pending":a.upload.status==="pending"})),n=e.computed(()=>_m),i=e.computed(()=>["uploading","processing"].includes(a.upload.status)),r=e.computed(()=>(a.upload.status==="processing",a.upload.progress||0)),l=e.computed(()=>{if(!a.upload.timeRemaining||a.upload.status!=="uploading")return null;const p=a.upload.timeRemaining;if(p<60)return`${Math.round(p)}s`;const f=Math.floor(p/60);return f<60?`${f}m ${Math.round(p%60)}s`:`${Math.floor(f/60)}h ${f%60}m`}),s=e.computed(()=>{var p;return a.upload.status==="completed"&&((p=a.upload.media)!=null&&p.thumbnail_url)?a.upload.media.thumbnail_url:null}),d=e.computed(()=>{var p;return(p=a.upload.media)==null?void 0:p.duration});function c(p){if(p===0)return"0 B";const f=["B","KB","MB","GB","TB"],h=1024,v=Math.floor(Math.log(p)/Math.log(h));return`${(p/Math.pow(h,v)).toFixed(1)} ${f[v]}`}function u(p){if(p===0)return"0 B/s";const f=["B/s","KB/s","MB/s","GB/s"],h=1024,v=Math.floor(Math.log(p)/Math.log(h));return`${(p/Math.pow(h,v)).toFixed(1)} ${f[v]}`}function m(p){const f=Math.floor(p/3600),h=Math.floor(p%3600/60),v=Math.floor(p%60);return f>0?`${f}:${h.toString().padStart(2,"0")}:${v.toString().padStart(2,"0")}`:`${h}:${v.toString().padStart(2,"0")}`}return(p,f)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["upload-progress-item",t.value]),"data-testid":`video-upload-progress-${p.upload.id}`},[e.createElementVNode("div",o3,[e.createElementVNode("div",i3,[e.createVNode(e.unref(G.IonIcon),{icon:n.value,class:"file-icon","aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("div",r3,[e.createElementVNode("h4",l3,e.toDisplayString(p.upload.filename),1),e.createElementVNode("p",s3,[e.createElementVNode("span",d3,e.toDisplayString(c(p.upload.bytesTotal||0)),1),p.upload.status==="uploading"?(e.openBlock(),e.createElementBlock("span",c3,"•")):e.createCommentVNode("",!0),p.upload.status==="uploading"?(e.openBlock(),e.createElementBlock("span",u3,e.toDisplayString(u(p.upload.uploadSpeed||0)),1)):e.createCommentVNode("",!0),l.value?(e.openBlock(),e.createElementBlock("span",m3,"•")):e.createCommentVNode("",!0),l.value?(e.openBlock(),e.createElementBlock("span",p3,e.toDisplayString(l.value)+" remaining ",1)):e.createCommentVNode("",!0)])])]),e.createElementVNode("div",f3,[p.upload.status==="completed"?(e.openBlock(),e.createElementBlock("div",h3,[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(gm)},null,8,["icon"])])):p.upload.status==="error"?(e.openBlock(),e.createElementBlock("div",v3,[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(lv),"aria-hidden":"true"},null,8,["icon"])])):p.upload.status==="processing"?(e.openBlock(),e.createElementBlock("div",g3,[e.createVNode(e.unref(G.IonSpinner),{name:"crescent"})])):e.createCommentVNode("",!0),p.upload.status==="uploading"?(e.openBlock(),e.createBlock(e.unref(G.IonButton),{key:3,fill:"clear",size:"small",onClick:f[0]||(f[0]=h=>p.$emit("cancel")),"data-testid":"btn-cancel-video-upload","aria-label":"Cancel upload"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{icon:e.unref($o),slot:"icon-only"},null,8,["icon"])]),_:1})):p.upload.status==="error"?(e.openBlock(),e.createBlock(e.unref(G.IonButton),{key:4,fill:"clear",size:"small",onClick:f[1]||(f[1]=h=>p.$emit("retry")),"data-testid":"btn-retry-video-upload","aria-label":"Retry upload"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Uo),slot:"icon-only"},null,8,["icon"])]),_:1})):p.upload.status==="completed"?(e.openBlock(),e.createBlock(e.unref(G.IonButton),{key:5,fill:"clear",size:"small",onClick:f[2]||(f[2]=h=>p.$emit("remove")),"data-testid":"btn-remove-video-upload","aria-label":"Remove from list"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{icon:e.unref($o),slot:"icon-only"},null,8,["icon"])]),_:1})):e.createCommentVNode("",!0)])]),i.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"progress-bar-container","data-testid":"video-upload-progress-bar",role:"progressbar","aria-valuenow":Math.round(r.value),"aria-valuemin":"0","aria-valuemax":"100","aria-label":p.upload.status==="processing"?"Processing progress":"Upload progress"},[e.createElementVNode("div",y3,[e.createElementVNode("div",{class:e.normalizeClass(["progress-fill",{indeterminate:p.upload.status==="processing"}]),style:e.normalizeStyle({width:r.value+"%"})},null,6)]),e.createElementVNode("span",w3,e.toDisplayString(Math.round(r.value))+"%",1)],8,b3)):e.createCommentVNode("",!0),p.upload.error?(e.openBlock(),e.createElementBlock("div",k3,[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Wv)},null,8,["icon"]),e.createElementVNode("span",null,e.toDisplayString(p.upload.error),1)])):e.createCommentVNode("",!0),s.value?(e.openBlock(),e.createElementBlock("div",_3,[e.createElementVNode("img",{src:s.value,alt:p.upload.filename},null,8,E3),d.value?(e.openBlock(),e.createElementBlock("div",S3,e.toDisplayString(m(d.value)),1)):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)],10,n3))}}),x3=Ae(C3,[["__scopeId","data-v-9eacbf91"]]),vs=4,N3=500,V3=new Set([408,425,429,500,502,503,504,520,521,522,523,524,525]);function Pl(o){return typeof o=="object"&&o!==null}function Iu(o){return Pl(o)?typeof o.upload_url=="string"&&typeof o.upload_id=="string"&&typeof o.media_uuid=="string"&&typeof o.expires_at=="string":!1}function T3(o){if(Iu(o))return o;if(Pl(o)&&Iu(o.data))return o.data;throw new Error("Invalid upload response from backend")}function $u(o){return Pl(o)?typeof o.uuid=="string"&&typeof o.processing_status=="string":!1}function B3(o){if($u(o))return o;if(Pl(o)&&$u(o.data))return o.data;throw new Error("Invalid media response from backend")}function Cr(o){return o?{...o}:{}}function Fu(o,a="PUT"){return typeof o.method=="string"&&o.method.trim()!==""?o.method.trim().toUpperCase():a}function M3(o){return o.resumable===!0?!0:/tusupload/i.test(o.upload_url)}function I3(o){if(typeof btoa=="function")try{return btoa(unescape(encodeURIComponent(o)))}catch{return btoa(o)}throw new Error("Base64 encoder is unavailable for TUS metadata")}function $3(o,a){return[["filename",o.filename],["filetype",o.file.type||"application/octet-stream"],["uploadid",a.upload_id],["mediauuid",a.media_uuid]].map(([n,i])=>`${n} ${I3(i)}`).join(",")}function xr(o,a){const t=Math.max(o.bytesTotal,1);o.bytesUploaded=a,o.progress=Math.min(100,a/t*100);const n=Math.max((Date.now()-o.startedAt.getTime())/1e3,.001);o.uploadSpeed=a/n;const i=Math.max(t-a,0);o.timeRemaining=i/Math.max(o.uploadSpeed,1)}function F3(o,a){return o instanceof Error?o:new Error(a)}function D3(o){if(!(o instanceof Error))return!1;const a=o.message.toLowerCase();return a.includes("failed to fetch")||a.includes("networkerror")||a.includes("network request failed")||a.includes("err_ssl_")}function Du(o){const a=Math.max(0,o-1),t=N3*Math.pow(2,a);return Math.min(5e3,t)}function Au(o){return new Promise(a=>{window.setTimeout(a,o)})}async function Ru(o,a){for(let t=1;t<=vs;t+=1)try{const n=await a();if(n.ok||!V3.has(n.status)||t>=vs)return n;await Au(Du(t))}catch(n){if(!D3(n)||t>=vs)throw n;await Au(Du(t))}throw new Error(`${o} failed after retry attempts`)}function A3(o={}){const a=e.ref(new Map),t=e.ref(new Set),n=e.ref(null),i=new Map,r=new Map,l=e.computed(()=>t.value.size>0),s=e.computed(()=>Array.from(a.value.values())),d=e.computed(()=>{const x=Array.from(a.value.values());return x.length===0?0:x.reduce((E,D)=>E+D.progress,0)/x.length});function c(x){n.value=x}function u(){}async function m(x){var E;const M=x.filter(D=>p(D));if(M.length!==0&&((E=o.onFilesSelected)==null||E.call(o,M),o.autoUpload!==!1))for(const D of M)await f(D)}function p(x){return!(o.maxFileSize&&x.size>o.maxFileSize||o.allowedFormats&&o.allowedFormats.length>0&&!o.allowedFormats.includes(x.type))}async function f(x){var D,j,L;const M=P(x);if(a.value.has(M)){const z=a.value.get(M);if((z==null?void 0:z.status)==="uploading")return}const E={id:M,file:x,filename:x.name,progress:0,status:"pending",startedAt:new Date,bytesTotal:x.size,bytesUploaded:0};a.value.set(E.id,E),t.value.add(E.id);try{E.status="uploading",(D=o.onUploadStart)==null||D.call(o,E);const z=await h(x);o.resumable===!0||z.resumable===!0?await y(E,z):await v(E,z),E.status="processing",E.progress=100;const A=await I(z.media_uuid);E.status="completed",E.media=A,(j=o.onUploadComplete)==null||j.call(o,A)}catch(z){if(E.status!=="cancelled"){const C=F3(z,"Upload failed");E.status="error",E.error=C.message,(L=o.onUploadError)==null||L.call(o,C,E)}}finally{t.value.delete(E.id),i.delete(E.id),r.delete(E.id)}}async function h(x){if(!n.value)throw new Error("API client not configured");const M={collection:o.collection||"videos",filename:x.name,size:x.size,mime_type:x.type,...o.ownerUuid!==void 0?{ownerUuid:o.ownerUuid}:{},...o.ownerType!==void 0?{ownerType:o.ownerType}:{}},E=await n.value.post("/api/v1/video/upload",M);return T3(E)}async function v(x,M){const E=new XMLHttpRequest,D=Fu(M),j=Cr(M.headers);return new Promise((L,z)=>{E.upload.addEventListener("progress",C=>{var A;C.lengthComputable&&(xr(x,C.loaded),(A=o.onUploadProgress)==null||A.call(o,x))}),E.addEventListener("load",()=>{i.delete(x.id),E.status>=200&&E.status<300?L():z(new Error(`Upload failed with status ${E.status}`))}),E.addEventListener("error",()=>{i.delete(x.id),z(new Error("Upload failed"))}),E.addEventListener("abort",()=>{i.delete(x.id),z(new Error("Upload cancelled"))}),E.open(D,M.upload_url),Object.entries(j).forEach(([C,A])=>{E.setRequestHeader(C,A)}),!Object.keys(j).some(C=>C.toLowerCase()==="content-type")&&x.file.type&&E.setRequestHeader("Content-Type",x.file.type),i.set(x.id,E),E.send(x.file)})}async function y(x,M){var z;if(M3(M)){await w(x,M);return}const E=o.chunkSize||5*1024*1024,D=_(x.file,E),j=new AbortController;r.set(x.id,j);const L=await g(M.upload_id);L&&(D.forEach(C=>{C.end<=L.bytesUploaded&&(C.uploaded=!0)}),xr(x,L.bytesUploaded));for(const C of D)C.uploaded||(await b(x,M,C,j),xr(x,C.end),(z=o.onUploadProgress)==null||z.call(o,x))}async function w(x,M){var O;const E=new AbortController;r.set(x.id,E);const D={...Cr(M.headers),"Tus-Resumable":"1.0.0","Upload-Length":String(x.file.size),"Upload-Metadata":$3(x,M)},j=await Ru("Resumable upload initialization",()=>fetch(M.upload_url,{method:"POST",headers:D,signal:E.signal}));if(!j.ok)throw new Error(`Failed to initialize resumable upload: ${j.status}`);const L=j.headers.get("Location");if(!L)throw new Error("Resumable upload endpoint did not return upload location");const z=new URL(L,M.upload_url).toString(),C=o.chunkSize||5*1024*1024;let A=0;for(;A<x.file.size;){const K=Math.min(A+C,x.file.size),se=x.file.slice(A,K),xe={...Cr(M.headers),"Tus-Resumable":"1.0.0","Upload-Offset":String(A),"Content-Type":"application/offset+octet-stream"},ue=await Ru("Resumable chunk upload",()=>fetch(z,{method:"PATCH",headers:xe,body:se,signal:E.signal}));if(ue.status===409){const Z=Number(ue.headers.get("Upload-Offset")??"-1");if(Number.isFinite(Z)&&Z>=0){A=Z;continue}}if(!ue.ok)throw new Error(`Resumable chunk upload failed: ${ue.status}`);const le=Number(ue.headers.get("Upload-Offset")??String(K));A=Number.isFinite(le)&&le>A?le:K,xr(x,A),(O=o.onUploadProgress)==null||O.call(o,x)}}function _(x,M){const E=[];let D=0,j=0;for(;D<x.size;){const L=Math.min(D+M,x.size);E.push({start:D,end:L,blob:x.slice(D,L),index:j,uploaded:!1}),D=L,j++}return E}async function b(x,M,E,D){const j={...Cr(M.headers),"Content-Range":`bytes ${E.start}-${E.end-1}/${x.file.size}`,"Content-Type":x.file.type||"application/octet-stream"},L=await fetch(M.upload_url,{method:Fu(M),headers:j,body:E.blob,signal:D.signal});if(!L.ok)throw new Error(`Chunk upload failed: ${L.status}`);E.uploaded=!0}async function g(x){return null}async function I(x){if(!n.value)throw new Error("API client not configured");const M=60;let E=0;for(;E<M;){const D=await n.value.get(`/api/v1/video/${x}`),j=B3(D),L=String(j.processing_status);if(L==="ready")return j;if(L==="failed"||L==="error")throw new Error("Video processing failed");await new Promise(z=>{window.setTimeout(z,5e3)}),E++}throw new Error("Video processing timeout")}function T(x){const M=a.value.get(x);if(!M)return;const E=i.get(x);E&&(E.abort(),i.delete(x));const D=r.get(x);D&&(D.abort(),r.delete(x)),M.status="cancelled",M.error="Upload cancelled",t.value.delete(x)}async function $(x){const M=a.value.get(x);M&&(M.status="pending",M.error="",M.progress=0,M.bytesUploaded=0,await f(M.file))}function N(x){a.value.delete(x),t.value.delete(x),i.delete(x),r.delete(x)}function B(){Array.from(a.value.entries()).forEach(([x,M])=>{M.status==="completed"&&a.value.delete(x)})}function P(x){return`${x.name}-${x.size}-${Date.now()}`}return{uploads:s,isUploading:l,totalProgress:d,openFilePicker:u,handleFileSelect:m,validateFile:p,startUpload:f,cancelUpload:T,retryUpload:$,removeUpload:N,clearCompleted:B,setApiClient:c}}const R3=["accept","multiple"],L3={key:0,class:"upload-trigger","data-testid":"video-uploader-trigger"},P3=["onKeydown"],U3={key:1,class:"upload-list","data-testid":"video-upload-list"},O3={class:"drag-content"},z3=e.defineComponent({__name:"VideoUploader",props:{collection:{default:"videos"},multiple:{type:Boolean,default:!1},maxFileSize:{default:5*1024*1024*1024},maxDuration:{},allowedFormats:{default:()=>["video/mp4","video/webm","video/quicktime","video/x-msvideo"]},autoUpload:{type:Boolean,default:!0},resumable:{type:Boolean,default:!0},label:{default:"Upload Video"},description:{default:"Click to select or drag and drop"},ownerUuid:{},ownerType:{},apiClient:{}},emits:["upload-start","upload-progress","upload-complete","upload-error","files-selected"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(),r=e.ref(!1),{uploads:l,isUploading:s,handleFileSelect:d,cancelUpload:c,retryUpload:u,removeUpload:m,setApiClient:p}=A3({collection:t.collection,...t.ownerUuid!==void 0?{ownerUuid:t.ownerUuid}:{},...t.ownerType!==void 0?{ownerType:t.ownerType}:{},maxFileSize:t.maxFileSize,...t.maxDuration!==void 0?{maxDuration:t.maxDuration}:{},allowedFormats:t.allowedFormats,autoUpload:t.autoUpload,resumable:t.resumable,onUploadStart:g=>n("upload-start",g),onUploadProgress:g=>n("upload-progress",g),onUploadComplete:g=>n("upload-complete",g),onUploadError:(g,I)=>n("upload-error",g,I),onFilesSelected:g=>n("files-selected",g)});t.apiClient&&p(t.apiClient);const f=e.computed(()=>t.allowedFormats.join(",")),h=e.computed(()=>t.multiple||l.value.length===0);function v(){i.value&&i.value.click()}function y(g){const I=g.target,T=Array.from(I.files||[]);T.length>0&&(d(T),I.value="")}function w(g){var $;g.preventDefault(),r.value=!1;const T=Array.from((($=g.dataTransfer)==null?void 0:$.files)||[]).filter(N=>N.type.startsWith("video/"));T.length>0&&d(T)}function _(g){var I;g.preventDefault(),(I=g.dataTransfer)!=null&&I.types.includes("Files")&&(r.value=!0)}function b(g){g.target.closest(".video-uploader")||(r.value=!1)}return e.onMounted(()=>{document.addEventListener("dragover",_),document.addEventListener("dragleave",b),document.addEventListener("drop",g=>g.preventDefault())}),e.onUnmounted(()=>{document.removeEventListener("dragover",_),document.removeEventListener("dragleave",b),document.removeEventListener("drop",g=>g.preventDefault())}),(g,I)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-uploader",{"is-uploading":e.unref(s)}]),"data-testid":"video-uploader"},[e.createElementVNode("input",{ref_key:"fileInputEl",ref:i,type:"file",accept:f.value,multiple:g.multiple,onChange:y,"data-testid":"video-uploader-input","aria-label":"Select video files to upload",hidden:""},null,40,R3),!e.unref(s)||h.value?(e.openBlock(),e.createElementBlock("div",L3,[e.renderSlot(g.$slots,"trigger",{open:v},()=>[e.createElementVNode("div",{class:"default-upload-area","data-testid":"video-uploader-area",role:"button",tabindex:"0","aria-label":"Click to select video for upload",onClick:v,onKeydown:[e.withKeys(v,["enter"]),e.withKeys(e.withModifiers(v,["prevent"]),["space"])]},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(_m),class:"upload-icon","aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("h3",null,e.toDisplayString(g.label),1),e.createElementVNode("p",null,e.toDisplayString(g.description),1),e.createVNode(e.unref(G.IonButton),{size:"small","data-testid":"btn-select-video","aria-label":"Select video file"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(md),slot:"start","aria-hidden":"true"},null,8,["icon"]),I[2]||(I[2]=e.createTextVNode(" Select Video ",-1))]),_:1})],40,P3)],!0)])):e.createCommentVNode("",!0),e.unref(l).length>0?(e.openBlock(),e.createElementBlock("div",U3,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(l),T=>(e.openBlock(),e.createBlock(x3,{key:T.id,upload:T,onCancel:$=>e.unref(c)(T.id),onRetry:$=>e.unref(u)(T.id),onRemove:$=>e.unref(m)(T.id)},null,8,["upload","onCancel","onRetry","onRemove"]))),128))])):e.createCommentVNode("",!0),r.value?(e.openBlock(),e.createElementBlock("div",{key:2,class:"drag-overlay","data-testid":"video-uploader-drag-overlay",onDrop:w,onDragover:I[0]||(I[0]=e.withModifiers(()=>{},["prevent"])),onDragleave:I[1]||(I[1]=T=>r.value=!1)},[e.createElementVNode("div",O3,[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(ni),"aria-hidden":"true"},null,8,["icon"]),I[3]||(I[3]=e.createElementVNode("p",null,"Drop video files here",-1))])],32)):e.createCommentVNode("",!0)],2))}}),j3=Ae(z3,[["__scopeId","data-v-ea7587f7"]]),W3=["aria-valuenow","aria-valuemax","aria-label"],H3={class:"progress-bar"},Z3={class:"time-display","data-testid":"video-time-display"},G3={class:"current-time"},X3={class:"duration"},K3={class:"control-buttons"},q3={class:"controls-left"},J3=["aria-label"],Y3={class:"controls-center"},Q3={key:0,class:"volume-controls"},e$=["aria-label"],t$=["value"],a$={class:"controls-right"},n$={key:0,class:"quality-selector"},o$=["aria-expanded"],i$={class:"quality-label"},r$={key:0,class:"quality-menu","data-testid":"video-quality-menu",role:"menu"},l$=["data-testid","aria-label","onClick"],s$=["aria-label"],d$=e.defineComponent({__name:"VideoControls",props:{playing:{type:Boolean},currentTime:{},duration:{},buffered:{},volume:{default:100},muted:{type:Boolean,default:!1},fullscreen:{type:Boolean,default:!1},isLive:{type:Boolean,default:!1},qualityLevels:{default:()=>[]},currentQuality:{default:"Auto"}},emits:["play-pause","play","pause","seek","skip-forward","skip-backward","toggleMute","setVolume","toggleFullscreen","togglePiP","selectQuality"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!0),r=e.ref(!1),l=e.ref(),s=G.isPlatform("mobile"),d="pictureInPictureEnabled"in document,c=e.computed(()=>({width:`${t.currentTime/t.duration*100}%`})),u=e.computed(()=>({left:`${t.currentTime/t.duration*100}%`})),m=e.computed(()=>{if(!t.buffered||t.buffered.length===0)return{width:"0%"};for(let g=0;g<t.buffered.length;g++){const I=t.buffered.start(g),T=t.buffered.end(g);if(t.currentTime>=I&&t.currentTime<=T)return{width:`${T/t.duration*100}%`}}return t.buffered.length>0?{width:`${t.buffered.end(0)/t.duration*100}%`}:{width:"0%"}}),p=e.computed(()=>t.muted||t.volume===0?zv:t.volume<33?Pv:t.volume<66?Uv:Lv);let f=null;function h(){i.value=!0,v()}function v(){f&&clearTimeout(f),t.playing&&!s&&(f=setTimeout(()=>{i.value=!1},3e3))}function y(g){if(!l.value||t.isLive)return;const I=l.value.getBoundingClientRect(),$=(g.clientX-I.left)/I.width*t.duration;n("seek",Math.max(0,Math.min($,t.duration)))}function w(g){const I=g.target;n("setVolume",parseInt(I.value))}function _(g){n("selectQuality",g),r.value=!1}function b(g){if(!isFinite(g))return"0:00";const I=Math.floor(g/3600),T=Math.floor(g%3600/60),$=Math.floor(g%60);return I>0?`${I}:${T.toString().padStart(2,"0")}:${$.toString().padStart(2,"0")}`:`${T}:${$.toString().padStart(2,"0")}`}return e.onMounted(()=>{document.addEventListener("mousemove",h),v()}),e.onUnmounted(()=>{document.removeEventListener("mousemove",h),f&&clearTimeout(f)}),(g,I)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-controls",{"controls-visible":i.value}]),"data-testid":"video-controls"},[e.createElementVNode("div",{class:"progress-container","data-testid":"video-progress-bar",role:"slider","aria-valuenow":Math.round(g.currentTime),"aria-valuemin":"0","aria-valuemax":Math.round(g.duration),"aria-label":g.isLive?"Live stream":"Video progress",tabindex:"0",onClick:y},[e.createElementVNode("div",H3,[e.createElementVNode("div",{class:"progress-buffered",style:e.normalizeStyle(m.value)},null,4),e.createElementVNode("div",{class:"progress-played",style:e.normalizeStyle(c.value)},null,4),e.createElementVNode("div",{class:"progress-thumb",style:e.normalizeStyle(u.value)},null,4)]),e.createElementVNode("div",Z3,[e.createElementVNode("span",G3,e.toDisplayString(b(g.currentTime)),1),I[7]||(I[7]=e.createElementVNode("span",{class:"separator"},"/",-1)),e.createElementVNode("span",X3,e.toDisplayString(g.isLive?"LIVE":b(g.duration)),1)])],8,W3),e.createElementVNode("div",K3,[e.createElementVNode("div",q3,[e.createElementVNode("button",{class:"control-btn play-pause","data-testid":"btn-video-play-pause",onClick:I[0]||(I[0]=T=>g.$emit("play-pause")),"aria-label":g.playing?"Pause":"Play"},[e.createVNode(e.unref(G.IonIcon),{icon:g.playing?e.unref(Sv):e.unref(xv),"aria-hidden":"true"},null,8,["icon"])],8,J3),g.isLive?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:0,class:"control-btn skip-backward","data-testid":"btn-video-skip-backward",onClick:I[1]||(I[1]=T=>g.$emit("skip-backward")),"aria-label":"Skip backward 10 seconds"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Nv),"aria-hidden":"true"},null,8,["icon"]),I[8]||(I[8]=e.createElementVNode("span",{class:"skip-label"},"10",-1))])),g.isLive?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("button",{key:1,class:"control-btn skip-forward","data-testid":"btn-video-skip-forward",onClick:I[2]||(I[2]=T=>g.$emit("skip-forward")),"aria-label":"Skip forward 10 seconds"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Bv),"aria-hidden":"true"},null,8,["icon"]),I[9]||(I[9]=e.createElementVNode("span",{class:"skip-label"},"10",-1))]))]),e.createElementVNode("div",Y3,[e.unref(s)?e.createCommentVNode("",!0):(e.openBlock(),e.createElementBlock("div",Q3,[e.createElementVNode("button",{class:"control-btn mute-btn","data-testid":"btn-video-mute",onClick:I[3]||(I[3]=T=>g.$emit("toggleMute")),"aria-label":g.muted?"Unmute":"Mute"},[e.createVNode(e.unref(G.IonIcon),{icon:p.value,"aria-hidden":"true"},null,8,["icon"])],8,e$),e.createElementVNode("input",{type:"range",class:"volume-slider","data-testid":"slider-video-volume",min:"0",max:"100",value:g.muted?0:g.volume,onInput:w,"aria-label":"Volume"},null,40,t$)]))]),e.createElementVNode("div",a$,[g.qualityLevels.length>1?(e.openBlock(),e.createElementBlock("div",n$,[e.createElementVNode("button",{class:"control-btn quality-btn","data-testid":"btn-video-quality",onClick:I[4]||(I[4]=T=>r.value=!r.value),"aria-label":"Quality settings","aria-expanded":r.value},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Av),"aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("span",i$,e.toDisplayString(g.currentQuality),1)],8,o$),r.value?(e.openBlock(),e.createElementBlock("div",r$,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(g.qualityLevels,T=>(e.openBlock(),e.createElementBlock("button",{key:T.label,class:e.normalizeClass(["quality-option",{active:T.label===g.currentQuality}]),"data-testid":`btn-video-quality-${T.label}`,"aria-label":`Set quality to ${T.label}`,role:"menuitem",onClick:$=>_(T)},e.toDisplayString(T.label),11,l$))),128))])):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0),!e.unref(s)&&d?(e.openBlock(),e.createElementBlock("button",{key:1,class:"control-btn pip-btn","data-testid":"btn-video-pip",onClick:I[5]||(I[5]=T=>g.$emit("togglePiP")),"aria-label":"Picture in Picture"},[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Rv),"aria-hidden":"true"},null,8,["icon"])])):e.createCommentVNode("",!0),e.createElementVNode("button",{class:"control-btn fullscreen-btn","data-testid":"btn-video-fullscreen",onClick:I[6]||(I[6]=T=>g.$emit("toggleFullscreen")),"aria-label":g.fullscreen?"Exit fullscreen":"Enter fullscreen"},[e.createVNode(e.unref(G.IonIcon),{icon:g.fullscreen?e.unref(fv):e.unref(gv),"aria-hidden":"true"},null,8,["icon"])],8,s$)])])],2))}}),c$=Ae(d$,[["__scopeId","data-v-2ae77c13"]]);function u$(o={}){var se,xe,ue;const a=e.ref(),t=e.ref(),n=e.ref(!1),i=e.ref(0),r=e.ref(0),l=e.ref(100),s=e.ref(o.muted||!1),d=e.ref(!1),c=e.ref(),u=e.ref(1),m=e.ref(!1),p=e.ref(null),f=e.ref("idle"),h=e.ref(o.playbackUrl||((se=o.media)==null?void 0:se.playback_url)||((xe=o.media)==null?void 0:xe.url)||""),v=e.ref(null),y=e.ref(o.isLive||!1),w=e.ref(null),_=e.ref(null);function b(le){_.value=le}if((ue=o.media)!=null&&ue.token_expires_at){const le=new Date(o.media.token_expires_at);v.value=Number.isNaN(le.getTime())?null:le}async function g(){var Z;const le=y.value?t.value:a.value;if(le)try{await le.play(),n.value=!0,f.value=y.value?"live":"playing",(Z=o.onPlay)==null||Z.call(o)}catch{p.value="Failed to play video",f.value="error"}}function I(){var Z;const le=y.value?t.value:a.value;le&&(le.pause(),n.value=!1,f.value="paused",(Z=o.onPause)==null||Z.call(o))}function T(){n.value?I():g()}function $(le){const Z=y.value?t.value:a.value;if(!Z||y.value)return;const k=Number.isFinite(Z.duration)?Z.duration:le;Z.currentTime=Math.max(0,Math.min(le,k)),i.value=Z.currentTime}function N(le=10){const Z=a.value;!Z||y.value||$(Z.currentTime+le)}function B(le=10){const Z=a.value;!Z||y.value||$(Z.currentTime-le)}function P(){const le=y.value?t.value:a.value;le&&(le.muted=!le.muted,s.value=le.muted)}function x(le){const Z=y.value?t.value:a.value;if(!Z)return;const k=Math.max(0,Math.min(100,le));Z.volume=k/100,l.value=k,k>0&&Z.muted&&(Z.muted=!1,s.value=!1)}function M(le){const Z=a.value;!Z||y.value||(Z.playbackRate=le,u.value=le)}async function E(){const le=document.querySelector(".video-player-container");if(le)try{document.fullscreenElement?(await document.exitFullscreen(),d.value=!1):(await le.requestFullscreen(),d.value=!0)}catch{}}async function D(){const le=y.value?t.value:a.value;if(le)try{document.pictureInPictureElement?await document.exitPictureInPicture():document.pictureInPictureEnabled&&await le.requestPictureInPicture()}catch{}}async function j(){var Z;p.value=null,f.value="loading",(Z=o.media)!=null&&Z.provider&&o.media.provider!=="local"&&await L();const le=y.value?t.value:a.value;le&&(le.load(),await g())}async function L(){if(!(!_.value||!o.media))try{m.value=!0;const le=await _.value.get(`/api/v1/video/${o.media.uuid}/playback`);h.value=le.playback_url,v.value=new Date(le.token_expires_at);const Z=y.value?t.value:a.value;if(Z&&Z.src!==h.value){const k=!Z.paused,F=Z.currentTime;Z.src=h.value,y.value||(Z.currentTime=F),k&&await g()}}catch{p.value="Failed to refresh playback token",f.value="error"}finally{m.value=!1}}async function z(le){if(t.value){if(t.value.canPlayType("application/vnd.apple.mpegurl")){t.value.src=le;return}try{t.value.src=le}catch{p.value="Live streaming not supported in this browser",f.value="error"}}}function C(){w.value&&(w.value.destroy(),w.value=null)}function A(){var Z;const le=y.value?t.value:a.value;le&&(i.value=le.currentTime,r.value=le.duration,(Z=o.onTimeUpdate)==null||Z.call(o,le.currentTime))}const O=e.computed(()=>{if(!c.value||c.value.length===0||!r.value)return 0;for(let le=0;le<c.value.length;le++){const Z=c.value.start(le),k=c.value.end(le);if(i.value>=Z&&i.value<=k)return k/r.value*100}return 0});function K(){if(!v.value)return!1;const le=new Date;return v.value.getTime()-le.getTime()<5*60*1e3}return e.watch([a,t],([le,Z])=>{const k=y.value?Z:le;k&&(k.addEventListener("timeupdate",A),k.addEventListener("loadedmetadata",()=>{r.value=k.duration,f.value="ready"}),k.addEventListener("progress",()=>{c.value=k.buffered}),k.addEventListener("ended",()=>{var F;n.value=!1,f.value="ended",(F=o.onEnded)==null||F.call(o)}),k.addEventListener("error",F=>{var W;f.value="error",(W=o.onError)==null||W.call(o,"Video playback error")}),k.volume=l.value/100,k.muted=s.value)}),e.onUnmounted(()=>{C();const le=y.value?t.value:a.value;le&&le.removeEventListener("timeupdate",A)}),{videoEl:a,liveVideoEl:t,playing:n,currentTime:i,duration:r,volume:l,muted:s,isFullscreen:d,bufferedRanges:c,bufferedPercent:O,playbackRate:u,isLoading:m,error:p,status:f,currentPlaybackUrl:h,tokenExpiresAt:v,play:g,pause:I,togglePlayPause:T,seek:$,skipForward:N,skipBackward:B,toggleMute:P,setVolume:x,setPlaybackRate:M,toggleFullscreen:E,togglePiP:D,retry:j,refreshToken:L,setupLiveStream:z,setApiClient:b,shouldRefreshToken:K}}const m$=["src","poster","controls","autoplay","muted","loop","preload"],p$={key:1,ref:"livePlayerEl",class:"live-player"},f$=["controls","muted"],h$={key:0,class:"live-indicator","data-testid":"video-live-indicator","aria-label":"Live stream"},v$={key:2,class:"video-loading","data-testid":"video-loading",role:"status","aria-label":"Loading video"},g$={key:3,class:"video-error","data-testid":"video-error",role:"alert"},b$={key:5,class:"gesture-zones","data-testid":"video-gesture-zones"},y$=e.defineComponent({__name:"VideoPlayer",props:{media:{},playbackUrl:{},apiClient:{},isLive:{type:Boolean,default:!1},controls:{type:Boolean,default:!0},autoplay:{type:Boolean,default:!1},muted:{type:Boolean,default:!1},loop:{type:Boolean,default:!1},poster:{},preload:{default:"metadata"},showCustomControls:{type:Boolean,default:!1},enableGestures:{type:Boolean,default:!0},className:{},crossorigin:{}},emits:["play","pause","ended","error","timeupdate","loadedmetadata","progress"],setup(o,{emit:a}){const t=o,n=a,{videoEl:i,liveVideoEl:r,playing:l,currentTime:s,duration:d,volume:c,muted:u,isFullscreen:m,bufferedRanges:p,isLoading:f,error:h,status:v,currentPlaybackUrl:y,tokenExpiresAt:w,play:_,pause:b,seek:g,toggleMute:I,setVolume:T,toggleFullscreen:$,togglePlayPause:N,skipForward:B,skipBackward:P,retry:x,refreshToken:M,setApiClient:E,shouldRefreshToken:D,setupLiveStream:j}=u$({...t.media!==void 0?{media:t.media}:{},...t.playbackUrl!==void 0?{playbackUrl:t.playbackUrl}:{},isLive:t.isLive??!1,autoplay:t.autoplay??!1,muted:t.muted??!1});async function L(){await M()}const z=e.computed(()=>{const W=["video-player-container"];return t.className&&W.push(t.className),m.value&&W.push("fullscreen"),t.isLive&&W.push("is-live"),l.value&&W.push("is-playing"),f.value&&W.push("is-loading"),W}),C=e.computed(()=>{var W,J;if(t.poster)return t.poster;if((W=t.media)!=null&&W.poster_url)return t.media.poster_url;if((J=t.media)!=null&&J.thumbnail_url)return t.media.thumbnail_url});function A(W){const J=W.target;n("loadedmetadata",{duration:J.duration,width:J.videoWidth,height:J.videoHeight})}function O(W){const J=W.target;s.value=J.currentTime,n("timeupdate",J.currentTime)}function K(){l.value=!0,n("play")}function se(){l.value=!1,n("pause")}function xe(){l.value=!1,n("ended")}function ue(W){const J=W.target;let ce="Failed to load video";if(J.error)switch(J.error.code){case J.error.MEDIA_ERR_ABORTED:ce="Video playback aborted";break;case J.error.MEDIA_ERR_NETWORK:ce="Network error while loading video";break;case J.error.MEDIA_ERR_DECODE:ce="Video decoding error";break;case J.error.MEDIA_ERR_SRC_NOT_SUPPORTED:ce="Video format not supported";break}h.value=ce,n("error",ce)}function le(W){const J=W.target;p.value=J.buffered,n("progress",J.buffered)}function Z(){f.value=!0}function k(){f.value=!1}e.watch(()=>t.apiClient,W=>{W&&E(W)},{immediate:!0}),e.watch(()=>t.playbackUrl,W=>{typeof W=="string"&&W.length>0&&(y.value=W)},{immediate:!0}),e.watch(()=>{var W;return(W=t.media)==null?void 0:W.token_expires_at},W=>{if(!W){w.value=null;return}const J=new Date(W);w.value=Number.isNaN(J.getTime())?null:J},{immediate:!0}),e.watch(()=>{var W;return(W=t.media)==null?void 0:W.playback_url},async(W,J)=>{if(t.playbackUrl||!W||W===J)return;const ce=i.value;if(!ce||t.isLive){y.value=W;return}const Ue=!ce.paused,be=ce.currentTime;y.value=W,await e.nextTick();try{ce.currentTime=be}catch{}Ue&&await _()},{immediate:!0});let F=null;return e.watch(()=>t.isLive,async W=>{var ce;if(!W)return;const J=t.playbackUrl||((ce=t.media)==null?void 0:ce.playback_url)||"";J&&await j(J)},{immediate:!0}),e.onMounted(()=>{var W;(W=t.media)!=null&&W.provider&&t.media.provider!=="local"&&(F=setInterval(()=>{D()&&L()},3e4)),G.isPlatform("mobile")&&t.showCustomControls}),e.onUnmounted(()=>{F&&clearInterval(F)}),(W,J)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["video-player-container",z.value]),"data-testid":"video-player"},[W.isLive?(e.openBlock(),e.createElementBlock("div",p$,[e.createElementVNode("video",{ref_key:"liveVideoEl",ref:r,controls:W.controls&&!W.showCustomControls,autoplay:!0,muted:e.unref(u),onPlay:K,onPause:se,onError:ue,playsinline:"",class:"video-element","data-testid":"video-element"},null,40,f$),e.unref(v)==="live"?(e.openBlock(),e.createElementBlock("div",h$,[...J[3]||(J[3]=[e.createElementVNode("span",{class:"live-dot"},null,-1),e.createElementVNode("span",{class:"live-text"},"LIVE",-1)])])):e.createCommentVNode("",!0)],512)):(e.openBlock(),e.createElementBlock("video",{key:0,ref_key:"videoEl",ref:i,src:e.unref(y),poster:C.value,controls:W.controls&&!W.showCustomControls,autoplay:W.autoplay,muted:e.unref(u),loop:W.loop,preload:W.preload,onLoadedmetadata:A,onTimeupdate:O,onPlay:K,onPause:se,onEnded:xe,onError:ue,onProgress:le,onWaiting:Z,onCanplay:k,playsinline:"",class:"video-element","data-testid":"video-element"},null,40,m$)),e.unref(f)?(e.openBlock(),e.createElementBlock("div",v$,[e.createVNode(e.unref(G.IonSpinner),{name:"crescent"})])):e.createCommentVNode("",!0),e.unref(h)?(e.openBlock(),e.createElementBlock("div",g$,[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(pd),"aria-hidden":"true"},null,8,["icon"]),e.createElementVNode("p",null,e.toDisplayString(e.unref(h)),1),e.createVNode(e.unref(G.IonButton),{size:"small",onClick:e.unref(x),"data-testid":"btn-video-retry","aria-label":"Retry loading video"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{icon:e.unref(Uo),slot:"start","aria-hidden":"true"},null,8,["icon"]),J[4]||(J[4]=e.createTextVNode(" Retry ",-1))]),_:1},8,["onClick"])])):e.createCommentVNode("",!0),W.showCustomControls&&!e.unref(h)?(e.openBlock(),e.createBlock(c$,{key:4,playing:e.unref(l),currentTime:e.unref(s),duration:e.unref(d),buffered:e.unref(p),volume:e.unref(c),muted:e.unref(u),fullscreen:e.unref(m),isLive:W.isLive,onPlay:e.unref(_),onPause:e.unref(b),onSeek:e.unref(g),onToggleMute:e.unref(I),onSetVolume:e.unref(T),onToggleFullscreen:e.unref($),class:"custom-controls"},null,8,["playing","currentTime","duration","buffered","volume","muted","fullscreen","isLive","onPlay","onPause","onSeek","onToggleMute","onSetVolume","onToggleFullscreen"])):e.createCommentVNode("",!0),W.enableGestures&&!e.unref(h)?(e.openBlock(),e.createElementBlock("div",b$,[e.createElementVNode("div",{class:"gesture-left","data-testid":"video-gesture-skip-back","aria-label":"Double tap to skip backward",onDblclick:J[0]||(J[0]=(...ce)=>e.unref(P)&&e.unref(P)(...ce))},null,32),e.createElementVNode("div",{class:"gesture-center","data-testid":"video-gesture-play-pause","aria-label":"Tap to play or pause",onClick:J[1]||(J[1]=(...ce)=>e.unref(N)&&e.unref(N)(...ce))}),e.createElementVNode("div",{class:"gesture-right","data-testid":"video-gesture-skip-forward","aria-label":"Double tap to skip forward",onDblclick:J[2]||(J[2]=(...ce)=>e.unref(B)&&e.unref(B)(...ce))},null,32)])):e.createCommentVNode("",!0)],2))}}),vf=Ae(y$,[["__scopeId","data-v-b8db4951"]]),w$=ml.defineStore("video",()=>{const o=e.ref(new Map),a=e.ref(new Map),t=e.ref(new Map),n=e.ref(null),i=e.ref(!1),r=e.computed(()=>Array.from(o.value.values())),l=e.computed(()=>Array.from(a.value.values())),s=e.computed(()=>l.value.filter(j=>j.status==="live")),d=e.computed(()=>r.value.filter(j=>j.processing_status==="processing"));function c(j){o.value.set(j.uuid,j)}function u(j,L){const z=o.value.get(j);z&&o.value.set(j,{...z,...L})}function m(j){o.value.delete(j)}function p(j){return o.value.get(j)}function f(j){a.value.set(j.id,j)}function h(j,L){const z=a.value.get(j);z&&a.value.set(j,{...z,...L})}function v(j,L){const z=a.value.get(j);z&&a.value.set(j,{...z,status:L.status,viewer_count:L.viewer_count,peak_viewers:L.peak_viewers})}function y(j){a.value.delete(j)}function w(j){return a.value.get(j)}function _(j){return l.value.find(L=>L.media_uuid===j)}function b(j){t.value.set(j.id,j)}function g(j,L){const z=t.value.get(j);z&&t.value.set(j,{...z,...L})}function I(j){t.value.delete(j)}function T(j){return t.value.get(j)}function $(j){return Array.from(t.value.values()).filter(L=>L.media_uuid===j)}function N(j){n.value=j}function B(j){n.value&&(n.value={...n.value,...j})}function P(){n.value=null}function x(j){i.value=j}function M(){o.value.clear(),a.value.clear(),t.value.clear(),n.value=null,i.value=!1}function E(j){o.value.clear(),j.forEach(L=>{o.value.set(L.uuid,L)})}function D(j){a.value.clear(),j.forEach(L=>{a.value.set(L.id,L)})}return{videos:o,liveStreams:a,exportJobs:t,currentEditorState:n,isProcessing:i,allVideos:r,allLiveStreams:l,activeLiveStreams:s,processingVideos:d,setVideo:c,updateVideo:u,removeVideo:m,getVideo:p,setLiveStream:f,updateLiveStream:h,updateLiveStreamStats:v,removeLiveStream:y,getLiveStream:w,getLiveStreamByMedia:_,addExportJob:b,updateExportJob:g,removeExportJob:I,getExportJob:T,getExportJobsByMedia:$,setEditorState:N,updateEditorState:B,clearEditorState:P,setProcessing:x,clearAll:M,loadVideos:E,loadLiveStreams:D}});let xo=null;function k$(o){xo=o}const Nr={post:async(o,a)=>{if(!xo)throw new Error("HTTP client not configured");return await xo(`/api/v1/video${o}`,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json"}})},get:async o=>{if(!xo)throw new Error("HTTP client not configured");return await xo(`/api/v1/video${o}`)},delete:async o=>{if(!xo)throw new Error("HTTP client not configured");return await xo(`/api/v1/video${o}`,{method:"DELETE"})}};function Vr(o,a=null){const t=typeof o.id=="string"&&o.id!==""?o.id:typeof o.stream_id=="string"&&o.stream_id!==""?o.stream_id:a==null?void 0:a.id;if(!t)throw new Error("Invalid live stream response: missing stream id");const n={id:t,media_uuid:o.media_uuid??(a==null?void 0:a.media_uuid)??"",stream_key:o.stream_key??(a==null?void 0:a.stream_key)??"",rtmp_url:o.rtmp_url??(a==null?void 0:a.rtmp_url)??"",status:o.status??(a==null?void 0:a.status)??"idle",viewer_count:o.viewer_count??(a==null?void 0:a.viewer_count)??0,peak_viewers:o.peak_viewers??(a==null?void 0:a.peak_viewers)??0,auto_record:o.auto_record??(a==null?void 0:a.auto_record)??!0,low_latency:o.low_latency??(a==null?void 0:a.low_latency)??!1},i=o.playback_url??(a==null?void 0:a.playback_url);i!==void 0&&(n.playback_url=i);const r=o.started_at??(a==null?void 0:a.started_at);r!==void 0&&(n.started_at=r);const l=o.ended_at??(a==null?void 0:a.ended_at);return l!==void 0&&(n.ended_at=l),(a==null?void 0:a.metadata)!==void 0&&(n.metadata=a.metadata),(a==null?void 0:a.vod_media_uuid)!==void 0&&(n.vod_media_uuid=a.vod_media_uuid),n}function gs(o,a){return o instanceof Error&&o.message?o.message:a}function _$(o){const a=w$(),t=e.ref(null),n=e.ref(!1),i=e.ref(!0),r=e.ref(""),l=e.ref(!1),s=e.ref(!1),d=e.ref(null),c=e.ref(null),u=e.ref(0),m=e.ref(0);let p;const f=e.computed(()=>c.value?Math.floor((new Date().getTime()-c.value.getTime())/1e3):0),h=e.computed(()=>{var P;if(!((P=t.value)!=null&&P.playback_url))return null;const B=new URL(t.value.playback_url);return B.searchParams.set("live","true"),n.value&&B.searchParams.set("latency","low"),B.toString()}),v=e.computed(()=>{var B;return((B=t.value)==null?void 0:B.status)==="live"}),y=e.computed(()=>{var B;return((B=t.value)==null?void 0:B.status)==="idle"}),w=e.computed(()=>{var B;return((B=t.value)==null?void 0:B.status)==="ended"});async function _(B={}){l.value=!0,d.value=null;try{const P=await Nr.post("/live",{title:r.value||B.title||"Live Stream",low_latency:B.low_latency??n.value,auto_record:B.auto_record??i.value,...B}),x=Vr(P);return t.value=x,a.setLiveStream(x),T(),x}catch(P){throw d.value=gs(P,"Failed to create stream"),P instanceof Error?P:new Error(d.value)}finally{l.value=!1}}async function b(){if(!t.value)throw new Error("No active stream");s.value=!0,d.value=null;try{const B=await Nr.post(`/live/${t.value.id}/end`),P=Vr(B,t.value);return t.value=P,a.setLiveStream(P),$(),P}catch(B){throw d.value=gs(B,"Failed to end stream"),B instanceof Error?B:new Error(d.value)}finally{s.value=!1}}async function g(){if(t.value)try{const B=await Nr.get(`/live/${t.value.id}`),P=Vr(B,t.value);u.value=P.viewer_count,m.value=P.peak_viewers,t.value=P;const x={status:P.status,viewer_count:P.viewer_count,peak_viewers:P.peak_viewers};P.started_at&&(x.started_at=P.started_at),P.ended_at&&(x.ended_at=P.ended_at),a.updateLiveStreamStats(P.id,x),P.status==="live"&&!c.value&&P.started_at&&(c.value=new Date(P.started_at)),P.status==="ended"&&$()}catch{}}async function I(B){try{const P=await Nr.get(`/live/${B}`),x=Vr(P,t.value);return{rtmp_url:x.rtmp_url,stream_key:x.stream_key,playback_url:x.playback_url||""}}catch(P){throw d.value=gs(P,"Failed to get stream credentials"),P instanceof Error?P:new Error(d.value)}}function T(B=5e3){$(),p=window.setInterval(()=>{g()},B)}function $(){p!==void 0&&(clearInterval(p),p=void 0)}async function N(){if(!o)return;const B=a.getLiveStreamByMedia(o);B&&(t.value=B,u.value=B.viewer_count,m.value=B.peak_viewers,B.status==="live"&&(T(),B.started_at&&(c.value=new Date(B.started_at))))}return o&&N(),e.onUnmounted(()=>{$()}),{stream:t,lowLatency:n,autoRecord:i,streamTitle:r,isCreating:l,isEnding:s,error:d,streamDuration:f,viewerCount:u,peakViewers:m,playbackUrl:h,isLive:v,isIdle:y,hasEnded:w,createStream:_,endStream:b,refreshStreamStatus:g,getStreamCredentials:I,startStatusPolling:T,stopStatusPolling:$}}const E$={class:"stream-status"},S$={class:"flex items-center justify-between"},C$={class:"flex items-center gap-3"},x$={key:0,class:"flex items-center"},N$={key:2,class:"text-sm text-gray-600"},V$={key:0,class:"flex items-center gap-2"},T$={class:"text-sm font-medium text-gray-700"},B$={key:0,class:"text-xs text-gray-500"},M$=e.defineComponent({__name:"StreamStatus",props:{status:{},viewers:{},peakViewers:{},duration:{}},setup(o){const a=o,t=e.computed(()=>({idle:"Ready to Stream",live:"Live",ended:"Stream Ended",error:"Error"})[a.status]||a.status),n=e.computed(()=>{const r="px-3 py-1 rounded-full text-xs font-semibold uppercase",l={idle:"bg-gray-100 text-gray-700",live:"bg-red-100 text-red-700",ended:"bg-blue-100 text-blue-700",error:"bg-yellow-100 text-yellow-700"};return`${r} ${l[a.status]||l.idle}`}),i=e.computed(()=>{if(!a.duration)return null;const r=Math.floor(a.duration/3600),l=Math.floor(a.duration%3600/60),s=a.duration%60;return r>0?`${r}:${l.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:`${l}:${s.toString().padStart(2,"0")}`});return(r,l)=>(e.openBlock(),e.createElementBlock("div",E$,[e.createElementVNode("div",S$,[e.createElementVNode("div",C$,[r.status==="live"?(e.openBlock(),e.createElementBlock("div",x$,[...l[0]||(l[0]=[e.createElementVNode("span",{class:"relative flex h-3 w-3"},[e.createElementVNode("span",{class:"animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"}),e.createElementVNode("span",{class:"relative inline-flex rounded-full h-3 w-3 bg-red-500"})],-1),e.createElementVNode("span",{class:"ml-2 text-sm font-semibold text-red-600 uppercase"},"Live",-1)])])):(e.openBlock(),e.createElementBlock("div",{key:1,class:e.normalizeClass(n.value)},e.toDisplayString(t.value),3)),i.value?(e.openBlock(),e.createElementBlock("div",N$,e.toDisplayString(i.value),1)):e.createCommentVNode("",!0)]),r.viewers!==void 0?(e.openBlock(),e.createElementBlock("div",V$,[l[1]||(l[1]=e.createElementVNode("svg",{class:"w-4 h-4 text-gray-500",fill:"currentColor",viewBox:"0 0 20 20"},[e.createElementVNode("path",{d:"M10 12a2 2 0 100-4 2 2 0 000 4z"}),e.createElementVNode("path",{"fill-rule":"evenodd",d:"M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z","clip-rule":"evenodd"})],-1)),e.createElementVNode("span",T$,e.toDisplayString(r.viewers)+" "+e.toDisplayString(r.viewers===1?"viewer":"viewers"),1),r.peakViewers>r.viewers?(e.openBlock(),e.createElementBlock("span",B$," (Peak: "+e.toDisplayString(r.peakViewers)+") ",1)):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])]))}}),I$=Ae(M$,[["__scopeId","data-v-1d09c19f"]]),$$={class:"stream-credentials"},F$={class:"space-y-3"},D$={class:"credential-field"},A$={class:"flex gap-2"},R$=["value"],L$={class:"credential-field"},P$={class:"flex gap-2"},U$=["value","type"],O$=["aria-label"],z$={key:0,class:"w-4 h-4 text-gray-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},j$={key:1,class:"w-4 h-4 text-gray-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},W$={key:0,class:"mt-2 text-sm text-green-600"},H$=e.defineComponent({__name:"StreamCredentials",props:{rtmpUrl:{},streamKey:{}},emits:["copy"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.ref(""),l=e.computed(()=>{if(i.value)return t.streamKey;if(t.streamKey.length>8){const c=t.streamKey.slice(0,4),u=t.streamKey.slice(-4);return`${c}${"•".repeat(16)}${u}`}return"•".repeat(t.streamKey.length)});function s(){i.value=!i.value}async function d(c,u){try{await navigator.clipboard.writeText(c),r.value=u,n("copy",c,u),setTimeout(()=>{r.value=""},2e3)}catch{}}return(c,u)=>(e.openBlock(),e.createElementBlock("div",$$,[u[8]||(u[8]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 mb-3"},"Stream Settings",-1)),e.createElementVNode("div",F$,[e.createElementVNode("div",D$,[u[3]||(u[3]=e.createElementVNode("label",{class:"block text-xs font-medium text-gray-500 mb-1"},"RTMP Server URL",-1)),e.createElementVNode("div",A$,[e.createElementVNode("input",{value:c.rtmpUrl,readonly:"",type:"text",class:"flex-1 px-3 py-2 bg-gray-50 border border-gray-200 rounded-md text-sm font-mono text-gray-700","aria-label":"RTMP server URL"},null,8,R$),e.createElementVNode("button",{onClick:u[0]||(u[0]=m=>d(c.rtmpUrl,"RTMP URL")),class:"px-3 py-2 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors","aria-label":"Copy RTMP URL"},[...u[2]||(u[2]=[e.createElementVNode("svg",{class:"w-4 h-4 text-gray-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})],-1)])])])]),e.createElementVNode("div",L$,[u[7]||(u[7]=e.createElementVNode("label",{class:"block text-xs font-medium text-gray-500 mb-1"},"Stream Key",-1)),e.createElementVNode("div",P$,[e.createElementVNode("input",{value:l.value,readonly:"",type:i.value?"text":"password",class:"flex-1 px-3 py-2 bg-gray-50 border border-gray-200 rounded-md text-sm font-mono text-gray-700","aria-label":"Stream key"},null,8,U$),e.createElementVNode("button",{onClick:s,class:"px-3 py-2 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors","aria-label":i.value?"Hide stream key":"Show stream key"},[i.value?(e.openBlock(),e.createElementBlock("svg",j$,[...u[5]||(u[5]=[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"},null,-1)])])):(e.openBlock(),e.createElementBlock("svg",z$,[...u[4]||(u[4]=[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"},null,-1),e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"},null,-1)])]))],8,O$),e.createElementVNode("button",{onClick:u[1]||(u[1]=m=>d(c.streamKey,"Stream Key")),class:"px-3 py-2 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors","aria-label":"Copy stream key"},[...u[6]||(u[6]=[e.createElementVNode("svg",{class:"w-4 h-4 text-gray-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[e.createElementVNode("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})],-1)])])])])]),u[9]||(u[9]=e.createElementVNode("details",{class:"mt-4"},[e.createElementVNode("summary",{class:"cursor-pointer text-sm text-blue-600 hover:text-blue-700"}," How to connect with OBS Studio "),e.createElementVNode("div",{class:"mt-2 p-3 bg-blue-50 rounded-md text-sm text-gray-700"},[e.createElementVNode("ol",{class:"list-decimal list-inside space-y-1"},[e.createElementVNode("li",null,"Open OBS Studio"),e.createElementVNode("li",null,"Go to Settings → Stream"),e.createElementVNode("li",null,'Set Service to "Custom"'),e.createElementVNode("li",null,'Paste the RTMP URL in "Server"'),e.createElementVNode("li",null,'Paste the Stream Key in "Stream Key"'),e.createElementVNode("li",null,'Click OK and then "Start Streaming"')])])],-1)),e.createVNode(e.Transition,{name:"fade"},{default:e.withCtx(()=>[r.value?(e.openBlock(),e.createElementBlock("div",W$,e.toDisplayString(r.value)+" copied to clipboard! ",1)):e.createCommentVNode("",!0)]),_:1})]))}}),Z$=Ae(H$,[["__scopeId","data-v-306d92f6"]]),G$={class:"live-stream-manager","data-testid":"live-stream-manager"},X$={key:0,class:"stream-setup"},K$={class:"space-y-4"},q$={class:"flex items-center justify-between p-4 bg-gray-50 rounded-lg"},J$={class:"flex items-center justify-between p-4 bg-gray-50 rounded-lg"},Y$=["disabled"],Q$={key:0},e5={key:1,class:"flex items-center justify-center"},t5={key:1,class:"stream-active space-y-6"},a5={key:1,class:"video-preview"},n5={key:2,class:"analytics-panel"},o5={class:"grid grid-cols-2 gap-4"},i5={class:"bg-gray-50 p-3 rounded"},r5={class:"text-2xl font-bold text-gray-900"},l5={class:"bg-gray-50 p-3 rounded"},s5={class:"text-2xl font-bold text-gray-900"},d5={class:"stream-controls flex gap-3"},c5=["disabled"],u5={key:0},m5={key:1},p5={key:2,class:"mt-4 p-4 bg-red-50 border border-red-200 rounded-lg"},f5={class:"text-red-600 text-sm"},h5=e.defineComponent({__name:"LiveStreamManager",props:{mediaUuid:{},onStreamCreated:{type:Function},onStreamEnded:{type:Function},httpClient:{type:Function}},emits:["stream-created","stream-ended","error"],setup(o,{emit:a}){const t=o,n=a;t.httpClient&&k$(t.httpClient);const{stream:i,lowLatency:r,autoRecord:l,streamTitle:s,isCreating:d,isEnding:c,error:u,createStream:m,endStream:p,streamDuration:f,playbackUrl:h,refreshStreamStatus:v}=_$(t.mediaUuid),y=e.ref(!1);async function w(){var T;try{const $=await m({title:s.value,low_latency:r.value,auto_record:l.value});n("stream-created",$),(T=t.onStreamCreated)==null||T.call(t,$)}catch($){n("error",$)}}async function _(){var T;try{const $=await p();n("stream-ended",$),(T=t.onStreamEnded)==null||T.call(t,$)}catch($){n("error",$)}}function b(){i.value=null,s.value="",y.value=!1,u.value=null}async function g(T,$){try{await navigator.clipboard.writeText(T)}catch{}}let I;return e.onMounted(()=>{var T;((T=i.value)==null?void 0:T.status)==="live"&&(I=window.setInterval(()=>{v()},5e3))}),e.onUnmounted(()=>{I&&clearInterval(I)}),(T,$)=>(e.openBlock(),e.createElementBlock("div",G$,[e.unref(i)?(e.openBlock(),e.createElementBlock("div",t5,[e.createVNode(I$,{status:e.unref(i).status,viewers:e.unref(i).viewer_count,duration:e.unref(f),"peak-viewers":e.unref(i).peak_viewers},null,8,["status","viewers","duration","peak-viewers"]),e.unref(i).status==="idle"?(e.openBlock(),e.createBlock(Z$,{key:0,"rtmp-url":e.unref(i).rtmp_url,"stream-key":e.unref(i).stream_key,onCopy:g},null,8,["rtmp-url","stream-key"])):e.createCommentVNode("",!0),e.unref(h)?(e.openBlock(),e.createElementBlock("div",a5,[$[9]||($[9]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 mb-2"},"Live Preview",-1)),e.createVNode(vf,{"playback-url":e.unref(h),"is-live":!0,muted:!0,controls:!1,class:"w-full rounded-lg overflow-hidden"},null,8,["playback-url"])])):e.createCommentVNode("",!0),e.unref(i).status==="live"?(e.openBlock(),e.createElementBlock("div",n5,[$[12]||($[12]=e.createElementVNode("h4",{class:"text-sm font-medium text-gray-700 mb-3"},"Live Analytics",-1)),e.createElementVNode("div",o5,[e.createElementVNode("div",i5,[e.createElementVNode("div",r5,e.toDisplayString(e.unref(i).viewer_count),1),$[10]||($[10]=e.createElementVNode("div",{class:"text-xs text-gray-500"},"Current Viewers",-1))]),e.createElementVNode("div",l5,[e.createElementVNode("div",s5,e.toDisplayString(e.unref(i).peak_viewers),1),$[11]||($[11]=e.createElementVNode("div",{class:"text-xs text-gray-500"},"Peak Viewers",-1))])])])):e.createCommentVNode("",!0),e.createElementVNode("div",d5,[e.unref(i).status==="idle"?(e.openBlock(),e.createElementBlock("button",{key:0,onClick:$[3]||($[3]=N=>y.value=!y.value),class:"flex-1 py-2 px-4 bg-gray-200 text-gray-700 font-medium rounded-lg hover:bg-gray-300 transition-colors"},e.toDisplayString(y.value?"Hide":"Show")+" Credentials ",1)):e.createCommentVNode("",!0),e.unref(i).status==="live"?(e.openBlock(),e.createElementBlock("button",{key:1,onClick:_,disabled:e.unref(c),class:"flex-1 py-2 px-4 bg-red-600 text-white font-medium rounded-lg hover:bg-red-700 disabled:opacity-50 transition-colors","aria-label":"End live stream"},[e.unref(c)?(e.openBlock(),e.createElementBlock("span",m5,"Ending...")):(e.openBlock(),e.createElementBlock("span",u5,"End Stream"))],8,c5)):e.createCommentVNode("",!0),e.unref(i).status==="ended"?(e.openBlock(),e.createElementBlock("button",{key:2,onClick:b,class:"flex-1 py-2 px-4 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition-colors"}," Start New Stream ")):e.createCommentVNode("",!0)])])):(e.openBlock(),e.createElementBlock("div",X$,[$[8]||($[8]=e.createElementVNode("h3",{class:"text-lg font-semibold mb-4"},"Start Live Stream",-1)),e.createElementVNode("div",K$,[e.createElementVNode("div",q$,[$[4]||($[4]=e.createElementVNode("div",{class:"flex-1"},[e.createElementVNode("label",{class:"font-medium text-gray-900"},"Low Latency Mode"),e.createElementVNode("p",{class:"text-sm text-gray-500 mt-1"}," 5-7 second delay (vs 15-20s standard) ")],-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":$[0]||($[0]=N=>e.isRef(r)?r.value=N:null),type:"checkbox",class:"h-5 w-5 text-blue-600 rounded focus:ring-blue-500","aria-label":"Enable low latency mode"},null,512),[[e.vModelCheckbox,e.unref(r)]])]),e.createElementVNode("div",J$,[$[5]||($[5]=e.createElementVNode("div",{class:"flex-1"},[e.createElementVNode("label",{class:"font-medium text-gray-900"},"Auto-Record Stream"),e.createElementVNode("p",{class:"text-sm text-gray-500 mt-1"}," Save stream as VOD for later viewing ")],-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":$[1]||($[1]=N=>e.isRef(l)?l.value=N:null),type:"checkbox",class:"h-5 w-5 text-blue-600 rounded focus:ring-blue-500","aria-label":"Enable auto-recording"},null,512),[[e.vModelCheckbox,e.unref(l)]])]),e.createElementVNode("div",null,[$[6]||($[6]=e.createElementVNode("label",{for:"stream-title",class:"block text-sm font-medium text-gray-700 mb-2"}," Stream Title (optional) ",-1)),e.withDirectives(e.createElementVNode("input",{id:"stream-title","onUpdate:modelValue":$[2]||($[2]=N=>e.isRef(s)?s.value=N:null),type:"text",class:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"My Live Stream"},null,512),[[e.vModelText,e.unref(s)]])]),e.createElementVNode("button",{onClick:w,disabled:e.unref(d),class:"w-full py-3 px-4 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors","data-testid":"create-stream-button","aria-label":"Create live stream"},[e.unref(d)?(e.openBlock(),e.createElementBlock("span",e5,[...$[7]||($[7]=[e.createElementVNode("svg",{class:"animate-spin h-5 w-5 mr-2",viewBox:"0 0 24 24"},[e.createElementVNode("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4",fill:"none"}),e.createElementVNode("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})],-1),e.createTextVNode(" Creating... ",-1)])])):(e.openBlock(),e.createElementBlock("span",Q$,"Create Stream"))],8,Y$)])])),e.unref(u)?(e.openBlock(),e.createElementBlock("div",p5,[e.createElementVNode("p",f5,e.toDisplayString(e.unref(u)),1)])):e.createCommentVNode("",!0)]))}}),v5=Ae(h5,[["__scopeId","data-v-26291f6f"]]),g5={class:"album-tree-node"},b5=["data-album-id","draggable","aria-selected","aria-expanded"],y5={key:1,class:"album-node__chevron-placeholder"},w5={key:2,"data-testid":"media-count",class:"album-node__count"},k5={key:0,class:"album-tree-node__children",role:"group"},_5=16,E5=e.defineComponent({__name:"AlbumTreeNode",props:{album:{},depth:{},selectedId:{},expandedIds:{},focusedId:{},draggable:{type:Boolean},showMediaCount:{type:Boolean},compact:{type:Boolean},dragState:{}},emits:["select","toggle-expand","drag-start","drag-over","drag-leave","drop"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>t.expandedIds.has(t.album.id)),r=e.computed(()=>t.selectedId===t.album.id),l=e.computed(()=>t.focusedId===t.album.id),s=e.computed(()=>t.album.children_count>0),d=e.computed(()=>`${t.depth*_5}px`),c=e.computed(()=>{var b;return((b=t.dragState)==null?void 0:b.draggedAlbumId)===t.album.id}),u=e.computed(()=>{var b;return((b=t.dragState)==null?void 0:b.dropTargetId)===t.album.id}),m=e.computed(()=>{var b;return(b=t.dragState)!=null&&b.draggedAlbumId?t.dragState.draggedAlbumId===t.album.id:!1}),p=e.computed(()=>{const b=["album-node"];return r.value&&b.push("album-node--selected"),l.value&&b.push("album-node--focused"),t.compact&&b.push("album-node--compact"),c.value&&b.push("album-node--dragging"),u.value&&b.push("album-node--drop-target"),m.value&&b.push("album-node--invalid-drop"),b});function f(){n("select",t.album)}function h(b){b.stopPropagation(),n("toggle-expand",t.album.id)}function v(b){t.draggable&&(b.dataTransfer&&(b.dataTransfer.setData("text/plain",t.album.id),b.dataTransfer.effectAllowed="move"),n("drag-start",t.album.id))}function y(b){t.draggable&&(b.preventDefault(),b.dataTransfer&&(b.dataTransfer.dropEffect="move"),n("drag-over",t.album.id))}function w(){n("drag-leave",t.album.id)}function _(b){t.draggable&&(b.preventDefault(),n("drop",t.album.id))}return(b,g)=>{var T;const I=e.resolveComponent("AlbumTreeNode",!0);return e.openBlock(),e.createElementBlock("div",g5,[e.createElementVNode("div",{"data-testid":"album-node","data-album-id":b.album.id,class:e.normalizeClass(p.value),style:e.normalizeStyle({paddingLeft:d.value}),draggable:b.draggable,role:"treeitem","aria-selected":r.value,"aria-expanded":s.value?i.value:void 0,onDragstart:v,onDragover:y,onDragleave:w,onDrop:_},[s.value?(e.openBlock(),e.createElementBlock("button",{key:0,"data-testid":"expand-chevron",class:"album-node__chevron",type:"button","aria-label":"Toggle expand",onClick:h},[e.createVNode(e.unref(G.IonIcon),{icon:i.value?e.unref(uv):e.unref(mv)},null,8,["icon"])])):(e.openBlock(),e.createElementBlock("span",y5)),e.createVNode(e.unref(G.IonIcon),{icon:e.unref(wv),class:"album-node__icon"},null,8,["icon"]),e.createElementVNode("span",{"data-testid":"album-name",class:"album-node__name",onClick:f},e.toDisplayString(b.album.name),1),b.showMediaCount?(e.openBlock(),e.createElementBlock("span",w5,e.toDisplayString(b.album.media_count),1)):e.createCommentVNode("",!0)],46,b5),i.value&&((T=b.album.children)!=null&&T.length)?(e.openBlock(),e.createElementBlock("div",k5,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(b.album.children,$=>(e.openBlock(),e.createBlock(I,{key:$.id,album:$,depth:b.depth+1,"selected-id":b.selectedId,"expanded-ids":b.expandedIds,"focused-id":b.focusedId,draggable:b.draggable,"show-media-count":b.showMediaCount,compact:b.compact,onSelect:g[0]||(g[0]=N=>n("select",N)),onToggleExpand:g[1]||(g[1]=N=>n("toggle-expand",N))},null,8,["album","depth","selected-id","expanded-ids","focused-id","draggable","show-media-count","compact"]))),128))])):e.createCommentVNode("",!0)])}}}),S5=Ae(E5,[["__scopeId","data-v-76be65a6"]]);let Ro={apiBaseUrl:"/api/v1"};function gf(o){Ro={...Ro,...o}}function C5(){return{...Ro}}function x5(o){Ro={...o}}function Lu(o,a){const t=(o??a).trim().replace(/\/+$/,"");return t===""?a:/^https?:\/\//i.test(t)||t.startsWith("/")?t:`/${t}`}function N5(){const o=Lu(Ro.apiBaseUrl,"/api/v1");return Lu(Ro.albumBaseUrl,`${o}/albums`)}function Fn(o){return encodeURIComponent(o)}function V5(o,a){const t=new URLSearchParams;for(const[i,r]of Object.entries(a))r!==void 0&&t.set(i,r===null?"null":String(r));const n=t.toString();return n===""?o:`${o}?${n}`}function si(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Go(o,a,t=""){const n=o[a];return typeof n=="string"?n:t}function T5(o,a){const t=o[a];if(typeof t!="string")return null;const n=t.trim();return n!==""&&n!=="null"?n:null}function Pu(o,a,t=0){const n=o[a];return typeof n=="number"&&Number.isFinite(n)?n:t}function B5(o){const a=o.owner;return si(a)&&typeof a.id=="string"?a.id:""}function er(o){if(!si(o))throw new Error("Album response was invalid");const a=Array.isArray(o.children)?o.children.map(t=>er(t)):void 0;return{...o,id:Go(o,"id"),name:Go(o,"name"),description:Go(o,"description"),parent_id:T5(o,"parent_id"),user_id:Go(o,"user_id",B5(o)),media_count:Pu(o,"media_count"),children_count:Pu(o,"children_count"),created_at:Go(o,"created_at"),updated_at:Go(o,"updated_at"),...a!==void 0?{children:a}:{}}}function bf(o){if(!si(o))return null;const a=o.message;if(typeof a=="string"&&a.trim()!=="")return a;const t=o.errors;if(si(t))for(const n of Object.values(t)){if(typeof n=="string"&&n.trim()!=="")return n;if(Array.isArray(n)){const i=n.find(r=>typeof r=="string"&&r.trim()!=="");if(i!==void 0)return i}}return null}function M5(o){if(!si(o))return null;const a=o.response;return si(a)&&"data"in a?a.data:"data"in o?o.data:null}function Dn(o,a="Unknown error"){const n=bf(M5(o))??(o instanceof Error&&o.message!==""?o.message:a);return o instanceof Error&&o.message===n?o:new Error(n)}function gn(o="",a={}){return V5(`${N5()}${o}`,a)}async function I5(o,a={}){const t=a.method??"GET",n={Accept:"application/json",...a.headers},i={method:t,credentials:a.credentials??"include",headers:n};a.body!==void 0&&(n["Content-Type"]=n["Content-Type"]??"application/json",i.body=JSON.stringify(a.body));const r=await fetch(o,i);if(!r.ok){const l=await r.json().catch(()=>null);throw new Error(bf(l)??`Album request failed with status ${r.status}.`)}return r.status===204?{}:await r.json()}const $5=3,F5=6e4,ei={count:0,haltUntil:0};function D5(){ei.count=0,ei.haltUntil=0}function A5(){ei.count+=1,ei.count>=$5&&(ei.haltUntil=Date.now()+F5)}function R5(){return Date.now()<ei.haltUntil}async function bn(o,a){if(R5())throw new Error("Album requests are temporarily halted after consecutive failures.");const t=Ro.httpClient??I5;try{const n=await t(o,a);return D5(),n}catch(n){throw A5(),n}}function Ci(o){if(typeof o!="object"||o===null)throw new Error("Album response was invalid");const a=o;if(typeof a.data!="object"||a.data===null)throw new Error("Album response was invalid");const t=a.data;return typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?er(t.data):er(a.data)}function L5(o){if(typeof o!="object"||o===null)return[];const a=o;if(Array.isArray(a.data))return a.data.map(t=>er(t));if(typeof a.data=="object"&&a.data!==null){const t=a.data;if(Array.isArray(t.data))return t.data.map(n=>er(n))}return[]}const Ul=ml.defineStore("albums",()=>{const o=e.ref([]),a=e.ref(new Map),t=e.ref(!1),n=e.ref(null),i=e.ref(new Set),r=e.computed(()=>{const N=new Map;return o.value.forEach(B=>N.set(B.id,B)),N}),l=e.computed(()=>o.value.filter(N=>N.parent_id===null));function s(N){const B=o.value.findIndex(P=>P.id===N.id);B>=0?o.value[B]=N:o.value.push(N)}function d(N,B){Array.isArray(B.media)&&a.value.set(N,B.media)}async function c(N){t.value=!0,n.value=null;try{const B=(N==null?void 0:N.parent_id)??null,P=await bn(gn("",{parent_id:B})),x=L5(P);for(const M of x)s(M);B!==null&&i.value.add(B)}catch(B){n.value=Dn(B).message}finally{t.value=!1}}async function u(N){t.value=!0,n.value=null;try{const B=await bn(gn(`/${Fn(N)}`)),P=Ci(B);return s(P),P}catch(B){const P=Dn(B);throw n.value=P.message,P}finally{t.value=!1}}async function m(N){t.value=!0,n.value=null;try{const B=await bn(gn(`/${Fn(N)}`,{include_media:!0})),P=Ci(B);s(P);const x=Array.isArray(P.media)?P.media:[];return a.value.set(N,x),x}catch(B){const P=Dn(B);throw n.value=P.message,P}finally{t.value=!1}}async function p(N,B,P){t.value=!0,n.value=null;try{const x={media_uuids:B};P!==void 0&&(x.order_column=P);const M=await bn(gn(`/${Fn(N)}/media`),{method:"POST",body:x}),E=Ci(M);return s(E),d(N,E),E}catch(x){const M=Dn(x);throw n.value=M.message,M}finally{t.value=!1}}async function f(N,B){t.value=!0,n.value=null;try{await bn(gn(`/${Fn(N)}/media/${Fn(B)}`),{method:"DELETE"});const P=a.value.get(N)||[];a.value.set(N,P.filter(x=>x.uuid!==B))}catch(P){const x=Dn(P);throw n.value=x.message,x}finally{t.value=!1}}async function h(N,B){t.value=!0,n.value=null;try{const P=await bn(gn(`/${Fn(N)}/media/reorder`),{method:"POST",body:{ordered_media_uuids:B}});if(P.data!==void 0){s(P.data),d(N,P.data);return}const x=a.value.get(N)||[],M=B.map(E=>x.find(D=>D.uuid===E)).filter(E=>E!==void 0);a.value.set(N,M)}catch(P){const x=Dn(P);throw n.value=x.message,x}finally{t.value=!1}}async function v(N){t.value=!0,n.value=null;try{const B=await bn(gn(),{method:"POST",body:N}),P=Ci(B);return s(P),P}catch(B){const P=Dn(B);throw n.value=P.message,P}finally{t.value=!1}}async function y(N,B){t.value=!0,n.value=null;try{const P=await bn(gn(`/${Fn(N)}`),{method:"PUT",body:B}),x=Ci(P);return s(x),x}catch(P){const x=Dn(P);throw n.value=x.message,x}finally{t.value=!1}}async function w(N){t.value=!0,n.value=null;try{await bn(gn(`/${Fn(N)}`),{method:"DELETE"});const B=o.value.findIndex(P=>P.id===N);B>=0&&o.value.splice(B,1),a.value.delete(N)}catch(B){throw n.value=B instanceof Error?B.message:"Unknown error",B}finally{t.value=!1}}function _(N){return o.value.filter(B=>B.parent_id===N)}function b(N){return i.value.has(N)}function g(N){return a.value.get(N)||[]}async function I(N,B){const P=o.value.findIndex(M=>M.id===N);if(P<0)return;const x=o.value[P];o.value[P]={...x,parent_id:B};try{const M=await bn(gn(`/${Fn(N)}/move`),{method:"POST",body:{parent_id:B}});M.data!==void 0&&s(M.data)}catch(M){o.value[P]=x;const E=Dn(M,"Failed to move album");throw n.value=E.message,E}}function T(N){o.value=N}function $(){o.value=[],a.value.clear(),t.value=!1,n.value=null,i.value.clear()}return{albums:o,albumMedia:a,loading:t,error:n,childrenLoadedById:i,albumsById:r,rootAlbums:l,fetchAlbums:c,fetchAlbum:u,fetchAlbumMedia:m,attachMedia:p,detachMedia:f,reorderAlbumMedia:h,createAlbum:v,updateAlbum:y,deleteAlbum:w,getChildrenOf:_,childrenLoaded:b,getAlbumMedia:g,moveAlbum:I,setAlbums:T,reset:$}});function Ol(){const o=Ul(),{albums:a,albumsById:t,rootAlbums:n,loading:i,error:r}=ml.storeToRefs(o);async function l(_){await o.fetchAlbums(_)}async function s(_){return await o.fetchAlbum(_)}async function d(_){return await o.fetchAlbumMedia(_)}async function c(_,b,g){return await o.attachMedia(_,b,g)}async function u(_,b){await o.detachMedia(_,b)}async function m(_,b){await o.reorderAlbumMedia(_,b)}async function p(_){return await o.createAlbum(_)}async function f(_,b){return await o.updateAlbum(_,b)}async function h(_){await o.deleteAlbum(_)}function v(_){return o.getChildrenOf(_)}function y(_){return o.childrenLoaded(_)}async function w(_,b){await o.moveAlbum(_,b)}return{albums:a,albumsById:t,rootAlbums:n,loading:i,error:r,fetchAlbums:l,fetchAlbum:s,fetchAlbumMedia:d,attachMedia:c,detachMedia:u,reorderAlbumMedia:m,createAlbum:p,updateAlbum:f,deleteAlbum:h,getChildrenOf:v,childrenLoaded:y,moveAlbum:w}}function yf(o){const{childrenByParentId:a,onMove:t}=o,n=e.ref({isDragging:!1,draggedAlbumId:null,dropTargetId:null,dropPosition:null});function i(m,p){if(m===p)return!0;const f=new Set,h=[m];for(;h.length>0;){const v=h.shift();if(!v||f.has(v))continue;f.add(v);const y=a.get(v)||[];for(const w of y){if(w===p)return!0;h.push(w)}}return!1}function r(m,p){return m===p?!1:p===null?!0:!i(m,p)}function l(m){n.value={isDragging:!0,draggedAlbumId:m,dropTargetId:null,dropPosition:null}}function s(){n.value={isDragging:!1,draggedAlbumId:null,dropTargetId:null,dropPosition:null}}function d(m){n.value.dropTargetId=m}function c(){n.value.dropTargetId=null,n.value.dropPosition=null}async function u(){const{draggedAlbumId:m,dropTargetId:p}=n.value;if(!m){s();return}if(!r(m,p)){s();return}try{await t(m,p)}finally{s()}}return{dragState:n,isDescendant:i,canDropOn:r,startDrag:l,endDrag:s,setDropTarget:d,clearDropTarget:c,executeDrop:u}}const P5={key:0,"data-testid":"loading-spinner",class:"album-tree__loading"},U5={key:1,"data-testid":"error-state",class:"album-tree__error"},O5={key:2,"data-testid":"empty-state",class:"album-tree__empty"},z5={key:3,class:"album-tree__content",role:"group"},j5=e.defineComponent({__name:"AlbumTree",props:{modelValue:{default:null},expandedIds:{default:()=>[]},draggable:{type:Boolean,default:!0},showMediaCount:{type:Boolean,default:!0},compact:{type:Boolean,default:!1},mode:{default:"standalone"}},emits:["update:modelValue","album-selected","album-moved","album-expanded","album-collapsed"],setup(o,{expose:a,emit:t}){const n=o,i=t,r=e.computed(()=>n.draggable===!0),l=e.computed(()=>n.showMediaCount===!0),s=e.computed(()=>n.compact===!0),d=e.computed(()=>({"album-tree--rail":n.mode==="rail"})),{albums:c,rootAlbums:u,loading:m,error:p,fetchAlbums:f,getChildrenOf:h,childrenLoaded:v,moveAlbum:y}=Ol(),w=e.shallowRef(new Set(n.expandedIds)),_=e.ref(n.modelValue??null),b=e.ref(null),g=new Map,I=new Map;function T(k){g.clear(),I.clear();for(const F of k){g.set(F.id,F);const W=F.parent_id??null,J=I.get(W)??[];J.push(F.id),I.set(W,J)}}e.watch(c,k=>{T(k)},{immediate:!0});const{dragState:$,canDropOn:N,startDrag:B,endDrag:P,setDropTarget:x,clearDropTarget:M,executeDrop:E}=yf({childrenByParentId:I,onMove:async(k,F)=>{await y(k,F),i("album-moved",{albumId:k,newParentId:F})}});e.watch(()=>n.modelValue,k=>{_.value=k??null}),e.watch(()=>n.expandedIds,k=>{w.value=new Set(k)}),e.onMounted(async()=>{await f({parent_id:null})});const D=e.computed(()=>u.value.map(k=>j(k)));function j(k){if(!w.value.has(k.id))return k;const F=h(k.id);return{...k,children:F.map(W=>j(W))}}const L=e.computed(()=>{const k=[];function F(W){var J;for(const ce of W)k.push(ce),w.value.has(ce.id)&&((J=ce.children)!=null&&J.length)&&F(ce.children)}return F(D.value),k});function z(k){var J;if(!L.value.length)return;const F=b.value?L.value.findIndex(ce=>ce.id===b.value):-1,W=F>=0?L.value[F]:null;switch(k.key){case"ArrowDown":k.preventDefault(),F<L.value.length-1?b.value=L.value[F+1].id:F===-1&&L.value.length>0&&(b.value=L.value[0].id);break;case"ArrowUp":k.preventDefault(),F>0&&(b.value=L.value[F-1].id);break;case"ArrowRight":k.preventDefault(),W&&(W.children_count>0&&!w.value.has(W.id)?C(W.id):w.value.has(W.id)&&((J=W.children)!=null&&J.length)&&(b.value=W.children[0].id));break;case"ArrowLeft":k.preventDefault(),W&&(w.value.has(W.id)&&W.children_count>0?C(W.id):W.parent_id&&(b.value=W.parent_id));break;case"Enter":case" ":k.preventDefault(),W&&A(W);break;case"Home":k.preventDefault(),L.value.length>0&&(b.value=L.value[0].id);break;case"End":k.preventDefault(),L.value.length>0&&(b.value=L.value[L.value.length-1].id);break}}async function C(k){w.value.has(k)?(w.value.delete(k),i("album-collapsed",k)):(v(k)||await f({parent_id:k}),w.value.add(k),i("album-expanded",k))}function A(k){_.value=k.id,i("update:modelValue",k.id),i("album-selected",k)}function O(k){n.draggable&&B(k)}function K(k){var W;if(!n.draggable)return;const F=(W=$.value)==null?void 0:W.draggedAlbumId;F&&(x(k),N(F,k))}function se(){n.draggable&&M()}async function xe(k){n.draggable&&(x(k),await E())}function ue(k){n.draggable&&(k.preventDefault(),x(null))}async function le(k){n.draggable&&(k.preventDefault(),x(null),await E())}function Z(){P()}return a({focusedId:b}),(k,F)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["album-tree",d.value]),"data-testid":"album-tree",tabindex:"0",role:"tree","aria-label":"Album tree",onKeydown:z,onDragover:ue,onDrop:le,onDragend:Z},[e.unref(m)?(e.openBlock(),e.createElementBlock("div",P5,[e.createVNode(e.unref(G.IonSpinner),{name:"crescent"})])):e.unref(p)?(e.openBlock(),e.createElementBlock("div",U5,[e.createElementVNode("p",null,e.toDisplayString(e.unref(p)),1)])):e.unref(u).length?(e.openBlock(),e.createElementBlock("div",z5,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(D.value,W=>(e.openBlock(),e.createBlock(S5,{key:W.id,album:W,depth:0,"selected-id":_.value,"expanded-ids":w.value,"focused-id":b.value,draggable:r.value,"drag-state":r.value?e.unref($):null,"show-media-count":l.value,compact:s.value,onSelect:A,onToggleExpand:C,onDragStart:O,onDragOver:K,onDragLeave:se,onDrop:xe},null,8,["album","selected-id","expanded-ids","focused-id","draggable","drag-state","show-media-count","compact"]))),128))])):(e.openBlock(),e.createElementBlock("div",O5,[F[0]||(F[0]=e.createElementVNode("p",null,"No albums yet",-1)),e.renderSlot(k.$slots,"empty-action",{},void 0,!0)]))],34))}}),zl=Ae(j5,[["__scopeId","data-v-ee405f62"]]),W5=300,H5=e.defineComponent({__name:"AlbumBrowser",props:{isOpen:{type:Boolean},selectedAlbumId:{default:null},title:{default:"Select Album"},confirmText:{default:"Select"}},emits:["close","confirm"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(t.selectedAlbumId??null),r=e.ref(null),l=e.ref(0),s=e.ref(null);e.watch(()=>t.selectedAlbumId,f=>{i.value=f??null});const d=e.computed(()=>r.value!==null);function c(f){const h=Date.now();if(s.value===f.id&&h-l.value<W5){n("confirm",f);return}l.value=h,s.value=f.id,i.value=f.id,r.value=f}function u(){r.value&&n("confirm",r.value)}function m(){n("close")}function p(){n("close")}return(f,h)=>(e.openBlock(),e.createBlock(e.unref(G.IonModal),{"is-open":f.isOpen,class:"album-browser-modal",onDidDismiss:p},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonTitle),null,{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(f.title),1)]),_:1}),e.createVNode(e.unref(G.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonButton),{"data-testid":"cancel-button",onClick:m},{default:e.withCtx(()=>[...h[1]||(h[1]=[e.createTextVNode(" Cancel ",-1)])]),_:1})]),_:1})]),_:1})]),_:1}),e.createVNode(e.unref(G.IonContent),{class:"album-browser-content"},{default:e.withCtx(()=>[e.createVNode(zl,{modelValue:i.value,"onUpdate:modelValue":h[0]||(h[0]=v=>i.value=v),draggable:!1,"show-media-count":!0,compact:!1,onAlbumSelected:c},null,8,["modelValue"])]),_:1}),e.createVNode(e.unref(G.IonFooter),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonButton),{fill:"clear",onClick:m},{default:e.withCtx(()=>[...h[2]||(h[2]=[e.createTextVNode(" Cancel ",-1)])]),_:1}),e.createVNode(e.unref(G.IonButton),{"data-testid":"confirm-button",fill:"solid",color:"primary",disabled:!d.value,onClick:u},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(f.confirmText),1)]),_:1},8,["disabled"])]),_:1})]),_:1})]),_:1})]),_:1},8,["is-open"]))}}),wf=Ae(H5,[["__scopeId","data-v-21676ec1"]]),Z5={class:"ion-padding-start text-sm"},G5={class:"ion-padding-start text-sm"},X5={key:1},K5={key:1,class:"album-manager-inline rounded-lg border border-gray-200 bg-white p-4"},q5={class:"flex items-center justify-between gap-3 pb-3"},J5={class:"text-base font-semibold text-gray-900"},Y5={class:"ion-padding-start text-sm"},Q5={class:"ion-padding-start text-sm"},eF={class:"flex justify-between pt-2"},tF={key:1},xi=255,Ni=1e3,aF=e.defineComponent({__name:"AlbumManager",props:{albumId:{default:null},parentId:{default:null},mode:{default:"inline"},isOpen:{type:Boolean,default:!1}},emits:["close","created","updated","deleted","error"],setup(o,{emit:a}){const t=o,n=a,i=Ul(),r=e.computed(()=>t.albumId!==null&&t.albumId!==void 0),l=e.computed(()=>r.value?"Edit Album":"Create Album"),s=e.computed(()=>r.value?"Save":"Create"),d=e.ref({name:"",description:"",parent_id:t.parentId}),c=e.ref({name:!1,description:!1}),u=e.ref(null),m=e.ref(!1),p=e.ref(null),f=e.ref(!1),h=e.ref(!1),v=e.computed(()=>c.value.name?d.value.name.trim()?d.value.name.length>xi?`Name must be ${xi} characters or less`:null:"Name is required":null),y=e.computed(()=>c.value.description&&d.value.description.length>Ni?`Description must be ${Ni} characters or less`:null),w=e.computed(()=>{const L=d.value.name.trim().length>0,z=d.value.name.length<=xi,C=d.value.description.length<=Ni;return L&&z&&C&&!f.value}),_=e.computed(()=>{var L;return((L=u.value)==null?void 0:L.name)??"None (Root)"}),b=e.computed(()=>p.value?p.value.children_count===0&&p.value.media_count===0:!1),g=e.computed(()=>p.value?p.value.children_count>0?"Cannot delete album with child albums. Move or delete children first.":p.value.media_count>0?"Cannot delete album with media. Remove media first.":`Are you sure you want to delete "${p.value.name}"? This action cannot be undone.`:"");e.onMounted(async()=>{t.albumId&&await I()});async function I(){if(t.albumId)try{const L=await i.fetchAlbum(t.albumId);p.value=L,d.value={name:L.name,description:L.description??"",parent_id:L.parent_id},L.parent_id&&(u.value={id:L.parent_id,name:"Parent Album"})}catch(L){n("error",L)}}function T(){c.value.name=!0}function $(){c.value.description=!0}function N(){m.value=!0}function B(L){u.value={id:L.id,name:L.name},d.value.parent_id=L.id,m.value=!1}function P(){m.value=!1}function x(){n("close")}function M(){n("close")}async function E(){if(c.value.name=!0,c.value.description=!0,!(!w.value||f.value)){f.value=!0;try{const L={name:d.value.name.trim(),description:d.value.description.trim(),parent_id:d.value.parent_id};if(r.value&&t.albumId){const z=await i.updateAlbum(t.albumId,L);n("updated",z)}else{const z=await i.createAlbum(L);n("created",z)}n("close")}catch(L){n("error",L)}finally{f.value=!1}}}function D(){b.value&&(h.value=!0)}async function j(L){var C;if((((C=L.detail)==null?void 0:C.role)??"")!=="confirm"){h.value=!1;return}if(t.albumId){f.value=!0;try{await i.deleteAlbum(t.albumId),n("deleted",t.albumId),n("close")}catch(A){n("error",A)}finally{f.value=!1,h.value=!1}}}return(L,z)=>(e.openBlock(),e.createElementBlock(e.Fragment,null,[L.mode==="modal"?(e.openBlock(),e.createBlock(e.unref(G.IonModal),{key:0,"is-open":L.isOpen,class:"album-manager-modal",onDidDismiss:M},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonHeader),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonTitle),null,{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(l.value),1)]),_:1}),e.createVNode(e.unref(G.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonButton),{"data-testid":"cancel-btn",fill:"clear",onClick:x},{default:e.withCtx(()=>[...z[4]||(z[4]=[e.createTextVNode(" Cancel ",-1)])]),_:1})]),_:1})]),_:1})]),_:1}),e.createVNode(e.unref(G.IonContent),{class:"album-manager-content"},{default:e.withCtx(()=>[e.createElementVNode("form",{"data-testid":"album-form",class:"p-4 space-y-3",onSubmit:e.withModifiers(E,["prevent"])},[e.createVNode(e.unref(G.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...z[5]||(z[5]=[e.createTextVNode("Name *",-1)])]),_:1}),e.createVNode(e.unref(G.IonInput),{modelValue:d.value.name,"onUpdate:modelValue":z[0]||(z[0]=C=>d.value.name=C),"data-testid":"name-input",maxlength:xi,onIonBlur:T},null,8,["modelValue"])]),_:1}),v.value?(e.openBlock(),e.createBlock(e.unref(G.IonText),{key:0,color:"danger","data-testid":"name-error"},{default:e.withCtx(()=>[e.createElementVNode("p",Z5,e.toDisplayString(v.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(G.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...z[6]||(z[6]=[e.createTextVNode("Description",-1)])]),_:1}),e.createVNode(e.unref(G.IonTextarea),{modelValue:d.value.description,"onUpdate:modelValue":z[1]||(z[1]=C=>d.value.description=C),"data-testid":"description-input",maxlength:Ni,onIonBlur:$},null,8,["modelValue"])]),_:1}),y.value?(e.openBlock(),e.createBlock(e.unref(G.IonText),{key:1,color:"danger","data-testid":"description-error"},{default:e.withCtx(()=>[e.createElementVNode("p",G5,e.toDisplayString(y.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(G.IonItem),{button:"","data-testid":"parent-selector",onClick:N},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonLabel),null,{default:e.withCtx(()=>[...z[7]||(z[7]=[e.createTextVNode("Parent Album",-1)])]),_:1}),e.createVNode(e.unref(G.IonNote),{slot:"end","data-testid":"parent-name"},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(_.value),1)]),_:1})]),_:1})],32)]),_:1}),e.createVNode(e.unref(G.IonFooter),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonToolbar),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonButtons),{slot:"start"},{default:e.withCtx(()=>[r.value?(e.openBlock(),e.createBlock(e.unref(G.IonButton),{key:0,"data-testid":"delete-btn",color:"danger",disabled:!b.value,title:b.value?void 0:g.value,onClick:D},{default:e.withCtx(()=>[...z[8]||(z[8]=[e.createTextVNode(" Delete ",-1)])]),_:1},8,["disabled","title"])):e.createCommentVNode("",!0)]),_:1}),e.createVNode(e.unref(G.IonButtons),{slot:"end"},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonButton),{"data-testid":"submit-btn",type:"submit",color:"primary",disabled:!w.value,onClick:E},{default:e.withCtx(()=>[f.value?(e.openBlock(),e.createBlock(e.unref(G.IonSpinner),{key:0,"data-testid":"loading-spinner",name:"crescent"})):(e.openBlock(),e.createElementBlock("span",X5,e.toDisplayString(s.value),1))]),_:1},8,["disabled"])]),_:1})]),_:1})]),_:1})]),_:1},8,["is-open"])):(e.openBlock(),e.createElementBlock("div",K5,[e.createElementVNode("div",q5,[e.createElementVNode("h2",J5,e.toDisplayString(l.value),1),e.createVNode(e.unref(G.IonButton),{"data-testid":"cancel-btn",fill:"clear",onClick:x},{default:e.withCtx(()=>[...z[9]||(z[9]=[e.createTextVNode(" Cancel ",-1)])]),_:1})]),e.createElementVNode("form",{"data-testid":"album-form",class:"space-y-3",onSubmit:e.withModifiers(E,["prevent"])},[e.createVNode(e.unref(G.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...z[10]||(z[10]=[e.createTextVNode("Name *",-1)])]),_:1}),e.createVNode(e.unref(G.IonInput),{modelValue:d.value.name,"onUpdate:modelValue":z[2]||(z[2]=C=>d.value.name=C),"data-testid":"name-input",maxlength:xi,onIonBlur:T},null,8,["modelValue"])]),_:1}),v.value?(e.openBlock(),e.createBlock(e.unref(G.IonText),{key:0,color:"danger","data-testid":"name-error"},{default:e.withCtx(()=>[e.createElementVNode("p",Y5,e.toDisplayString(v.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(G.IonItem),null,{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonLabel),{position:"stacked"},{default:e.withCtx(()=>[...z[11]||(z[11]=[e.createTextVNode("Description",-1)])]),_:1}),e.createVNode(e.unref(G.IonTextarea),{modelValue:d.value.description,"onUpdate:modelValue":z[3]||(z[3]=C=>d.value.description=C),"data-testid":"description-input",maxlength:Ni,onIonBlur:$},null,8,["modelValue"])]),_:1}),y.value?(e.openBlock(),e.createBlock(e.unref(G.IonText),{key:1,color:"danger","data-testid":"description-error"},{default:e.withCtx(()=>[e.createElementVNode("p",Q5,e.toDisplayString(y.value),1)]),_:1})):e.createCommentVNode("",!0),e.createVNode(e.unref(G.IonItem),{button:"","data-testid":"parent-selector",onClick:N},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonLabel),null,{default:e.withCtx(()=>[...z[12]||(z[12]=[e.createTextVNode("Parent Album",-1)])]),_:1}),e.createVNode(e.unref(G.IonNote),{slot:"end","data-testid":"parent-name"},{default:e.withCtx(()=>[e.createTextVNode(e.toDisplayString(_.value),1)]),_:1})]),_:1}),e.createElementVNode("div",eF,[e.createElementVNode("div",null,[r.value?(e.openBlock(),e.createBlock(e.unref(G.IonButton),{key:0,"data-testid":"delete-btn",color:"danger",fill:"outline",disabled:!b.value,title:b.value?void 0:g.value,onClick:D},{default:e.withCtx(()=>[...z[13]||(z[13]=[e.createTextVNode(" Delete ",-1)])]),_:1},8,["disabled","title"])):e.createCommentVNode("",!0)]),e.createVNode(e.unref(G.IonButton),{"data-testid":"submit-btn",type:"submit",color:"primary",disabled:!w.value,onClick:E},{default:e.withCtx(()=>[f.value?(e.openBlock(),e.createBlock(e.unref(G.IonSpinner),{key:0,"data-testid":"loading-spinner",name:"crescent"})):(e.openBlock(),e.createElementBlock("span",tF,e.toDisplayString(s.value),1))]),_:1},8,["disabled"])])],32)])),e.createVNode(wf,{"is-open":m.value,"selected-album-id":d.value.parent_id,title:"Select Parent Album",onClose:P,onConfirm:B},null,8,["is-open","selected-album-id"]),e.createVNode(e.unref(G.IonAlert),{"is-open":h.value,header:"Delete Album?",message:g.value,buttons:[{text:"Cancel",role:"cancel"},{text:"Delete",role:"confirm",cssClass:"alert-button-danger"}],onDidDismiss:j},null,8,["is-open","message"])],64))}}),nF=Ae(aF,[["__scopeId","data-v-22083f3a"]]),oF={class:"album-media-grid"},iF={class:"aspect-square"},rF={key:1,"data-testid":"empty-state",class:"flex flex-col items-center justify-center py-12 gap-4"},lF={class:"text-gray-500"},sF=["data-media-id","draggable","onDragstart","onDragover","onDrop","onMouseenter"],dF={key:0,"data-testid":"drop-indicator",class:"absolute inset-0 border-2 border-primary rounded-lg pointer-events-none z-30"},cF={key:1,class:"absolute top-2 right-2 z-20 opacity-0 group-hover:opacity-100 transition-opacity cursor-grab"},uF={class:"aspect-square relative"},mF=["src","alt"],pF={key:0,class:"absolute inset-0 bg-black/50 flex items-center justify-center gap-2 transition-opacity"},fF=e.defineComponent({__name:"AlbumMediaGrid",props:{albumId:{},selectionMode:{type:Boolean,default:!1},selectedItems:{default:()=>[]},reorderable:{type:Boolean,default:!1},showActions:{type:Boolean,default:!0},columns:{default:()=>({mobile:2,sm:3,md:4,lg:5,xl:6})},isLoading:{type:Boolean,default:!1},emptyText:{default:"No media in this album"}},emits:["toggle-select","preview","edit","detach","reorder","add","selection-change"],setup(o,{emit:a}){const t=o,n=a,i=Ul(),r=e.ref([]),l=e.ref(!1),s=e.ref(null),d=e.ref(null),c=e.ref(null),u=e.computed(()=>t.isLoading||l.value),m=e.computed(()=>!u.value&&r.value.length===0),p=e.computed(()=>{const M=t.columns;return["grid","gap-4",`grid-cols-${M.mobile??2}`,`sm:grid-cols-${M.sm??3}`,`md:grid-cols-${M.md??4}`,`lg:grid-cols-${M.lg??5}`,`xl:grid-cols-${M.xl??6}`]}),f=e.computed(()=>(t.columns.md??4)*2);e.onMounted(async()=>{await h()}),e.watch(()=>t.albumId,async()=>{await h()});async function h(){l.value=!0;try{const M=await i.fetchAlbumMedia(t.albumId);r.value=M}catch{r.value=[]}finally{l.value=!1}}function v(M){return t.selectedItems.includes(M)}function y(M){n("toggle-select",M);const E=v(M.uuid)?t.selectedItems.filter(D=>D!==M.uuid):[...t.selectedItems,M.uuid];n("selection-change",E)}function w(M){if(M.conversions&&typeof M.conversions=="object"){const E=M.conversions.thumb;if(typeof E=="string")return E}return M.original_url}function _(M){s.value=M}function b(){s.value=null}function g(M){n("preview",M)}function I(M){n("edit",M)}function T(M){n("detach",M.uuid)}function $(){n("add")}function N(M,E){t.reorderable&&(d.value=E,M.dataTransfer&&(M.dataTransfer.effectAllowed="move",M.dataTransfer.setData("text/plain",String(E))))}function B(M,E){!t.reorderable||d.value===null||(M.preventDefault(),c.value=E)}function P(M,E){if(!t.reorderable||d.value===null)return;M.preventDefault();const D=d.value;if(D!==E){const j=[...r.value],[L]=j.splice(D,1);j.splice(E,0,L),r.value=j;const z=j.map(C=>C.uuid);n("reorder",z),i.reorderAlbumMedia(t.albumId,z).catch(()=>{h()})}d.value=null,c.value=null}function x(){d.value=null,c.value=null}return(M,E)=>(e.openBlock(),e.createElementBlock("div",oF,[u.value?(e.openBlock(),e.createElementBlock("div",{key:0,"data-testid":"loading-grid",class:e.normalizeClass(p.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(f.value,D=>(e.openBlock(),e.createBlock(e.unref(G.IonCard),{key:D,class:"m-0"},{default:e.withCtx(()=>[e.createElementVNode("div",iF,[e.createVNode(e.unref(G.IonSkeletonText),{animated:"",class:"w-full h-full skeleton"})])]),_:1}))),128))],2)):m.value?(e.openBlock(),e.createElementBlock("div",rF,[e.createVNode(e.unref(G.IonIcon),{name:"images-outline",class:"text-6xl text-gray-400"}),e.createElementVNode("p",lF,e.toDisplayString(M.emptyText),1),e.createVNode(e.unref(G.IonButton),{"data-testid":"add-media-btn",onClick:$},{default:e.withCtx(()=>[...E[0]||(E[0]=[e.createTextVNode(" Add Media ",-1)])]),_:1})])):(e.openBlock(),e.createElementBlock("div",{key:2,"data-testid":"media-grid",class:e.normalizeClass(p.value)},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.value,(D,j)=>(e.openBlock(),e.createElementBlock("div",{key:D.uuid,"data-media-id":D.uuid,class:e.normalizeClass(["media-item relative group",{"opacity-50":d.value===j,"ring-2 ring-primary":c.value===j&&d.value!==j}]),draggable:M.reorderable,onDragstart:L=>N(L,j),onDragover:L=>B(L,j),onDrop:L=>P(L,j),onDragend:x,onMouseenter:L=>_(D.uuid),onMouseleave:b},[c.value===j&&d.value!==j&&M.reorderable?(e.openBlock(),e.createElementBlock("div",dF)):e.createCommentVNode("",!0),M.reorderable?(e.openBlock(),e.createElementBlock("div",cF,[e.createVNode(e.unref(G.IonIcon),{name:"reorder-three-outline",class:"text-white drop-shadow-md"})])):e.createCommentVNode("",!0),M.selectionMode?(e.openBlock(),e.createBlock(e.unref(G.IonCheckbox),{key:2,"data-testid":"media-checkbox",checked:v(D.uuid),class:"absolute top-2 left-2 z-20",onIonChange:L=>y(D)},null,8,["checked","onIonChange"])):e.createCommentVNode("",!0),e.createVNode(e.unref(G.IonCard),{class:"m-0 overflow-hidden"},{default:e.withCtx(()=>[e.createElementVNode("div",uF,[e.createElementVNode("img",{src:w(D),alt:D.file_name,class:"w-full h-full object-cover"},null,8,mF),M.showActions&&s.value===D.uuid?(e.openBlock(),e.createElementBlock("div",pF,[e.createVNode(e.unref(G.IonButton),{"data-testid":"action-preview",fill:"clear",size:"small",color:"light",onClick:L=>g(D)},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{slot:"icon-only",name:"eye-outline"})]),_:1},8,["onClick"]),e.createVNode(e.unref(G.IonButton),{"data-testid":"action-edit",fill:"clear",size:"small",color:"light",onClick:L=>I(D)},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{slot:"icon-only",name:"create-outline"})]),_:1},8,["onClick"]),e.createVNode(e.unref(G.IonButton),{"data-testid":"action-detach",fill:"clear",size:"small",color:"danger",onClick:L=>T(D)},{default:e.withCtx(()=>[e.createVNode(e.unref(G.IonIcon),{slot:"icon-only",name:"close-circle-outline"})]),_:1},8,["onClick"])])):e.createCommentVNode("",!0)])]),_:2},1024)],42,sF))),128)),e.createElementVNode("div",{class:"aspect-square border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center gap-2 cursor-pointer hover:border-primary hover:bg-gray-50 transition-colors","data-testid":"add-more-card",onClick:$},[e.createVNode(e.unref(G.IonIcon),{name:"add-circle-outline",class:"text-4xl text-gray-400"}),E[1]||(E[1]=e.createElementVNode("span",{class:"text-sm text-gray-500"},"Add Media",-1))])],2))]))}}),hF=Ae(fF,[["__scopeId","data-v-d84b796a"]]),vF={key:0,class:"media-album-inline-create","data-testid":"media-album-inline-create"},gF={class:"media-album-inline-create__field"},bF={class:"media-album-inline-create__field"},yF=["value"],wF={key:1,class:"media-album-inline-create__autocomplete"},kF={class:"media-album-inline-create__autocomplete-input-wrap"},_F={key:0,class:"media-album-inline-create__autocomplete-list"},EF=["onMousedown"],SF={key:1,class:"media-album-inline-create__autocomplete-empty"},CF={class:"media-album-inline-create__actions"},xF=e.defineComponent({__name:"MediaAlbumInlineCreate",props:{open:{type:Boolean,default:!1},nameLabel:{default:"Album name"},albums:{default:()=>[]}},emits:["cancel","create"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(""),r=e.ref(""),l=e.ref(""),s=e.ref(!1),d=e.computed(()=>t.albums.length>5),c=e.computed(()=>{if(l.value.trim()==="")return t.albums;const y=l.value.toLowerCase();return t.albums.filter(w=>w.name.toLowerCase().includes(y))}),u=e.computed(()=>{if(r.value==="")return"";const y=t.albums.find(w=>w.id===r.value);return(y==null?void 0:y.name)??""}),m=y=>{r.value=y.id,l.value=y.name,s.value=!1},p=()=>{r.value="",l.value="",s.value=!1},f=()=>{s.value=!0,r.value!==""&&(l.value=u.value)},h=()=>{setTimeout(()=>{s.value=!1,r.value!==""?l.value=u.value:l.value=""},150)},v=()=>{i.value.trim()!==""&&(n("create",i.value.trim(),r.value!==""?r.value:void 0),i.value="",r.value="",l.value="")};return(y,w)=>y.open?(e.openBlock(),e.createElementBlock("section",vF,[w[7]||(w[7]=e.createElementVNode("h4",{class:"media-album-inline-create__heading"}," New album ",-1)),e.createElementVNode("label",gF,[e.createElementVNode("span",null,e.toDisplayString(y.nameLabel),1),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":w[0]||(w[0]=_=>i.value=_),type:"text",class:"media-album-inline-create__input",placeholder:"e.g. Marbles, Pendants","data-testid":"input-media-album-name"},null,512),[[e.vModelText,i.value]])]),e.createElementVNode("label",bF,[w[6]||(w[6]=e.createElementVNode("span",null,"Parent album (optional)",-1)),d.value?(e.openBlock(),e.createElementBlock("div",wF,[e.createElementVNode("div",kF,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":w[2]||(w[2]=_=>l.value=_),type:"text",class:"media-album-inline-create__input",placeholder:"Search albums...","data-testid":"input-media-album-parent-search",onFocus:f,onBlur:h},null,544),[[e.vModelText,l.value]]),r.value!==""?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-album-inline-create__autocomplete-clear","aria-label":"Clear parent album",onMousedown:e.withModifiers(p,["prevent"])},[...w[5]||(w[5]=[e.createElementVNode("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2.5","stroke-linecap":"round"},[e.createElementVNode("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.createElementVNode("line",{x1:"6",y1:"6",x2:"18",y2:"18"})],-1)])],32)):e.createCommentVNode("",!0)]),s.value?(e.openBlock(),e.createElementBlock("ul",_F,[r.value!==""?(e.openBlock(),e.createElementBlock("li",{key:0,class:"media-album-inline-create__autocomplete-option media-album-inline-create__autocomplete-option--none",onMousedown:e.withModifiers(p,["prevent"])}," None ",32)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(c.value,_=>(e.openBlock(),e.createElementBlock("li",{key:_.id,class:e.normalizeClass(["media-album-inline-create__autocomplete-option",{"is-selected":_.id===r.value}]),onMousedown:e.withModifiers(b=>m(_),["prevent"])},e.toDisplayString(_.name),43,EF))),128)),c.value.length===0?(e.openBlock(),e.createElementBlock("li",SF," No albums match ")):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])):e.withDirectives((e.openBlock(),e.createElementBlock("select",{key:0,"onUpdate:modelValue":w[1]||(w[1]=_=>r.value=_),class:"media-album-inline-create__input","data-testid":"select-media-album-parent"},[w[4]||(w[4]=e.createElementVNode("option",{value:""}," None ",-1)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(y.albums,_=>(e.openBlock(),e.createElementBlock("option",{key:_.id,value:_.id},e.toDisplayString(_.name),9,yF))),128))],512)),[[e.vModelSelect,r.value]])]),e.createElementVNode("div",CF,[e.createElementVNode("button",{type:"button",class:"media-album-inline-create__button","data-testid":"btn-media-album-cancel",onClick:w[3]||(w[3]=_=>n("cancel"))}," Cancel "),e.createElementVNode("button",{type:"button",class:"media-album-inline-create__button media-album-inline-create__button--primary","data-testid":"btn-media-album-create",onClick:v}," Create ")])])):e.createCommentVNode("",!0)}}),jd=Ae(xF,[["__scopeId","data-v-a85162fe"]]),NF={class:"media-album-unavailable-state","data-testid":"media-album-unavailable-state"},VF=e.defineComponent({__name:"MediaAlbumUnavailableState",props:{title:{default:"Album unavailable"},body:{default:"You no longer have access to this album."},actionLabel:{default:"Go to library"}},emits:["goToLibrary"],setup(o,{emit:a}){const t=a;return(n,i)=>(e.openBlock(),e.createElementBlock("section",NF,[e.createElementVNode("h3",null,e.toDisplayString(n.title),1),e.createElementVNode("p",null,e.toDisplayString(n.body),1),e.createElementVNode("button",{type:"button",class:"media-album-unavailable-state__button",onClick:i[0]||(i[0]=r=>t("goToLibrary"))},e.toDisplayString(n.actionLabel),1)]))}}),kf=Ae(VF,[["__scopeId","data-v-04620e64"]]);/*!
350
+ * tabbable 6.2.0
351
+ * @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE
352
+ */var _f=["input:not([inert])","select:not([inert])","textarea:not([inert])","a[href]:not([inert])","button:not([inert])","[tabindex]:not(slot):not([inert])","audio[controls]:not([inert])","video[controls]:not([inert])",'[contenteditable]:not([contenteditable="false"]):not([inert])',"details>summary:first-of-type:not([inert])","details:not([inert])"],ll=_f.join(","),Ef=typeof Element>"u",Lo=Ef?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,sl=!Ef&&Element.prototype.getRootNode?function(o){var a;return o==null||(a=o.getRootNode)===null||a===void 0?void 0:a.call(o)}:function(o){return o==null?void 0:o.ownerDocument},dl=function o(a,t){var n;t===void 0&&(t=!0);var i=a==null||(n=a.getAttribute)===null||n===void 0?void 0:n.call(a,"inert"),r=i===""||i==="true",l=r||t&&a&&o(a.parentNode);return l},TF=function(a){var t,n=a==null||(t=a.getAttribute)===null||t===void 0?void 0:t.call(a,"contenteditable");return n===""||n==="true"},Sf=function(a,t,n){if(dl(a))return[];var i=Array.prototype.slice.apply(a.querySelectorAll(ll));return t&&Lo.call(a,ll)&&i.unshift(a),i=i.filter(n),i},Cf=function o(a,t,n){for(var i=[],r=Array.from(a);r.length;){var l=r.shift();if(!dl(l,!1))if(l.tagName==="SLOT"){var s=l.assignedElements(),d=s.length?s:l.children,c=o(d,!0,n);n.flatten?i.push.apply(i,c):i.push({scopeParent:l,candidates:c})}else{var u=Lo.call(l,ll);u&&n.filter(l)&&(t||!a.includes(l))&&i.push(l);var m=l.shadowRoot||typeof n.getShadowRoot=="function"&&n.getShadowRoot(l),p=!dl(m,!1)&&(!n.shadowRootFilter||n.shadowRootFilter(l));if(m&&p){var f=o(m===!0?l.children:m.children,!0,n);n.flatten?i.push.apply(i,f):i.push({scopeParent:l,candidates:f})}else r.unshift.apply(r,l.children)}}return i},xf=function(a){return!isNaN(parseInt(a.getAttribute("tabindex"),10))},Vo=function(a){if(!a)throw new Error("No node provided");return a.tabIndex<0&&(/^(AUDIO|VIDEO|DETAILS)$/.test(a.tagName)||TF(a))&&!xf(a)?0:a.tabIndex},BF=function(a,t){var n=Vo(a);return n<0&&t&&!xf(a)?0:n},MF=function(a,t){return a.tabIndex===t.tabIndex?a.documentOrder-t.documentOrder:a.tabIndex-t.tabIndex},Nf=function(a){return a.tagName==="INPUT"},IF=function(a){return Nf(a)&&a.type==="hidden"},$F=function(a){var t=a.tagName==="DETAILS"&&Array.prototype.slice.apply(a.children).some(function(n){return n.tagName==="SUMMARY"});return t},FF=function(a,t){for(var n=0;n<a.length;n++)if(a[n].checked&&a[n].form===t)return a[n]},DF=function(a){if(!a.name)return!0;var t=a.form||sl(a),n=function(s){return t.querySelectorAll('input[type="radio"][name="'+s+'"]')},i;if(typeof window<"u"&&typeof window.CSS<"u"&&typeof window.CSS.escape=="function")i=n(window.CSS.escape(a.name));else try{i=n(a.name)}catch{return!1}var r=FF(i,a.form);return!r||r===a},AF=function(a){return Nf(a)&&a.type==="radio"},RF=function(a){return AF(a)&&!DF(a)},LF=function(a){var t,n=a&&sl(a),i=(t=n)===null||t===void 0?void 0:t.host,r=!1;if(n&&n!==a){var l,s,d;for(r=!!((l=i)!==null&&l!==void 0&&(s=l.ownerDocument)!==null&&s!==void 0&&s.contains(i)||a!=null&&(d=a.ownerDocument)!==null&&d!==void 0&&d.contains(a));!r&&i;){var c,u,m;n=sl(i),i=(c=n)===null||c===void 0?void 0:c.host,r=!!((u=i)!==null&&u!==void 0&&(m=u.ownerDocument)!==null&&m!==void 0&&m.contains(i))}}return r},Uu=function(a){var t=a.getBoundingClientRect(),n=t.width,i=t.height;return n===0&&i===0},PF=function(a,t){var n=t.displayCheck,i=t.getShadowRoot;if(getComputedStyle(a).visibility==="hidden")return!0;var r=Lo.call(a,"details>summary:first-of-type"),l=r?a.parentElement:a;if(Lo.call(l,"details:not([open]) *"))return!0;if(!n||n==="full"||n==="legacy-full"){if(typeof i=="function"){for(var s=a;a;){var d=a.parentElement,c=sl(a);if(d&&!d.shadowRoot&&i(d)===!0)return Uu(a);a.assignedSlot?a=a.assignedSlot:!d&&c!==a.ownerDocument?a=c.host:a=d}a=s}if(LF(a))return!a.getClientRects().length;if(n!=="legacy-full")return!0}else if(n==="non-zero-area")return Uu(a);return!1},UF=function(a){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(a.tagName))for(var t=a.parentElement;t;){if(t.tagName==="FIELDSET"&&t.disabled){for(var n=0;n<t.children.length;n++){var i=t.children.item(n);if(i.tagName==="LEGEND")return Lo.call(t,"fieldset[disabled] *")?!0:!i.contains(a)}return!0}t=t.parentElement}return!1},cl=function(a,t){return!(t.disabled||dl(t)||IF(t)||PF(t,a)||$F(t)||UF(t))},sd=function(a,t){return!(RF(t)||Vo(t)<0||!cl(a,t))},OF=function(a){var t=parseInt(a.getAttribute("tabindex"),10);return!!(isNaN(t)||t>=0)},zF=function o(a){var t=[],n=[];return a.forEach(function(i,r){var l=!!i.scopeParent,s=l?i.scopeParent:i,d=BF(s,l),c=l?o(i.candidates):s;d===0?l?t.push.apply(t,c):t.push(s):n.push({documentOrder:r,tabIndex:d,item:i,isScope:l,content:c})}),n.sort(MF).reduce(function(i,r){return r.isScope?i.push.apply(i,r.content):i.push(r.content),i},[]).concat(t)},jF=function(a,t){t=t||{};var n;return t.getShadowRoot?n=Cf([a],t.includeContainer,{filter:sd.bind(null,t),flatten:!1,getShadowRoot:t.getShadowRoot,shadowRootFilter:OF}):n=Sf(a,t.includeContainer,sd.bind(null,t)),zF(n)},WF=function(a,t){t=t||{};var n;return t.getShadowRoot?n=Cf([a],t.includeContainer,{filter:cl.bind(null,t),flatten:!0,getShadowRoot:t.getShadowRoot}):n=Sf(a,t.includeContainer,cl.bind(null,t)),n},Xo=function(a,t){if(t=t||{},!a)throw new Error("No node provided");return Lo.call(a,ll)===!1?!1:sd(t,a)},HF=_f.concat("iframe").join(","),bs=function(a,t){if(t=t||{},!a)throw new Error("No node provided");return Lo.call(a,HF)===!1?!1:cl(t,a)};/*!
353
+ * focus-trap 7.6.5
354
+ * @license MIT, https://github.com/focus-trap/focus-trap/blob/master/LICENSE
355
+ */function dd(o,a){(a==null||a>o.length)&&(a=o.length);for(var t=0,n=Array(a);t<a;t++)n[t]=o[t];return n}function ZF(o){if(Array.isArray(o))return dd(o)}function GF(o,a,t){return(a=YF(a))in o?Object.defineProperty(o,a,{value:t,enumerable:!0,configurable:!0,writable:!0}):o[a]=t,o}function XF(o){if(typeof Symbol<"u"&&o[Symbol.iterator]!=null||o["@@iterator"]!=null)return Array.from(o)}function KF(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
356
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Ou(o,a){var t=Object.keys(o);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(o);a&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(o,i).enumerable})),t.push.apply(t,n)}return t}function zu(o){for(var a=1;a<arguments.length;a++){var t=arguments[a]!=null?arguments[a]:{};a%2?Ou(Object(t),!0).forEach(function(n){GF(o,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(t)):Ou(Object(t)).forEach(function(n){Object.defineProperty(o,n,Object.getOwnPropertyDescriptor(t,n))})}return o}function qF(o){return ZF(o)||XF(o)||QF(o)||KF()}function JF(o,a){if(typeof o!="object"||!o)return o;var t=o[Symbol.toPrimitive];if(t!==void 0){var n=t.call(o,a);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(o)}function YF(o){var a=JF(o,"string");return typeof a=="symbol"?a:a+""}function QF(o,a){if(o){if(typeof o=="string")return dd(o,a);var t={}.toString.call(o).slice(8,-1);return t==="Object"&&o.constructor&&(t=o.constructor.name),t==="Map"||t==="Set"?Array.from(o):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?dd(o,a):void 0}}var ju={activateTrap:function(a,t){if(a.length>0){var n=a[a.length-1];n!==t&&n._setPausedState(!0)}var i=a.indexOf(t);i===-1||a.splice(i,1),a.push(t)},deactivateTrap:function(a,t){var n=a.indexOf(t);n!==-1&&a.splice(n,1),a.length>0&&!a[a.length-1]._isManuallyPaused()&&a[a.length-1]._setPausedState(!1)}},e8=function(a){return a.tagName&&a.tagName.toLowerCase()==="input"&&typeof a.select=="function"},t8=function(a){return(a==null?void 0:a.key)==="Escape"||(a==null?void 0:a.key)==="Esc"||(a==null?void 0:a.keyCode)===27},Zi=function(a){return(a==null?void 0:a.key)==="Tab"||(a==null?void 0:a.keyCode)===9},a8=function(a){return Zi(a)&&!a.shiftKey},n8=function(a){return Zi(a)&&a.shiftKey},Wu=function(a){return setTimeout(a,0)},Vi=function(a){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return typeof a=="function"?a.apply(void 0,n):a},Tr=function(a){return a.target.shadowRoot&&typeof a.composedPath=="function"?a.composedPath()[0]:a.target},o8=[],i8=function(a,t){var n=(t==null?void 0:t.document)||document,i=(t==null?void 0:t.trapStack)||o8,r=zu({returnFocusOnDeactivate:!0,escapeDeactivates:!0,delayInitialFocus:!0,isKeyForward:a8,isKeyBackward:n8},t),l={containers:[],containerGroups:[],tabbableGroups:[],nodeFocusedBeforeActivation:null,mostRecentlyFocusedNode:null,active:!1,paused:!1,manuallyPaused:!1,delayInitialFocusTimer:void 0,recentNavEvent:void 0},s,d=function(E,D,j){return E&&E[D]!==void 0?E[D]:r[j||D]},c=function(E,D){var j=typeof(D==null?void 0:D.composedPath)=="function"?D.composedPath():void 0;return l.containerGroups.findIndex(function(L){var z=L.container,C=L.tabbableNodes;return z.contains(E)||(j==null?void 0:j.includes(z))||C.find(function(A){return A===E})})},u=function(E){var D=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},j=D.hasFallback,L=j===void 0?!1:j,z=D.params,C=z===void 0?[]:z,A=r[E];if(typeof A=="function"&&(A=A.apply(void 0,qF(C))),A===!0&&(A=void 0),!A){if(A===void 0||A===!1)return A;throw new Error("`".concat(E,"` was specified but was not a node, or did not return a node"))}var O=A;if(typeof A=="string"){try{O=n.querySelector(A)}catch(K){throw new Error("`".concat(E,'` appears to be an invalid selector; error="').concat(K.message,'"'))}if(!O&&!L)throw new Error("`".concat(E,"` as selector refers to no known node"))}return O},m=function(){var E=u("initialFocus",{hasFallback:!0});if(E===!1)return!1;if(E===void 0||E&&!bs(E,r.tabbableOptions))if(c(n.activeElement)>=0)E=n.activeElement;else{var D=l.tabbableGroups[0],j=D&&D.firstTabbableNode;E=j||u("fallbackFocus")}else E===null&&(E=u("fallbackFocus"));if(!E)throw new Error("Your focus-trap needs to have at least one focusable element");return E},p=function(){if(l.containerGroups=l.containers.map(function(E){var D=jF(E,r.tabbableOptions),j=WF(E,r.tabbableOptions),L=D.length>0?D[0]:void 0,z=D.length>0?D[D.length-1]:void 0,C=j.find(function(K){return Xo(K)}),A=j.slice().reverse().find(function(K){return Xo(K)}),O=!!D.find(function(K){return Vo(K)>0});return{container:E,tabbableNodes:D,focusableNodes:j,posTabIndexesFound:O,firstTabbableNode:L,lastTabbableNode:z,firstDomTabbableNode:C,lastDomTabbableNode:A,nextTabbableNode:function(se){var xe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,ue=D.indexOf(se);return ue<0?xe?j.slice(j.indexOf(se)+1).find(function(le){return Xo(le)}):j.slice(0,j.indexOf(se)).reverse().find(function(le){return Xo(le)}):D[ue+(xe?1:-1)]}}}),l.tabbableGroups=l.containerGroups.filter(function(E){return E.tabbableNodes.length>0}),l.tabbableGroups.length<=0&&!u("fallbackFocus"))throw new Error("Your focus-trap must have at least one container with at least one tabbable node in it at all times");if(l.containerGroups.find(function(E){return E.posTabIndexesFound})&&l.containerGroups.length>1)throw new Error("At least one node with a positive tabindex was found in one of your focus-trap's multiple containers. Positive tabindexes are only supported in single-container focus-traps.")},f=function(E){var D=E.activeElement;if(D)return D.shadowRoot&&D.shadowRoot.activeElement!==null?f(D.shadowRoot):D},h=function(E){if(E!==!1&&E!==f(document)){if(!E||!E.focus){h(m());return}E.focus({preventScroll:!!r.preventScroll}),l.mostRecentlyFocusedNode=E,e8(E)&&E.select()}},v=function(E){var D=u("setReturnFocus",{params:[E]});return D||(D===!1?!1:E)},y=function(E){var D=E.target,j=E.event,L=E.isBackward,z=L===void 0?!1:L;D=D||Tr(j),p();var C=null;if(l.tabbableGroups.length>0){var A=c(D,j),O=A>=0?l.containerGroups[A]:void 0;if(A<0)z?C=l.tabbableGroups[l.tabbableGroups.length-1].lastTabbableNode:C=l.tabbableGroups[0].firstTabbableNode;else if(z){var K=l.tabbableGroups.findIndex(function(k){var F=k.firstTabbableNode;return D===F});if(K<0&&(O.container===D||bs(D,r.tabbableOptions)&&!Xo(D,r.tabbableOptions)&&!O.nextTabbableNode(D,!1))&&(K=A),K>=0){var se=K===0?l.tabbableGroups.length-1:K-1,xe=l.tabbableGroups[se];C=Vo(D)>=0?xe.lastTabbableNode:xe.lastDomTabbableNode}else Zi(j)||(C=O.nextTabbableNode(D,!1))}else{var ue=l.tabbableGroups.findIndex(function(k){var F=k.lastTabbableNode;return D===F});if(ue<0&&(O.container===D||bs(D,r.tabbableOptions)&&!Xo(D,r.tabbableOptions)&&!O.nextTabbableNode(D))&&(ue=A),ue>=0){var le=ue===l.tabbableGroups.length-1?0:ue+1,Z=l.tabbableGroups[le];C=Vo(D)>=0?Z.firstTabbableNode:Z.firstDomTabbableNode}else Zi(j)||(C=O.nextTabbableNode(D))}}else C=u("fallbackFocus");return C},w=function(E){var D=Tr(E);if(!(c(D,E)>=0)){if(Vi(r.clickOutsideDeactivates,E)){s.deactivate({returnFocus:r.returnFocusOnDeactivate});return}Vi(r.allowOutsideClick,E)||E.preventDefault()}},_=function(E){var D=Tr(E),j=c(D,E)>=0;if(j||D instanceof Document)j&&(l.mostRecentlyFocusedNode=D);else{E.stopImmediatePropagation();var L,z=!0;if(l.mostRecentlyFocusedNode)if(Vo(l.mostRecentlyFocusedNode)>0){var C=c(l.mostRecentlyFocusedNode),A=l.containerGroups[C].tabbableNodes;if(A.length>0){var O=A.findIndex(function(K){return K===l.mostRecentlyFocusedNode});O>=0&&(r.isKeyForward(l.recentNavEvent)?O+1<A.length&&(L=A[O+1],z=!1):O-1>=0&&(L=A[O-1],z=!1))}}else l.containerGroups.some(function(K){return K.tabbableNodes.some(function(se){return Vo(se)>0})})||(z=!1);else z=!1;z&&(L=y({target:l.mostRecentlyFocusedNode,isBackward:r.isKeyBackward(l.recentNavEvent)})),h(L||l.mostRecentlyFocusedNode||m())}l.recentNavEvent=void 0},b=function(E){var D=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;l.recentNavEvent=E;var j=y({event:E,isBackward:D});j&&(Zi(E)&&E.preventDefault(),h(j))},g=function(E){(r.isKeyForward(E)||r.isKeyBackward(E))&&b(E,r.isKeyBackward(E))},I=function(E){t8(E)&&Vi(r.escapeDeactivates,E)!==!1&&(E.preventDefault(),s.deactivate())},T=function(E){var D=Tr(E);c(D,E)>=0||Vi(r.clickOutsideDeactivates,E)||Vi(r.allowOutsideClick,E)||(E.preventDefault(),E.stopImmediatePropagation())},$=function(){if(l.active)return ju.activateTrap(i,s),l.delayInitialFocusTimer=r.delayInitialFocus?Wu(function(){h(m())}):h(m()),n.addEventListener("focusin",_,!0),n.addEventListener("mousedown",w,{capture:!0,passive:!1}),n.addEventListener("touchstart",w,{capture:!0,passive:!1}),n.addEventListener("click",T,{capture:!0,passive:!1}),n.addEventListener("keydown",g,{capture:!0,passive:!1}),n.addEventListener("keydown",I),s},N=function(){if(l.active)return n.removeEventListener("focusin",_,!0),n.removeEventListener("mousedown",w,!0),n.removeEventListener("touchstart",w,!0),n.removeEventListener("click",T,!0),n.removeEventListener("keydown",g,!0),n.removeEventListener("keydown",I),s},B=function(E){var D=E.some(function(j){var L=Array.from(j.removedNodes);return L.some(function(z){return z===l.mostRecentlyFocusedNode})});D&&h(m())},P=typeof window<"u"&&"MutationObserver"in window?new MutationObserver(B):void 0,x=function(){P&&(P.disconnect(),l.active&&!l.paused&&l.containers.map(function(E){P.observe(E,{subtree:!0,childList:!0})}))};return s={get active(){return l.active},get paused(){return l.paused},activate:function(E){if(l.active)return this;var D=d(E,"onActivate"),j=d(E,"onPostActivate"),L=d(E,"checkCanFocusTrap");L||p(),l.active=!0,l.paused=!1,l.nodeFocusedBeforeActivation=f(n),D==null||D();var z=function(){L&&p(),$(),x(),j==null||j()};return L?(L(l.containers.concat()).then(z,z),this):(z(),this)},deactivate:function(E){if(!l.active)return this;var D=zu({onDeactivate:r.onDeactivate,onPostDeactivate:r.onPostDeactivate,checkCanReturnFocus:r.checkCanReturnFocus},E);clearTimeout(l.delayInitialFocusTimer),l.delayInitialFocusTimer=void 0,N(),l.active=!1,l.paused=!1,x(),ju.deactivateTrap(i,s);var j=d(D,"onDeactivate"),L=d(D,"onPostDeactivate"),z=d(D,"checkCanReturnFocus"),C=d(D,"returnFocus","returnFocusOnDeactivate");j==null||j();var A=function(){Wu(function(){C&&h(v(l.nodeFocusedBeforeActivation)),L==null||L()})};return C&&z?(z(v(l.nodeFocusedBeforeActivation)).then(A,A),this):(A(),this)},pause:function(E){return l.active?(l.manuallyPaused=!0,this._setPausedState(!0,E)):this},unpause:function(E){return l.active?(l.manuallyPaused=!1,i[i.length-1]!==this?this:this._setPausedState(!1,E)):this},updateContainerElements:function(E){var D=[].concat(E).filter(Boolean);return l.containers=D.map(function(j){return typeof j=="string"?n.querySelector(j):j}),l.active&&p(),x(),this}},Object.defineProperties(s,{_isManuallyPaused:{value:function(){return l.manuallyPaused}},_setPausedState:{value:function(E,D){if(l.paused===E)return this;if(l.paused=E,E){var j=d(D,"onPause"),L=d(D,"onPostPause");j==null||j(),N(),x(),L==null||L()}else{var z=d(D,"onUnpause"),C=d(D,"onPostUnpause");z==null||z(),p(),$(),x(),C==null||C()}return this}}}),s.updateContainerElements(a),s};const r8=["aria-labelledby"],l8={class:"media-preview-sheet__header"},s8=["id"],d8=["aria-label"],c8=["src","alt"],u8=["src"],m8={class:"media-preview-sheet__actions"},p8=["disabled","aria-label"],f8=["aria-label","aria-pressed"],h8=["disabled","aria-label"],v8=e.defineComponent({__name:"MediaPreviewSheet",props:{open:{type:Boolean,default:!1},media:{default:null},canGoPrevious:{type:Boolean,default:!1},canGoNext:{type:Boolean,default:!1},selected:{type:Boolean,default:!1},closeLabel:{default:"Close"},previousLabel:{default:"Previous"},nextLabel:{default:"Next"},selectLabel:{default:"Select"},deselectLabel:{default:"Deselect"}},emits:["close","previous","next","toggleSelect"],setup(o,{emit:a}){const t=o,n=a,i=e.useId(),r=e.ref(null),l=e.ref(null);let s=null,d=null;const c=e.computed(()=>{var P;return((P=t.media)==null?void 0:P.mime_type.startsWith("image/"))===!0}),u=/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/ig,m=/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i,p=e.computed(()=>t.media?t.media.preview_url??t.media.original_url:"");function f(P){const x=P.replace(/\.[^.]+$/,""),E=x.replace(u,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return E!==""?E:x||P}function h(P){var D,j;const x=(D=P.name)==null?void 0:D.trim(),M=P.file_name.replace(/\.[^.]+$/,"");if(x!==void 0&&x!==""&&x!==P.file_name&&x!==M&&!m.test(x))return x;const E=(j=P.alt_text)==null?void 0:j.trim();return E!==void 0&&E!==""?E:f(x||P.file_name)}const v=e.computed(()=>t.media?h(t.media):"media"),y=e.computed(()=>t.media?`Preview ${v.value}`:"Media preview"),w=e.computed(()=>t.media?`Close preview of ${v.value}`:"Close preview"),_=e.computed(()=>t.canGoPrevious?"Previous media":"No previous media"),b=e.computed(()=>t.canGoNext?"Next media":"No next media"),g=e.computed(()=>{const P=t.selected?t.deselectLabel:t.selectLabel;return t.media?t.selected?`${t.deselectLabel} ${v.value}`:`${t.selectLabel} ${v.value}`:P}),I=e.computed(()=>t.selected?t.deselectLabel:t.selectLabel),T=()=>{t.media&&n("toggleSelect",t.media)},$=P=>{if(P.key==="Escape"){P.preventDefault(),n("close");return}if(P.key==="ArrowLeft"&&t.canGoPrevious){P.preventDefault(),n("previous");return}P.key==="ArrowRight"&&t.canGoNext&&(P.preventDefault(),n("next"))},N=()=>{if(s){try{s.deactivate({returnFocus:!1})}catch{}s=null}},B=()=>{const P=d;d=null,P&&typeof P.focus=="function"&&e.nextTick(()=>{P.focus()})};return e.watch(()=>t.open&&t.media!==null,async P=>{var x;if(P){d=document.activeElement instanceof HTMLElement?document.activeElement:null,await e.nextTick();const M=r.value;if(M)try{s=i8(M,{initialFocus:()=>l.value??M,escapeDeactivates:!1,clickOutsideDeactivates:!1,returnFocusOnDeactivate:!1,allowOutsideClick:!0}),s.activate()}catch{(x=l.value)==null||x.focus()}}else N(),B()},{immediate:!0}),e.onBeforeUnmount(()=>{N()}),(P,x)=>(e.openBlock(),e.createBlock(e.Teleport,{to:"body"},[P.open&&P.media?(e.openBlock(),e.createElementBlock("section",{key:0,ref_key:"sheetRef",ref:r,class:"media-preview-sheet",role:"dialog","aria-modal":"true","aria-labelledby":e.unref(i),tabindex:"-1","data-testid":"media-preview-sheet",onKeydown:$},[e.createElementVNode("header",l8,[e.createElementVNode("strong",{id:e.unref(i),"data-testid":"media-preview-sheet-title"},e.toDisplayString(y.value),9,s8),e.createElementVNode("button",{ref_key:"closeButtonRef",ref:l,type:"button",class:"media-preview-sheet__close","aria-label":w.value,"data-testid":"btn-media-preview-close",onClick:x[0]||(x[0]=M=>n("close"))},e.toDisplayString(P.closeLabel),9,d8)]),c.value?(e.openBlock(),e.createElementBlock("img",{key:0,class:"media-preview-sheet__image",src:p.value,alt:P.media.alt_text||v.value},null,8,c8)):(e.openBlock(),e.createElementBlock("video",{key:1,class:"media-preview-sheet__video",src:p.value,controls:""},null,8,u8)),e.createElementVNode("div",m8,[e.createElementVNode("button",{type:"button",class:"media-preview-sheet__nav",disabled:!P.canGoPrevious,"aria-label":_.value,"data-testid":"btn-media-preview-previous",onClick:x[1]||(x[1]=M=>n("previous"))},e.toDisplayString(P.previousLabel),9,p8),e.createElementVNode("button",{type:"button",class:"media-preview-sheet__select","aria-label":g.value,"aria-pressed":P.selected,"data-testid":"btn-media-preview-select",onClick:T},e.toDisplayString(I.value),9,f8),e.createElementVNode("button",{type:"button",class:"media-preview-sheet__nav",disabled:!P.canGoNext,"aria-label":b.value,"data-testid":"btn-media-preview-next",onClick:x[2]||(x[2]=M=>n("next"))},e.toDisplayString(P.nextLabel),9,h8)])],40,r8)):e.createCommentVNode("",!0)]))}}),Wd=Ae(v8,[["__scopeId","data-v-fa05530d"]]),g8={key:0,class:"media-album-grid","data-testid":"media-source-sheet"},b8={class:"media-album-grid__items"},y8={class:"media-album-grid__card-name"},w8={class:"media-album-grid__card-name"},k8=["data-testid","onClick"],_8={class:"media-album-grid__card-name"},E8={key:0,class:"media-album-grid__card-meta"},S8={key:0,class:"media-album-grid__empty"},C8=e.defineComponent({__name:"MediaSourceSheet",props:{open:{type:Boolean,default:!1},currentView:{},albums:{},viewLibraryLabel:{default:"Library"},browseAlbumsLabel:{default:"Albums"},createAlbumLabel:{default:"Create album"},enableAlbumCreation:{type:Boolean,default:!1}},emits:["close","selectLibrary","selectAlbum","createAlbum"],setup(o,{emit:a}){const t=a;return(n,i)=>n.open?(e.openBlock(),e.createElementBlock("section",g8,[e.createElementVNode("div",b8,[n.enableAlbumCreation?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-album-grid__card media-album-grid__card--create","data-testid":"btn-media-source-create-album",onClick:i[0]||(i[0]=r=>t("createAlbum"))},[i[2]||(i[2]=e.createElementVNode("div",{class:"media-album-grid__card-icon"},[e.createElementVNode("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"},[e.createElementVNode("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.createElementVNode("line",{x1:"5",y1:"12",x2:"19",y2:"12"})])],-1)),e.createElementVNode("span",y8,e.toDisplayString(n.createAlbumLabel),1)])):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["media-album-grid__card",{"is-active":n.currentView.scope==="library"}]),"data-testid":"btn-media-source-library",onClick:i[1]||(i[1]=r=>t("selectLibrary"))},[i[3]||(i[3]=e.createStaticVNode('<div class="media-album-grid__card-icon" data-v-129f67b1><svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" data-v-129f67b1><rect x="3" y="3" width="7" height="7" data-v-129f67b1></rect><rect x="14" y="3" width="7" height="7" data-v-129f67b1></rect><rect x="14" y="14" width="7" height="7" data-v-129f67b1></rect><rect x="3" y="14" width="7" height="7" data-v-129f67b1></rect></svg></div>',1)),e.createElementVNode("span",w8,e.toDisplayString(n.viewLibraryLabel),1),i[4]||(i[4]=e.createElementVNode("span",{class:"media-album-grid__card-meta"},"All media",-1))],2),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.albums,r=>(e.openBlock(),e.createElementBlock("button",{key:r.id,type:"button",class:e.normalizeClass(["media-album-grid__card",{"is-active":n.currentView.scope==="album"&&n.currentView.albumId===r.id}]),"data-testid":`btn-media-source-album-${r.id}`,onClick:l=>t("selectAlbum",r)},[i[5]||(i[5]=e.createElementVNode("div",{class:"media-album-grid__card-icon"},[e.createElementVNode("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round"},[e.createElementVNode("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})])],-1)),e.createElementVNode("span",_8,e.toDisplayString(r.name),1),r.mediaCount!==void 0?(e.openBlock(),e.createElementBlock("span",E8,e.toDisplayString(r.mediaCount)+" item"+e.toDisplayString(r.mediaCount===1?"":"s"),1)):e.createCommentVNode("",!0)],10,k8))),128))]),n.albums.length===0?(e.openBlock(),e.createElementBlock("p",S8," No albums yet. ")):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)}}),Vf=Ae(C8,[["__scopeId","data-v-129f67b1"]]),x8={key:0,class:"media-upload-sheet","data-testid":"media-upload-sheet"},N8={class:"media-upload-sheet__dropzone-text"},V8={key:0,class:"media-upload-sheet__dropzone-helper","data-testid":"text-media-upload-sheet-helper"},T8={class:"media-upload-sheet__sr-only"},B8=["accept","aria-label"],M8=["aria-label"],I8={class:"media-upload-sheet__queue-row"},$8={key:0,class:"media-upload-sheet__preview"},F8=["src","alt","data-testid"],D8={class:"media-upload-sheet__queue-body"},A8={class:"media-upload-sheet__queue-info"},R8={class:"media-upload-sheet__queue-status"},L8=["aria-valuenow","aria-label","data-testid"],P8=["aria-label"],U8=e.defineComponent({__name:"MediaUploadSheet",props:{open:{type:Boolean,default:!1},queue:{},accept:{default:""},uploadLabel:{default:"Upload"},dropzoneLabel:{default:"Drop files here or browse"},dropzoneHelperText:{default:""},fileInputLabel:{default:"Choose media files"},closeButtonAriaLabel:{default:"Close upload panel"},closeButtonLabel:{default:"Done"},progressAriaLabel:{}},emits:["close","filesSelected"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=p=>{var h;return t.progressAriaLabel!==void 0?t.progressAriaLabel(p):`Uploading ${((h=p.file)==null?void 0:h.name)??"file"}`},l=p=>{const f=Number.isFinite(p.progress)?p.progress:0;return f<0?0:f>100?100:Math.round(f)},s=e.computed(()=>t.queue.length===0?"":`${t.queue.length} upload${t.queue.length===1?"":"s"} in progress`),d=p=>{const f=p.target;!(f instanceof HTMLInputElement)||f.files===null||(n("filesSelected",Array.from(f.files)),f.value="")},c=p=>{p.preventDefault(),i.value=!0},u=()=>{i.value=!1},m=p=>{var f;p.preventDefault(),i.value=!1,(f=p.dataTransfer)!=null&&f.files&&p.dataTransfer.files.length>0&&n("filesSelected",Array.from(p.dataTransfer.files))};return(p,f)=>p.open?(e.openBlock(),e.createElementBlock("section",x8,[e.createElementVNode("label",{class:e.normalizeClass(["media-upload-sheet__dropzone",{"is-drag-over":i.value}]),onDragover:c,onDragleave:u,onDrop:m},[f[1]||(f[1]=e.createStaticVNode('<div class="media-upload-sheet__dropzone-icon" data-v-df614629><svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" data-v-df614629><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" data-v-df614629></path><polyline points="17 8 12 3 7 8" data-v-df614629></polyline><line x1="12" y1="3" x2="12" y2="15" data-v-df614629></line></svg></div>',1)),e.createElementVNode("span",N8,e.toDisplayString(p.dropzoneLabel),1),p.dropzoneHelperText?(e.openBlock(),e.createElementBlock("span",V8,e.toDisplayString(p.dropzoneHelperText),1)):e.createCommentVNode("",!0),e.createElementVNode("span",T8,e.toDisplayString(p.fileInputLabel),1),e.createElementVNode("input",{type:"file",accept:p.accept,multiple:"",class:"media-upload-sheet__file-input","data-testid":"input-media-upload-sheet","aria-label":p.fileInputLabel,onChange:d},null,40,B8)],34),p.queue.length>0?(e.openBlock(),e.createElementBlock("ul",{key:0,class:"media-upload-sheet__queue","aria-live":"polite","aria-label":s.value,"data-testid":"list-media-upload-sheet-queue"},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(p.queue,h=>(e.openBlock(),e.createElementBlock("li",{key:h.id,class:"media-upload-sheet__queue-item"},[e.createElementVNode("div",I8,[h.previewUrl?(e.openBlock(),e.createElementBlock("div",$8,[e.createElementVNode("img",{src:h.previewUrl,alt:`Preview of ${h.file.name}`,"data-testid":`img-media-upload-sheet-preview-${h.id}`},null,8,F8)])):e.createCommentVNode("",!0),e.createElementVNode("div",D8,[e.createElementVNode("div",A8,[e.createElementVNode("strong",null,e.toDisplayString(h.file.name),1),e.createElementVNode("span",R8,e.toDisplayString(h.status),1)]),e.createElementVNode("div",{class:"media-upload-sheet__progress-bar",role:"progressbar","aria-valuemin":"0","aria-valuemax":"100","aria-valuenow":l(h),"aria-label":r(h),"data-testid":`progress-media-upload-sheet-${h.id}`},[e.createElementVNode("div",{class:"media-upload-sheet__progress-fill",style:e.normalizeStyle({width:`${l(h)}%`})},null,4)],8,L8)])])]))),128))],8,M8)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",class:"media-upload-sheet__close-btn","aria-label":p.closeButtonAriaLabel,"data-testid":"btn-close-upload-sheet",onClick:f[0]||(f[0]=h=>n("close"))},e.toDisplayString(p.closeButtonLabel),9,P8)])):e.createCommentVNode("",!0)}}),Tf=Ae(U8,[["__scopeId","data-v-df614629"]]),O8=["aria-label","aria-pressed","data-testid"],z8=["src","alt"],j8={key:1,class:"media-thumbnail-cell__video"},W8={class:"media-thumbnail-cell__video-name"},H8={key:2,class:"media-thumbnail-cell__selected-badge"},Z8={key:3,class:"media-thumbnail-cell__status-badge"},G8=["aria-label"],X8=e.defineComponent({__name:"MediaThumbnailCell",props:{media:{},selected:{type:Boolean,default:!1},status:{},testId:{default:"media-library-thumbnail"}},emits:["toggle","preview"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>t.media.thumbnail_url??t.media.preview_url??t.media.original_url),r=e.computed(()=>t.media.mime_type.startsWith("image/")),l=e.computed(()=>{switch(t.status){case"missing":return"Unavailable";case"forbidden":return"Restricted";case"uploading":return"Uploading";case"failed":return"Failed";case"file_lost":return"Needs file";default:return null}}),s=e.computed(()=>{const u=t.media.file_name;return t.selected?`Deselect ${u}`:`Select ${u}`}),d=()=>{n("toggle",t.media)},c=()=>{n("preview",t.media)};return(u,m)=>(e.openBlock(),e.createElementBlock("article",{class:e.normalizeClass(["media-thumbnail-cell",{"is-selected":u.selected,"has-status":l.value!==null}])},[e.createElementVNode("button",{type:"button",class:"media-thumbnail-cell__button","aria-label":s.value,"aria-pressed":u.selected?"true":"false","data-testid":u.testId,onClick:d},[r.value?(e.openBlock(),e.createElementBlock("img",{key:0,class:"media-thumbnail-cell__image",src:i.value,alt:u.media.file_name},null,8,z8)):(e.openBlock(),e.createElementBlock("div",j8,[m[0]||(m[0]=e.createElementVNode("span",{class:"media-thumbnail-cell__video-label"},"Video",-1)),e.createElementVNode("span",W8,e.toDisplayString(u.media.file_name),1)])),u.selected?(e.openBlock(),e.createElementBlock("span",H8," Selected ")):e.createCommentVNode("",!0),l.value!==null?(e.openBlock(),e.createElementBlock("span",Z8,e.toDisplayString(l.value),1)):e.createCommentVNode("",!0)],8,O8),e.createElementVNode("button",{type:"button",class:"media-thumbnail-cell__preview-button","aria-label":`Preview ${u.media.file_name}`,onClick:c}," Preview ",8,G8)],2))}}),Bf=Ae(X8,[["__scopeId","data-v-edd4f0ad"]]),K8={class:"virtual-media-grid"},q8={key:0,class:"virtual-media-grid__state","data-testid":"media-grid-loading"},J8={key:1,class:"virtual-media-grid__state","data-testid":"media-grid-empty"},Y8={key:2,class:"virtual-media-grid__items"},Q8=["disabled"],eD=e.defineComponent({__name:"VirtualMediaGrid",props:{items:{},selectedItems:{},loading:{type:Boolean,default:!1},loadingMore:{type:Boolean,default:!1},hasMore:{type:Boolean,default:!1},emptyMessage:{default:"No media found."},testIdPrefix:{default:"media-grid-item"},loadingMessage:{default:"Loading media..."},loadMoreLabel:{default:"Load more"},loadingMoreLabel:{default:"Loading…"}},emits:["toggle","preview","loadMore"],setup(o,{emit:a}){const t=o,n=a;function i(r){return t.selectedItems.find(l=>l.id===r)}return(r,l)=>(e.openBlock(),e.createElementBlock("div",K8,[r.loading&&r.items.length===0?(e.openBlock(),e.createElementBlock("div",q8,e.toDisplayString(r.loadingMessage),1)):r.items.length===0?(e.openBlock(),e.createElementBlock("div",J8,e.toDisplayString(r.emptyMessage),1)):(e.openBlock(),e.createElementBlock("div",Y8,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.items,s=>{var d,c;return e.openBlock(),e.createBlock(Bf,{key:s.uuid,media:s,selected:((d=i(s.uuid))==null?void 0:d.status)==="ready",status:(c=i(s.uuid))==null?void 0:c.status,"test-id":`${r.testIdPrefix}-${s.uuid}`,onToggle:l[0]||(l[0]=u=>n("toggle",u)),onPreview:l[1]||(l[1]=u=>n("preview",u))},null,8,["media","selected","status","test-id"])}),128))])),r.hasMore?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button",class:"virtual-media-grid__load-more",disabled:r.loadingMore,"data-testid":"btn-media-grid-load-more",onClick:l[2]||(l[2]=s=>n("loadMore"))},e.toDisplayString(r.loadingMore?r.loadingMoreLabel:r.loadMoreLabel),9,Q8)):e.createCommentVNode("",!0)]))}}),Mf=Ae(eD,[["__scopeId","data-v-34667f65"]]);function ul(o){if(o===0)return"0 Bytes";const a=1024,t=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(o)/Math.log(a));return parseFloat((o/Math.pow(a,n)).toFixed(2))+" "+t[n]}function If(o){var t;const a=o.split(".");return a.length>1?`.${(t=a.pop())==null?void 0:t.toLowerCase()}`:""}function Hd(o){return o.type.startsWith("image/")}async function $f(o){return Hd(o)?new Promise(a=>{const t=new Image,n=URL.createObjectURL(o);t.onload=()=>{URL.revokeObjectURL(n),a({width:t.naturalWidth,height:t.naturalHeight})},t.onerror=()=>{URL.revokeObjectURL(n),a(null)},t.src=n}):null}async function Ff(o,a){const t=[];if(a.maxFileSize&&o.size>a.maxFileSize&&t.push({field:"size",message:`File exceeds maximum size of ${ul(a.maxFileSize)}`,code:"MAX_FILE_SIZE"}),a.minFileSize&&o.size<a.minFileSize&&t.push({field:"size",message:`File is smaller than minimum size of ${ul(a.minFileSize)}`,code:"MIN_FILE_SIZE"}),a.acceptedMimeTypes&&a.acceptedMimeTypes.length>0&&(a.acceptedMimeTypes.some(i=>i.endsWith("/*")?o.type.startsWith(i.slice(0,-1)):o.type===i)||t.push({field:"type",message:`File type "${o.type}" is not allowed`,code:"INVALID_MIME_TYPE"})),a.acceptedExtensions&&a.acceptedExtensions.length>0){const n=If(o.name);a.acceptedExtensions.some(r=>r.toLowerCase()===n.toLowerCase())||t.push({field:"extension",message:`File extension "${n}" is not allowed`,code:"INVALID_EXTENSION"})}if(Hd(o)&&(a.maxDimensions||a.minDimensions)){const n=await $f(o);n&&(a.maxDimensions&&(n.width>a.maxDimensions.width&&t.push({field:"dimensions",message:`Image width (${n.width}px) exceeds maximum (${a.maxDimensions.width}px)`,code:"MAX_WIDTH"}),n.height>a.maxDimensions.height&&t.push({field:"dimensions",message:`Image height (${n.height}px) exceeds maximum (${a.maxDimensions.height}px)`,code:"MAX_HEIGHT"})),a.minDimensions&&(n.width<a.minDimensions.width&&t.push({field:"dimensions",message:`Image width (${n.width}px) is smaller than minimum (${a.minDimensions.width}px)`,code:"MIN_WIDTH"}),n.height<a.minDimensions.height&&t.push({field:"dimensions",message:`Image height (${n.height}px) is smaller than minimum (${a.minDimensions.height}px)`,code:"MIN_HEIGHT"})))}if(a.customValidator){const n=await a.customValidator(o);t.push(...n)}return{valid:t.length===0,errors:t}}function Zd(o={}){const a=e.ref(o.rules||{});function t(d){a.value=d}async function n(d){return Ff(d,a.value)}async function i(d){const c=new Map;return await Promise.all(d.map(async u=>{const m=await n(u);c.set(u,m)})),c}function r(d,c){return a.value.maxItems?c+d<=a.value.maxItems:!0}const l=e.computed(()=>{const d=[];return a.value.acceptedMimeTypes&&d.push(...a.value.acceptedMimeTypes),a.value.acceptedExtensions&&d.push(...a.value.acceptedExtensions),d.join(",")});function s(d){return!a.value.acceptedMimeTypes||a.value.acceptedMimeTypes.length===0?!0:a.value.acceptedMimeTypes.some(c=>c.endsWith("/*")?d.startsWith(c.slice(0,-1)):d===c)}return{rules:a,setRules:t,validateFile:n,validateFiles:i,canAddFiles:r,acceptString:l,isMimeTypeAllowed:s}}function tD(){return`upload-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function aD(o){if(o.type.startsWith("image/"))return URL.createObjectURL(o)}function Gd(o){const{adapter:a,maxConcurrent:t=3,rules:n,collection:i,onUploadStart:r,onUploadProgress:l,onUploadComplete:s,onUploadError:d,onQueueComplete:c,postUpload:u}=o,m=e.ref(new Map),p=e.ref(new Set),f=n?{rules:n}:{},{validateFile:h}=Zd(f);async function v(){if(p.value.size>=t)return;const M=Array.from(m.value.entries()).find(([j,L])=>L.status==="pending"&&!p.value.has(j));if(!M){Array.from(m.value.values()).every(L=>L.status==="completed"||L.status==="error")&&m.value.size>0&&(c==null||c());return}const[E,D]=M;await y(E,D)}async function y(M,E){p.value.add(M),E.status="uploading",E.abortController=new AbortController,m.value.set(M,{...E}),r==null||r(E);try{const D={onProgress:L=>{E.progress=L,m.value.set(M,{...E}),l==null||l(E)},signal:E.abortController.signal};i&&(D.collection=i);const j=await a.upload(E.file,D);u&&(E.status="attaching",m.value.set(M,{...E}),l==null||l(E),await u(E,j.media,a)),E.status="completed",E.progress=100,E.media=j.media,m.value.set(M,{...E}),s==null||s(E,j.media)}catch(D){D.name==="AbortError"?m.value.delete(M):(E.status="error",E.error=D.message,m.value.set(M,{...E}),d==null||d(E,D))}finally{p.value.delete(M),delete E.abortController,v()}}async function w(M){var j;const E=Array.from(M),D=[];for(const L of E){const z=await h(L),C=tD(),A=aD(L),O={id:C,file:L,progress:0,status:z.valid?"pending":"error"};!z.valid&&((j=z.errors[0])!=null&&j.message)&&(O.error=z.errors[0].message),A&&(O.previewUrl=A),m.value.set(C,O);const K={media:null,clientId:C,name:L.name,order:0,upload:O,errors:z.errors};D.push(K)}for(let L=0;L<t;L++)v();return D}function _(M){const E=m.value.get(M);E&&(E.abortController&&E.abortController.abort(),E.previewUrl&&URL.revokeObjectURL(E.previewUrl),m.value.delete(M),p.value.delete(M),v())}async function b(M){const E=m.value.get(M);!E||E.status!=="error"||(E.status="pending",E.progress=0,delete E.error,m.value.set(M,{...E}),v())}function g(){for(const[M,E]of m.value.entries())(E.status==="completed"||E.status==="error")&&(E.previewUrl&&URL.revokeObjectURL(E.previewUrl),m.value.delete(M))}function I(){for(const M of m.value.values())M.abortController&&M.abortController.abort(),M.previewUrl&&URL.revokeObjectURL(M.previewUrl);m.value.clear(),p.value.clear()}function T(M){return m.value.get(M)}const $=e.computed(()=>p.value.size>0),N=e.computed(()=>p.value.size),B=e.computed(()=>Array.from(m.value.values()).filter(M=>M.status==="pending").length),P=e.computed(()=>m.value.size===0?!0:Array.from(m.value.values()).every(M=>M.status==="completed"||M.status==="error")),x=e.computed(()=>Array.from(m.value.values()));return{uploads:m,isUploading:$,activeCount:N,pendingCount:B,isComplete:P,addFiles:w,cancelUpload:_,retryUpload:b,clearCompleted:g,clearAll:I,getUpload:T,uploadsArray:x}}const nD=["missing_alt","has_alt","missing_caption","has_caption","has_tags","decorative"];function Po(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function oD(o){return typeof o=="string"&&nD.includes(o)}function tr(o){return typeof o=="string"?o:null}function Ti(o){return typeof o=="number"?o:null}function iD(o){return typeof o=="boolean"?o:null}function Df(o){return Po(o)&&typeof o.uuid=="string"&&typeof o.file_name=="string"&&typeof o.mime_type=="string"&&(typeof o.original_url=="string"||o.original_url===null)&&typeof o.size=="number"&&typeof o.disk=="string"&&typeof o.created_at=="string"&&typeof o.updated_at=="string"}function rD(o){return!Po(o)||typeof o.id!="string"||typeof o.status!="string"?null:o.status==="ready"?Df(o.media)?{id:o.id,status:"ready",media:o.media}:null:o.status==="missing"||o.status==="forbidden"?{id:o.id,status:o.status}:null}function lD(o){return Po(o)?{next_cursor:tr(o.next_cursor),previous_cursor:tr(o.previous_cursor),has_more:iD(o.has_more)??!1,per_page:Ti(o.per_page),count:Ti(o.count),total:Ti(o.total),current_page:Ti(o.current_page),last_page:Ti(o.last_page)}:null}function Hu(o){const a=Po(o)?o:{},t=Array.isArray(a.data)?a.data.filter(Df):[],n=Po(a.meta)?a.meta:{},i=lD(n.pagination),r=(i==null?void 0:i.next_cursor)??tr(n.next_cursor)??tr(n.cursor),l=(i==null?void 0:i.has_more)??n.has_more===!0,s=Array.isArray(a.hydrated)?a.hydrated.map(rD).filter(c=>c!==null):[],d={cursor:r,has_more:l};return i!==null&&(d.pagination=i),{data:t,meta:d,hydrated:s}}function Zu(o,a,t,n,i,r){const l={view:o.scope==="album"?{scope:"album",album_id:o.albumId}:{scope:o.scope},per_page:t,sort:a.sort??"newest"};return a.query&&a.query.trim()!==""&&(l.query=a.query.trim()),a.kinds&&a.kinds.length>0&&(l.kinds=a.kinds),a.created_after&&a.created_after.trim()!==""&&(l.created_after=a.created_after.trim()),a.created_before&&a.created_before.trim()!==""&&(l.created_before=a.created_before.trim()),(a.usage_status==="used"||a.usage_status==="not_used")&&(l.usage_status=a.usage_status),oD(a.metadata_status)&&(l.metadata_status=a.metadata_status),(a.unfiled_only===!0||o.scope==="unfiled")&&(l.unfiled_only=1),a.selected_uuids&&a.selected_uuids.length>0&&(l.selected_uuids=[...a.selected_uuids]),r!=null?(l.page=r,l.include_total=1):n!==null&&(l.cursor=n),i&&i.length>0&&(l.hydrate_ids=i),l}function Gu(o){const a=new Set,t=[];for(const n of o)a.has(n.uuid)||(a.add(n.uuid),t.push(n));return t}function sD(o){var t;if(!(o instanceof Error))return null;const a=(t=o.response)==null?void 0:t.status;return typeof a=="number"?a:null}function dD(o){var a;return o instanceof Error?((a=o.response)==null?void 0:a.data)??null:null}function cD(o){if(!Po(o))return[];const a=[];for(const t of Object.values(o)){if(typeof t=="string"&&t.trim()!==""){a.push(t.trim());continue}if(Array.isArray(t))for(const n of t){if(typeof n!="string")continue;const i=n.trim();i!==""&&a.push(i)}}return Array.from(new Set(a))}function uD(o){var r;const a=dD(o),t=Po(a)?a:null,n=((r=tr(t==null?void 0:t.message))==null?void 0:r.trim())??null,i=cD(t==null?void 0:t.errors);return n!==null&&i.length>0?n==="Validation failed"?i.join(" "):i.every(s=>n.includes(s))?n:`${n} ${i.join(" ")}`:n!==null?n:i.length>0?i.join(" "):o instanceof Error?o.message:"Failed to load media."}function Xu(o,a){const t=uD(a),n=sD(a);return{code:n===403?"permission_denied":o,message:t,retriable:n!==403,cause:a}}function Xd(o){const a=()=>{const T=o.perPage!==void 0?e.toValue(o.perPage):40;return T>0?T:40},t=()=>{const T=o.page!==void 0?e.toValue(o.page):null;return T==null?null:T>0?T:1},n=e.ref([]),i=e.ref([]),r=e.ref(null),l=e.ref(!1),s=e.ref(!1),d=e.ref(!1),c=e.ref(!1),u=e.ref(null),m=e.ref(null),p=e.ref(null),f=e.ref(null);let h=null,v=0;const y=async(T,$)=>{v+=1;const N=v;h==null||h.abort();const B=new AbortController;h=B,T?d.value=!0:s.value=!0,u.value=null,c.value=!1;const P=$??t(),x=P!==null;try{const M=await o.httpClient.get("/v1/media/library",{params:Zu(o.view.value,o.filters.value,a(),x?null:T?r.value:null,void 0,P),signal:B.signal});if(N!==v)return;const E=Hu(M);n.value=T&&!x?Gu([...n.value,...E.data]):E.data,i.value=E.hydrated,r.value=E.meta.cursor,l.value=E.meta.has_more;const D=E.meta.pagination;m.value=(D==null?void 0:D.total)??null,p.value=(D==null?void 0:D.current_page)??(x&&P!==null?P:null);const j=(D==null?void 0:D.per_page)??a();f.value=(D==null?void 0:D.last_page)??(m.value!==null&&j>0?Math.max(1,Math.ceil(m.value/j)):null)}catch(M){if(B.signal.aborted||N!==v)return;const E=Xu(T?"load_more_failed":"query_failed",M);u.value=E,c.value=E.code==="permission_denied",T||(n.value=[],r.value=null,l.value=!1)}finally{N===v&&(s.value=!1,d.value=!1)}},w=async T=>{if(T.length===0)return i.value=[],[];try{const $=await o.httpClient.get("/v1/media/library",{params:Zu(o.view.value,o.filters.value,1,null,T)}),N=Hu($);return i.value=N.hydrated,N.hydrated}catch($){return u.value=Xu("hydration_failed",$),[]}},_=T=>{n.value=Gu([T,...n.value])},b=async()=>{!l.value||d.value||t()===null&&await y(!0)};return{items:n,hydrated:i,cursor:r,hasMore:l,loading:s,loadingMore:d,permissionDenied:c,error:u,total:m,currentPage:p,totalPages:f,loadInitial:async()=>{r.value=null,await y(!1)},loadMore:b,loadAll:async T=>{const $=(T==null?void 0:T.maxItems)??5e3;if(!(s.value||d.value))for(;l.value&&n.value.length<$;){const N=n.value.length;if(await b(),u.value!==null||n.value.length===N)return}},goToPage:async T=>{!Number.isFinite(T)||T<1||s.value||d.value||await y(!1,T)},refresh:async()=>{r.value=null,await y(!1)},hydrateSelection:w,prepend:_}}const mD="mediables.media-library.";function pD(o){return!o||o.key.trim()===""?null:`${mD}${o.key}`}function ys(){return typeof window>"u"||typeof window.sessionStorage>"u"?null:window.sessionStorage}function fD(o,a){const t=Date.parse(o);return Number.isFinite(t)?Date.now()-t>a*60*1e3:!0}function Af(o){const a=pD(o),t=(o==null?void 0:o.ttlMinutes)??30,n=`${(o==null?void 0:o.key)??"media-library"}:${Date.now()}`;return{restore:()=>{if(a===null)return null;const s=ys();if(s===null)return null;const d=s.getItem(a);if(d===null)return null;let c;try{c=JSON.parse(d)}catch{return s.removeItem(a),null}if(typeof c!="object"||c===null||Array.isArray(c))return s.removeItem(a),null;const u=c;if(u.version!==1||typeof u.savedAt!="string"||fD(u.savedAt,t))return s.removeItem(a),null;const m={selectedIds:Array.isArray(u.selectedIds)?u.selectedIds.filter(p=>typeof p=="string"&&p.trim()!==""):[]};return((o==null?void 0:o.restoreView)??!0)&&u.view&&(m.view=u.view),u.filters&&(m.filters=u.filters),m},save:s=>{if(a===null)return;const d=ys();if(d===null)return;const c={version:1,savedAt:new Date().toISOString(),selectedIds:[...s.selectedIds]};((o==null?void 0:o.restoreView)??!0)&&s.view&&(c.view=s.view),s.filters&&(c.filters=s.filters),d.setItem(a,JSON.stringify(c))},clear:()=>{if(a===null)return;const s=ys();s==null||s.removeItem(a)},sessionId:n}}function Rf(o){const a=e.ref(o);return{state:a,transition:n=>{a.value=n}}}function Lf(o){return{emitMetric:(t,n)=>{const i={name:t,timestamp:new Date().toISOString()};n!==void 0&&(i.payload=n),o==null||o(i)}}}function ti(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function hD(o){const a=ti(o)?o:{};return(Array.isArray(a.data)?a.data:ti(a.data)&&Array.isArray(a.data.data)?a.data.data:Array.isArray(o)?o:[]).map(n=>{if(!ti(n)||typeof n.id!="string"||typeof n.name!="string")return null;const i={id:n.id,name:n.name};return typeof n.description=="string"&&n.description.trim()!==""&&(i.description=n.description),typeof n.media_count=="number"&&(i.mediaCount=n.media_count),i}).filter(n=>n!==null)}function vD(o){const a=ti(o)?o:{},t=ti(a.data)?a.data:ti(o)?o:null;if(t===null||typeof t.id!="string"||typeof t.name!="string")return null;const n={id:t.id,name:t.name};return typeof t.description=="string"&&t.description.trim()!==""&&(n.description=t.description),n}function gD(o){return o==="ready"||o==="uploading"||o==="failed"}function ko(o,a="ready"){return{id:o.uuid,media:o,status:a,countsTowardMax:gD(a)}}function bD(o,a){return o.scope==="library"?!0:o.scope!=="album"?!1:a.type==="album"&&a.albumId===o.albumId}function yD(o,a){return o.scope==="library"?a.type==="library"||a.type==="album":o.scope!=="album"?!1:a.type==="album"&&a.albumId===o.albumId}function ws(o){return{code:"configuration_error",message:o,retriable:!1}}const Pf="/v1/albums";function wD(o){var a;return((a=o.deps.albumEndpoints)==null?void 0:a.list)??Pf}function kD(o){var a,t;return((a=o.deps.albumEndpoints)==null?void 0:a.create)??((t=o.deps.albumEndpoints)==null?void 0:t.list)??Pf}function _D(o){return typeof o!="string"||o.length===0?"document":o.startsWith("image/")?"image":o.startsWith("video/")?"video":o.startsWith("audio/")?"audio":"document"}function ED(o,a){return a.length===0||o===null?!0:a.includes(_D(o.mime_type))}function Ku(o){return{...o??{},...(o==null?void 0:o.kinds)!==void 0?{kinds:[...o.kinds]}:{},...(o==null?void 0:o.selected_uuids)!==void 0?{selected_uuids:[...o.selected_uuids]}:{}}}function Uf(o){var Z,k;const a=o.selectionMode??"multiple",t=o.maxSelection,n=o.uploadBehavior??"adapter",i=e.ref(o.initialView??{scope:"library"}),r=((Z=o.initialFilters)==null?void 0:Z.kinds)??(o.allowedMediaKinds&&o.allowedMediaKinds.length>0?[...o.allowedMediaKinds]:void 0),l=e.ref({...Ku(o.initialFilters),sort:((k=o.initialFilters)==null?void 0:k.sort)??"newest",...r?{kinds:r}:{}}),s=o.allowedMediaKinds?[...o.allowedMediaKinds]:[],d=e.ref([]),c=e.ref([]),u=e.ref(null),m=e.ref(null),p=Af(o.sessionPolicy),{emitMetric:f}=Lf(o.telemetry),h=Rf("idle"),v=Xd({httpClient:o.deps.httpClient,view:i,filters:l}),y=e.computed(()=>c.value.map(F=>F.id)),w=e.computed(()=>{const F=u.value;return F===null?null:v.items.value[F]??null}),_=e.computed(()=>o.uploadTarget??{type:"library"}),b=Gd({adapter:o.deps.uploadAdapter??{name:"missing-upload-adapter",upload:async()=>{throw new Error("Upload adapter is not configured.")},attach:async()=>{},attachMany:async()=>{},detach:async()=>{},reorder:async()=>{},fetchModelMedia:async()=>[],getUrl:F=>F.original_url,getThumbnailUrl:F=>F.thumbnail_url??F.preview_url??F.original_url},postUpload:async(F,W,J)=>{const ce=_.value;ce.type!=="album"||!ce.albumId||await J.attach(W.uuid,{modelType:"album",modelId:ce.albumId})},onUploadComplete:(F,W)=>{const J=_.value;bD(i.value,J)&&v.prepend(W),o.autoSelectUploaded&&yD(i.value,J)&&P(W),f("upload-complete",{mediaId:W.uuid,targetType:J.type,targetAlbumId:J.albumId})},onUploadError:(F,W)=>{m.value={code:"upload_failed",message:W.message,retriable:!0,cause:W}}}),g=e.computed(()=>b.isUploading.value),I=()=>{p.save({selectedIds:[...y.value],view:i.value,filters:l.value})},T=async F=>{const W=await v.hydrateSelection(F);c.value=W.map(J=>J.status==="ready"&&J.media?ko(J.media):{id:J.id,media:null,status:J.status,countsTowardMax:!1})},$=e.computed(()=>c.value.filter(F=>F.countsTowardMax).length),N=()=>a==="single"||t===void 0?!0:$.value<t,B=F=>{if(c.value.findIndex(J=>J.id===F.uuid)>=0){a==="multiple"?c.value=c.value.filter(J=>J.id!==F.uuid):c.value=[ko(F)],I();return}if(!N()){m.value={code:"selection_invalid",message:t!==void 0?`You can only select up to ${t} items.`:"You cannot select more items.",retriable:!0};return}a==="single"?c.value=[ko(F)]:c.value=[...c.value,ko(F)],m.value=null,I()},P=F=>{const W=c.value.findIndex(J=>J.id===F.uuid);if(W>=0){c.value=c.value.map((J,ce)=>ce===W?ko(F):J),m.value=null,I();return}if(!N()){m.value={code:"selection_invalid",message:t!==void 0?`You can only select up to ${t} items.`:"You cannot select more items.",retriable:!0};return}a==="single"?c.value=[ko(F)]:c.value=[...c.value,ko(F)],m.value=null,I()},x=async()=>{var W;h.transition("restoring");const F=p.restore();if(F===null){h.transition("ready");return}F.view&&(i.value=F.view),F.filters&&(l.value={...Ku(F.filters),sort:F.filters.sort??"newest"}),await v.loadInitial(),(((W=o.sessionPolicy)==null?void 0:W.restoreSelection)??!0)&&await T(F.selectedIds),h.transition("ready")};e.watch(()=>v.error.value,F=>{F!==null&&(m.value=F,h.transition("error"))});const M=async()=>{m.value=null,h.transition("idle"),await x(),v.items.value.length===0&&!v.loading.value&&!v.permissionDenied.value&&await v.loadInitial();const F=o.defaultSelectedIds??[];c.value.length===0&&F.length>0&&await T(F),h.transition("ready")},E=async(F,W="user")=>{const J=i.value;i.value=F,W==="user"&&o.preserveSelectionOnViewChange===!1&&(c.value=[]),f("view-change",{from:J.scope,to:F.scope,reason:W}),await v.loadInitial(),I()},D=async()=>{const F=await o.deps.httpClient.get(wD(o));d.value=hD(F)},j=async(F,W)=>{try{const J={name:F,visibility:"private"};W&&W.trim()!==""&&(J.parent_id=W);const ce=await o.deps.httpClient.post(kD(o),J),Ue=vD(ce);return Ue===null?ws("Album creation response was invalid."):(d.value=[Ue,...d.value.filter(be=>be.id!==Ue.id)],await E({scope:"album",albumId:Ue.id,albumName:Ue.name},"inline-album-created"),Ue)}catch(J){const ce={code:"album_create_failed",message:J instanceof Error?J.message:"Album creation failed.",retriable:!0,cause:J};return m.value=ce,ce}},L=async F=>{if(!o.enableUpload){m.value=ws("Uploads are not enabled for this picker.");return}if(n!=="delegate"){if(!o.deps.uploadAdapter){m.value=ws("Uploads require a configured upload adapter.");return}await b.addFiles(F)}},z=()=>{var J;if(s.length>0&&c.value.find(Ue=>Ue.media!==null&&!ED(Ue.media,s))){const be={code:"selection_invalid",message:`Selected media is not allowed here. Choose one of: ${s.join(", ")}.`,retriable:!0};return m.value=be,be}const F=((J=o.validateSelection)==null?void 0:J.call(o,c.value))??null;if(F!==null){const ce={code:"selection_invalid",message:F,retriable:!0};return m.value=ce,ce}if(c.value.filter(ce=>ce.status==="ready"&&ce.media!==null).length===0){const ce={code:"selection_invalid",message:"Select at least one available media item.",retriable:!0};return m.value=ce,ce}return{orderedIds:y.value,items:[...c.value],view:i.value,filters:l.value,dirty:!0,sessionId:p.sessionId}},C=F=>{const W=v.items.value.findIndex(J=>J.uuid===F.uuid);u.value=W>=0?W:null},A=()=>{u.value=null},O=()=>{u.value===null||u.value<=0||(u.value-=1)},K=()=>{u.value===null||u.value>=v.items.value.length-1||(u.value+=1)},se=F=>{c.value=c.value.filter(W=>W.id!==F),I()},xe=async()=>{await v.refresh()},ue=async F=>{l.value={...l.value,...F&&F.trim()!==""?{query:F.trim()}:{}},(!F||F.trim()==="")&&delete l.value.query,await v.loadInitial(),I()},le=async()=>{await E({scope:"library"},"permission-unavailable")};return{view:i,filters:l,albums:d,selectedItems:c,orderedIds:y,queryItems:v.items,cursor:v.cursor,hasMore:v.hasMore,loading:v.loading,loadingMore:v.loadingMore,permissionDenied:v.permissionDenied,error:m,uploadQueue:b.uploadsArray,isUploading:g,previewIndex:u,previewItem:w,initialize:M,refresh:xe,loadMore:v.loadMore,setQuery:ue,setView:E,toggleSelection:B,removeSelected:se,confirmSelection:z,openPreview:C,closePreview:A,showPreviousPreview:O,showNextPreview:K,loadAlbums:D,createAlbum:j,addUploadFiles:L,goToLibrary:le,sessionId:p.sessionId}}const SD=["data-testid"],CD={class:"mlp-location-bar"},xD={class:"mlp-location-bar__left"},ND={class:"mlp-location-bar__label"},VD={class:"mlp-tabs","data-testid":"media-picker-tabs"},TD={key:0,class:"mlp-search-row"},BD=["placeholder"],MD={key:2,class:"mlp-overlay-panel"},ID={key:0,class:"mlp-error","data-testid":"media-picker-error"},$D={key:5,class:"mlp-bottom-bar"},FD={key:0,class:"mlp-bottom-bar__selection"},DD={class:"mlp-bottom-bar__count"},AD={class:"mlp-bottom-bar__thumbs"},RD=["src","alt"],LD={key:1,class:"mlp-bottom-bar__thumb-placeholder"},PD=["aria-label","onClick"],UD={class:"mlp-bottom-bar__actions"},OD=e.defineComponent({__name:"MediaLibraryPicker",props:{deps:{},mode:{default:"picker-multi"},capabilities:{default:()=>({})},itemFilter:{},modelValue:{default:()=>[]},defaultSelectedIds:{default:()=>[]},selectionMode:{default:"multiple"},maxSelection:{},preserveSelectionOnViewChange:{type:Boolean,default:!0},initialView:{default:()=>({scope:"library"})},initialFilters:{default:()=>({sort:"newest"})},enableUpload:{type:Boolean,default:!1},uploadBehavior:{default:"adapter"},enablePreview:{type:Boolean,default:!0},enableAlbumCreation:{type:Boolean,default:!1},allowedMediaKinds:{},accept:{},validateSelection:{},uploadTarget:{},autoSelectUploaded:{type:Boolean,default:!1},createAlbumDefaultVisibility:{default:"private"},sessionPolicy:{},labels:{default:()=>({})},showFooter:{type:Boolean,default:!0},testIdPrefix:{default:"media-picker"},telemetry:{}},emits:["update:modelValue","confirm","cancel","selection-change","select","view-change","error","metric","request-upload-files"],setup(o,{expose:a,emit:t}){const n=o,i=t,r=e.computed(()=>{var k,F,W,J,ce,Ue,be,_e,ye,Ne,Se,Re,Oe,it,rt,Pt,bt,Ct,mt,pt,Nt,Ce,Ve,Le,nt,Ge,Je,_t,ht,Wt,Pe,Ht,Zt,It,Ut,Gt,sa,ae,ge;return{title:((k=n.labels)==null?void 0:k.title)??"Media library",searchPlaceholder:((F=n.labels)==null?void 0:F.searchPlaceholder)??"Search your media",viewLibrary:((W=n.labels)==null?void 0:W.viewLibrary)??"Library",browseAlbums:((J=n.labels)==null?void 0:J.browseAlbums)??"Albums",createAlbum:((ce=n.labels)==null?void 0:ce.createAlbum)??"Create album",createAlbumNameLabel:((Ue=n.labels)==null?void 0:Ue.createAlbumNameLabel)??"Album name",emptyLibrary:((be=n.labels)==null?void 0:be.emptyLibrary)??"No media found in your library.",emptyAlbum:((_e=n.labels)==null?void 0:_e.emptyAlbum)??"No media found in this album.",networkError:((ye=n.labels)==null?void 0:ye.networkError)??"Unable to load media right now.",retry:((Ne=n.labels)==null?void 0:Ne.retry)??"Retry",selectedCount:((Se=n.labels)==null?void 0:Se.selectedCount)??(pe=>`${pe} selected`),confirmAction:((Re=n.labels)==null?void 0:Re.confirmAction)??"Attach selected",cancel:((Oe=n.labels)==null?void 0:Oe.cancel)??"Cancel",dismiss:((it=n.labels)==null?void 0:it.dismiss)??"Remove",uploadLabel:((rt=n.labels)==null?void 0:rt.uploadLabel)??"Upload",albumUnavailableTitle:((Pt=n.labels)==null?void 0:Pt.albumUnavailableTitle)??"Album unavailable",albumUnavailableBody:((bt=n.labels)==null?void 0:bt.albumUnavailableBody)??"You no longer have access to this album.",goToLibrary:((Ct=n.labels)==null?void 0:Ct.goToLibrary)??"Go to library",allMediaTab:((mt=n.labels)==null?void 0:mt.allMediaTab)??"All Media",loadingMedia:((pt=n.labels)==null?void 0:pt.loadingMedia)??"Loading media…",loadMore:((Nt=n.labels)==null?void 0:Nt.loadMore)??"Load more",loadingMore:((Ce=n.labels)==null?void 0:Ce.loadingMore)??"Loading…",uploadDropzone:((Ve=n.labels)==null?void 0:Ve.uploadDropzone)??"Drop files here or browse",uploadDropzoneHelper:((Le=n.labels)==null?void 0:Le.uploadDropzoneHelper)??"",uploadDone:((nt=n.labels)==null?void 0:nt.uploadDone)??"Done",uploadDoneAria:((Ge=n.labels)==null?void 0:Ge.uploadDoneAria)??"Close upload panel",uploadFileInputLabel:((Je=n.labels)==null?void 0:Je.uploadFileInputLabel)??"Choose media files",previewClose:((_t=n.labels)==null?void 0:_t.previewClose)??"Close preview",previewPrevious:((ht=n.labels)==null?void 0:ht.previewPrevious)??"Previous media",previewNext:((Wt=n.labels)==null?void 0:Wt.previewNext)??"Next media",previewSelect:((Pe=n.labels)==null?void 0:Pe.previewSelect)??"Select media",previewDeselect:((Ht=n.labels)==null?void 0:Ht.previewDeselect)??"Deselect media",selectAction:((Zt=n.labels)==null?void 0:Zt.selectAction)??"Select",allMedia:((It=n.labels)==null?void 0:It.allMedia)??((Ut=n.labels)==null?void 0:Ut.allMediaTab)??"All media",unfiled:((Gt=n.labels)==null?void 0:Gt.unfiled)??"Unfiled",pageTitle:((sa=n.labels)==null?void 0:sa.pageTitle)??((ae=n.labels)==null?void 0:ae.title)??"Media library",albumLabel:((ge=n.labels)==null?void 0:ge.albumLabel)??"Album"}}),l=e.computed(()=>n.mode),s=e.computed(()=>l.value==="picker-single"?"single":n.selectionMode),d=e.computed(()=>n.showFooter===!0&&l.value!=="picker-single"),c=e.computed(()=>n.enablePreview===!0&&l.value!=="picker-single"),u={deps:n.deps,selectionMode:s.value,initialView:n.initialView,initialFilters:n.initialFilters,...n.maxSelection!==void 0?{maxSelection:n.maxSelection}:{},...n.modelValue.length>0||n.defaultSelectedIds.length>0?{defaultSelectedIds:n.modelValue.length>0?n.modelValue:n.defaultSelectedIds}:{},...n.sessionPolicy?{sessionPolicy:n.sessionPolicy}:{},...n.enableUpload?{enableUpload:!0}:{},uploadBehavior:n.uploadBehavior,...n.uploadTarget?{uploadTarget:n.uploadTarget}:{},...n.autoSelectUploaded?{autoSelectUploaded:!0}:{},...n.validateSelection?{validateSelection:n.validateSelection}:{},...n.allowedMediaKinds&&n.allowedMediaKinds.length>0?{allowedMediaKinds:n.allowedMediaKinds}:{},preserveSelectionOnViewChange:n.preserveSelectionOnViewChange,telemetry:k=>{var F;(F=n.telemetry)==null||F.call(n,k),i("metric",k)}},m=Uf(u),p=e.ref(n.initialFilters.query??""),f=e.ref(n.enableUpload?"upload":"media"),h=e.ref(!1),v=JSON.stringify(n.modelValue.length>0?n.modelValue:n.defaultSelectedIds);let y=null;const w=e.computed(()=>JSON.stringify(m.orderedIds.value)!==v),_=e.computed(()=>m.view.value.scope==="album"?r.value.emptyAlbum:r.value.emptyLibrary),b=e.computed(()=>r.value.selectedCount(m.selectedItems.value.length));function g(k){return typeof k=="boolean"?{allowed:k}:typeof k=="string"?{allowed:!1,reason:k}:k}function I(k){return n.itemFilter?g(n.itemFilter(k)):{allowed:!0}}const T=e.computed(()=>n.itemFilter?m.queryItems.value.filter(k=>I(k).allowed):m.queryItems.value),$=e.computed(()=>m.view.value.scope==="album"?m.view.value.albumName??"Album":r.value.viewLibrary),N=e.computed(()=>m.view.value.scope==="album"),B=()=>{y!==null&&(window.clearTimeout(y),y=null)},P=()=>{i("update:modelValue",[...m.orderedIds.value]),i("selection-change",{orderedIds:[...m.orderedIds.value],items:[...m.selectedItems.value],dirty:w.value})},x=k=>{k!==null&&i("error",k)},M=k=>typeof k.code=="string",E=k=>typeof k=="object"&&k!==null&&"code"in k&&typeof k.code=="string",D=()=>{const k=m.confirmSelection();if(M(k)){x(k);return}i("confirm",{...k,dirty:w.value})},j=k=>{const F=I(k);if(!F.allowed){x({code:"selection_invalid",message:F.reason??"This media item is not available for this picker.",retriable:!0});return}m.toggleSelection(k),l.value==="picker-single"&&i("select",k)},L=(k="user")=>{i("cancel",{dirty:w.value,reason:k,sessionId:m.sessionId})},z=async()=>{f.value="albums",await m.loadAlbums()},C=async()=>{await m.goToLibrary(),f.value="albums",await m.loadAlbums()},A=k=>{m.setView({scope:"album",albumId:k.id,albumName:k.name}),f.value="media"},O=async(k,F)=>{const W=m.view.value,J=await m.createAlbum(k,F);if(E(J)){x(J);return}h.value=!1,f.value="media",i("view-change",{from:W,to:{scope:"album",albumId:J.id,albumName:J.name},reason:"inline-album-created",restoredFromSession:!1})},K=async k=>{if(n.uploadBehavior==="delegate"){i("request-upload-files",{files:[...k],view:m.view.value,filters:m.filters.value,sessionId:m.sessionId});return}await m.addUploadFiles(k)};function se(k){var F;return k?k.thumbnail_url??((F=k.conversion_urls)==null?void 0:F.thumb)??k.preview_url??k.original_url??k.url??null:null}function xe(k){return k!=null&&k.mime_type?k.mime_type.startsWith("image/"):!1}e.watch(()=>p.value,k=>{B(),y=window.setTimeout(()=>{m.setQuery(k)},250)}),e.watch(()=>m.selectedItems.value,()=>{P()},{deep:!0}),e.watch(()=>m.error.value,k=>{x(k)}),e.watch(()=>n.enableUpload,k=>{!k&&f.value==="upload"&&(f.value="media")}),e.onMounted(()=>{m.initialize()}),e.onBeforeUnmount(()=>{B()}),a({refresh:m.refresh});function ue(k){if(k==="albums"){z();return}if(k==="upload"&&!n.enableUpload){f.value="media";return}f.value=k}const le=e.computed(()=>({activeTab:f.value,setActiveTab:ue,enableUpload:n.enableUpload,labels:{uploadLabel:r.value.uploadLabel,allMediaTab:r.value.allMediaTab,browseAlbums:r.value.browseAlbums}})),Z=e.computed(()=>({query:p.value,setQuery:k=>{p.value=k},placeholder:r.value.searchPlaceholder}));return(k,F)=>(e.openBlock(),e.createElementBlock("section",{class:"media-library-picker","data-testid":k.testIdPrefix},[e.createElementVNode("header",CD,[e.createElementVNode("div",xD,[N.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"mlp-location-bar__back","aria-label":"Back to library","data-testid":"btn-media-picker-back",onClick:C},[...F[8]||(F[8]=[e.createElementVNode("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},[e.createElementVNode("polyline",{points:"15 18 9 12 15 6"})],-1)])])):e.createCommentVNode("",!0),e.createElementVNode("span",ND,e.toDisplayString($.value),1)])]),e.renderSlot(k.$slots,"tabs",e.normalizeProps(e.guardReactiveProps(le.value)),()=>[e.createElementVNode("nav",VD,[k.enableUpload?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:e.normalizeClass(["mlp-tabs__tab",{"is-active":f.value==="upload"}]),"data-testid":"tab-media-picker-upload",onClick:F[0]||(F[0]=W=>f.value="upload")},e.toDisplayString(r.value.uploadLabel),3)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["mlp-tabs__tab",{"is-active":f.value==="media"}]),"data-testid":"tab-media-picker-all",onClick:F[1]||(F[1]=W=>f.value="media")},e.toDisplayString(r.value.allMediaTab),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["mlp-tabs__tab",{"is-active":f.value==="albums"}]),"data-testid":"tab-media-picker-albums",onClick:z},e.toDisplayString(r.value.browseAlbums),3)])],!0),f.value==="media"||f.value==="albums"?(e.openBlock(),e.createElementBlock("div",TD,[e.renderSlot(k.$slots,"search",e.normalizeProps(e.guardReactiveProps(Z.value)),()=>[F[9]||(F[9]=e.createElementVNode("svg",{class:"mlp-search-row__icon",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"},[e.createElementVNode("circle",{cx:"11",cy:"11",r:"8"}),e.createElementVNode("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})],-1)),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":F[2]||(F[2]=W=>p.value=W),class:"mlp-search-row__input",type:"search",placeholder:r.value.searchPlaceholder,"data-testid":"input-media-picker-search"},null,8,BD),[[e.vModelText,p.value]])],!0)])):e.createCommentVNode("",!0),k.enableUpload&&f.value==="upload"?(e.openBlock(),e.createBlock(Tf,{key:1,open:!0,queue:e.unref(m).uploadQueue.value,accept:k.accept,"upload-label":r.value.uploadLabel,"dropzone-label":r.value.uploadDropzone,"dropzone-helper-text":r.value.uploadDropzoneHelper,"file-input-label":r.value.uploadFileInputLabel,"close-button-label":r.value.uploadDone,"close-button-aria-label":r.value.uploadDoneAria,onClose:F[3]||(F[3]=W=>f.value="media"),onFilesSelected:K},null,8,["queue","accept","upload-label","dropzone-label","dropzone-helper-text","file-input-label","close-button-label","close-button-aria-label"])):e.createCommentVNode("",!0),h.value?(e.openBlock(),e.createElementBlock("div",MD,[e.createVNode(jd,{open:h.value,"name-label":r.value.createAlbumNameLabel,albums:e.unref(m).albums.value,onCancel:F[4]||(F[4]=W=>h.value=!1),onCreate:O},null,8,["open","name-label","albums"])])):e.createCommentVNode("",!0),e.unref(m).permissionDenied.value&&e.unref(m).view.value.scope==="album"?(e.openBlock(),e.createBlock(kf,{key:3,title:r.value.albumUnavailableTitle,body:r.value.albumUnavailableBody,"action-label":r.value.goToLibrary,onGoToLibrary:e.unref(m).goToLibrary},null,8,["title","body","action-label","onGoToLibrary"])):e.createCommentVNode("",!0),!e.unref(m).permissionDenied.value||e.unref(m).view.value.scope!=="album"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:4},[e.unref(m).error.value?(e.openBlock(),e.createElementBlock("div",ID,[e.createElementVNode("p",null,e.toDisplayString(e.unref(m).error.value.message||r.value.networkError),1),e.createElementVNode("button",{type:"button",class:"mlp-error__retry",onClick:F[5]||(F[5]=(...W)=>e.unref(m).refresh&&e.unref(m).refresh(...W))},e.toDisplayString(r.value.retry),1)])):e.createCommentVNode("",!0),f.value==="media"?(e.openBlock(),e.createBlock(Mf,{key:1,items:T.value,"selected-items":e.unref(m).selectedItems.value,loading:e.unref(m).loading.value,"loading-more":e.unref(m).loadingMore.value,"has-more":e.unref(m).hasMore.value,"empty-message":_.value,"loading-message":r.value.loadingMedia,"load-more-label":r.value.loadMore,"loading-more-label":r.value.loadingMore,"test-id-prefix":`${k.testIdPrefix}-item`,onToggle:j,onPreview:e.unref(m).openPreview,onLoadMore:e.unref(m).loadMore},null,8,["items","selected-items","loading","loading-more","has-more","empty-message","loading-message","load-more-label","loading-more-label","test-id-prefix","onPreview","onLoadMore"])):f.value==="albums"?(e.openBlock(),e.createBlock(Vf,{key:2,open:!0,"current-view":e.unref(m).view.value,albums:e.unref(m).albums.value,"view-library-label":r.value.viewLibrary,"browse-albums-label":r.value.browseAlbums,"create-album-label":r.value.createAlbum,"enable-album-creation":k.enableAlbumCreation,onSelectLibrary:C,onSelectAlbum:A,onCreateAlbum:F[6]||(F[6]=W=>h.value=!0)},null,8,["current-view","albums","view-library-label","browse-albums-label","create-album-label","enable-album-creation"])):e.createCommentVNode("",!0)],64)):e.createCommentVNode("",!0),d.value?(e.openBlock(),e.createElementBlock("footer",$D,[e.unref(m).selectedItems.value.length>0?(e.openBlock(),e.createElementBlock("div",FD,[e.createElementVNode("span",DD,e.toDisplayString(b.value),1),e.createElementVNode("div",AD,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(m).selectedItems.value,W=>{var J,ce,Ue;return e.openBlock(),e.createElementBlock("div",{key:W.id,class:"mlp-bottom-bar__thumb-item"},[xe(W.media)&&se(W.media)?(e.openBlock(),e.createElementBlock("img",{key:0,src:se(W.media),alt:((J=W.media)==null?void 0:J.alt_text)??((ce=W.media)==null?void 0:ce.file_name)??"Selected",class:"mlp-bottom-bar__thumb-img"},null,8,RD)):(e.openBlock(),e.createElementBlock("div",LD,[...F[10]||(F[10]=[e.createElementVNode("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[e.createElementVNode("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.createElementVNode("polyline",{points:"14 2 14 8 20 8"})],-1)])])),e.createElementVNode("button",{type:"button",class:"mlp-bottom-bar__thumb-remove","aria-label":`${r.value.dismiss} ${((Ue=W.media)==null?void 0:Ue.file_name)??W.id}`,"data-testid":"btn-media-picker-remove-selected",onClick:be=>e.unref(m).removeSelected(W.id)},[...F[11]||(F[11]=[e.createElementVNode("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"3","stroke-linecap":"round"},[e.createElementVNode("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.createElementVNode("line",{x1:"6",y1:"6",x2:"18",y2:"18"})],-1)])],8,PD)])}),128))])])):e.createCommentVNode("",!0),e.createElementVNode("div",UD,[e.createElementVNode("button",{type:"button",class:"mlp-bottom-bar__cancel","data-testid":"btn-media-picker-cancel",onClick:F[7]||(F[7]=W=>L())},e.toDisplayString(r.value.cancel),1),e.createElementVNode("button",{type:"button",class:"mlp-bottom-bar__confirm","data-testid":"btn-media-picker-confirm",onClick:D},e.toDisplayString(r.value.confirmAction),1)])])):e.createCommentVNode("",!0),c.value?(e.openBlock(),e.createBlock(Wd,{key:6,open:e.unref(m).previewItem.value!==null,media:e.unref(m).previewItem.value,"can-go-previous":e.unref(m).previewIndex.value!==null&&e.unref(m).previewIndex.value>0,"can-go-next":e.unref(m).previewIndex.value!==null&&e.unref(m).previewIndex.value<e.unref(m).queryItems.value.length-1,selected:e.unref(m).previewItem.value!==null&&e.unref(m).orderedIds.value.includes(e.unref(m).previewItem.value.uuid),"close-label":r.value.previewClose,"previous-label":r.value.previewPrevious,"next-label":r.value.previewNext,"select-label":r.value.previewSelect,"deselect-label":r.value.previewDeselect,onClose:e.unref(m).closePreview,onPrevious:e.unref(m).showPreviousPreview,onNext:e.unref(m).showNextPreview,onToggleSelect:e.unref(m).toggleSelection},null,8,["open","media","can-go-previous","can-go-next","selected","close-label","previous-label","next-label","select-label","deselect-label","onClose","onPrevious","onNext","onToggleSelect"])):e.createCommentVNode("",!0)],8,SD))}}),Of=Ae(OD,[["__scopeId","data-v-307fef12"]]),zD={key:0,class:"media-library-picker-modal","data-testid":"media-library-picker-modal"},jD={class:"media-library-picker-modal__panel"},WD=e.defineComponent({__name:"MediaLibraryPickerModal",props:{deps:{},mode:{},capabilities:{},itemFilter:{},modelValue:{},defaultSelectedIds:{},selectionMode:{},maxSelection:{},preserveSelectionOnViewChange:{type:Boolean},initialView:{},initialFilters:{},enableUpload:{type:Boolean},uploadBehavior:{},enablePreview:{type:Boolean},enableAlbumCreation:{type:Boolean},allowedMediaKinds:{},accept:{},validateSelection:{},uploadTarget:{},autoSelectUploaded:{type:Boolean},createAlbumDefaultVisibility:{},sessionPolicy:{},labels:{},showFooter:{type:Boolean},testIdPrefix:{},telemetry:{},isOpen:{type:Boolean,default:!1},closeOnBackdrop:{type:Boolean,default:!0}},emits:["update:modelValue","confirm","cancel","close"],setup(o,{emit:a}){const t=o,n=a,i=()=>{t.closeOnBackdrop&&n("close")};return(r,l)=>r.isOpen?(e.openBlock(),e.createElementBlock("div",zD,[e.createElementVNode("button",{type:"button",class:"media-library-picker-modal__backdrop","aria-label":"Close media picker",onClick:i}),e.createElementVNode("div",jD,[e.createVNode(Of,e.mergeProps(t,{"onUpdate:modelValue":l[0]||(l[0]=s=>n("update:modelValue",s)),onConfirm:l[1]||(l[1]=s=>n("confirm",s)),onCancel:l[2]||(l[2]=s=>n("cancel",s))}),null,16)])])):e.createCommentVNode("",!0)}}),HD=Ae(WD,[["__scopeId","data-v-a92e8703"]]),ZD=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", ");function GD(o){return o.getAttribute("aria-hidden")==="true"||o.hasAttribute("disabled")?!1:o.tabIndex>=0}function jl(o){return Array.from(o.querySelectorAll(ZD)).filter(GD)}function fa(o){o instanceof HTMLElement&&typeof o.focus=="function"&&o.focus()}function Kd(o,a){if(o.key!=="Tab"||!(a instanceof HTMLElement))return;const t=jl(a);if(t.length===0){o.preventDefault(),fa(a);return}const n=t[0],i=t[t.length-1];if(o.shiftKey&&document.activeElement===n){o.preventDefault(),fa(i);return}!o.shiftKey&&document.activeElement===i&&(o.preventDefault(),fa(n))}function cd(o,a){if(!(a instanceof HTMLElement)||!["ArrowDown","ArrowUp","Home","End"].includes(o.key))return!1;const t=jl(a);if(t.length===0)return!1;o.preventDefault();const n=t.findIndex(d=>d===document.activeElement);if(o.key==="Home")return fa(t[0]),!0;if(o.key==="End")return fa(t[t.length-1]),!0;const i=o.key==="ArrowDown"?-1:0,r=n>=0?n:i,l=o.key==="ArrowDown"?1:-1,s=(r+l+t.length)%t.length;return fa(t[s]),!0}const XD=["aria-labelledby","aria-describedby"],KD={class:"media-album-picker-modal__header"},qD=["id"],JD=["id"],YD={key:0,class:"media-album-picker-modal__create-row"},QD={class:"media-album-picker-modal__create-field",for:"media-album-picker-create-name"},e6={class:"media-album-picker-modal__create-label"},t6=["maxlength","aria-invalid","disabled"],a6={class:"media-album-picker-modal__create-meta"},n6={key:0,id:"media-album-picker-create-error",class:"media-album-picker-modal__create-error","data-testid":"media-album-picker-create-error",role:"alert"},o6={key:1,class:"media-album-picker-modal__create-helper"},i6={class:"media-album-picker-modal__create-actions"},r6=["disabled"],l6=["disabled"],s6={key:0},d6={key:1},c6={key:2,class:"media-album-picker-modal__selection","data-testid":"media-album-picker-selection"},u6={class:"media-album-picker-modal__actions"},m6=["disabled"],p6=e.defineComponent({__name:"MediaAlbumPickerModal",props:{open:{type:Boolean},selectedCount:{},labels:{default:()=>({})},nameMaxLength:{default:120}},emits:["cancel","confirm","error"],setup(o,{emit:a}){const t=o,n=a,i=Ol(),r=e.ref(null),l=e.ref(!1),s=e.ref(""),d=e.ref(""),c=e.ref(!1),u=e.ref(null),m=e.ref(null),p=e.ref(null),f=e.ref(null),h=e.ref(null),v=e.ref(null),y=e.useId(),w=e.useId(),_=e.computed(()=>{var C,A,O,K,se,xe,ue,le,Z,k,F,W;return{title:((C=t.labels)==null?void 0:C.title)??"Add to album",body:((A=t.labels)==null?void 0:A.body)??`Choose an album for ${t.selectedCount} selected item${t.selectedCount===1?"":"s"}.`,confirm:((O=t.labels)==null?void 0:O.confirm)??"Add",cancel:((K=t.labels)==null?void 0:K.cancel)??"Cancel",selectedAlbum:((se=t.labels)==null?void 0:se.selectedAlbum)??(J=>`Selected: ${J}`),createNew:((xe=t.labels)==null?void 0:xe.createNew)??"+ Create new album",createNewPrompt:((ue=t.labels)==null?void 0:ue.createNewPrompt)??"Name this album",createNewSubmit:((le=t.labels)==null?void 0:le.createNewSubmit)??"Create",createNewCancel:((Z=t.labels)==null?void 0:Z.createNewCancel)??"Cancel",createNewEmptyError:((k=t.labels)==null?void 0:k.createNewEmptyError)??"Please enter a name.",createNewTooLongError:((F=t.labels)==null?void 0:F.createNewTooLongError)??`Name must be ${t.nameMaxLength} characters or fewer.`,createNewGenericError:((W=t.labels)==null?void 0:W.createNewGenericError)??"Could not create album. Try again."}}),b=e.computed(()=>s.value.trim()),g=e.computed(()=>b.value===""),I=e.computed(()=>b.value.length>t.nameMaxLength),T=e.computed(()=>!c.value&&!g.value&&!I.value),$=e.computed(()=>b.value.length),N=e.computed(()=>s.value.length>t.nameMaxLength*.6);function B(){s.value="",d.value="",c.value=!1}function P(){r.value=null,l.value=!1,B()}e.watch(()=>t.open,C=>{if(C)v.value=typeof document<"u"&&document.activeElement instanceof HTMLElement?document.activeElement:null,e.nextTick(()=>{fa(p.value??f.value??m.value)});else{P();const A=v.value;v.value=null,e.nextTick(()=>fa(A))}},{immediate:!0});function x(C){l.value||(r.value=C)}function M(){r.value!==null&&n("confirm",r.value.id)}async function E(){var C;l.value=!0,B(),await e.nextTick(),(C=h.value)==null||C.focus()}function D(){l.value=!1,B(),e.nextTick(()=>fa(p.value))}function j(){d.value!==""&&!g.value&&!I.value&&(d.value="")}async function L(){var C,A,O,K;if(!c.value){if(g.value){d.value=_.value.createNewEmptyError,(C=h.value)==null||C.focus();return}if(I.value){d.value=_.value.createNewTooLongError,(A=h.value)==null||A.focus();return}c.value=!0,d.value="";try{const se=await i.createAlbum({name:b.value});if(se==null){d.value=_.value.createNewGenericError,c.value=!1,(O=h.value)==null||O.focus();return}r.value=se,l.value=!1,B(),n("confirm",se.id)}catch(se){const xe=se instanceof Error?se:new Error(String(se));d.value=xe.message!==""?xe.message:_.value.createNewGenericError,c.value=!1,(K=h.value)==null||K.focus(),n("error",xe)}}}function z(C){if(C.key==="Escape"&&l.value){C.preventDefault(),C.stopPropagation(),D();return}if(C.key==="Escape"){C.preventDefault(),C.stopPropagation(),n("cancel");return}C.key==="Tab"&&Kd(C,u.value)}return(C,A)=>{var O;return e.openBlock(),e.createBlock(e.Teleport,{to:"body"},[t.open?(e.openBlock(),e.createElementBlock("div",{key:0,ref_key:"modalRef",ref:u,class:"media-album-picker-modal","data-testid":"media-album-picker-modal",role:"dialog","aria-modal":"true","aria-labelledby":e.unref(y),"aria-describedby":e.unref(w),tabindex:"-1",onKeydown:z},[e.createElementVNode("div",{ref_key:"panelRef",ref:m,class:"media-album-picker-modal__panel"},[e.createElementVNode("header",KD,[e.createElementVNode("h2",{id:e.unref(y)},e.toDisplayString(_.value.title),9,qD),e.createElementVNode("p",{id:e.unref(w)},e.toDisplayString(_.value.body),9,JD)]),l.value?(e.openBlock(),e.createElementBlock("form",{key:1,class:"media-album-picker-modal__create-form","data-testid":"media-album-picker-create-form",novalidate:"",onSubmit:A[2]||(A[2]=e.withModifiers(K=>void L(),["prevent"]))},[e.createElementVNode("label",QD,[e.createElementVNode("span",e6,e.toDisplayString(_.value.createNewPrompt),1),e.withDirectives(e.createElementVNode("input",{id:"media-album-picker-create-name",ref_key:"createInputRef",ref:h,"onUpdate:modelValue":A[1]||(A[1]=K=>s.value=K),type:"text",class:e.normalizeClass(["media-album-picker-modal__create-input",{"media-album-picker-modal__create-input--error":d.value!==""}]),maxlength:t.nameMaxLength+16,"aria-invalid":d.value!==""?"true":"false","aria-describedby":"media-album-picker-create-error media-album-picker-create-counter",autocomplete:"off","data-testid":"input-media-album-picker-create-name",disabled:c.value,onInput:j},null,42,t6),[[e.vModelText,s.value]]),e.createElementVNode("div",a6,[d.value!==""?(e.openBlock(),e.createElementBlock("span",n6,e.toDisplayString(d.value),1)):(e.openBlock(),e.createElementBlock("span",o6," Press Enter to create. ")),N.value?(e.openBlock(),e.createElementBlock("span",{key:2,id:"media-album-picker-create-counter",class:e.normalizeClass(["media-album-picker-modal__create-counter",{"media-album-picker-modal__create-counter--over":I.value}]),"data-testid":"media-album-picker-create-counter"},e.toDisplayString($.value)+" / "+e.toDisplayString(t.nameMaxLength),3)):e.createCommentVNode("",!0)])]),e.createElementVNode("div",i6,[e.createElementVNode("button",{type:"button",class:"media-album-picker-modal__btn media-album-picker-modal__btn--ghost","data-testid":"btn-media-album-picker-create-cancel",disabled:c.value,onClick:D},e.toDisplayString(_.value.createNewCancel),9,r6),e.createElementVNode("button",{type:"submit",class:"media-album-picker-modal__btn media-album-picker-modal__btn--primary","data-testid":"btn-media-album-picker-create-submit",disabled:!T.value},[c.value?(e.openBlock(),e.createElementBlock("span",s6,"…")):(e.openBlock(),e.createElementBlock("span",d6,e.toDisplayString(_.value.createNewSubmit),1))],8,l6)])],32)):(e.openBlock(),e.createElementBlock("div",YD,[e.createElementVNode("button",{ref_key:"createNewButtonRef",ref:p,type:"button",class:"media-album-picker-modal__create-new","data-testid":"btn-media-album-picker-create-new","aria-label":"Create new album",onClick:A[0]||(A[0]=K=>void E())},e.toDisplayString(_.value.createNew),513)])),e.createVNode(zl,{class:"media-album-picker-modal__tree","model-value":((O=r.value)==null?void 0:O.id)??null,draggable:!1,compact:!0,"data-testid":"media-album-picker-tree",onAlbumSelected:x},null,8,["model-value"]),r.value!==null&&!l.value?(e.openBlock(),e.createElementBlock("p",c6,e.toDisplayString(_.value.selectedAlbum(r.value.name)),1)):e.createCommentVNode("",!0),e.createElementVNode("footer",u6,[e.createElementVNode("button",{ref_key:"cancelButtonRef",ref:f,type:"button",class:"media-album-picker-modal__btn media-album-picker-modal__btn--ghost","data-testid":"btn-media-album-picker-cancel",onClick:A[3]||(A[3]=K=>n("cancel"))},e.toDisplayString(_.value.cancel),513),e.createElementVNode("button",{type:"button",class:"media-album-picker-modal__btn media-album-picker-modal__btn--primary","data-testid":"btn-media-album-picker-confirm",disabled:r.value===null||l.value,onClick:M},e.toDisplayString(_.value.confirm),9,m6)])],512)],40,XD)):e.createCommentVNode("",!0)])}}}),zf=Ae(p6,[["__scopeId","data-v-4bc0ef5f"]]),f6={key:0,class:"media-bulk-action-bar","data-testid":"media-bulk-action-bar","aria-live":"polite"},h6=["aria-label"],v6={class:"media-bulk-action-bar__actions"},g6=["disabled"],b6=e.defineComponent({__name:"MediaBulkActionBar",props:{selectedCount:{},crossPageCount:{default:0},overCap:{type:Boolean,default:!1},totalMatching:{default:null},scope:{},sourceAlbum:{default:null},capabilities:{default:()=>({})},labels:{default:()=>({})}},emits:["bulk-add-to-album","bulk-move-between-albums","bulk-remove-from-current-album","bulk-move-to-trash","bulk-create-post","bulk-create-gallery","bulk-restore","bulk-purge","bulk-download","clear","inspect"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>{var s,d,c,u,m,p,f,h,v,y,w,_,b,g;return{selectedCount:((s=t.labels)==null?void 0:s.selectedCount)??(I=>`${I} selected`),selectedAcrossPages:((d=t.labels)==null?void 0:d.selectedAcrossPages)??((I,T)=>`${I} selected, including ${T} not on this page`),cappedSelection:((c=t.labels)==null?void 0:c.cappedSelection)??((I,T)=>`Selected first ${I} of ${T??"many"} matching items`),addToAlbum:((u=t.labels)==null?void 0:u.addToAlbum)??"Add to album",moveBetweenAlbums:((m=t.labels)==null?void 0:m.moveBetweenAlbums)??(I=>`Move from ${I} to...`),removeFromCurrentAlbum:((p=t.labels)==null?void 0:p.removeFromCurrentAlbum)??"Remove from this album",moveToTrash:((f=t.labels)==null?void 0:f.moveToTrash)??"Move to trash",createPost:((h=t.labels)==null?void 0:h.createPost)??"Create post",createGallery:((v=t.labels)==null?void 0:v.createGallery)??"Create gallery",restore:((y=t.labels)==null?void 0:y.restore)??"Restore",purge:((w=t.labels)==null?void 0:w.purge)??"Delete forever",download:((_=t.labels)==null?void 0:_.download)??"Download",inspect:((b=t.labels)==null?void 0:b.inspect)??"Inspect",clear:((g=t.labels)==null?void 0:g.clear)??"Clear"}}),r=e.computed(()=>t.overCap?i.value.cappedSelection(t.selectedCount,t.totalMatching):t.crossPageCount>0?i.value.selectedAcrossPages(t.selectedCount,t.crossPageCount):i.value.selectedCount(t.selectedCount)),l=e.computed(()=>t.sourceAlbum?i.value.moveBetweenAlbums(t.sourceAlbum.name):i.value.addToAlbum);return(s,d)=>(e.openBlock(),e.createBlock(e.Transition,{name:"media-bulk-action-bar"},{default:e.withCtx(()=>[t.selectedCount>0?(e.openBlock(),e.createElementBlock("aside",f6,[e.createElementVNode("button",{type:"button",class:"media-bulk-action-bar__count","data-testid":"media-bulk-action-count","aria-label":`${i.value.inspect}: ${r.value}`,onClick:d[0]||(d[0]=c=>n("inspect"))},e.toDisplayString(r.value),9,h6),e.createElementVNode("div",v6,[t.scope!=="trash"&&t.capabilities.allowAddToAlbum===!0?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button","data-testid":"btn-media-bulk-add-album",onClick:d[1]||(d[1]=c=>t.scope==="album"?n("bulk-move-between-albums"):n("bulk-add-to-album"))},e.toDisplayString(t.scope==="album"?l.value:i.value.addToAlbum),1)):e.createCommentVNode("",!0),t.scope!=="trash"&&t.capabilities.allowCreatePost===!0?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button","data-testid":"btn-media-bulk-create-post",onClick:d[2]||(d[2]=c=>n("bulk-create-post"))},e.toDisplayString(i.value.createPost),1)):e.createCommentVNode("",!0),t.scope!=="trash"&&t.capabilities.allowCreateGallery===!0?(e.openBlock(),e.createElementBlock("button",{key:2,type:"button","data-testid":"btn-media-bulk-create-gallery",onClick:d[3]||(d[3]=c=>n("bulk-create-gallery"))},e.toDisplayString(i.value.createGallery),1)):e.createCommentVNode("",!0),t.scope==="album"?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button","data-testid":"btn-media-bulk-remove-current-album",onClick:d[4]||(d[4]=c=>n("bulk-remove-from-current-album"))},e.toDisplayString(i.value.removeFromCurrentAlbum),1)):e.createCommentVNode("",!0),t.scope!=="trash"?(e.openBlock(),e.createElementBlock("button",{key:4,type:"button","data-testid":"btn-media-bulk-trash",onClick:d[5]||(d[5]=c=>n("bulk-move-to-trash"))},e.toDisplayString(i.value.moveToTrash),1)):e.createCommentVNode("",!0),t.scope==="trash"?(e.openBlock(),e.createElementBlock("button",{key:5,type:"button","data-testid":"btn-media-bulk-restore",onClick:d[6]||(d[6]=c=>n("bulk-restore"))},e.toDisplayString(i.value.restore),1)):e.createCommentVNode("",!0),t.scope==="trash"?(e.openBlock(),e.createElementBlock("button",{key:6,type:"button","data-testid":"btn-media-bulk-purge",onClick:d[7]||(d[7]=c=>n("bulk-purge"))},e.toDisplayString(i.value.purge),1)):e.createCommentVNode("",!0),e.createElementVNode("button",{type:"button","data-testid":"btn-media-bulk-download",disabled:t.capabilities.allowDownloadZip!==!0,onClick:d[8]||(d[8]=c=>n("bulk-download"))},e.toDisplayString(i.value.download),9,g6),e.createElementVNode("button",{type:"button","data-testid":"btn-media-bulk-clear",onClick:d[9]||(d[9]=c=>n("clear"))},e.toDisplayString(i.value.clear),1)])])):e.createCommentVNode("",!0)]),_:1}))}}),qd=Ae(b6,[["__scopeId","data-v-f934b5b2"]]),y6={class:"media-library-toolbar__group"},w6=["aria-controls","aria-expanded"],k6=["id"],_6={class:"media-library-toolbar__group"},E6=["aria-controls","aria-expanded"],S6=["id"],C6={key:0,class:"media-library-toolbar__menu-status"},x6={key:1,class:"media-library-toolbar__menu-status"},N6=["data-testid","onClick"],V6={"aria-hidden":"true"},T6={class:"media-library-toolbar__group"},B6=["aria-controls","aria-expanded"],M6=["id"],I6=e.defineComponent({__name:"MediaLibraryToolbar",props:{sort:{default:"newest"},density:{default:"comfortable"},hasDateFilter:{type:Boolean,default:!1},httpClient:{},timelineEndpoint:{default:"/v1/media/library/timeline"},labels:{default:()=>({})}},emits:["update:sort","update:density","jump-to","jump-to-all","upload-files"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>{var z,C,A,O,K,se,xe,ue,le,Z,k,F;return{sort:((z=t.labels)==null?void 0:z.sort)??"Sort",sortNewest:((C=t.labels)==null?void 0:C.sortNewest)??"Newest",sortOldest:((A=t.labels)==null?void 0:A.sortOldest)??"Oldest",sortName:((O=t.labels)==null?void 0:O.sortName)??"Name A–Z",sortLargest:((K=t.labels)==null?void 0:K.sortLargest)??"Largest first",jumpTo:((se=t.labels)==null?void 0:se.jumpTo)??"Jump to",jumpToAll:((xe=t.labels)==null?void 0:xe.jumpToAll)??"All time",jumpToEmpty:((ue=t.labels)==null?void 0:ue.jumpToEmpty)??"No history yet",density:((le=t.labels)==null?void 0:le.density)??"Density",densityComfortable:((Z=t.labels)==null?void 0:Z.densityComfortable)??"Comfortable",densityCompact:((k=t.labels)==null?void 0:k.densityCompact)??"Compact",upload:((F=t.labels)==null?void 0:F.upload)??"Upload"}}),r=e.ref(null);function l(){var z;(z=r.value)==null||z.click()}function s(z){const C=z.target;!(C instanceof HTMLInputElement)||C.files===null||C.files.length===0||(n("upload-files",Array.from(C.files)),C.value="")}const d=e.ref(null),c=e.ref(null),u=e.ref(null),m=e.ref(null),p=e.ref(null),f=e.useId(),h={sort:`${f}-sort`,jump:`${f}-jump`,density:`${f}-density`};function v(z){return z==="sort"?u.value:z==="jump"?m.value:p.value}function y(){e.nextTick(()=>{const z=c.value;if(z===null)return;const C=z.querySelector('[role="menu"]');C!==null&&fa(jl(C)[0]??null)})}function w(z){if(d.value===z){_(!0);return}d.value=z,y()}function _(z=!1){const C=d.value;d.value=null,z&&C!==null&&e.nextTick(()=>fa(v(C)))}function b(z){if(d.value===null)return;const C=c.value;C!==null&&(z.target instanceof Node&&C.contains(z.target)||_())}function g(z){d.value!==null&&z.key==="Escape"&&(z.preventDefault(),_(!0))}function I(z){if(z.key==="Escape"){z.preventDefault(),_(!0);return}cd(z,z.currentTarget instanceof HTMLElement?z.currentTarget:null)}const T=e.computed(()=>{switch(t.sort){case"oldest":return i.value.sortOldest;case"name":return i.value.sortName;case"largest":return i.value.sortLargest;default:return i.value.sortNewest}}),$=e.computed(()=>t.density==="compact"?i.value.densityCompact:i.value.densityComfortable);function N(z){_(!0),n("update:sort",z)}function B(z){_(!0),n("update:density",z)}const P=e.ref([]),x=e.ref(!1),M=e.ref(!1);async function E(){if(!(x.value||M.value||t.httpClient===void 0)){M.value=!0;try{const z=await t.httpClient.get(t.timelineEndpoint),C=z.data,A=(C==null?void 0:C.buckets)??z.buckets??[];P.value=Array.isArray(A)?A:[],x.value=!0}finally{M.value=!1}}}async function D(){w("jump"),d.value==="jump"&&await E()}function j(z){_(!0),n("jump-to",z)}function L(){_(!0),n("jump-to-all")}return e.onMounted(()=>{typeof window<"u"&&(document.addEventListener("pointerdown",b,!0),document.addEventListener("keydown",g))}),e.onBeforeUnmount(()=>{typeof window<"u"&&(document.removeEventListener("pointerdown",b,!0),document.removeEventListener("keydown",g))}),(z,C)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"toolbarRoot",ref:c,class:"media-library-toolbar","data-testid":"media-library-toolbar"},[e.createElementVNode("button",{type:"button",class:"media-library-toolbar__upload","data-testid":"btn-media-toolbar-upload",onClick:l}," ⤴ "+e.toDisplayString(i.value.upload),1),e.createElementVNode("input",{ref_key:"fileInputRef",ref:r,type:"file",multiple:"",accept:"image/*,video/*","data-testid":"input-media-toolbar-upload",class:"media-library-toolbar__file-input",onChange:s},null,544),e.createElementVNode("div",y6,[e.createElementVNode("button",{ref_key:"sortTriggerRef",ref:u,type:"button",class:"media-library-toolbar__trigger","data-testid":"btn-media-toolbar-sort","aria-haspopup":"menu","aria-controls":h.sort,"aria-expanded":d.value==="sort"?"true":"false",onClick:C[0]||(C[0]=A=>w("sort"))},e.toDisplayString(i.value.sort)+": "+e.toDisplayString(T.value),9,w6),d.value==="sort"?(e.openBlock(),e.createElementBlock("div",{key:0,id:h.sort,class:"media-library-toolbar__menu",role:"menu","data-testid":"media-library-toolbar-sort-menu",onKeydown:I},[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-sort-newest",onClick:C[1]||(C[1]=A=>N("newest"))},e.toDisplayString(i.value.sortNewest),1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-sort-oldest",onClick:C[2]||(C[2]=A=>N("oldest"))},e.toDisplayString(i.value.sortOldest),1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-sort-name",onClick:C[3]||(C[3]=A=>N("name"))},e.toDisplayString(i.value.sortName),1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-sort-largest",onClick:C[4]||(C[4]=A=>N("largest"))},e.toDisplayString(i.value.sortLargest),1)],40,k6)):e.createCommentVNode("",!0)]),e.createElementVNode("div",_6,[e.createElementVNode("button",{ref_key:"jumpTriggerRef",ref:m,type:"button",class:"media-library-toolbar__trigger","data-testid":"btn-media-toolbar-jump-to","aria-haspopup":"menu","aria-controls":h.jump,"aria-expanded":d.value==="jump"?"true":"false",onClick:C[5]||(C[5]=A=>void D())},e.toDisplayString(i.value.jumpTo),9,E6),d.value==="jump"?(e.openBlock(),e.createElementBlock("div",{key:0,id:h.jump,class:"media-library-toolbar__menu",role:"menu","data-testid":"media-library-toolbar-jump-menu",onKeydown:I},[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-jump-all",onClick:L},e.toDisplayString(i.value.jumpToAll),1),M.value?(e.openBlock(),e.createElementBlock("p",C6,"Loading…")):x.value&&P.value.length===0?(e.openBlock(),e.createElementBlock("p",x6,e.toDisplayString(i.value.jumpToEmpty),1)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(P.value,A=>(e.openBlock(),e.createElementBlock("button",{key:A.starts_at,type:"button",role:"menuitem","data-testid":`opt-jump-${A.starts_at}`,onClick:O=>j(A)},[e.createTextVNode(e.toDisplayString(A.label)+" ",1),e.createElementVNode("span",V6,"("+e.toDisplayString(A.count)+")",1)],8,N6))),128))],40,S6)):e.createCommentVNode("",!0)]),e.createElementVNode("div",T6,[e.createElementVNode("button",{ref_key:"densityTriggerRef",ref:p,type:"button",class:"media-library-toolbar__trigger","data-testid":"btn-media-toolbar-density","aria-haspopup":"menu","aria-controls":h.density,"aria-expanded":d.value==="density"?"true":"false",onClick:C[6]||(C[6]=A=>w("density"))},e.toDisplayString(i.value.density)+": "+e.toDisplayString($.value),9,B6),d.value==="density"?(e.openBlock(),e.createElementBlock("div",{key:0,id:h.density,class:"media-library-toolbar__menu",role:"menu","data-testid":"media-library-toolbar-density-menu",onKeydown:I},[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-density-comfortable",onClick:C[7]||(C[7]=A=>B("comfortable"))},e.toDisplayString(i.value.densityComfortable),1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"opt-density-compact",onClick:C[8]||(C[8]=A=>B("compact"))},e.toDisplayString(i.value.densityCompact),1)],40,M6)):e.createCommentVNode("",!0)])],512))}}),jf=Ae(I6,[["__scopeId","data-v-2bd00d6a"]]),$6={class:"media-shortcut-help__panel"},F6={class:"media-shortcut-help__header"},D6=e.defineComponent({__name:"MediaShortcutHelp",props:{open:{type:Boolean},shortcuts:{default:()=>[{key:"j / k",label:"Move focus",group:"Navigation"},{key:"x",label:"Toggle selection",group:"Selection"},{key:"?",label:"Open shortcuts",group:"Help"},{key:"Esc",label:"Close panel",group:"Navigation"}]},title:{default:"Shortcuts"},closeLabel:{default:"Close"}},emits:["close"],setup(o,{emit:a}){const t=o,n=a;function i(){const r=new Map;for(const l of t.shortcuts)r.set(l.group,[...r.get(l.group)??[],l]);return Array.from(r.entries()).map(([l,s])=>({group:l,shortcuts:s}))}return(r,l)=>t.open?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-shortcut-help",role:"dialog","aria-modal":"true","data-testid":"media-shortcut-help",onKeydown:l[1]||(l[1]=e.withKeys(s=>n("close"),["escape"]))},[e.createElementVNode("div",$6,[e.createElementVNode("header",F6,[e.createElementVNode("h3",null,e.toDisplayString(t.title),1),e.createElementVNode("button",{type:"button","data-testid":"btn-media-shortcut-close",onClick:l[0]||(l[0]=s=>n("close"))},e.toDisplayString(t.closeLabel),1)]),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i(),s=>(e.openBlock(),e.createElementBlock("section",{key:s.group,class:"media-shortcut-help__group"},[e.createElementVNode("h4",null,e.toDisplayString(s.group),1),e.createElementVNode("dl",null,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(s.shortcuts,d=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:`${s.group}-${d.key}`},[e.createElementVNode("dt",null,[e.createElementVNode("kbd",null,e.toDisplayString(d.key),1)]),e.createElementVNode("dd",null,e.toDisplayString(d.label),1)],64))),128))])]))),128))])],32)):e.createCommentVNode("",!0)}}),Wf=Ae(D6,[["__scopeId","data-v-abcdccb6"]]),A6="/v1/media/upload";function Hf(o){const a=o.endpoint??A6,t=e.ref([]),n=e.computed(()=>t.value.some(u=>u.status==="uploading"||u.status==="queued"));function i(){return`upload-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function r(u){if(u.type.startsWith("image/")&&typeof URL<"u")try{return URL.createObjectURL(u)}catch{return}}function l(u){t.value=t.value.filter(m=>m.cid!==u)}async function s(u){const m=i(),p=r(u),f={cid:m,fileName:u.name,size:u.size,status:"uploading",progress:0,...p!==void 0?{previewUrl:p}:{}};t.value=[f,...t.value];const h=new FormData;h.append("file",u);try{const v=await o.httpClient.post(a,h),y=v.data??v;return t.value=t.value.map(w=>w.cid===m?{...w,status:"success",progress:100}:w),typeof o.onMediaUploaded=="function"&&y&&typeof y.uuid=="string"&&await o.onMediaUploaded(y),setTimeout(()=>l(m),350),t.value.find(w=>w.cid===m)??f}catch(v){const y=v instanceof Error?v.message:"Upload failed";return t.value=t.value.map(w=>w.cid===m?{...w,status:"error",errorMessage:y}:w),t.value.find(w=>w.cid===m)??f}finally{if(p!==void 0&&typeof URL<"u")try{URL.revokeObjectURL(p)}catch{}}}async function d(u){const m=Array.from(u);return Promise.all(m.map(p=>s(p)))}function c(){t.value=[]}return{uploads:t,hasActiveUploads:n,uploadFile:s,uploadFiles:d,dismiss:l,clear:c}}const R6={class:"media-usage-list","data-testid":"media-usage-list"},L6={class:"media-usage-list__title"},P6={key:0,class:"media-usage-list__empty","data-testid":"media-usage-loading"},U6={key:1,class:"media-usage-list__empty","data-testid":"media-usage-empty"},O6={key:2,class:"media-usage-list__items"},z6=["data-testid"],j6=["href"],W6={key:1},H6={key:2,class:"media-usage-list__count"},Z6=e.defineComponent({__name:"MediaUsageList",props:{media:{},httpClient:{},items:{default:()=>[]},title:{default:"Used in"},emptyLabel:{default:"No visible usages"}},setup(o){const a=o,t=e.ref(!1),n=e.ref([]),i=e.computed(()=>a.items.length>0?a.items:n.value);function r(s){var m;if(typeof s!="object"||s===null||!("data"in s))return[];const d=s.data;if(!Array.isArray(d))return[];const c=d[0];return(Array.isArray((m=c==null?void 0:c.report)==null?void 0:m.blocks)?c.report.blocks:[]).map((p,f)=>({id:`${p.type??"usage"}-${f}`,label:p.context??p.type??"Usage"}))}async function l(){if(!a.httpClient||a.media===null){n.value=[];return}t.value=!0;try{const s=await a.httpClient.post("/v1/media/deletion/check",{uuids:[a.media.uuid]});n.value=r(s)}finally{t.value=!1}}return e.watch(()=>{var s;return(s=a.media)==null?void 0:s.uuid},()=>{l()}),e.onMounted(()=>{l()}),(s,d)=>(e.openBlock(),e.createElementBlock("section",R6,[e.createElementVNode("h4",L6,e.toDisplayString(a.title),1),t.value?(e.openBlock(),e.createElementBlock("p",P6," Loading... ")):i.value.length===0?(e.openBlock(),e.createElementBlock("p",U6,e.toDisplayString(a.emptyLabel),1)):(e.openBlock(),e.createElementBlock("ul",O6,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,c=>(e.openBlock(),e.createElementBlock("li",{key:c.id,class:"media-usage-list__item","data-testid":`media-usage-${c.id}`},[c.href?(e.openBlock(),e.createElementBlock("a",{key:0,href:c.href},e.toDisplayString(c.label),9,j6)):(e.openBlock(),e.createElementBlock("span",W6,e.toDisplayString(c.label),1)),typeof c.count=="number"?(e.openBlock(),e.createElementBlock("span",H6,e.toDisplayString(c.count),1)):e.createCommentVNode("",!0)],8,z6))),128))]))]))}}),Zf=Ae(Z6,[["__scopeId","data-v-ef6f09cf"]]),G6={class:"media-variant-strip","data-testid":"media-variant-strip"},X6={class:"media-variant-strip__title"},K6={key:0,class:"media-variant-strip__empty"},q6={key:1,class:"media-variant-strip__empty"},J6={key:2,class:"media-variant-strip__list"},Y6=["data-testid"],Q6=["src","alt"],eA={key:1,class:"media-variant-strip__placeholder"},tA={class:"media-variant-strip__label"},aA=e.defineComponent({__name:"MediaVariantStrip",props:{media:{},httpClient:{},variants:{default:()=>[]},title:{default:"Variants"}},setup(o){const a=o,t=e.ref(!1),n=e.ref([]),i=e.computed(()=>{const c=a.variants.length>0?a.variants:n.value;return a.media?[a.media,...c.filter(u=>{var m;return u.uuid!==((m=a.media)==null?void 0:m.uuid)})]:c});function r(c){if(typeof c!="object"||c===null||!("data"in c))return[];const u=c.data;return Array.isArray(u)?u.filter(m=>typeof m=="object"&&m!==null&&typeof m.uuid=="string"&&typeof m.file_name=="string"):[]}async function l(){if(!a.httpClient||a.media===null){n.value=[];return}t.value=!0;try{const c=await a.httpClient.get(`/v1/media/${encodeURIComponent(a.media.uuid)}/variants`);n.value=r(c)}finally{t.value=!1}}function s(c){return c.thumbnail_url??c.preview_url??c.original_url??null}function d(c,u){if(c===0)return"Current";if(c===1)return"Original";const m=new Date(u.created_at);if(Number.isNaN(m.getTime()))return"Edited";const p=Math.max(0,Math.round((Date.now()-m.getTime())/864e5));return p===0?"Edited today":p===1?"Edited 1 day ago":`Edited ${p} days ago`}return e.watch(()=>{var c;return(c=a.media)==null?void 0:c.uuid},()=>{l()}),e.onMounted(()=>{l()}),(c,u)=>(e.openBlock(),e.createElementBlock("section",G6,[e.createElementVNode("h4",X6,e.toDisplayString(a.title),1),t.value?(e.openBlock(),e.createElementBlock("p",K6,"Loading...")):i.value.length<=1?(e.openBlock(),e.createElementBlock("p",q6," No edits ")):(e.openBlock(),e.createElementBlock("ol",J6,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(i.value,(m,p)=>(e.openBlock(),e.createElementBlock("li",{key:m.uuid,class:"media-variant-strip__item","data-testid":`media-variant-${m.uuid}`},[s(m)?(e.openBlock(),e.createElementBlock("img",{key:0,src:s(m)??"",alt:m.alt_text??m.file_name},null,8,Q6)):(e.openBlock(),e.createElementBlock("span",eA,e.toDisplayString(m.file_name),1)),e.createElementVNode("span",tA,e.toDisplayString(d(p,m)),1)],8,Y6))),128))]))]))}}),Gf=Ae(aA,[["__scopeId","data-v-adb529cb"]]),nA=/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/ig,qu=/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i;function Ju(o){const a=o.replace(/\.[^.]+$/,""),t=a.replace(nA,""),n=t.replace(/(?:[-_\s]+edited)+$/i,""),i=t.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/(?:[-_\s]+edited)+$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim();return i!==""?i:n||a||o}function Yu(o,a){var n;const t=(n=o.custom_properties)==null?void 0:n[a];return typeof t=="string"&&t.trim()!==""?t.trim():null}function Xf(o){const a=Yu(o,"display_name");if(a!==null&&!qu.test(a))return a;const t=Yu(o,"original_filename");return t!==null&&!qu.test(t)?Ju(t):Ju(o.file_name)}const oA=o=>`/v1/media/${encodeURIComponent(o)}`,iA=new Set(["caption","alt_text","is_decorative","tags"]);function ks(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Br(o,a){return Object.prototype.hasOwnProperty.call(o,a)}function Qu(o){if(o==null)return null;const a=o.trim();return a===""?null:a}function rA(o){const a=[];for(const t of o){const n=t.trim();n===""||a.includes(n)||a.push(n)}return a}function lA(o){const a=o,t={};for(const n of Object.keys(a))if(!iA.has(n))throw new Error(`Unsupported media metadata field: ${n}`);if(Br(o,"caption")&&(t.caption=Qu(o.caption)),Br(o,"alt_text")&&(t.alt_text=Qu(o.alt_text)),Br(o,"is_decorative")&&(t.is_decorative=o.is_decorative===!0),Br(o,"tags")&&(t.tags=Array.isArray(o.tags)?rA(o.tags):[]),Object.keys(t).length===0)throw new Error("At least one media metadata field must be provided");return t}function sA(o){const a=ks(o)&&ks(o.data)?o.data:o;if(ks(a)&&typeof a.uuid=="string")return a;throw new Error("Media metadata update response did not include a media record")}function Kf(o){const a=e.ref(!1),t=e.ref(null),n=o.endpoint??oA;async function i(r,l){const s=r.trim();if(s==="")throw new Error("media uuid must not be empty");if(typeof o.httpClient.patch!="function")throw new Error("httpClient.patch is required to update media metadata");const d=lA(l);a.value=!0,t.value=null;try{const c=await o.httpClient.patch(n(s),d,o.requestConfig);return sA(c)}catch(c){throw t.value=c instanceof Error?c.message:"Failed to update media metadata",c}finally{a.value=!1}}return{updateMetadata:i,isUpdating:a,error:t}}const dA=["role","aria-modal"],cA={key:0,class:"media-inspector-panel__overlay-bar"},uA=["aria-label"],mA={class:"media-inspector-panel__header"},pA={key:0,class:"media-inspector-panel__raw-name"},fA={class:"media-inspector-panel__preview"},hA=["src","alt"],vA={class:"media-inspector-panel__meta"},gA={class:"media-inspector-panel__metadata","data-testid":"media-inspector-metadata-editor","aria-labelledby":"media-inspector-metadata-heading"},bA={class:"media-inspector-panel__metadata-heading"},yA={id:"media-inspector-metadata-heading"},wA={key:0,class:"media-inspector-panel__metadata-warning","data-testid":"media-inspector-missing-alt"},kA={class:"media-inspector-panel__field"},_A={class:"media-inspector-panel__field"},EA=["disabled"],SA={class:"media-inspector-panel__checkbox"},CA={id:"media-inspector-decorative-help",class:"media-inspector-panel__metadata-help"},xA={class:"media-inspector-panel__field"},NA={key:0,class:"media-inspector-panel__metadata-error","data-testid":"media-inspector-metadata-error",role:"alert"},VA={class:"media-inspector-panel__metadata-actions"},TA=["disabled"],BA=["disabled"],MA={key:2,class:"media-inspector-panel__metadata-read"},IA={key:0,class:"media-inspector-panel__metadata-status","data-testid":"media-inspector-metadata-status",role:"status"},$A={class:"media-inspector-panel__actions"},FA=["aria-label"],DA=["aria-label"],AA=["aria-label"],RA=["aria-label"],LA=["aria-label"],PA=["aria-label"],UA=["aria-label"],OA=["aria-label"],zA={class:"media-inspector-panel__actions"},jA=["aria-label"],WA=["aria-label"],HA=["aria-label"],ZA=["aria-label"],GA={key:3,class:"media-inspector-panel__empty"},XA=e.defineComponent({__name:"MediaInspectorPanel",props:{target:{},httpClient:{},capabilities:{default:()=>({})},inAlbumScope:{type:Boolean,default:!1},labels:{default:()=>({})},mode:{default:"pinned"}},emits:["edit","replace","download","set-visibility","move-to-trash","remove-from-this-album","remove-from-albums","set-as-album-cover","bulk-add-to-album","bulk-create-album","bulk-move-to-trash","bulk-download","metadata-updated","close"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null),r=e.ref(null),l=e.ref(null),s=e.ref(null),d=e.ref(!1),c=e.ref(""),u=e.ref(""),m=e.ref(!1),p=e.ref(""),f=e.ref(""),h=e.ref("");function v(){return Promise.reject(new Error("Media metadata editing requires a PATCH-capable httpClient."))}const w=Kf({httpClient:{get:async(k,F)=>{var W;return((W=t.httpClient)==null?void 0:W.get(k,F))??v()},post:async(k,F,W)=>{var J;return((J=t.httpClient)==null?void 0:J.post(k,F,W))??v()},patch:async(k,F,W)=>{var J,ce;return((ce=(J=t.httpClient)==null?void 0:J.patch)==null?void 0:ce.call(J,k,F,W))??v()}}});e.watch(()=>t.target,(k,F)=>{const W=F==null,J=k==null;if(W&&!J){typeof document<"u"&&document.activeElement instanceof HTMLElement&&(s.value=document.activeElement),e.nextTick(()=>{var ce,Ue;if(t.mode==="overlay"){(ce=l.value)==null||ce.focus();return}(Ue=r.value)==null||Ue.focus()});return}if(!W&&J){const ce=s.value;s.value=null,ce instanceof HTMLElement&&ce.focus()}});function _(k){if(t.mode==="overlay"&&k.key==="Escape"){k.preventDefault(),k.stopPropagation(),n("close");return}t.mode==="overlay"&&k.key==="Tab"&&Kd(k,i.value)}const b=e.computed(()=>t.mode==="overlay"?"dialog":"complementary"),g=e.computed(()=>{var k,F,W,J,ce,Ue,be,_e,ye,Ne,Se,Re,Oe,it,rt,Pt,bt,Ct,mt,pt,Nt,Ce,Ve,Le,nt,Ge;return{title:((k=t.labels)==null?void 0:k.title)??"Inspector",emptyTitle:((F=t.labels)==null?void 0:F.emptyTitle)??"Select media to inspect",multiTitle:((W=t.labels)==null?void 0:W.multiTitle)??(Je=>`${Je} selected`),edit:((J=t.labels)==null?void 0:J.edit)??"Edit",replace:((ce=t.labels)==null?void 0:ce.replace)??"Replace",download:((Ue=t.labels)==null?void 0:Ue.download)??"Download",setVisibility:((be=t.labels)==null?void 0:be.setVisibility)??"Set visibility",moveToTrash:((_e=t.labels)==null?void 0:_e.moveToTrash)??"Move to trash",removeFromThisAlbum:((ye=t.labels)==null?void 0:ye.removeFromThisAlbum)??"Remove from this album",removeFromAlbums:((Ne=t.labels)==null?void 0:Ne.removeFromAlbums)??(t.inAlbumScope?"Move to another album":"Add to album"),addToAlbum:((Se=t.labels)==null?void 0:Se.addToAlbum)??"Add to album",createAlbum:((Re=t.labels)==null?void 0:Re.createAlbum)??"Create album from selection",setAsAlbumCover:((Oe=t.labels)==null?void 0:Oe.setAsAlbumCover)??"Set as album cover",metadataTitle:((it=t.labels)==null?void 0:it.metadataTitle)??"Metadata",metadataEdit:((rt=t.labels)==null?void 0:rt.metadataEdit)??"Edit metadata",caption:((Pt=t.labels)==null?void 0:Pt.caption)??"Caption",altText:((bt=t.labels)==null?void 0:bt.altText)??"Alt text",decorative:((Ct=t.labels)==null?void 0:Ct.decorative)??"Decorative image",tags:((mt=t.labels)==null?void 0:mt.tags)??"Tags",saveMetadata:((pt=t.labels)==null?void 0:pt.saveMetadata)??"Save metadata",cancelMetadata:((Nt=t.labels)==null?void 0:Nt.cancelMetadata)??"Cancel",metadataSaved:((Ce=t.labels)==null?void 0:Ce.metadataSaved)??"Metadata saved",close:((Ve=t.labels)==null?void 0:Ve.close)??"Close inspector",missingAltTitle:((Le=t.labels)==null?void 0:Le.missingAltTitle)??"Missing alt text",missingAltDescription:((nt=t.labels)==null?void 0:nt.missingAltDescription)??"Add alt text or mark this image as decorative.",decorativeHelp:((Ge=t.labels)==null?void 0:Ge.decorativeHelp)??"Decorative media does not need alt text."}}),I=e.computed(()=>{var k;return((k=t.target)==null?void 0:k.kind)==="single"?t.target.media:null});function T(k){const F=k.mime_type.toLowerCase();return k.is_image===!0||F.startsWith("image/")?"image":F.startsWith("video/")?"video":null}const $=e.computed(()=>{const k=I.value;if(k===null)return!1;const F=T(k);return F==="image"?t.capabilities.allowImageEdit===!0:F==="video"?t.capabilities.allowVideoEdit===!0:!1}),N=e.computed(()=>t.capabilities.allowReplaceMedia===!0),B=e.computed(()=>t.capabilities.allowDownloadOriginal===!0),P=e.computed(()=>t.capabilities.allowBulkDelete===!0),x=e.computed(()=>t.inAlbumScope||t.capabilities.allowAddToAlbum===!0),M=e.computed(()=>t.capabilities.allowAddToAlbum===!0),E=e.computed(()=>t.capabilities.allowBulkDelete===!0),D=e.computed(()=>t.capabilities.allowDownloadZip===!0),j=e.computed(()=>{var k;return I.value!==null&&t.capabilities.allowMetadataEdit===!0&&typeof((k=t.httpClient)==null?void 0:k.patch)=="function"}),L=e.computed(()=>{const k=I.value;return k===null?null:T(k)}),z=e.computed(()=>{const k=I.value;return k!==null&&L.value==="image"&&k.is_decorative!==!0&&!O(k.alt_text)}),C=e.computed(()=>w.isUpdating.value),A=e.computed(()=>{var k;return K((k=I.value)==null?void 0:k.tags)});function O(k){return typeof k=="string"&&k.trim()!==""}function K(k){return Array.isArray(k)?k.filter(F=>F.trim()!=="").join(", "):""}function se(k){const F=[];for(const W of k.split(",")){const J=W.trim();J===""||F.includes(J)||F.push(J)}return F}function xe(k,F=!0){c.value=(k==null?void 0:k.caption)??"",u.value=(k==null?void 0:k.alt_text)??"",m.value=(k==null?void 0:k.is_decorative)===!0,p.value=K(k==null?void 0:k.tags),f.value="",F&&(h.value="")}function ue(){xe(I.value),d.value=!0}function le(){xe(I.value),d.value=!1}async function Z(){const k=I.value;if(!(k===null||!j.value||C.value)){f.value="",h.value="";try{const F=await w.updateMetadata(k.uuid,{caption:c.value,alt_text:m.value?null:u.value,is_decorative:m.value,tags:se(p.value)});xe(F,!1),d.value=!1,h.value=g.value.metadataSaved,n("metadata-updated",F)}catch(F){f.value=F instanceof Error?F.message:"Failed to save media metadata"}}}return e.watch(I,(k,F)=>{const W=(k==null?void 0:k.uuid)!==(F==null?void 0:F.uuid);xe(k,W),d.value=!1},{immediate:!0}),e.watch(m,k=>{k&&(u.value="")}),(k,F)=>{var W;return e.openBlock(),e.createElementBlock("aside",{ref_key:"panelRef",ref:i,class:"media-inspector-panel","data-testid":"media-inspector-panel",role:b.value,"aria-modal":t.mode==="overlay"?"true":void 0,"aria-labelledby":"media-inspector-heading",onKeydown:_},[t.mode==="overlay"?(e.openBlock(),e.createElementBlock("div",cA,[e.createElementVNode("button",{ref_key:"closeButtonRef",ref:l,type:"button",class:"media-inspector-panel__close","data-testid":"btn-media-inspector-close","aria-label":g.value.close,onClick:F[0]||(F[0]=J=>n("close"))}," × ",8,uA)])):e.createCommentVNode("",!0),I.value?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[e.createElementVNode("header",mA,[e.createElementVNode("h3",{id:"media-inspector-heading",ref_key:"headingRef",ref:r,tabindex:"-1"},e.toDisplayString(e.unref(Xf)(I.value)),513),I.value.file_name?(e.openBlock(),e.createElementBlock("p",pA,e.toDisplayString(I.value.file_name),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",fA,[I.value.thumbnail_url??I.value.preview_url??I.value.original_url?(e.openBlock(),e.createElementBlock("img",{key:0,src:I.value.thumbnail_url??I.value.preview_url??I.value.original_url,alt:I.value.alt_text??I.value.file_name},null,8,hA)):e.createCommentVNode("",!0)]),e.createElementVNode("dl",vA,[e.createElementVNode("div",null,[F[17]||(F[17]=e.createElementVNode("dt",null,"Type",-1)),e.createElementVNode("dd",null,e.toDisplayString(I.value.mime_type),1)]),e.createElementVNode("div",null,[F[18]||(F[18]=e.createElementVNode("dt",null,"Size",-1)),e.createElementVNode("dd",null,e.toDisplayString(I.value.formatted_size??I.value.size),1)])]),e.createElementVNode("section",gA,[e.createElementVNode("div",bA,[e.createElementVNode("h4",yA,e.toDisplayString(g.value.metadataTitle),1),j.value&&!d.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button","data-testid":"btn-media-inspector-metadata-edit",onClick:ue},e.toDisplayString(g.value.metadataEdit),1)):e.createCommentVNode("",!0)]),z.value?(e.openBlock(),e.createElementBlock("p",wA,[e.createElementVNode("strong",null,e.toDisplayString(g.value.missingAltTitle),1),e.createElementVNode("span",null,e.toDisplayString(g.value.missingAltDescription),1)])):e.createCommentVNode("",!0),d.value?(e.openBlock(),e.createElementBlock("form",{key:1,class:"media-inspector-panel__metadata-form",onSubmit:e.withModifiers(Z,["prevent"])},[e.createElementVNode("label",kA,[e.createElementVNode("span",null,e.toDisplayString(g.value.caption),1),e.withDirectives(e.createElementVNode("textarea",{"onUpdate:modelValue":F[1]||(F[1]=J=>c.value=J),"data-testid":"textarea-media-inspector-caption",rows:"3"},null,512),[[e.vModelText,c.value]])]),e.createElementVNode("label",_A,[e.createElementVNode("span",null,e.toDisplayString(g.value.altText),1),e.withDirectives(e.createElementVNode("textarea",{"onUpdate:modelValue":F[2]||(F[2]=J=>u.value=J),"data-testid":"textarea-media-inspector-alt-text",rows:"3",disabled:m.value,"aria-describedby":"media-inspector-decorative-help"},null,8,EA),[[e.vModelText,u.value]])]),e.createElementVNode("label",SA,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":F[3]||(F[3]=J=>m.value=J),type:"checkbox","data-testid":"checkbox-media-inspector-decorative","aria-describedby":"media-inspector-decorative-help"},null,512),[[e.vModelCheckbox,m.value]]),e.createElementVNode("span",null,e.toDisplayString(g.value.decorative),1)]),e.createElementVNode("p",CA,e.toDisplayString(g.value.decorativeHelp),1),e.createElementVNode("label",xA,[e.createElementVNode("span",null,e.toDisplayString(g.value.tags),1),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":F[4]||(F[4]=J=>p.value=J),type:"text","data-testid":"input-media-inspector-tags"},null,512),[[e.vModelText,p.value]])]),f.value?(e.openBlock(),e.createElementBlock("p",NA,e.toDisplayString(f.value),1)):e.createCommentVNode("",!0),e.createElementVNode("div",VA,[e.createElementVNode("button",{type:"submit","data-testid":"btn-media-inspector-metadata-save",disabled:C.value,onClick:e.withModifiers(Z,["prevent"])},e.toDisplayString(g.value.saveMetadata),9,TA),e.createElementVNode("button",{type:"button","data-testid":"btn-media-inspector-metadata-cancel",disabled:C.value,onClick:le},e.toDisplayString(g.value.cancelMetadata),9,BA)])],32)):(e.openBlock(),e.createElementBlock("div",MA,[e.createElementVNode("dl",null,[e.createElementVNode("div",null,[e.createElementVNode("dt",null,e.toDisplayString(g.value.caption),1),e.createElementVNode("dd",null,e.toDisplayString(I.value.caption||"None"),1)]),e.createElementVNode("div",null,[e.createElementVNode("dt",null,e.toDisplayString(g.value.altText),1),e.createElementVNode("dd",null,e.toDisplayString(I.value.alt_text||"None"),1)]),e.createElementVNode("div",null,[e.createElementVNode("dt",null,e.toDisplayString(g.value.decorative),1),e.createElementVNode("dd",null,e.toDisplayString(I.value.is_decorative===!0?"Yes":"No"),1)]),e.createElementVNode("div",null,[e.createElementVNode("dt",null,e.toDisplayString(g.value.tags),1),e.createElementVNode("dd",null,e.toDisplayString(A.value||"None"),1)])]),h.value?(e.openBlock(),e.createElementBlock("p",IA,e.toDisplayString(h.value),1)):e.createCommentVNode("",!0)]))]),e.createVNode(Zf,{media:I.value,"http-client":t.httpClient},null,8,["media","http-client"]),e.createVNode(Gf,{media:I.value,"http-client":t.httpClient},null,8,["media","http-client"]),e.createElementVNode("div",$A,[$.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button","data-testid":"btn-media-inspector-edit","aria-label":g.value.edit,onClick:F[5]||(F[5]=J=>n("edit",I.value))},e.toDisplayString(g.value.edit),9,FA)):e.createCommentVNode("",!0),N.value?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button","data-testid":"btn-media-inspector-replace","aria-label":g.value.replace,onClick:F[6]||(F[6]=J=>n("replace",I.value))},e.toDisplayString(g.value.replace),9,DA)):e.createCommentVNode("",!0),B.value?(e.openBlock(),e.createElementBlock("button",{key:2,type:"button","data-testid":"btn-media-inspector-download","aria-label":g.value.download,onClick:F[7]||(F[7]=J=>n("download",I.value))},e.toDisplayString(g.value.download),9,AA)):e.createCommentVNode("",!0),t.capabilities.allowVisibilityChange?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button","data-testid":"btn-media-inspector-visibility","aria-label":g.value.setVisibility,onClick:F[8]||(F[8]=J=>n("set-visibility",I.value))},e.toDisplayString(g.value.setVisibility),9,RA)):e.createCommentVNode("",!0),t.inAlbumScope?(e.openBlock(),e.createElementBlock("button",{key:4,type:"button","data-testid":"btn-set-as-album-cover","aria-label":g.value.setAsAlbumCover,onClick:F[9]||(F[9]=J=>n("set-as-album-cover",I.value))},e.toDisplayString(g.value.setAsAlbumCover),9,LA)):e.createCommentVNode("",!0),t.inAlbumScope?(e.openBlock(),e.createElementBlock("button",{key:5,type:"button","data-testid":"btn-media-inspector-remove-current-album","aria-label":g.value.removeFromThisAlbum,onClick:F[10]||(F[10]=J=>n("remove-from-this-album",I.value))},e.toDisplayString(g.value.removeFromThisAlbum),9,PA)):e.createCommentVNode("",!0),x.value?(e.openBlock(),e.createElementBlock("button",{key:6,type:"button","data-testid":"btn-media-inspector-album-membership","aria-label":g.value.removeFromAlbums,onClick:F[11]||(F[11]=J=>n("remove-from-albums",I.value))},e.toDisplayString(g.value.removeFromAlbums),9,UA)):e.createCommentVNode("",!0),P.value?(e.openBlock(),e.createElementBlock("button",{key:7,type:"button","data-testid":"btn-media-inspector-trash","aria-label":g.value.moveToTrash,onClick:F[12]||(F[12]=J=>n("move-to-trash",I.value))},e.toDisplayString(g.value.moveToTrash),9,OA)):e.createCommentVNode("",!0)])],64)):((W=t.target)==null?void 0:W.kind)==="multi"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[e.createElementVNode("h3",{id:"media-inspector-heading",ref_key:"headingRef",ref:r,tabindex:"-1"},e.toDisplayString(g.value.multiTitle(t.target.count)),513),e.createElementVNode("div",zA,[M.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button","data-testid":"btn-media-inspector-bulk-add-album","aria-label":g.value.addToAlbum,onClick:F[13]||(F[13]=J=>n("bulk-add-to-album"))},e.toDisplayString(g.value.addToAlbum),9,jA)):e.createCommentVNode("",!0),M.value?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button","data-testid":"btn-media-inspector-bulk-create-album","aria-label":g.value.createAlbum,onClick:F[14]||(F[14]=J=>n("bulk-create-album"))},e.toDisplayString(g.value.createAlbum),9,WA)):e.createCommentVNode("",!0),E.value?(e.openBlock(),e.createElementBlock("button",{key:2,type:"button","data-testid":"btn-media-inspector-bulk-trash","aria-label":g.value.moveToTrash,onClick:F[15]||(F[15]=J=>n("bulk-move-to-trash"))},e.toDisplayString(g.value.moveToTrash),9,HA)):e.createCommentVNode("",!0),D.value?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button","data-testid":"btn-media-inspector-bulk-download","aria-label":g.value.download,onClick:F[16]||(F[16]=J=>n("bulk-download"))},e.toDisplayString(g.value.download),9,ZA)):e.createCommentVNode("",!0)])],64)):(e.openBlock(),e.createElementBlock("p",GA,e.toDisplayString(g.value.emptyTitle),1))],40,dA)}}}),qf=Ae(XA,[["__scopeId","data-v-f6d70239"]]),KA={class:"media-filter-chips__scroll"},qA={key:0,class:"media-filter-chips__chip media-filter-chips__chip--scope","data-testid":"media-filter-scope-chip"},JA=["data-testid","aria-label","onClick"],YA={class:"media-filter-chips__add-wrap"},QA=["aria-controls","aria-expanded"],eR=["id","aria-label"],tR=["placeholder","aria-label"],aR={class:"media-filter-chips__search-actions"},nR={type:"submit",class:"media-filter-chips__search-button","data-testid":"btn-media-filter-query-apply"},oR=e.defineComponent({__name:"MediaFilterChips",props:{filters:{},scopeLabel:{default:""},labels:{default:()=>({})}},emits:["update:filters","change","clear"],setup(o,{emit:a}){var z;const t=o,n=a,i=e.ref(!1),r=e.ref(((z=t.filters.query)==null?void 0:z.trim())??""),l=e.ref(null),s=e.ref(null),d=e.ref(null),c=e.useId(),u=e.computed(()=>{var C,A,O,K,se,xe,ue,le,Z,k,F,W,J,ce,Ue,be,_e,ye,Ne,Se,Re;return{addFilter:((C=t.labels)==null?void 0:C.addFilter)??"Filter",clearAll:((A=t.labels)==null?void 0:A.clearAll)??"Clear all filters",typeLabel:((O=t.labels)==null?void 0:O.typeLabel)??"Type",usageLabel:((K=t.labels)==null?void 0:K.usageLabel)??"Usage",metadataLabel:((se=t.labels)==null?void 0:se.metadataLabel)??"Metadata",imageLabel:((xe=t.labels)==null?void 0:xe.imageLabel)??"Image",videoLabel:((ue=t.labels)==null?void 0:ue.videoLabel)??"Video",usedLabel:((le=t.labels)==null?void 0:le.usedLabel)??"Used",notUsedLabel:((Z=t.labels)==null?void 0:Z.notUsedLabel)??"Not used",missingAltLabel:((k=t.labels)==null?void 0:k.missingAltLabel)??"Missing alt text",hasAltLabel:((F=t.labels)==null?void 0:F.hasAltLabel)??"Has alt text",missingCaptionLabel:((W=t.labels)==null?void 0:W.missingCaptionLabel)??"Missing caption",hasCaptionLabel:((J=t.labels)==null?void 0:J.hasCaptionLabel)??"Has caption",hasTagsLabel:((ce=t.labels)==null?void 0:ce.hasTagsLabel)??"Has tags",decorativeLabel:((Ue=t.labels)==null?void 0:Ue.decorativeLabel)??"Decorative",dateAfterLabel:((be=t.labels)==null?void 0:be.dateAfterLabel)??"After",dateBeforeLabel:((_e=t.labels)==null?void 0:_e.dateBeforeLabel)??"Before",searchLabel:((ye=t.labels)==null?void 0:ye.searchLabel)??"Search",searchPlaceholder:((Ne=t.labels)==null?void 0:Ne.searchPlaceholder)??"Search media",applySearch:((Se=t.labels)==null?void 0:Se.applySearch)??"Apply",clearSearch:((Re=t.labels)==null?void 0:Re.clearSearch)??"Clear"}});e.watch(()=>t.filters.query,C=>{r.value=(C==null?void 0:C.trim())??""});function m(){return{...t.filters,...t.filters.kinds!==void 0?{kinds:[...t.filters.kinds]}:{},...t.filters.selected_uuids!==void 0?{selected_uuids:[...t.filters.selected_uuids]}:{}}}function p(C){n("update:filters",C),n("change",C)}function f(C){const A=m(),O=(A.kinds??[]).filter(K=>K!==C);O.length>0?A.kinds=O:delete A.kinds,p(A)}function h(C){const A=m(),O=new Set(A.kinds??[]);O.add(C),A.kinds=Array.from(O),p(A),g(!0)}function v(){const C=m();delete C.usage_status,p(C)}function y(C){const A=m();A.usage_status=C,p(A),g(!0)}function w(C){const A=u.value;return{missing_alt:A.missingAltLabel,has_alt:A.hasAltLabel,missing_caption:A.missingCaptionLabel,has_caption:A.hasCaptionLabel,has_tags:A.hasTagsLabel,decorative:A.decorativeLabel}[C]}function _(){const C=m();delete C.metadata_status,p(C)}function b(C){const A=m();A.metadata_status=C,p(A),g(!0)}function g(C=!1){i.value&&(i.value=!1,C&&e.nextTick(()=>fa(s.value)))}function I(){var C;i.value=!0,r.value=((C=t.filters.query)==null?void 0:C.trim())??"",e.nextTick(()=>fa(d.value))}function T(){if(i.value){g(!0);return}I()}function $(){const C=m(),A=r.value.trim();A===""?delete C.query:C.query=A,p(C),g(!0)}function N(){const C=m();delete C.query,r.value="",p(C),g(!0)}function B(C){const A=new Date;return A.setHours(0,0,0,0),A.setDate(A.getDate()-C),A.toISOString()}function P(){const C=new Date;return new Date(C.getFullYear(),0,1).toISOString()}function x(C,A=null){const O=m();C===null?delete O.created_after:O.created_after=C,A===null?delete O.created_before:O.created_before=A,p(O),g(!0)}function M(C){const A=m();delete A[C],p(A)}function E(){p({sort:t.filters.sort??"newest"}),n("clear")}function D(C){if(!i.value)return;const A=l.value;A!==null&&(C.target instanceof Node&&A.contains(C.target)||g(!1))}function j(C){!i.value||C.key!=="Escape"||(C.preventDefault(),g(!0))}e.onMounted(()=>{document.addEventListener("pointerdown",D,!0),document.addEventListener("keydown",j)}),e.onBeforeUnmount(()=>{document.removeEventListener("pointerdown",D,!0),document.removeEventListener("keydown",j)});const L=e.computed(()=>{const C=[];for(const A of t.filters.kinds??[]){const O=A==="image"?u.value.imageLabel:A==="video"?u.value.videoLabel:String(A);C.push({key:`kind-${A}`,label:`${u.value.typeLabel}: ${O}`,remove:()=>f(A)})}return(t.filters.usage_status==="used"||t.filters.usage_status==="not_used")&&C.push({key:"usage",label:`${u.value.usageLabel}: ${t.filters.usage_status==="used"?u.value.usedLabel:u.value.notUsedLabel}`,remove:v}),t.filters.metadata_status&&C.push({key:"metadata-status",label:`${u.value.metadataLabel}: ${w(t.filters.metadata_status)}`,remove:_}),t.filters.created_after&&C.push({key:"created-after",label:`${u.value.dateAfterLabel}: ${t.filters.created_after}`,remove:()=>M("created_after")}),t.filters.created_before&&C.push({key:"created-before",label:`${u.value.dateBeforeLabel}: ${t.filters.created_before}`,remove:()=>M("created_before")}),t.filters.query&&t.filters.query.trim()!==""&&C.push({key:"query",label:`${u.value.searchLabel}: "${t.filters.query.trim()}"`,remove:()=>M("query")}),C});return(C,A)=>(e.openBlock(),e.createElementBlock("div",{ref_key:"rootRef",ref:l,class:"media-filter-chips","data-testid":"media-filter-chips"},[e.createElementVNode("div",KA,[t.scopeLabel!==""?(e.openBlock(),e.createElementBlock("span",qA,e.toDisplayString(t.scopeLabel),1)):e.createCommentVNode("",!0),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(L.value,O=>(e.openBlock(),e.createElementBlock("button",{key:O.key,type:"button",class:"media-filter-chips__chip","data-testid":`media-filter-chip-${O.key}`,"aria-label":`Remove filter ${O.label}`,onClick:O.remove},[e.createElementVNode("span",null,e.toDisplayString(O.label),1),A[14]||(A[14]=e.createElementVNode("span",{"aria-hidden":"true"},"×",-1))],8,JA))),128)),L.value.length>=2?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",class:"media-filter-chips__clear","data-testid":"btn-media-filter-clear-all",onClick:E},e.toDisplayString(u.value.clearAll),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",YA,[e.createElementVNode("button",{ref_key:"triggerRef",ref:s,type:"button",class:"media-filter-chips__add","data-testid":"btn-media-filter-add","aria-haspopup":"dialog","aria-controls":e.unref(c),"aria-expanded":i.value?"true":"false",onClick:T}," + "+e.toDisplayString(u.value.addFilter),9,QA),i.value?(e.openBlock(),e.createElementBlock("div",{key:0,id:e.unref(c),class:"media-filter-chips__menu","data-testid":"media-filter-menu",role:"dialog","aria-label":u.value.addFilter},[e.createElementVNode("form",{class:"media-filter-chips__search","data-testid":"media-filter-query-form",onSubmit:e.withModifiers($,["prevent"])},[e.withDirectives(e.createElementVNode("input",{ref_key:"queryInputRef",ref:d,"onUpdate:modelValue":A[0]||(A[0]=O=>r.value=O),type:"search",class:"media-filter-chips__search-input","data-testid":"input-media-filter-query",placeholder:u.value.searchPlaceholder,"aria-label":u.value.searchPlaceholder},null,8,tR),[[e.vModelText,r.value]]),e.createElementVNode("div",aR,[e.createElementVNode("button",nR,e.toDisplayString(u.value.applySearch),1),e.createElementVNode("button",{type:"button",class:"media-filter-chips__search-button media-filter-chips__search-button--muted","data-testid":"btn-media-filter-query-clear",onClick:N},e.toDisplayString(u.value.clearSearch),1)])],32),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-image",onClick:A[1]||(A[1]=O=>h("image"))},e.toDisplayString(u.value.typeLabel)+": "+e.toDisplayString(u.value.imageLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-video",onClick:A[2]||(A[2]=O=>h("video"))},e.toDisplayString(u.value.typeLabel)+": "+e.toDisplayString(u.value.videoLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-used",onClick:A[3]||(A[3]=O=>y("used"))},e.toDisplayString(u.value.usageLabel)+": "+e.toDisplayString(u.value.usedLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-not-used",onClick:A[4]||(A[4]=O=>y("not_used"))},e.toDisplayString(u.value.usageLabel)+": "+e.toDisplayString(u.value.notUsedLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-missing-alt",onClick:A[5]||(A[5]=O=>b("missing_alt"))},e.toDisplayString(u.value.metadataLabel)+": "+e.toDisplayString(u.value.missingAltLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-has-alt",onClick:A[6]||(A[6]=O=>b("has_alt"))},e.toDisplayString(u.value.metadataLabel)+": "+e.toDisplayString(u.value.hasAltLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-missing-caption",onClick:A[7]||(A[7]=O=>b("missing_caption"))},e.toDisplayString(u.value.metadataLabel)+": "+e.toDisplayString(u.value.missingCaptionLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-has-caption",onClick:A[8]||(A[8]=O=>b("has_caption"))},e.toDisplayString(u.value.metadataLabel)+": "+e.toDisplayString(u.value.hasCaptionLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-has-tags",onClick:A[9]||(A[9]=O=>b("has_tags"))},e.toDisplayString(u.value.metadataLabel)+": "+e.toDisplayString(u.value.hasTagsLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-decorative",onClick:A[10]||(A[10]=O=>b("decorative"))},e.toDisplayString(u.value.metadataLabel)+": "+e.toDisplayString(u.value.decorativeLabel),1),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-date-7d",onClick:A[11]||(A[11]=O=>x(B(7)))},"Date: Last 7 days"),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-date-30d",onClick:A[12]||(A[12]=O=>x(B(30)))},"Date: Last 30 days"),e.createElementVNode("button",{type:"button","data-testid":"opt-filter-date-year",onClick:A[13]||(A[13]=O=>x(P()))},"Date: This year")],8,eR)):e.createCommentVNode("",!0)])],512))}}),Jf=Ae(oR,[["__scopeId","data-v-42cb25b6"]]);class Wl extends Error{constructor(a,t="Media deletion requires explicit confirmation."){super(t),this.name="RequiresConfirmationError",this.softBlocks=a}}const iR="/v1/media/deletion/check",rR="/v1/media/deletion/delete",Mr=100;function em(o){const a=new Set,t=[];for(const n of o){const i=n.trim().toLowerCase();i===""||a.has(i)||(a.add(i),t.push(i))}return t.sort()}function Jd(o){const a=o.checkEndpoint??iR,t=o.deleteEndpoint??rR,n=e.ref(!1),i=e.ref(!1),r=e.ref(null),l=e.ref(null),s=e.ref(null);async function d(f){s.value=null;const h=em(f);if(h.length===0)return r.value=[],[];if(h.length>Mr){const v=new Error(`Cannot check more than ${Mr} media items at once.`);throw s.value=v,v}n.value=!0;try{const v=await o.httpClient.post(a,{uuids:h}),y=((v==null?void 0:v.data)??[]).map(w=>{var _,b,g,I;return{uuid:w.uuid,canDelete:((_=w.report)==null?void 0:_.canDelete)??!1,blocks:Array.isArray((b=w.report)==null?void 0:b.blocks)?w.report.blocks:[],cascade:Array.isArray((g=w.report)==null?void 0:g.cascade)?w.report.cascade:[],variantCount:typeof((I=w.report)==null?void 0:I.variantCount)=="number"?w.report.variantCount:0}});return r.value=y,y}catch(v){throw s.value=v instanceof Error?v:new Error(String(v)),s.value}finally{n.value=!1}}async function c(f,h={}){s.value=null;const v=em(f);if(v.length===0){const y={results:[],summary:{}};return l.value=y,y}if(v.length>Mr){const y=new Error(`Cannot delete more than ${Mr} media items at once.`);throw s.value=y,y}i.value=!0;try{const y=await o.httpClient.post(t,{uuids:v,force:h.force===!0,confirmed:h.confirmed===!0}),w={results:Array.isArray(y==null?void 0:y.results)?y.results:[],summary:(y==null?void 0:y.summary)??{}};return l.value=w,w}catch(y){const w=u(y);if(w&&w.requires_confirmation===!0){const _=m(w.soft_blocks),b=new Wl(_);throw s.value=b,b}throw s.value=y instanceof Error?y:new Error(String(y)),s.value}finally{i.value=!1}}function u(f){if(typeof f!="object"||f===null)return null;const h=f;if(h.response&&typeof h.response=="object"&&h.response.data&&typeof h.response.data=="object")return h.response.data;const v=f;return"requires_confirmation"in v||"soft_blocks"in v?v:null}function m(f){if(typeof f!="object"||f===null)return{};const h={};for(const[v,y]of Object.entries(f)){if(!Array.isArray(y))continue;const w=[];for(const _ of y){if(typeof _!="object"||_===null)continue;const b=_;typeof b.type=="string"&&typeof b.context=="string"&&w.push({type:b.type,context:b.context})}h[v]=w}return h}function p(){r.value=null,l.value=null,s.value=null}return{isChecking:n,isDeleting:i,lastReport:r,lastResponse:l,error:s,checkDependencies:d,deleteMany:c,reset:p}}const lR="/v1/user/media/trash";function sR(o){return`/v1/user/media/${encodeURIComponent(o)}/restore`}function dR(o){return`/v1/user/media/${encodeURIComponent(o)}/purge`}function Yd(o){const a=o.listEndpoint??lR,t=o.buildRestoreEndpoint??sR,n=o.buildPurgeEndpoint??dR,i=o.perPage??50,r=e.ref([]),l=e.ref(0),s=e.ref(1),d=e.ref(!1),c=e.ref(!1),u=e.ref(!1),m=e.ref(null);async function p(y=1){var w,_;m.value=null,d.value=!0;try{const b=await o.httpClient.get(a,{params:{page:y,per_page:i}});r.value=Array.isArray(b==null?void 0:b.data)?b.data:[],l.value=typeof((w=b==null?void 0:b.meta)==null?void 0:w.total)=="number"?b.meta.total:0,s.value=typeof((_=b==null?void 0:b.meta)==null?void 0:_.current_page)=="number"?b.meta.current_page:y}catch(b){throw m.value=b instanceof Error?b:new Error(String(b)),m.value}finally{d.value=!1}}async function f(y){m.value=null,c.value=!0;try{const w=await o.httpClient.post(t(y)),_={status:(w==null?void 0:w.status)??"failed",data:(w==null?void 0:w.data)??null,duplicate_uuid:(w==null?void 0:w.duplicate_uuid)??null};return typeof(w==null?void 0:w.message)=="string"&&(_.message=w.message),_.status==="restored"&&(r.value=r.value.filter(b=>b.uuid!==y),l.value=Math.max(0,l.value-1)),_}catch(w){const _=tm(w);if(_&&typeof _.status=="string"){const b={status:_.status,duplicate_uuid:typeof _.duplicate_uuid=="string"?_.duplicate_uuid:null};return typeof _.message=="string"&&(b.message=_.message),b}throw m.value=w instanceof Error?w:new Error(String(w)),m.value}finally{c.value=!1}}async function h(y){m.value=null,u.value=!0;try{if(typeof o.httpClient.delete!="function")throw new Error("Media trash purge requires an HTTP client with delete support.");const w=await o.httpClient.delete(n(y)),_={status:(w==null?void 0:w.status)??"failed"};return typeof(w==null?void 0:w.message)=="string"&&(_.message=w.message),_.status==="purging"&&(r.value=r.value.filter(b=>b.uuid!==y),l.value=Math.max(0,l.value-1)),_}catch(w){const _=tm(w);if(_&&typeof _.status=="string"){const b={status:_.status};return typeof _.message=="string"&&(b.message=_.message),b}throw m.value=w instanceof Error?w:new Error(String(w)),m.value}finally{u.value=!1}}function v(){r.value=[],l.value=0,s.value=1,m.value=null}return{items:r,total:l,currentPage:s,isLoading:d,isRestoring:c,isPurging:u,error:m,fetch:p,restore:f,purge:h,reset:v}}function tm(o){var t;if(typeof o!="object"||o===null)return null;const a=o;return(t=a.response)!=null&&t.data&&typeof a.response.data=="object"?a.response.data:null}const cR={class:"media-management-view","data-testid":"media-management-view"},uR={key:0,class:"media-management-view__header"},mR={class:"media-management-view__title"},pR={class:"media-management-view__actions"},fR={key:0,class:"media-management-view__badge"},hR={key:1,class:"media-management-view__panel","data-testid":"panel-library"},vR={key:0,class:"media-management-view__view-mode",role:"radiogroup","aria-label":"Media library layout","data-testid":"media-management-layout-mode"},gR=["aria-checked"],bR=["aria-checked"],yR={key:1,class:"media-management-view__status","data-testid":"library-loading"},wR={key:2,class:"media-management-view__status media-management-view__status--error","data-testid":"library-error"},kR={key:3,class:"media-management-view__empty","data-testid":"library-empty"},_R={class:"media-management-view__empty-state"},ER={class:"media-management-view__empty-title","data-testid":"library-empty-title"},SR={class:"media-management-view__empty-description","data-testid":"library-empty-description"},CR={key:4,class:"media-management-view__table","data-testid":"library-table"},xR={scope:"col","data-testid":"table-header-select"},NR={class:"media-management-view__checkbox-label"},VR=["checked",".indeterminate","aria-label"],TR={class:"media-management-view__sr-only"},BR={scope:"col","data-testid":"table-header-thumbnail"},MR={scope:"col","data-testid":"table-header-name"},IR={scope:"col","data-testid":"table-header-type"},$R={scope:"col","data-testid":"table-header-created"},FR={scope:"col","data-testid":"table-header-size"},DR={scope:"col","data-testid":"table-header-status"},AR={scope:"col","data-testid":"table-header-actions"},RR=["data-testid"],LR={class:"media-management-view__checkbox-label"},PR=["checked","aria-label","data-testid","onChange"],UR=["data-testid","onClick"],OR=["src","alt","onError"],zR=["data-testid"],jR=["title","data-testid"],WR=["data-testid"],HR=["data-testid"],ZR={class:"media-management-view__item-actions"},GR=["onKeydown"],XR=["data-testid","aria-label","aria-expanded","onClick"],KR=["data-testid"],qR=["data-testid","onClick"],JR={key:5,class:"media-management-view__grid","data-testid":"library-grid"},YR=["data-testid"],QR=["data-testid","aria-pressed","onClick"],eL=["src","alt","onError"],tL=["data-testid"],aL={class:"media-management-view__selection-corner"},nL={class:"media-management-view__sr-only"},oL=["checked","data-testid","onChange"],iL={class:"media-management-view__item-meta"},rL=["title","data-testid"],lL=["data-testid"],sL=["data-testid"],dL={key:2,class:"media-management-view__item-badge","data-testid":"badge-orphaned"},cL=["data-testid"],uL={class:"media-management-view__item-actions media-management-view__item-actions--grid"},mL=["onKeydown"],pL=["data-testid","aria-label","aria-expanded","onClick"],fL=["data-testid"],hL=["data-testid","onClick"],vL={class:"media-management-view__bulk-bar","data-testid":"bulk-bar"},gL={"data-testid":"bulk-count"},bL=["disabled"],yL={key:7,class:"media-management-view__pagination","data-testid":"media-management-pagination"},wL={class:"media-management-view__pagination-count","data-testid":"media-management-pagination-count","aria-live":"polite"},kL={key:0,class:"media-management-view__page-size",role:"group","aria-label":"Items per page","data-testid":"media-management-page-size"},_L=["value","disabled"],EL=["value","data-testid"],SL=["disabled"],CL={key:2,class:"media-management-view__page-bar","aria-label":"Media library pagination","data-testid":"media-management-page-bar"},xL=["disabled"],NL=["data-testid","disabled","aria-current","aria-label","onClick"],VL=["disabled"],TL={key:2,class:"media-management-view__panel","data-testid":"panel-trash"},BL={key:0,class:"media-management-view__status","data-testid":"trash-loading"},ML={key:1,class:"media-management-view__empty","data-testid":"trash-empty"},IL={class:"media-management-view__empty-state"},$L={class:"media-management-view__empty-title","data-testid":"trash-empty-title"},FL={class:"media-management-view__empty-description","data-testid":"trash-empty-description"},DL={key:2,class:"media-management-view__grid","data-testid":"trash-grid"},AL=["data-testid"],RL={class:"media-management-view__item-thumb"},LL=["src","alt","onError"],PL=["data-testid"],UL={class:"media-management-view__item-meta"},OL={class:"media-management-view__item-name"},zL={key:0,class:"media-management-view__item-meta-line"},jL=["data-testid","disabled","onClick"],WL=["data-testid"],HL=e.defineComponent({__name:"MediaManagementView",props:{httpClient:{},capabilities:{default:()=>({})},labels:{default:()=>({})},filters:{},initialView:{},perPage:{},pageSizeOptions:{default:()=>[]},showAllOption:{type:Boolean,default:!1},loadAllMaxItems:{},paginated:{type:Boolean,default:!1},groupVariants:{type:Boolean,default:!0},paginationWindow:{default:7},initialLayoutMode:{},layoutMode:{},confirmBulkDelete:{},confirmDestructiveAction:{},onRestoreCollision:{}},emits:["deleted","restored","restore-conflict","create-post","create-gallery","add-to-album","edit","update:layoutMode","error"],setup(o,{expose:a,emit:t}){const n=o,i=t,r=e.computed(()=>({showTrash:!0,showHeader:!0,showLayoutSwitcher:!0,allowBulkDelete:!0,allowPreview:!0,allowCreatePost:!1,allowCreateGallery:!1,allowAddToAlbum:!1,allowImageEdit:!1,allowVideoEdit:!1,showOwner:!1,showRawFileName:!1,...n.capabilities})),l=e.computed(()=>{var q,ke,oe,$e,At,zt,Ft,wt,yt,Yt,Et,Kt,Ca,X,Y,fe,he,Te,Ke,ct,tt,qe,vt,gt,ot,Qt,Rt,Za,ha,Cn,Ta,xa,Aa,va,Qa,On,Ga,zn,ga;return{title:((q=n.labels)==null?void 0:q.title)??"My Media",libraryTab:((ke=n.labels)==null?void 0:ke.libraryTab)??"Library",trashTab:((oe=n.labels)==null?void 0:oe.trashTab)??"Trash",loading:(($e=n.labels)==null?void 0:$e.loading)??"Loading…",emptyLibrary:((At=n.labels)==null?void 0:At.emptyLibrary)??"No media yet — upload your first creation.",emptyLibraryTitle:((zt=n.labels)==null?void 0:zt.emptyLibraryTitle)??"Your media library is ready",emptyLibraryDescription:((Ft=n.labels)==null?void 0:Ft.emptyLibraryDescription)??"Images and videos you upload for creations are saved here so you can reuse them later.",emptyTrash:((wt=n.labels)==null?void 0:wt.emptyTrash)??"Trash is empty.",emptyTrashTitle:((yt=n.labels)==null?void 0:yt.emptyTrashTitle)??"No media in trash",emptyTrashDescription:((Yt=n.labels)==null?void 0:Yt.emptyTrashDescription)??"Deleted files appear here for 30 days before permanent removal.",orphanedBadge:((Et=n.labels)==null?void 0:Et.orphanedBadge)??"Not in use",selectedCount:((Kt=n.labels)==null?void 0:Kt.selectedCount)??(Ra=>`${Ra} selected`),deleteButton:((Ca=n.labels)==null?void 0:Ca.deleteButton)??"Delete",createPostButton:((X=n.labels)==null?void 0:X.createPostButton)??"Create Post",createGalleryButton:((Y=n.labels)==null?void 0:Y.createGalleryButton)??"Create Gallery",addToAlbumButton:((fe=n.labels)==null?void 0:fe.addToAlbumButton)??"Add to Album",previewButton:((he=n.labels)==null?void 0:he.previewButton)??"Preview",previewCloseButton:((Te=n.labels)==null?void 0:Te.previewCloseButton)??"Close",previewPreviousButton:((Ke=n.labels)==null?void 0:Ke.previewPreviousButton)??"Previous",previewNextButton:((ct=n.labels)==null?void 0:ct.previewNextButton)??"Next",previewSelectButton:((tt=n.labels)==null?void 0:tt.previewSelectButton)??"Select",previewDeselectButton:((qe=n.labels)==null?void 0:qe.previewDeselectButton)??"Deselect",editButton:((vt=n.labels)==null?void 0:vt.editButton)??"Edit",loadMoreButton:((gt=n.labels)==null?void 0:gt.loadMoreButton)??"Load more",loadingMoreButton:((ot=n.labels)==null?void 0:ot.loadingMoreButton)??"Loading more...",restoreButton:((Qt=n.labels)==null?void 0:Qt.restoreButton)??"Restore",restoreUnavailable:((Rt=n.labels)==null?void 0:Rt.restoreUnavailable)??"Restore unavailable",gridView:((Za=n.labels)==null?void 0:Za.gridView)??"Grid",tableView:((ha=n.labels)==null?void 0:ha.tableView)??"Table",tableSelectHeader:((Cn=n.labels)==null?void 0:Cn.tableSelectHeader)??"Select",tableThumbnailHeader:((Ta=n.labels)==null?void 0:Ta.tableThumbnailHeader)??"Preview",tableNameHeader:((xa=n.labels)==null?void 0:xa.tableNameHeader)??"Name",tableTypeHeader:((Aa=n.labels)==null?void 0:Aa.tableTypeHeader)??"Type",tableCreatedHeader:((va=n.labels)==null?void 0:va.tableCreatedHeader)??"Uploaded",tableSizeHeader:((Qa=n.labels)==null?void 0:Qa.tableSizeHeader)??"Size",tableStatusHeader:((On=n.labels)==null?void 0:On.tableStatusHeader)??"Status",tableActionsHeader:((Ga=n.labels)==null?void 0:Ga.tableActionsHeader)??"Actions",purgeAfter:((zn=n.labels)==null?void 0:zn.purgeAfter)??(Ra=>`Purges ${Ra}`),ownerLabel:((ga=n.labels)==null?void 0:ga.ownerLabel)??(Ra=>`User ${Ra.user_id??""}`)}}),s=e.computed(()=>l.value.title),d=e.computed(()=>l.value.libraryTab),c=e.computed(()=>l.value.trashTab),u=e.computed(()=>l.value.loading),m=e.computed(()=>l.value.emptyLibraryTitle),p=e.computed(()=>l.value.emptyLibraryDescription),f=e.computed(()=>l.value.emptyTrashTitle),h=e.computed(()=>l.value.emptyTrashDescription),v=e.computed(()=>l.value.orphanedBadge),y=e.computed(()=>l.value.deleteButton),w=e.computed(()=>l.value.restoreButton),_=e.computed(()=>l.value.restoreUnavailable),b=e.computed(()=>l.value.gridView),g=e.computed(()=>l.value.tableView);function I(q){const ke=r.value.canRestore;return ke?ke(q):!0}const T=e.ref("library"),$=e.ref(n.layoutMode??n.initialLayoutMode??"grid"),N=e.ref(null),B=e.ref(null);function P(q){return{...q??{},...(q==null?void 0:q.kinds)!==void 0?{kinds:[...q.kinds]}:{}}}const x=e.ref(n.initialView??{scope:"library"}),M=e.ref(P(n.filters)),E=e.ref(n.perPage??50),D=e.ref(!1),j=e.ref(n.paginated?1:null),L=Xd({httpClient:n.httpClient,view:x,filters:M,perPage:E,page:j}),z=e.computed(()=>n.groupVariants!==!0?L.items.value:L.items.value.filter(q=>typeof q.parent_media_uuid!="string"||q.parent_media_uuid.trim()==="")),C=e.computed(()=>L.loading.value),A=e.computed(()=>{var q;return((q=L.error.value)==null?void 0:q.message)??null}),O=e.computed(()=>r.value.allowBulkDelete!==!1||r.value.allowCreatePost===!0||r.value.allowCreateGallery===!0||r.value.allowAddToAlbum===!0),K=e.computed(()=>{const q=N.value;return q===null?null:z.value[q]??null}),se=fl(z),xe=Jd({httpClient:n.httpClient}),ue=Yd({httpClient:n.httpClient});function le(q){return l.value.selectedCount(q)}function Z(q){return l.value.purgeAfter(q)}function k(q){return l.value.ownerLabel(q)}const F=e.computed(()=>{const q=z.value.length;return q===0?"":L.hasMore.value?q===1?"Showing 1 item":`Showing ${q} items`:q===1?"Showing all 1 item":`Showing all ${q} items`});function W(q){$.value!==q&&(Ut(),$.value=q,i("update:layoutMode",q))}function J(q){return q.mime_type.startsWith("image/")}function ce(q){return q.mime_type.startsWith("video/")}function Ue(q){return J(q)?"image":ce(q)?"video":null}function be(q){return J(q)?r.value.allowImageEdit===!0:ce(q)?r.value.allowVideoEdit===!0:!1}const _e=Xf;function ye(q){return typeof q.variant_count=="number"&&Number.isFinite(q.variant_count)?Math.max(0,q.variant_count):0}function Ne(q){return q===1?"1 edit":`${q} edits`}function Se(q){return J(q)?"Image":ce(q)?"Video":q.mime_type.startsWith("audio/")?"Audio":"File"}function Re(q){if(typeof q.formatted_size=="string"&&q.formatted_size.trim()!=="")return q.formatted_size;if(!Number.isFinite(q.size)||q.size<=0)return"";const ke=["B","KB","MB","GB"];let oe=q.size,$e=0;for(;oe>=1024&&$e<ke.length-1;)oe/=1024,$e+=1;return`${oe>=10||$e===0?Math.round(oe):oe.toFixed(1)} ${ke[$e]}`}function Oe(q){const ke=new Date(q.created_at);return Number.isNaN(ke.getTime())?q.created_at:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(ke)}function it(q){return q.deletion_status==="active"||q.deletion_status===void 0||q.deletion_status===null?"Ready":q.deletion_status.replace(/_/g," ").replace(/\b\w/g,ke=>ke.toUpperCase())}function rt(q){if(typeof q.thumbnail_url=="string"&&q.thumbnail_url.length>0)return q.thumbnail_url;const ke=typeof q.mime_type=="string"&&q.mime_type.startsWith("image/"),oe=typeof q.mime_type=="string"&&q.mime_type.startsWith("video/");return ke?q.original_url||null:oe&&typeof q.preview_url=="string"&&q.preview_url.length>0?q.preview_url:null}function Pt(q){return typeof q.mime_type=="string"&&q.mime_type.startsWith("video/")?`Video — ${q.file_name}`:q.file_name}const bt=e.ref(new Set);function Ct(q){if(bt.value.has(q.uuid))return;const ke=new Set(bt.value);ke.add(q.uuid),bt.value=ke}function mt(q){if(r.value.allowPreview===!1)return;const ke=z.value.findIndex(oe=>oe.uuid===q.uuid);N.value=ke>=0?ke:null}function pt(){N.value=null}function Nt(){N.value===null||N.value<=0||(N.value-=1)}function Ce(){N.value===null||N.value>=z.value.length-1||(N.value+=1)}async function Ve(){try{await L.loadMore()}catch(q){i("error",q instanceof Error?q:new Error(String(q)))}}const Le=e.computed(()=>{const q=L.totalPages.value??0,ke=L.currentPage.value??1;if(q<=1)return[];const oe=Math.max(3,n.paginationWindow);if(q<=oe)return Array.from({length:q},(yt,Yt)=>({kind:"page",key:`p-${Yt+1}`,value:Yt+1}));const $e=oe-2,At=Math.floor($e/2);let zt=Math.max(2,ke-At),Ft=Math.min(q-1,zt+$e-1);Ft===q-1&&(zt=Math.max(2,Ft-$e+1));const wt=[{kind:"page",key:"p-1",value:1}];zt>2&&wt.push({kind:"ellipsis",key:"el-left"});for(let yt=zt;yt<=Ft;yt++)wt.push({kind:"page",key:`p-${yt}`,value:yt});return Ft<q-1&&wt.push({kind:"ellipsis",key:"el-right"}),wt.push({kind:"page",key:`p-${q}`,value:q}),wt});async function nt(q){if(!(q===L.currentPage.value||L.loading.value)){j.value=q;try{await L.goToPage(q)}catch(ke){i("error",ke instanceof Error?ke:new Error(String(ke)))}}}async function Ge(q){const ke=L.currentPage.value??1,oe=L.totalPages.value??1,$e=Math.min(Math.max(1,ke+q),oe);$e!==ke&&await nt($e)}const Je=e.computed(()=>{const q=n.pageSizeOptions.map(ke=>({value:String(ke),label:String(ke)}));return q.length===0&&!n.showAllOption?[]:(n.showAllOption&&q.push({value:"all",label:"All"}),q)}),_t=e.computed(()=>D.value?"all":String(E.value));async function ht(q){const ke=q.target;if(!(ke instanceof HTMLSelectElement))return;const oe=ke.value;try{if(oe==="all"){const $e=n.pageSizeOptions,At=$e.length>0?Math.max(...$e):E.value;j.value=null,E.value=At,D.value=!1,await L.refresh();const zt=n.loadAllMaxItems!==void 0?{maxItems:n.loadAllMaxItems}:void 0;await L.loadAll(zt),D.value=!L.hasMore.value}else{const $e=Number.parseInt(oe,10);Number.isFinite($e)&&$e>0&&(E.value=$e),D.value=!1,n.paginated&&(j.value=1),await L.refresh()}}catch($e){i("error",$e instanceof Error?$e:new Error(String($e)))}}function Wt(q,ke){i("create-post",{mediaIds:q.map(oe=>oe.uuid),items:q,source:ke})}function Pe(q,ke){i("create-gallery",{mediaIds:q.map(oe=>oe.uuid),items:q,source:ke})}function Ht(q,ke){i("add-to-album",{mediaIds:q.map(oe=>oe.uuid),items:q,source:ke})}function Zt(q){const ke=Ue(q);ke===null||!be(q)||i("edit",{media:q,kind:ke})}function It(q){B.value=B.value===q?null:q}function Ut(){B.value=null}function Gt(q){q.run(),Ut()}function sa(q){const ke=[];return r.value.allowPreview!==!1&&ke.push({id:"preview",label:l.value.previewButton,testId:`btn-preview-${q.uuid}`,run:()=>mt(q)}),be(q)&&ke.push({id:"edit",label:l.value.editButton,testId:`btn-edit-${q.uuid}`,run:()=>Zt(q)}),r.value.allowCreatePost===!0&&ke.push({id:"create-post",label:l.value.createPostButton,testId:`btn-create-post-${q.uuid}`,run:()=>Wt([q],"item")}),r.value.allowCreateGallery===!0&&ke.push({id:"create-gallery",label:l.value.createGalleryButton,testId:`btn-create-gallery-${q.uuid}`,run:()=>Pe([q],"item")}),r.value.allowAddToAlbum===!0&&ke.push({id:"add-to-album",label:l.value.addToAlbumButton,testId:`btn-add-to-album-${q.uuid}`,run:()=>Ht([q],"item")}),ke}async function ae(q){const ke=q.results.filter(oe=>oe.status==="trashed"||oe.status==="already_trashed").map(oe=>oe.uuid);if(ke.length!==0){for(const oe of ke)se.deselect(oe);i("deleted",ke),await L.refresh(),r.value.showTrash!==!1&&await ue.fetch(ue.currentPage.value).catch(()=>{})}}function ge(q){const ke=new Set;for(const At of q)for(const zt of At.blocks)zt.context&&ke.add(zt.context);const oe=Array.from(ke),$e=oe.length>0?`This media is still attached to: ${oe.map(At=>`"${At}"`).join(", ")}. Remove from those and delete?`:"This media is still attached to other items. Remove from those and delete?";return window.confirm($e)}function pe(q){return Object.entries(q).map(([ke,oe])=>({uuid:ke,blocks:oe}))}async function me(){const q=se.selectedItems.value;if(q.length===0)return;const ke=r.value.canDelete?q.filter($e=>r.value.canDelete($e)):q;if(ke.length===0||n.confirmBulkDelete&&!await n.confirmBulkDelete(ke))return;const oe=ke.map($e=>$e.uuid);try{const $e=await xe.deleteMany(oe);await ae($e)}catch($e){if($e instanceof Wl){const At=pe($e.softBlocks);if(!(n.confirmDestructiveAction?await n.confirmDestructiveAction({items:ke,softBlocks:At}):ge(At)))return;try{const Ft=await xe.deleteMany(oe,{confirmed:!0});await ae(Ft)}catch(Ft){i("error",Ft instanceof Error?Ft:new Error(String(Ft)))}return}i("error",$e instanceof Error?$e:new Error(String($e)))}}async function Be(q){var oe;const ke=ue.items.value.find($e=>$e.uuid===q);if(!(ke&&!I(ke)))try{const $e=await ue.restore(q);if($e.status==="restored"){i("restored",q),await L.refresh().catch(()=>{});return}if($e.status==="duplicate_conflict"){i("restore-conflict",{uuid:q,duplicateUuid:$e.duplicate_uuid??null}),(oe=n.onRestoreCollision)==null||oe.call(n,q,$e.duplicate_uuid??null);return}}catch($e){i("error",$e instanceof Error?$e:new Error(String($e)))}}async function He(){T.value="trash",ue.items.value.length===0&&!ue.isLoading.value&&await ue.fetch().catch(q=>{i("error",q instanceof Error?q:new Error(String(q)))})}function lt(q){if(q==="trash"){He();return}T.value=q}const Vt=e.computed(()=>({activeTab:T.value,setActiveTab:lt,trashCount:ue.total.value,showTrash:r.value.showTrash!==!1,labels:{libraryTab:l.value.libraryTab,trashTab:l.value.trashTab}})),Ot=e.computed(()=>({selectedCount:se.selectedCount.value,selectedItemIds:Array.from(se.selectedIds.value),selectedItems:se.selectedItems.value,crossPageCount:se.crossPageCount.value,isDeleting:xe.isDeleting.value,onBulkDelete:me,...r.value.allowCreatePost===!0?{onCreatePost:()=>Wt(se.selectedItems.value,"bulk")}:{},...r.value.allowCreateGallery===!0?{onCreateGallery:()=>Pe(se.selectedItems.value,"bulk")}:{},...r.value.allowAddToAlbum===!0?{onAddToAlbum:()=>Ht(se.selectedItems.value,"bulk")}:{},clearSelection:se.clear,labels:{deleteButton:l.value.deleteButton,...r.value.allowCreatePost===!0?{createPostButton:l.value.createPostButton}:{},...r.value.allowCreateGallery===!0?{createGalleryButton:l.value.createGalleryButton}:{},...r.value.allowAddToAlbum===!0?{addToAlbumButton:l.value.addToAlbumButton}:{},selectedCount:l.value.selectedCount}})),$t=e.computed(()=>({filters:M.value,view:x.value,total:L.total.value,shown:z.value.length,loading:L.loading.value}));function st(q){return{media:q,selected:se.isSelected(q.uuid),canEdit:be(q),onPreview:()=>mt(q),...be(q)?{onEdit:()=>Zt(q)}:{},...r.value.allowCreatePost===!0?{onCreatePost:()=>Wt([q],"item")}:{},...r.value.allowCreateGallery===!0?{onCreateGallery:()=>Pe([q],"item")}:{},...r.value.allowAddToAlbum===!0?{onAddToAlbum:()=>Ht([q],"item")}:{},labels:{previewButton:l.value.previewButton,editButton:l.value.editButton,createPostButton:l.value.createPostButton,createGalleryButton:l.value.createGalleryButton,addToAlbumButton:l.value.addToAlbumButton}}}function Jt(q){return{media:q,canRestore:I(q),isRestoring:ue.isRestoring.value,onRestore:()=>Be(q.uuid),labels:{restoreButton:l.value.restoreButton,restoreUnavailable:l.value.restoreUnavailable}}}return e.watch(T,async q=>{q==="library"&&z.value.length===0&&!C.value&&await L.refresh().catch(()=>{})}),e.watch(()=>n.layoutMode,q=>{q!==void 0&&($.value=q)}),e.watch(()=>n.filters,async q=>{M.value=P(q),se.clear(),pt(),await L.refresh().catch(ke=>{i("error",ke instanceof Error?ke:new Error(String(ke)))})},{deep:!0}),e.onMounted(async()=>{await L.refresh().catch(q=>{i("error",q instanceof Error?q:new Error(String(q)))}),r.value.showTrash!==!1&&ue.fetch().catch(()=>{})}),a({refresh:()=>L.refresh(),refreshTrash:()=>ue.fetch(),selection:se,deletion:xe,trash:ue}),(q,ke)=>(e.openBlock(),e.createElementBlock("div",cR,[r.value.showHeader!==!1?(e.openBlock(),e.createElementBlock("header",uR,[e.createElementVNode("h2",mR,e.toDisplayString(s.value),1),e.createElementVNode("div",pR,[e.renderSlot(q.$slots,"tabs",e.normalizeProps(e.guardReactiveProps(Vt.value)),()=>[r.value.showTrash!==!1?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["media-management-view__tab-button",{"is-active":T.value==="library"}]),"data-testid":"tab-library",onClick:ke[0]||(ke[0]=oe=>T.value="library")},e.toDisplayString(d.value),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["media-management-view__tab-button",{"is-active":T.value==="trash"}]),"data-testid":"tab-trash",onClick:He},[e.createTextVNode(e.toDisplayString(c.value)+" ",1),e.unref(ue).total.value>0?(e.openBlock(),e.createElementBlock("span",fR,e.toDisplayString(e.unref(ue).total.value),1)):e.createCommentVNode("",!0)],2)],64)):e.createCommentVNode("",!0)],!0)])])):e.createCommentVNode("",!0),T.value==="library"?(e.openBlock(),e.createElementBlock("section",hR,[r.value.showLayoutSwitcher!==!1?(e.openBlock(),e.createElementBlock("div",vR,[e.createElementVNode("button",{type:"button",role:"radio",class:e.normalizeClass(["media-management-view__view-mode-button",{"is-active":$.value==="grid"}]),"aria-checked":$.value==="grid"?"true":"false","data-testid":"view-mode-grid",onClick:ke[1]||(ke[1]=oe=>W("grid"))},e.toDisplayString(b.value),11,gR),e.createElementVNode("button",{type:"button",role:"radio",class:e.normalizeClass(["media-management-view__view-mode-button",{"is-active":$.value==="table"}]),"aria-checked":$.value==="table"?"true":"false","data-testid":"view-mode-table",onClick:ke[2]||(ke[2]=oe=>W("table"))},e.toDisplayString(g.value),11,bR)])):e.createCommentVNode("",!0),e.renderSlot(q.$slots,"filter-bar",e.normalizeProps(e.guardReactiveProps($t.value)),void 0,!0),C.value?(e.openBlock(),e.createElementBlock("div",yR,e.toDisplayString(u.value),1)):A.value?(e.openBlock(),e.createElementBlock("div",wR,e.toDisplayString(A.value),1)):z.value.length===0?(e.openBlock(),e.createElementBlock("div",kR,[e.renderSlot(q.$slots,"empty-library",{},()=>[e.createElementVNode("div",_R,[e.createElementVNode("p",ER,e.toDisplayString(m.value),1),e.createElementVNode("p",SR,e.toDisplayString(p.value),1)])],!0)])):$.value==="table"?(e.openBlock(),e.createElementBlock("table",CR,[e.createElementVNode("thead",null,[e.createElementVNode("tr",null,[e.createElementVNode("th",xR,[e.createElementVNode("label",NR,[e.createElementVNode("input",{class:"media-management-view__checkbox",type:"checkbox",checked:e.unref(se).isAllSelected.value,".indeterminate":e.unref(se).isSomeSelected.value&&!e.unref(se).isAllSelected.value,"aria-label":l.value.tableSelectHeader,"data-testid":"checkbox-select-all",onChange:ke[3]||(ke[3]=(...oe)=>e.unref(se).toggleAll&&e.unref(se).toggleAll(...oe))},null,40,VR),e.createElementVNode("span",TR,e.toDisplayString(l.value.tableSelectHeader),1)])]),e.createElementVNode("th",BR,e.toDisplayString(l.value.tableThumbnailHeader),1),e.createElementVNode("th",MR,e.toDisplayString(l.value.tableNameHeader),1),e.createElementVNode("th",IR,e.toDisplayString(l.value.tableTypeHeader),1),e.createElementVNode("th",$R,e.toDisplayString(l.value.tableCreatedHeader),1),e.createElementVNode("th",FR,e.toDisplayString(l.value.tableSizeHeader),1),e.createElementVNode("th",DR,e.toDisplayString(l.value.tableStatusHeader),1),e.createElementVNode("th",AR,e.toDisplayString(l.value.tableActionsHeader),1)])]),e.createElementVNode("tbody",null,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(z.value,oe=>(e.openBlock(),e.createElementBlock("tr",{key:oe.uuid,class:e.normalizeClass({"is-selected":e.unref(se).isSelected(oe.uuid),"has-open-actions":B.value===oe.uuid}),"data-testid":`media-row-${oe.uuid}`},[e.createElementVNode("td",null,[e.createElementVNode("label",LR,[e.createElementVNode("input",{class:"media-management-view__checkbox",type:"checkbox",checked:e.unref(se).isSelected(oe.uuid),"aria-label":`${l.value.tableSelectHeader} ${e.unref(_e)(oe)}`,"data-testid":`checkbox-select-${oe.uuid}`,onChange:$e=>e.unref(se).toggle(oe.uuid)},null,40,PR)])]),e.createElementVNode("td",null,[e.createElementVNode("button",{type:"button",class:"media-management-view__table-thumb","data-testid":`btn-preview-thumb-${oe.uuid}`,onClick:$e=>mt(oe)},[rt(oe)&&!bt.value.has(oe.uuid)?(e.openBlock(),e.createElementBlock("img",{key:0,src:rt(oe)??"",alt:oe.alt_text||oe.file_name,loading:"lazy",onError:$e=>Ct(oe)},null,40,OR)):(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__item-placeholder","data-testid":`placeholder-${oe.uuid}`},e.toDisplayString(Pt(oe)),9,zR))],8,UR)]),e.createElementVNode("td",null,[e.createElementVNode("span",{class:"media-management-view__display-name",title:oe.file_name,"data-testid":`media-display-name-${oe.uuid}`},e.toDisplayString(e.unref(_e)(oe)),9,jR),ye(oe)>0?(e.openBlock(),e.createElementBlock("span",{key:0,class:"media-management-view__variant-badge","data-testid":`media-variant-badge-${oe.uuid}`},e.toDisplayString(Ne(ye(oe))),9,WR)):e.createCommentVNode("",!0),r.value.showRawFileName===!0?(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__raw-filename","data-testid":`media-raw-filename-${oe.uuid}`},e.toDisplayString(oe.file_name),9,HR)):e.createCommentVNode("",!0)]),e.createElementVNode("td",null,e.toDisplayString(Se(oe)),1),e.createElementVNode("td",null,e.toDisplayString(Oe(oe)),1),e.createElementVNode("td",null,e.toDisplayString(Re(oe)),1),e.createElementVNode("td",null,e.toDisplayString(it(oe)),1),e.createElementVNode("td",null,[e.renderSlot(q.$slots,"item-actions",e.mergeProps({ref_for:!0},st(oe)),()=>[e.createElementVNode("div",ZR,[e.createElementVNode("div",{class:"media-management-view__action-menu",onKeydown:e.withKeys(e.withModifiers(Ut,["stop"]),["escape"])},[e.createElementVNode("button",{type:"button",class:"media-management-view__action-menu-trigger","data-testid":`btn-actions-menu-${oe.uuid}`,"aria-label":`Actions for ${e.unref(_e)(oe)}`,"aria-haspopup":"menu","aria-expanded":B.value===oe.uuid?"true":"false",onClick:$e=>It(oe.uuid)}," ... ",8,XR),B.value===oe.uuid?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-management-view__action-menu-panel",role:"menu","data-testid":`media-item-actions-menu-${oe.uuid}`},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(sa(oe),$e=>(e.openBlock(),e.createElementBlock("button",{key:$e.id,type:"button",class:"media-management-view__action-menu-item",role:"menuitem","data-testid":$e.testId,onClick:At=>Gt($e)},e.toDisplayString($e.label),9,qR))),128))],8,KR)):e.createCommentVNode("",!0)],40,GR)])],!0)])],10,RR))),128))])])):(e.openBlock(),e.createElementBlock("ul",JR,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(z.value,oe=>(e.openBlock(),e.createElementBlock("li",{key:oe.uuid,class:e.normalizeClass(["media-management-view__item",{"is-selected":e.unref(se).isSelected(oe.uuid),"has-open-actions":B.value===oe.uuid}]),"data-testid":`media-item-${oe.uuid}`},[e.createElementVNode("button",{type:"button",class:"media-management-view__item-thumb","data-testid":`btn-select-${oe.uuid}`,"aria-pressed":e.unref(se).isSelected(oe.uuid),onClick:$e=>e.unref(se).toggle(oe.uuid)},[rt(oe)&&!bt.value.has(oe.uuid)?(e.openBlock(),e.createElementBlock("img",{key:0,src:rt(oe)??"",alt:oe.alt_text||oe.file_name,loading:"lazy",onError:$e=>Ct(oe)},null,40,eL)):(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__item-placeholder","data-testid":`placeholder-${oe.uuid}`},e.toDisplayString(Pt(oe)),9,tL))],8,QR),e.createElementVNode("label",aL,[e.createElementVNode("span",nL,e.toDisplayString(l.value.tableSelectHeader)+" "+e.toDisplayString(e.unref(_e)(oe)),1),e.createElementVNode("input",{class:"media-management-view__checkbox media-management-view__checkbox--overlay",type:"checkbox",checked:e.unref(se).isSelected(oe.uuid),"data-testid":`checkbox-select-${oe.uuid}`,onClick:ke[4]||(ke[4]=e.withModifiers(()=>{},["stop"])),onChange:$e=>e.unref(se).toggle(oe.uuid)},null,40,oL)]),e.createElementVNode("div",iL,[e.createElementVNode("span",{class:"media-management-view__item-name",title:oe.file_name,"data-testid":`media-display-name-${oe.uuid}`},e.toDisplayString(e.unref(_e)(oe)),9,rL),r.value.showRawFileName===!0?(e.openBlock(),e.createElementBlock("span",{key:0,class:"media-management-view__raw-filename","data-testid":`media-raw-filename-${oe.uuid}`},e.toDisplayString(oe.file_name),9,lL)):e.createCommentVNode("",!0),r.value.showOwner&&oe.user_id?(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__item-owner","data-testid":`owner-${oe.uuid}`},e.toDisplayString(k(oe)),9,sL)):e.createCommentVNode("",!0),oe.is_orphaned?(e.openBlock(),e.createElementBlock("span",dL,e.toDisplayString(v.value),1)):e.createCommentVNode("",!0),ye(oe)>0?(e.openBlock(),e.createElementBlock("span",{key:3,class:"media-management-view__variant-badge","data-testid":`media-variant-badge-${oe.uuid}`},e.toDisplayString(Ne(ye(oe))),9,cL)):e.createCommentVNode("",!0)]),e.renderSlot(q.$slots,"item-actions",e.mergeProps({ref_for:!0},st(oe)),()=>[e.createElementVNode("div",uL,[e.createElementVNode("div",{class:"media-management-view__action-menu",onKeydown:e.withKeys(e.withModifiers(Ut,["stop"]),["escape"])},[e.createElementVNode("button",{type:"button",class:"media-management-view__action-menu-trigger","data-testid":`btn-actions-menu-${oe.uuid}`,"aria-label":`Actions for ${e.unref(_e)(oe)}`,"aria-haspopup":"menu","aria-expanded":B.value===oe.uuid?"true":"false",onClick:$e=>It(oe.uuid)}," ... ",8,pL),B.value===oe.uuid?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-management-view__action-menu-panel",role:"menu","data-testid":`media-item-actions-menu-${oe.uuid}`},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(sa(oe),$e=>(e.openBlock(),e.createElementBlock("button",{key:$e.id,type:"button",class:"media-management-view__action-menu-item",role:"menuitem","data-testid":$e.testId,onClick:At=>Gt($e)},e.toDisplayString($e.label),9,hL))),128))],8,fL)):e.createCommentVNode("",!0)],40,mL)])],!0)],10,YR))),128))])),e.unref(se).selectedCount.value>0&&O.value?e.renderSlot(q.$slots,"bulk-actions",e.normalizeProps(e.mergeProps({key:6},Ot.value)),()=>[e.createElementVNode("footer",vL,[e.createElementVNode("span",gL,e.toDisplayString(le(e.unref(se).selectedCount.value)),1),r.value.allowCreatePost===!0?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-management-view__btn-action","data-testid":"btn-bulk-create-post",onClick:ke[5]||(ke[5]=oe=>Wt(e.unref(se).selectedItems.value,"bulk"))},e.toDisplayString(l.value.createPostButton),1)):e.createCommentVNode("",!0),r.value.allowCreateGallery===!0?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",class:"media-management-view__btn-action","data-testid":"btn-bulk-create-gallery",onClick:ke[6]||(ke[6]=oe=>Pe(e.unref(se).selectedItems.value,"bulk"))},e.toDisplayString(l.value.createGalleryButton),1)):e.createCommentVNode("",!0),r.value.allowAddToAlbum===!0?(e.openBlock(),e.createElementBlock("button",{key:2,type:"button",class:"media-management-view__btn-action","data-testid":"btn-bulk-add-to-album",onClick:ke[7]||(ke[7]=oe=>Ht(e.unref(se).selectedItems.value,"bulk"))},e.toDisplayString(l.value.addToAlbumButton),1)):e.createCommentVNode("",!0),r.value.allowBulkDelete!==!1?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button",class:"media-management-view__btn-delete","data-testid":"btn-bulk-delete",disabled:e.unref(xe).isDeleting.value,onClick:me},e.toDisplayString(y.value),9,bL)):e.createCommentVNode("",!0)])],!0):e.createCommentVNode("",!0),z.value.length>0?(e.openBlock(),e.createElementBlock("footer",yL,[e.createElementVNode("span",wL,e.toDisplayString(F.value),1),Je.value.length>0?(e.openBlock(),e.createElementBlock("div",kL,[ke[11]||(ke[11]=e.createElementVNode("label",{class:"media-management-view__page-size-label",for:"media-management-page-size-select"},"Show:",-1)),e.createElementVNode("select",{id:"media-management-page-size-select",class:"media-management-view__page-size-select","data-testid":"select-media-management-page-size",value:_t.value,disabled:e.unref(L).loading.value||e.unref(L).loadingMore.value,onChange:ht},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Je.value,oe=>(e.openBlock(),e.createElementBlock("option",{key:oe.value,value:oe.value,"data-testid":`option-page-size-${oe.value}`},e.toDisplayString(oe.label),9,EL))),128))],40,_L)])):e.createCommentVNode("",!0),!q.paginated&&e.unref(L).hasMore.value?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",class:"media-management-view__load-more","data-testid":"btn-media-management-load-more",disabled:e.unref(L).loadingMore.value,onClick:Ve},e.toDisplayString(e.unref(L).loadingMore.value?l.value.loadingMoreButton:l.value.loadMoreButton),9,SL)):e.createCommentVNode("",!0),q.paginated&&(e.unref(L).totalPages.value??0)>1?(e.openBlock(),e.createElementBlock("nav",CL,[e.createElementVNode("button",{type:"button",class:"media-management-view__page-bar-step","data-testid":"btn-media-management-page-prev",disabled:(e.unref(L).currentPage.value??1)<=1||e.unref(L).loading.value,"aria-label":"Previous page",onClick:ke[8]||(ke[8]=oe=>Ge(-1))}," ‹ ",8,xL),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Le.value,oe=>(e.openBlock(),e.createElementBlock("button",{key:oe.key,type:"button",class:e.normalizeClass(["media-management-view__page-bar-page",{"is-current":oe.kind==="page"&&oe.value===e.unref(L).currentPage.value}]),"data-testid":oe.kind==="page"?`btn-media-management-page-${oe.value}`:"media-management-page-ellipsis",disabled:oe.kind!=="page"||e.unref(L).loading.value,"aria-current":oe.kind==="page"&&oe.value===e.unref(L).currentPage.value?"page":void 0,"aria-label":oe.kind==="page"?`Page ${oe.value}`:void 0,onClick:$e=>oe.kind==="page"?nt(oe.value):void 0},e.toDisplayString(oe.kind==="page"?oe.value:"…"),11,NL))),128)),e.createElementVNode("button",{type:"button",class:"media-management-view__page-bar-step","data-testid":"btn-media-management-page-next",disabled:(e.unref(L).currentPage.value??1)>=(e.unref(L).totalPages.value??1)||e.unref(L).loading.value,"aria-label":"Next page",onClick:ke[9]||(ke[9]=oe=>Ge(1))}," › ",8,VL)])):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])):T.value==="trash"?(e.openBlock(),e.createElementBlock("section",TL,[e.unref(ue).isLoading.value?(e.openBlock(),e.createElementBlock("div",BL,e.toDisplayString(u.value),1)):e.unref(ue).items.value.length===0?(e.openBlock(),e.createElementBlock("div",ML,[e.renderSlot(q.$slots,"empty-trash",{},()=>[e.createElementVNode("div",IL,[e.createElementVNode("p",$L,e.toDisplayString(f.value),1),e.createElementVNode("p",FL,e.toDisplayString(h.value),1)])],!0)])):(e.openBlock(),e.createElementBlock("ul",DL,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(ue).items.value,oe=>(e.openBlock(),e.createElementBlock("li",{key:oe.uuid,class:"media-management-view__item is-trashed","data-testid":`trash-item-${oe.uuid}`},[e.createElementVNode("div",RL,[rt(oe)&&!bt.value.has(oe.uuid)?(e.openBlock(),e.createElementBlock("img",{key:0,src:rt(oe)??"",alt:oe.alt_text||oe.file_name,loading:"lazy",onError:$e=>Ct(oe)},null,40,LL)):(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__item-placeholder","data-testid":`placeholder-trash-${oe.uuid}`},e.toDisplayString(Pt(oe)),9,PL))]),e.createElementVNode("div",UL,[e.createElementVNode("span",OL,e.toDisplayString(oe.file_name),1),oe.purge_after?(e.openBlock(),e.createElementBlock("span",zL,e.toDisplayString(Z(oe.purge_after)),1)):e.createCommentVNode("",!0)]),e.renderSlot(q.$slots,"trash-action",e.mergeProps({ref_for:!0},Jt(oe)),()=>[I(oe)?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-management-view__btn-restore","data-testid":`btn-restore-${oe.uuid}`,disabled:e.unref(ue).isRestoring.value,onClick:$e=>Be(oe.uuid)},e.toDisplayString(w.value),9,jL)):(e.openBlock(),e.createElementBlock("span",{key:1,class:"media-management-view__btn-restore is-unavailable","data-testid":`btn-restore-${oe.uuid}-unavailable`,"aria-disabled":!0},e.toDisplayString(_.value),9,WL))],!0)],8,AL))),128))]))])):e.createCommentVNode("",!0),r.value.allowPreview!==!1?(e.openBlock(),e.createBlock(Wd,{key:3,open:K.value!==null,media:K.value,"can-go-previous":N.value!==null&&N.value>0,"can-go-next":N.value!==null&&N.value<z.value.length-1,selected:K.value!==null&&e.unref(se).isSelected(K.value.uuid),"close-label":l.value.previewCloseButton,"previous-label":l.value.previewPreviousButton,"next-label":l.value.previewNextButton,"select-label":l.value.previewSelectButton,"deselect-label":l.value.previewDeselectButton,onClose:pt,onPrevious:Nt,onNext:Ce,onToggleSelect:ke[10]||(ke[10]=oe=>e.unref(se).toggle(oe.uuid))},null,8,["open","media","can-go-previous","can-go-next","selected","close-label","previous-label","next-label","select-label","deselect-label"])):e.createCommentVNode("",!0)]))}}),Yf=Ae(HL,[["__scopeId","data-v-8c4b53f6"]]),ZL={class:"media-library-workspace","data-testid":"media-library-workspace"},GL=e.defineComponent({__name:"MediaLibraryWorkspace",props:{httpClient:{},filters:{default:()=>({sort:"newest"})},initialView:{default:()=>({scope:"library"})},capabilities:{default:()=>({})},labels:{default:()=>({})},groupVariants:{type:Boolean,default:!0}},emits:["filters-change","create-post","create-gallery","add-to-album","edit","deleted","restored","restore-conflict","error"],setup(o,{emit:a}){const t=o,n=a;function i(s){return{...s,...s.kinds!==void 0?{kinds:[...s.kinds]}:{},...s.selected_uuids!==void 0?{selected_uuids:[...s.selected_uuids]}:{}}}const r=e.ref(i(t.filters));e.watch(()=>t.filters,s=>{r.value=i(s)},{deep:!0});function l(s){r.value=i(s),n("filters-change",r.value)}return(s,d)=>(e.openBlock(),e.createElementBlock("section",ZL,[e.createVNode(Yf,{"http-client":t.httpClient,filters:r.value,"initial-view":t.initialView,"group-variants":t.groupVariants,capabilities:{showHeader:!1,showTrash:!1,allowAddToAlbum:t.capabilities.allowAddToAlbum,allowBulkDelete:t.capabilities.allowBulkDelete,allowCreateGallery:t.capabilities.allowCreateGallery,allowCreatePost:t.capabilities.allowCreatePost,showRawFileName:t.capabilities.showRawFileName,allowPreview:t.capabilities.allowPreview,allowImageEdit:t.capabilities.allowImageEdit,allowVideoEdit:t.capabilities.allowVideoEdit},labels:{title:t.labels.title??"Media"},onCreatePost:d[0]||(d[0]=c=>n("create-post",c)),onCreateGallery:d[1]||(d[1]=c=>n("create-gallery",c)),onAddToAlbum:d[2]||(d[2]=c=>n("add-to-album",c)),onEdit:d[3]||(d[3]=c=>n("edit",c)),onDeleted:d[4]||(d[4]=c=>n("deleted",c)),onRestored:d[5]||(d[5]=c=>n("restored",c)),onRestoreConflict:d[6]||(d[6]=c=>n("restore-conflict",c)),onError:d[7]||(d[7]=c=>n("error",c))},{"filter-bar":e.withCtx(()=>[e.createVNode(Jf,{filters:r.value,"scope-label":t.labels.scopeLabel??"","onUpdate:filters":l},null,8,["filters","scope-label"])]),"bulk-actions":e.withCtx(c=>[e.renderSlot(s.$slots,"bulk-actions",e.normalizeProps(e.guardReactiveProps(c)),void 0,!0)]),"item-actions":e.withCtx(c=>[e.renderSlot(s.$slots,"item-actions",e.normalizeProps(e.guardReactiveProps(c)),void 0,!0)]),"empty-library":e.withCtx(()=>[e.renderSlot(s.$slots,"empty-library",{},void 0,!0)]),_:3},8,["http-client","filters","initial-view","group-variants","capabilities","labels"])]))}}),Qf=Ae(GL,[["__scopeId","data-v-54a820dd"]]),XL=["data-testid"],KL={class:"media-empty-state__illustration","aria-hidden":"true"},qL={class:"media-empty-state__copy"},JL={class:"media-empty-state__title"},YL={key:0,class:"media-empty-state__description"},QL={class:"media-empty-state__actions"},eP=e.defineComponent({__name:"MediaEmptyState",props:{title:{},description:{default:""},actionLabel:{default:""},testId:{default:"media-empty-state"}},emits:["action"],setup(o,{emit:a}){const t=o,n=a;return(i,r)=>(e.openBlock(),e.createElementBlock("section",{class:"media-empty-state","data-testid":t.testId},[e.createElementVNode("div",KL,[e.renderSlot(i.$slots,"illustration",{},()=>[r[1]||(r[1]=e.createElementVNode("span",{class:"media-empty-state__icon"},"□",-1))],!0)]),e.createElementVNode("div",qL,[e.createElementVNode("h3",JL,e.toDisplayString(t.title),1),t.description!==""?(e.openBlock(),e.createElementBlock("p",YL,e.toDisplayString(t.description),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",QL,[e.renderSlot(i.$slots,"actions",{},()=>[t.actionLabel!==""?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-empty-state__action","data-testid":"btn-media-empty-state-action",onClick:r[0]||(r[0]=l=>n("action"))},e.toDisplayString(t.actionLabel),1)):e.createCommentVNode("",!0)],!0)])],8,XL))}}),eh=Ae(eP,[["__scopeId","data-v-7b8e2619"]]),tP=["aria-busy"],aP={class:"media-trash-workspace__header"},nP=["disabled"],oP={key:0,class:"media-trash-workspace__status media-trash-workspace__status--error","data-testid":"media-trash-error",role:"alert"},iP={key:1,class:"media-trash-workspace__status","data-testid":"media-trash-status","aria-live":"polite"},rP={key:2,class:"media-trash-workspace__status"},lP={key:4,class:"media-trash-workspace__grid"},sP=["data-testid"],dP={class:"media-trash-workspace__select"},cP=["checked","data-testid","onChange"],uP=["src","alt"],mP={key:1,class:"media-trash-workspace__purge"},pP=e.defineComponent({__name:"MediaTrashWorkspace",props:{httpClient:{},labels:{default:()=>({})}},emits:["restored","purged","error"],setup(o,{emit:a}){const t=o,n=a,i=e.computed(()=>{var y,w,_,b,g,I,T,$,N,B,P;return{title:((y=t.labels)==null?void 0:y.title)??"Trash",emptyTitle:((w=t.labels)==null?void 0:w.emptyTitle)??"Your trash is empty",emptyDescription:((_=t.labels)==null?void 0:_.emptyDescription)??"Deleted files appear here before permanent removal.",restore:((b=t.labels)==null?void 0:b.restore)??"Restore",purge:((g=t.labels)==null?void 0:g.purge)??"Delete forever",emptyTrash:((I=t.labels)==null?void 0:I.emptyTrash)??"Empty trash",confirmPurgeSelected:((T=t.labels)==null?void 0:T.confirmPurgeSelected)??(x=>`Delete ${x} ${x===1?"item":"items"} forever? This cannot be undone.`),confirmEmptyTrash:(($=t.labels)==null?void 0:$.confirmEmptyTrash)??(x=>`Empty trash and permanently delete ${x} ${x===1?"item":"items"}? This cannot be undone.`),purgeSuccess:((N=t.labels)==null?void 0:N.purgeSuccess)??(x=>`${x} ${x===1?"item":"items"} deleted forever.`),purgeError:((B=t.labels)==null?void 0:B.purgeError)??"Could not delete one or more items forever. Try again.",restoreError:((P=t.labels)==null?void 0:P.restoreError)??"Could not restore one or more items. Try again."}}),r=Yd({httpClient:t.httpClient}),l=fl(r.items),s=e.ref(""),d=e.ref(""),c=e.computed(()=>r.isPurging.value||r.isRestoring.value);function u(y){return y.thumbnail_url??y.preview_url??y.original_url??null}async function m(){const y=Array.from(l.selectedIds.value),w=[];s.value="",d.value="";try{for(const _ of y){const b=await r.restore(_);b.status==="restored"?w.push(_):s.value=b.message??i.value.restoreError}l.clear(),w.length>0&&n("restored",w)}catch(_){const b=_ instanceof Error?_:new Error(String(_));s.value=b.message!==""?b.message:i.value.restoreError,n("error",b)}}async function p(){const y=Array.from(l.selectedIds.value);h(i.value.confirmPurgeSelected(y.length),y.length)&&await v(y)}async function f(){const y=r.items.value.map(w=>w.uuid);h(i.value.confirmEmptyTrash(y.length),y.length)&&await v(y)}function h(y,w){return w===0||typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(y)}async function v(y){if(y.length===0)return;const w=[],_=[];s.value="",d.value="";try{for(const b of y){const g=await r.purge(b);g.status==="purging"?w.push(b):_.push(g.message??i.value.purgeError)}l.clear(),w.length>0&&(d.value=i.value.purgeSuccess(w.length),n("purged",w)),_.length>0&&(s.value=Array.from(new Set(_)).join(" "),n("error",new Error(s.value)))}catch(b){const g=b instanceof Error?b:new Error(String(b));s.value=g.message!==""?g.message:i.value.purgeError,n("error",g)}}return e.onMounted(()=>{r.fetch().catch(y=>{n("error",y instanceof Error?y:new Error(String(y)))})}),(y,w)=>(e.openBlock(),e.createElementBlock("section",{class:"media-trash-workspace","data-testid":"media-trash-workspace","aria-busy":c.value?"true":"false"},[e.createElementVNode("header",aP,[e.createElementVNode("h2",null,e.toDisplayString(i.value.title),1),e.unref(r).items.value.length>0?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button","data-testid":"btn-media-empty-trash",disabled:e.unref(r).isPurging.value,onClick:f},e.toDisplayString(i.value.emptyTrash),9,nP)):e.createCommentVNode("",!0)]),s.value?(e.openBlock(),e.createElementBlock("p",oP,e.toDisplayString(s.value),1)):d.value?(e.openBlock(),e.createElementBlock("p",iP,e.toDisplayString(d.value),1)):e.createCommentVNode("",!0),e.unref(r).isLoading.value?(e.openBlock(),e.createElementBlock("p",rP,"Loading...")):e.unref(r).items.value.length===0?(e.openBlock(),e.createBlock(eh,{key:3,title:i.value.emptyTitle,description:i.value.emptyDescription,"test-id":"media-empty-trash"},null,8,["title","description"])):(e.openBlock(),e.createElementBlock("ul",lP,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(r).items.value,_=>(e.openBlock(),e.createElementBlock("li",{key:_.uuid,class:e.normalizeClass(["media-trash-workspace__item",{"is-selected":e.unref(l).isSelected(_.uuid)}]),"data-testid":`media-trash-item-${_.uuid}`},[e.createElementVNode("label",dP,[e.createElementVNode("input",{type:"checkbox",checked:e.unref(l).isSelected(_.uuid),"data-testid":`checkbox-trash-${_.uuid}`,onChange:b=>e.unref(l).toggle(_.uuid)},null,40,cP),e.createElementVNode("span",null,e.toDisplayString(_.file_name),1)]),u(_)?(e.openBlock(),e.createElementBlock("img",{key:0,src:u(_)??"",alt:_.alt_text??_.file_name},null,8,uP)):e.createCommentVNode("",!0),_.purge_after?(e.openBlock(),e.createElementBlock("span",mP,e.toDisplayString(_.purge_after),1)):e.createCommentVNode("",!0)],10,sP))),128))])),e.createVNode(qd,{"selected-count":e.unref(l).selectedCount.value,"cross-page-count":e.unref(l).crossPageCount.value,scope:"trash",labels:{restore:i.value.restore,purge:i.value.purge},onBulkRestore:m,onBulkPurge:p,onClear:e.unref(l).clear},null,8,["selected-count","cross-page-count","labels","onClear"])],8,tP))}}),th=Ae(pP,[["__scopeId","data-v-1bce0570"]]),fP=["data-density"],hP={class:"media-library-shell__toolbar"},vP={class:"media-library-shell__tabs","aria-label":"Media library sections"},gP=["aria-label"],bP=["data-testid","onClick"],yP={key:2,class:"media-library-shell__uploads","data-testid":"media-library-uploads","aria-live":"polite"},wP=["data-testid"],kP={class:"media-library-shell__upload-thumb"},_P=["src","alt"],EP={key:1,"aria-hidden":"true"},SP={class:"media-library-shell__upload-meta"},CP={class:"media-library-shell__upload-name"},xP={class:"media-library-shell__upload-status"},NP=["data-testid","onClick"],VP={class:"media-library-shell__workspace"},TP={key:0,class:"media-library-shell__breadcrumb","data-testid":"media-album-breadcrumb"},BP={class:"media-library-shell__breadcrumb-current"},MP={class:"media-library-shell__breadcrumb-name"},IP={key:0,class:"media-library-shell__album-actions","data-media-album-menu-root":""},$P=["aria-label","aria-controls","aria-expanded"],FP=["id"],DP=["aria-label"],AP={class:"media-album-grid__toolbar"},RP=["placeholder","aria-label"],LP={class:"media-album-grid__tiles",role:"list"},PP={class:"media-album-grid__new-tile-label"},UP={class:"media-album-grid__new-tile-field",for:"media-album-grid-new-name"},OP={class:"media-album-grid__new-tile-field-label"},zP=["maxlength","aria-invalid","disabled"],jP={key:0,id:"media-album-grid-new-error",class:"media-album-grid__new-tile-error","data-testid":"media-album-new-tile-error",role:"alert"},WP={class:"media-album-grid__new-tile-actions"},HP=["disabled"],ZP=["disabled"],GP={key:0},XP={key:1},KP=["data-testid"],qP=["data-testid","onClick"],JP={class:"media-album-grid__cover","aria-hidden":"true"},YP=["src"],QP={key:1,class:"media-album-grid__cover-initial"},eU={class:"media-album-grid__tile-meta"},tU={class:"media-album-grid__tile-name"},aU={class:"media-album-grid__tile-count"},nU={class:"media-album-grid__tile-actions","data-media-album-menu-root":""},oU=["data-testid","aria-label","aria-controls","aria-expanded","onClick"],iU=["id","data-testid"],rU=["data-testid","onClick"],lU=["data-testid","onClick"],sU={key:0,class:"media-album-grid__empty","data-testid":"media-album-grid-empty-search"},dU={key:1,class:"media-album-grid__empty","data-testid":"media-album-grid-empty"},cU={class:"media-library-shell__item-actions"},uU={class:"media-library-shell__item-action-menu","data-media-item-menu-root":""},mU=["data-testid","aria-label","aria-controls","aria-expanded","onClick"],pU=["id","data-testid"],fU=["data-testid","onClick"],hU=["data-testid","onClick"],vU=["data-testid","onClick"],gU=["data-testid","onClick"],bU=["data-testid","onClick"],yU=["data-testid","onClick"],wU=["data-testid","onClick"],kU=["aria-label"],_U=["aria-describedby"],EU={class:"media-album-dialog__header"},SU={id:"media-album-dialog-title"},CU={class:"media-album-dialog__field"},xU=["maxlength","aria-invalid","disabled"],NU={class:"media-album-dialog__field"},VU=["disabled"],TU={key:0,id:"media-album-dialog-error",class:"media-album-dialog__error","data-testid":"media-album-edit-error",role:"alert"},BU={class:"media-album-dialog__actions"},MU=["disabled"],IU=["disabled"],$U={key:1,class:"media-album-dialog__form","data-testid":"media-album-delete-confirmation"},FU={class:"media-album-dialog__header"},DU={id:"media-album-dialog-title"},AU={id:"media-album-dialog-delete-description",class:"media-album-dialog__description"},RU={key:0,id:"media-album-dialog-error",class:"media-album-dialog__error","data-testid":"media-album-delete-error",role:"alert"},LU={class:"media-album-dialog__actions"},PU=["disabled"],UU=["disabled"],am="media-library:density",nm="media-library:recent-albums",om=5,Ir=120,OU=e.defineComponent({__name:"MediaLibraryShell",props:{httpClient:{},albumHttpClient:{},albumBaseUrl:{},initialTab:{default:"library"},initialAlbumId:{default:null},initialFilters:{default:()=>({sort:"newest"})},capabilities:{default:()=>({})},labels:{default:()=>({})},currentRoute:{},routerPush:{},routerReplace:{}},emits:["tab-change","album-change","filters-change","selection-change","create-post","create-gallery","add-to-album","edit","deleted","restored","restore-conflict","metadata-updated","error"],setup(o,{emit:a}){function t(){if(typeof window>"u")return"comfortable";try{return window.localStorage.getItem(am)==="compact"?"compact":"comfortable"}catch{return"comfortable"}}function n(H){if(!(typeof window>"u"))try{window.localStorage.setItem(am,H)}catch{}}function i(){if(typeof window>"u")return[];try{const H=window.localStorage.getItem(nm);if(typeof H!="string"||H==="")return[];const Q=JSON.parse(H);return Array.isArray(Q)?Q.filter(Fe=>typeof Fe=="string"):[]}catch{return[]}}function r(H){if(!(typeof window>"u"))try{window.localStorage.setItem(nm,JSON.stringify(H.slice(0,om)))}catch{}}const l=o,s=a,d=e.ref(l.initialTab),c=e.ref(l.initialAlbumId),u=e.ref({...l.initialFilters}),m=e.ref(null),p=e.ref(null),f=e.ref(null),h=e.ref(null),v=e.ref(!1),y=e.ref(null),w=e.ref(null),_=e.ref(t()),b=e.ref(i()),g=e.ref(!1),I=e.ref(""),T=e.ref(null),$=e.ref(null),N=e.ref(null),B=e.ref(null),P=e.ref(""),x=e.ref(""),M=e.ref(""),E=e.ref(!1),D=e.ref(!1),j=e.ref(null),L=e.ref(null),z=e.ref(null),C=e.ref(null),A=e.ref(!1);let O=null;function K(){if(typeof document>"u")return!1;const H=document.activeElement;if(!(H instanceof HTMLElement))return!1;if(H.isContentEditable)return!0;const Q=H.tagName.toLowerCase();return Q==="input"||Q==="textarea"||Q==="select"}function se(H){H.key==="?"&&(H.metaKey||H.ctrlKey||H.altKey||K()||(H.preventDefault(),g.value=!0))}function xe(H){H.target instanceof Element&&(T.value!==null&&H.target.closest("[data-media-album-menu-root]")===null&&it(!1),f.value!==null&&H.target.closest("[data-media-item-menu-root]")===null&&Ga(!1))}function ue(H){A.value=H.matches}function le(){typeof window>"u"||typeof window.matchMedia=="function"&&(O=window.matchMedia("(max-width: 1535px)"),A.value=O.matches,O.addEventListener("change",ue))}function Z(){O==null||O.removeEventListener("change",ue),O=null}const k=e.computed(()=>A.value?"overlay":"pinned");function F(){m.value=null}const W=e.computed(()=>d.value==="albums"&&c.value===null),J=e.computed(()=>d.value==="albums"&&c.value!==null&&c.value!=="unfiled"),ce=e.computed(()=>{var H;return c.value===null||c.value==="unfiled"?"":((H=Ge.albumsById.value.get(c.value))==null?void 0:H.name)??""}),Ue=e.computed(()=>c.value===null||c.value==="unfiled"?null:Ge.albumsById.value.get(c.value)??null),be=e.computed(()=>{const H=I.value.trim().toLowerCase(),Q=Ge.albums.value;return H===""?Q:Q.filter(Fe=>Fe.name.toLowerCase().includes(H)||(Fe.description??"").toLowerCase().includes(H))});function _e(H){const Q=H.name.trim();return Q.length===0?"·":Q.charAt(0).toUpperCase()}function ye(H){var ne,Qe,Tt;const Q=H.cover_media;if(Q==null)return null;const Fe=((ne=Q.urls)==null?void 0:ne.thumb)??((Qe=Q.urls)==null?void 0:Qe.preview)??((Tt=Q.urls)==null?void 0:Tt.original)??null;return typeof Fe=="string"&&Fe!==""?Fe:null}function Ne(H){return Pe.value.itemsCount(H.media_count)}function Se(H){return`media-album-action-menu-${H}`}function Re(H){e.nextTick(()=>{if(typeof document>"u")return;const Q=document.getElementById(H);Q!==null&&fa(jl(Q)[0]??null)})}function Oe(H,Q){if(T.value===H){it(!0);return}$.value=(Q==null?void 0:Q.currentTarget)instanceof HTMLElement?Q.currentTarget:null,T.value=H,Re(Se(H))}function it(H=!1){T.value=null,H&&e.nextTick(()=>fa($.value))}function rt(H){if(H.key==="Escape"){H.preventDefault(),H.stopPropagation(),it(!0);return}cd(H,H.currentTarget instanceof HTMLElement?H.currentTarget:null)}function Pt(){C.value=typeof document<"u"&&document.activeElement instanceof HTMLElement?document.activeElement:$.value}function bt(H){Pt(),it(!1),N.value="edit",B.value=H,P.value=H.name,x.value=H.description??"",M.value="",E.value=!1,D.value=!1,e.nextTick(()=>{var Q,Fe;(Q=j.value)==null||Q.focus(),(Fe=j.value)==null||Fe.select()})}function Ct(H){Pt(),it(!1),N.value="delete",B.value=H,M.value="",E.value=!1,D.value=!1,e.nextTick(()=>{var Q;(Q=L.value)==null||Q.focus()})}function mt(){if(E.value||D.value)return;const H=C.value;N.value=null,B.value=null,P.value="",x.value="",M.value="",C.value=null,e.nextTick(()=>fa(H))}function pt(H){if(H.key==="Escape"){H.preventDefault(),H.stopPropagation(),mt();return}H.key==="Tab"&&Kd(H,z.value)}async function Nt(){var Q,Fe,ne;const H=B.value;if(!(H===null||N.value!=="edit"||E.value)){if(lt.value){M.value=Pe.value.albumEditEmptyError,(Q=j.value)==null||Q.focus();return}if(He.value){M.value=Pe.value.albumEditTooLongError,(Fe=j.value)==null||Fe.focus();return}E.value=!0,M.value="";try{await Ge.updateAlbum(H.id,{name:Be.value,description:x.value.trim()}),E.value=!1,mt()}catch(Qe){E.value=!1;const Tt=Qe instanceof Error?Qe:new Error(String(Qe));M.value=Tt.message!==""?Tt.message:Pe.value.albumEditGenericError,(ne=j.value)==null||ne.focus(),s("error",Tt)}}}async function Ce(){const H=B.value;if(!(H===null||N.value!=="delete"||D.value)){D.value=!0,M.value="";try{await Ge.deleteAlbum(H.id),b.value=b.value.filter(Q=>Q!==H.id),r(b.value),D.value=!1,mt(),c.value===H.id&&At(),Ge.fetchAlbums({parent_id:null}).catch(Q=>{s("error",Q instanceof Error?Q:new Error(String(Q)))})}catch(Q){D.value=!1;const Fe=Q instanceof Error?Q:new Error(String(Q));M.value=Fe.message!==""?Fe.message:Pe.value.albumDeleteGenericError,s("error",Fe)}}}const Ve=e.computed(()=>b.value.map(H=>{const Q=Ge.albumsById.value.get(H);return Q?{id:H,name:Q.name}:null}).filter(H=>H!==null));function Le(H){const Q=[H,...b.value.filter(Fe=>Fe!==H)].slice(0,om);b.value=Q,r(Q)}const nt=e.computed(()=>u.value.sort??"newest"),Ge=Ol(),Je=Jd({httpClient:l.httpClient}),_t=Hf({httpClient:l.httpClient,onMediaUploaded:()=>{ht.value+=1}}),ht=e.ref(0);function Wt(H){H.length!==0&&_t.uploadFiles(H).catch(Q=>{s("error",Q instanceof Error?Q:new Error(String(Q)))})}const Pe=e.computed(()=>{var H,Q,Fe,ne,Qe,Tt,dn,La,Hn,Nn,Pa,ya,Zn,uo,cn,Vn,Ua,mo,Tn,Bn,an,Gn,un,Mn,mn,In,nn,po,Xn,gi,bi,$n,Kn,qn,fo,ho,vo,go,bo,S,R,te,we,ze,je,ut,Bt,qt,ca;return{library:((H=l.labels)==null?void 0:H.library)??((Q=l.labels)==null?void 0:Q.libraryTab)??"Library",libraryTab:((Fe=l.labels)==null?void 0:Fe.libraryTab)??((ne=l.labels)==null?void 0:ne.library)??"Library",albums:((Qe=l.labels)==null?void 0:Qe.albums)??((Tt=l.labels)==null?void 0:Tt.albumsTab)??"Albums",albumsTab:((dn=l.labels)==null?void 0:dn.albumsTab)??((La=l.labels)==null?void 0:La.albums)??"Albums",trash:((Hn=l.labels)==null?void 0:Hn.trash)??((Nn=l.labels)==null?void 0:Nn.trashTab)??"Trash",trashTab:((Pa=l.labels)==null?void 0:Pa.trashTab)??((ya=l.labels)==null?void 0:ya.trash)??"Trash",allMedia:((Zn=l.labels)==null?void 0:Zn.allMedia)??"All media",unfiled:((uo=l.labels)==null?void 0:uo.unfiled)??"Unfiled",newAlbum:((cn=l.labels)==null?void 0:cn.newAlbum)??"New album",selectionScope:((Vn=l.labels)==null?void 0:Vn.selectionScope)??"Showing selected items",exitSelectionScope:((Ua=l.labels)==null?void 0:Ua.exitSelectionScope)??"Exit selection view",findAlbum:((mo=l.labels)==null?void 0:mo.findAlbum)??"Find album…",noAlbumsYet:((Tn=l.labels)==null?void 0:Tn.noAlbumsYet)??"No albums yet — albums are private buckets where you group photos and videos. Create your first one above to start organising your work.",noAlbumMatchesFound:((Bn=l.labels)==null?void 0:Bn.noAlbumMatchesFound)??"No albums match your search.",itemsCount:((an=l.labels)==null?void 0:an.itemsCount)??(Na=>`${Na} ${Na===1?"item":"items"}`),newAlbumNamePrompt:((Gn=l.labels)==null?void 0:Gn.newAlbumNamePrompt)??"Name this album",newAlbumSubmit:((un=l.labels)==null?void 0:un.newAlbumSubmit)??"Create",newAlbumCancel:((Mn=l.labels)==null?void 0:Mn.newAlbumCancel)??"Cancel",newAlbumEmptyError:((mn=l.labels)==null?void 0:mn.newAlbumEmptyError)??"Please enter a name.",newAlbumTooLongError:((In=l.labels)==null?void 0:In.newAlbumTooLongError)??"Name must be 120 characters or fewer.",newAlbumGenericError:((nn=l.labels)==null?void 0:nn.newAlbumGenericError)??"Could not create album. Try again.",recentSection:((po=l.labels)==null?void 0:po.recentSection)??"Recent albums",albumActions:((Xn=l.labels)==null?void 0:Xn.albumActions)??(Na=>`Album actions for ${Na}`),editAlbum:((gi=l.labels)==null?void 0:gi.editAlbum)??"Edit album",deleteAlbum:((bi=l.labels)==null?void 0:bi.deleteAlbum)??"Delete album",editAlbumTitle:(($n=l.labels)==null?void 0:$n.editAlbumTitle)??"Edit album",albumNameLabel:((Kn=l.labels)==null?void 0:Kn.albumNameLabel)??"Album name",albumDescriptionLabel:((qn=l.labels)==null?void 0:qn.albumDescriptionLabel)??"Description",saveAlbum:((fo=l.labels)==null?void 0:fo.saveAlbum)??"Save changes",cancelAlbumEdit:((ho=l.labels)==null?void 0:ho.cancelAlbumEdit)??"Cancel",albumEditEmptyError:((vo=l.labels)==null?void 0:vo.albumEditEmptyError)??"Please enter a name.",albumEditTooLongError:((go=l.labels)==null?void 0:go.albumEditTooLongError)??"Name must be 120 characters or fewer.",albumEditGenericError:((bo=l.labels)==null?void 0:bo.albumEditGenericError)??"Could not update album. Try again.",deleteAlbumTitle:((S=l.labels)==null?void 0:S.deleteAlbumTitle)??(Na=>`Delete ${Na}?`),deleteAlbumDescription:((R=l.labels)==null?void 0:R.deleteAlbumDescription)??"This deletes the album only. The photos and videos inside it stay in your media library.",confirmDeleteAlbum:((te=l.labels)==null?void 0:te.confirmDeleteAlbum)??"Delete album",cancelDeleteAlbum:((we=l.labels)==null?void 0:we.cancelDeleteAlbum)??"Cancel",albumDeleteGenericError:((ze=l.labels)==null?void 0:ze.albumDeleteGenericError)??"Could not delete album. Try again.",closeAlbumDialog:((je=l.labels)==null?void 0:je.closeAlbumDialog)??"Close album dialog",itemActions:((ut=l.labels)==null?void 0:ut.itemActions)??(Na=>`Actions for ${Na}`),moveToAnotherAlbum:((Bt=l.labels)==null?void 0:Bt.moveToAnotherAlbum)??"Move to another album",removeFromThisAlbum:((qt=l.labels)==null?void 0:qt.removeFromThisAlbum)??"Remove from this album",addToAlbum:((ca=l.labels)==null?void 0:ca.addToAlbum)??"Add to album"}}),Ht=e.ref(!1),Zt=e.ref(""),It=e.ref(""),Ut=e.ref(!1),Gt=e.ref(null),sa=e.computed(()=>Zt.value.trim()),ae=e.computed(()=>sa.value.length>Ir),ge=e.computed(()=>sa.value===""),pe=e.computed(()=>!Ut.value&&!ge.value&&!ae.value),me=e.computed(()=>N.value!==null&&B.value!==null),Be=e.computed(()=>P.value.trim()),He=e.computed(()=>Be.value.length>Ir),lt=e.computed(()=>Be.value===""),Vt=e.computed(()=>!E.value&&!lt.value&&!He.value),Ot=e.computed(()=>y.value!==null?{scope:"library"}:c.value==="unfiled"?{scope:"unfiled"}:c.value!==null?{scope:"album",albumId:c.value}:{scope:"library"}),$t=e.computed(()=>y.value!==null?{...u.value,selected_uuids:[...y.value],unfiled_only:!1}:u.value),st=e.computed(()=>{if(c.value===null||c.value==="unfiled")return null;const H=Ge.albumsById.value.get(c.value);return{uuid:c.value,name:(H==null?void 0:H.name)??"this album"}}),Jt=e.computed(()=>d.value==="trash"?"trash":y.value!==null?"selection":st.value!==null?"album":"all"),q=e.computed(()=>({...l.capabilities,allowReplaceMedia:!1,allowVisibilityChange:!1,allowDownloadZip:!1})),ke=e.computed(()=>d.value==="trash"?Pe.value.trash:y.value!==null?Pe.value.selectionScope:c.value==="unfiled"?Pe.value.unfiled:st.value!==null?st.value.name:Pe.value.allMedia);function oe(H){var Q,Fe,ne;d.value!==H&&(d.value=H,s("tab-change",H),H==="trash"?(Q=l.routerPush)==null||Q.call(l,"/media/trash"):H==="albums"?(Fe=l.routerPush)==null||Fe.call(l,"/media/albums"):(ne=l.routerPush)==null||ne.call(l,"/media"))}function $e(H){var Q;Y(),c.value=H,d.value="albums",Le(H),u.value={...u.value,unfiled_only:!1},s("album-change",H),(Q=l.routerPush)==null||Q.call(l,`/media/album/${encodeURIComponent(H)}`)}function At(){var H;Y(),c.value=null,d.value="albums",u.value={...u.value,unfiled_only:!1},s("album-change",null),(H=l.routerPush)==null||H.call(l,"/media/albums")}async function zt(H){if(c.value===null||c.value==="unfiled")return;const Q=c.value;try{await Ge.updateAlbum(Q,{meta:{cover_media_uuid:H.uuid}}),Ge.fetchAlbums({parent_id:null})}catch(Fe){s("error",Fe instanceof Error?Fe:new Error(String(Fe)))}}function Ft(){Zt.value="",It.value="",Ut.value=!1}async function wt(){var H;Ht.value=!0,Ft(),await e.nextTick(),(H=Gt.value)==null||H.focus()}function yt(){Ht.value=!1,Ft()}function Yt(){It.value!==""&&!ge.value&&!ae.value&&(It.value="")}async function Et(){var H,Q,Fe,ne;if(!Ut.value){if(ge.value){It.value=Pe.value.newAlbumEmptyError,(H=Gt.value)==null||H.focus();return}if(ae.value){It.value=Pe.value.newAlbumTooLongError,(Q=Gt.value)==null||Q.focus();return}Ut.value=!0,It.value="";try{const Qe=await Ge.createAlbum({name:sa.value});if(Qe==null){It.value=Pe.value.newAlbumGenericError,Ut.value=!1,(Fe=Gt.value)==null||Fe.focus();return}Ht.value=!1,Ft(),$e(Qe.id)}catch(Qe){const Tt=Qe instanceof Error?Qe:new Error(String(Qe));It.value=Tt.message!==""?Tt.message:Pe.value.newAlbumGenericError,Ut.value=!1,(ne=Gt.value)==null||ne.focus(),s("error",Tt)}}}function Kt(H){H.key==="Escape"&&(H.stopPropagation(),yt())}function Ca(){return d.value==="trash"?"/media/trash":c.value==="unfiled"?"/media/unfiled":c.value!==null?`/media/album/${encodeURIComponent(c.value)}`:"/media"}function X(H){var Q;H.length!==0&&(y.value===null&&(w.value=Ca()),y.value=[...H],(Q=l.routerPush)==null||Q.call(l,{path:"/media",query:{view:"selection"}}))}function Y(){y.value=null,w.value=null}function fe(){var Q;const H=w.value;Y(),H!==null&&((Q=l.routerPush)==null||Q.call(l,H))}function he(H){var Q;u.value={...u.value,sort:H},s("filters-change",u.value),(Q=l.routerReplace)==null||Q.call(l,{query:u.value})}function Te(H){_.value=H,n(H)}function Ke(H){var Q;u.value={...u.value,created_after:H.starts_at,created_before:H.ends_at},s("filters-change",u.value),(Q=l.routerReplace)==null||Q.call(l,{query:u.value})}function ct(){var Q;const H={...u.value};delete H.created_after,delete H.created_before,u.value=H,s("filters-change",u.value),(Q=l.routerReplace)==null||Q.call(l,{query:u.value})}const tt=e.computed(()=>u.value.created_after!==void 0||u.value.created_before!==void 0);function qe(H){var Q;u.value={...H,...H.kinds!==void 0?{kinds:[...H.kinds]}:{},...H.selected_uuids!==void 0?{selected_uuids:[...H.selected_uuids]}:{}},s("filters-change",u.value),(Q=l.routerReplace)==null||Q.call(l,{query:u.value})}function vt(){gf({...l.albumHttpClient!==void 0?{httpClient:l.albumHttpClient}:{},...l.albumBaseUrl!==void 0?{albumBaseUrl:l.albumBaseUrl}:{}})}function gt(H){H.mediaIds.length!==0&&(p.value=H,v.value=!0)}function ot(){v.value=!1,p.value=null,ha.value=null}function Qt(H){const Q=new Set(H.mediaIds),Fe=m.value;if((Fe==null?void 0:Fe.kind)==="single"&&Q.has(Fe.media.uuid)){m.value=null;return}(Fe==null?void 0:Fe.kind)==="multi"&&(m.value=null)}function Rt(H){ht.value+=1,Qt(H)}async function Za(H){const Q=p.value;if(Q===null)return;const Fe=ha.value;try{await Ge.attachMedia(H,Q.mediaIds),Fe!==null&&await Promise.all(Q.mediaIds.map(ne=>Ge.detachMedia(Fe,ne))),v.value=!1,p.value=null,ha.value=null,Rt(Q),s("add-to-album",Q)}catch(ne){s("error",ne instanceof Error?ne:new Error(String(ne)))}}const ha=e.ref(null);function Cn(H){H.mediaIds.length===0||st.value===null||(p.value=H,ha.value=st.value.uuid,v.value=!0)}async function Ta(H){if(H.mediaIds.length===0||st.value===null)return;const Q=st.value.uuid;try{await Promise.all(H.mediaIds.map(Fe=>Ge.detachMedia(Q,Fe))),Rt(H)}catch(Fe){s("error",Fe instanceof Error?Fe:new Error(String(Fe)))}}function xa(H){return{mediaIds:[H.uuid],items:[H],source:"item"}}function Aa(){const H=m.value;if(H===null)return null;if(H.kind==="single")return xa(H.media);const Q=H.items??[];return Q.length===0?null:{mediaIds:Q.map(Fe=>Fe.uuid),items:Q,source:"bulk"}}function va(H){return H.name??H.file_name}function Qa(H){return`media-shell-item-actions-menu-${H}`}function On(H,Q){if(f.value===H){Ga(!0);return}h.value=(Q==null?void 0:Q.currentTarget)instanceof HTMLElement?Q.currentTarget:null,f.value=H,Re(Qa(H))}function Ga(H=!1){f.value=null,H&&e.nextTick(()=>fa(h.value))}function zn(H){if(H.key==="Escape"){H.preventDefault(),H.stopPropagation(),Ga(!0);return}cd(H,H.currentTarget instanceof HTMLElement?H.currentTarget:null)}function ga(H){H(),Ga(!1)}function Ra(H){Cn(xa(H))}async function Wo(H){await Ta(xa(H))}function lo(H){Wo(H)}function hi(H){const Q=H.mime_type.toLowerCase();return(H.is_image===!0||Q.startsWith("image/"))&&l.capabilities.allowImageEdit===!0?"image":Q.startsWith("video/")&&l.capabilities.allowVideoEdit===!0?"video":null}function vi(H){const Q=hi(H);Q!==null&&s("edit",{media:H,kind:Q})}function xn(H){const Q=m.value;(Q==null?void 0:Q.kind)==="single"&&Q.media.uuid===H.uuid&&(m.value={kind:"single",media:H}),ht.value+=1,s("metadata-updated",H)}function ba(H){const Q=H.original_url!==""?H.original_url:H.url;if(typeof document>"u"||typeof Q!="string"||Q==="")return;const Fe=document.createElement("a");Fe.href=Q,Fe.download=H.file_name,Fe.rel="noopener",Fe.target="_blank",document.body.appendChild(Fe),Fe.click(),Fe.remove()}function sn(H){return Object.entries(H).map(([Q,Fe])=>({uuid:Q,blocks:Fe}))}function so(H){if(typeof window>"u"||typeof window.confirm!="function")return!1;const Q=new Set;for(const Qe of H)for(const Tt of Qe.blocks)Tt.context&&Q.add(Tt.context);const Fe=Array.from(Q),ne=Fe.length>0?`This media is still attached to: ${Fe.map(Qe=>`"${Qe}"`).join(", ")}. Remove from those and move to trash?`:"This media is still attached to other items. Remove from those and move to trash?";return window.confirm(ne)}function jn(H,Q){const Fe=H.results.filter(ne=>ne.status==="trashed"||ne.status==="already_trashed").map(ne=>ne.uuid);if(Fe.length!==0){if(y.value!==null){const ne=new Set(Fe);y.value=y.value.filter(Qe=>!ne.has(Qe)),y.value.length===0&&Y()}Rt(Q),s("deleted",Fe)}}async function en(H){if(!(l.capabilities.allowBulkDelete!==!0||H.mediaIds.length===0))try{const Q=await Je.deleteMany(H.mediaIds);jn(Q,H)}catch(Q){if(Q instanceof Wl){const Fe=sn(Q.softBlocks);if(!so(Fe))return;try{const ne=await Je.deleteMany(H.mediaIds,{confirmed:!0});jn(ne,H)}catch(ne){s("error",ne instanceof Error?ne:new Error(String(ne)))}return}s("error",Q instanceof Error?Q:new Error(String(Q)))}}function Wn(H){en(xa(H))}function Xa(){const H=Aa();H!==null&&gt(H)}function da(){const H=Aa();H!==null&&en(H)}function Ba(H){if(st.value!==null){Ra(H);return}l.capabilities.allowAddToAlbum===!0&&gt(xa(H))}function tn(H,Q){if(Q>0){X(H.mediaIds);return}if(H.mediaIds.length===1&&H.items.length===1){m.value={kind:"single",media:H.items[0]};return}m.value={kind:"multi",count:H.mediaIds.length,items:H.items}}e.watch(()=>l.initialAlbumId,H=>{c.value=H});function co(H){H===null||H==="unfiled"||Ge.albumsById.value.has(H)||Ge.fetchAlbum(H).catch(Q=>{s("error",Q instanceof Error?Q:new Error(String(Q)))})}return e.watch(()=>c.value,H=>co(H)),vt(),e.onMounted(()=>{co(c.value),Ge.fetchAlbums({parent_id:null}).catch(H=>{s("error",H instanceof Error?H:new Error(String(H)))}),typeof window<"u"&&(window.addEventListener("keydown",se),document.addEventListener("pointerdown",xe,!0),le())}),e.onUnmounted(()=>{typeof window<"u"&&(window.removeEventListener("keydown",se),document.removeEventListener("pointerdown",xe,!0),Z())}),e.watch(()=>[l.albumHttpClient,l.albumBaseUrl],()=>vt()),(H,Q)=>{var Fe;return e.openBlock(),e.createElementBlock("section",{class:e.normalizeClass(["media-library-shell",{"is-density-compact":_.value==="compact"}]),"data-density":_.value,"data-testid":"media-library-shell"},[e.createElementVNode("header",hP,[e.createElementVNode("nav",vP,[e.createElementVNode("button",{type:"button",class:e.normalizeClass({"is-active":d.value==="library"}),"data-testid":"tab-media-library",onClick:Q[0]||(Q[0]=ne=>oe("library"))},e.toDisplayString(Pe.value.library),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass({"is-active":d.value==="albums"}),"data-testid":"tab-media-albums",onClick:Q[1]||(Q[1]=ne=>oe("albums"))},e.toDisplayString(Pe.value.albums),3),e.createElementVNode("button",{type:"button",class:e.normalizeClass({"is-active":d.value==="trash"}),"data-testid":"tab-media-trash",onClick:Q[2]||(Q[2]=ne=>oe("trash"))},e.toDisplayString(Pe.value.trash),3)]),e.createElementVNode("button",{type:"button",class:"media-library-shell__shortcut-trigger","data-testid":"btn-media-shortcuts","aria-label":"Show keyboard shortcuts",onClick:Q[3]||(Q[3]=ne=>g.value=!0)}," ? "),y.value!==null?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-library-shell__exit-selection","data-testid":"btn-media-exit-selection-scope",onClick:fe},e.toDisplayString(Pe.value.exitSelectionScope),1)):e.createCommentVNode("",!0)]),d.value!=="trash"&&!W.value?(e.openBlock(),e.createBlock(jf,{key:0,class:"media-library-shell__toolbar-row",sort:nt.value,density:_.value,"has-date-filter":tt.value,"http-client":l.httpClient,"onUpdate:sort":he,"onUpdate:density":Te,onJumpTo:Ke,onJumpToAll:ct,onUploadFiles:Wt},null,8,["sort","density","has-date-filter","http-client"])):e.createCommentVNode("",!0),Ve.value.length>0&&d.value!=="trash"&&!W.value&&!J.value?(e.openBlock(),e.createElementBlock("nav",{key:1,class:"media-library-shell__recent-albums","data-testid":"media-library-recent-albums","aria-label":Pe.value.recentSection},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Ve.value,ne=>(e.openBlock(),e.createElementBlock("button",{key:ne.id,type:"button",class:"media-library-shell__recent-chip","data-testid":`btn-media-recent-album-${ne.id}`,onClick:Qe=>$e(ne.id)},e.toDisplayString(ne.name),9,bP))),128))],8,gP)):e.createCommentVNode("",!0),e.unref(_t).uploads.value.length>0&&d.value!=="trash"?(e.openBlock(),e.createElementBlock("div",yP,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(_t).uploads.value,ne=>(e.openBlock(),e.createElementBlock("article",{key:ne.cid,class:e.normalizeClass(["media-library-shell__upload-tile",`is-status-${ne.status}`]),"data-testid":`upload-tile-${ne.cid}`},[e.createElementVNode("div",kP,[ne.previewUrl?(e.openBlock(),e.createElementBlock("img",{key:0,src:ne.previewUrl,alt:ne.fileName},null,8,_P)):(e.openBlock(),e.createElementBlock("span",EP,"⤴"))]),e.createElementVNode("div",SP,[e.createElementVNode("span",CP,e.toDisplayString(ne.fileName),1),e.createElementVNode("span",xP,[ne.status==="uploading"||ne.status==="queued"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[e.createTextVNode("Uploading…")],64)):ne.status==="success"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[e.createTextVNode("Uploaded")],64)):(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[e.createTextVNode(e.toDisplayString(ne.errorMessage??"Upload failed"),1)],64))])]),e.createElementVNode("button",{type:"button",class:"media-library-shell__upload-dismiss","data-testid":`btn-upload-dismiss-${ne.cid}`,onClick:Qe=>e.unref(_t).dismiss(ne.cid)}," × ",8,NP)],10,wP))),128))])):e.createCommentVNode("",!0),e.createElementVNode("div",{class:e.normalizeClass(["media-library-shell__body",{"has-inspector-target":m.value!==null}])},[e.createElementVNode("main",VP,[J.value?(e.openBlock(),e.createElementBlock("header",TP,[e.createElementVNode("button",{type:"button",class:"media-library-shell__breadcrumb-back","data-testid":"btn-media-album-back",onClick:At}," ← "+e.toDisplayString(Pe.value.albums),1),Q[25]||(Q[25]=e.createElementVNode("span",{class:"media-library-shell__breadcrumb-sep","aria-hidden":"true"},"/",-1)),e.createElementVNode("div",BP,[e.createElementVNode("span",MP,e.toDisplayString(ce.value),1),Ue.value?(e.openBlock(),e.createElementBlock("div",IP,[e.createElementVNode("button",{type:"button",class:"media-library-shell__album-action-trigger","data-testid":"btn-media-active-album-actions","aria-label":Pe.value.albumActions(Ue.value.name),"aria-haspopup":"menu","aria-controls":Se(Ue.value.id),"aria-expanded":T.value===Ue.value.id?"true":"false",onClick:Q[4]||(Q[4]=e.withModifiers(ne=>Oe(Ue.value.id,ne),["stop"]))}," ⋯ ",8,$P),T.value===Ue.value.id?(e.openBlock(),e.createElementBlock("div",{key:0,id:Se(Ue.value.id),class:"media-library-shell__album-action-menu",role:"menu","data-testid":"media-active-album-action-menu",onKeydown:rt},[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"btn-media-active-album-edit",onClick:Q[5]||(Q[5]=e.withModifiers(ne=>bt(Ue.value),["stop"]))},e.toDisplayString(Pe.value.editAlbum),1),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":"btn-media-active-album-delete",onClick:Q[6]||(Q[6]=e.withModifiers(ne=>Ct(Ue.value),["stop"]))},e.toDisplayString(Pe.value.deleteAlbum),1)],40,FP)):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])])):e.createCommentVNode("",!0),d.value==="trash"?(e.openBlock(),e.createBlock(th,{key:1,"http-client":l.httpClient,onError:Q[7]||(Q[7]=ne=>s("error",ne))},null,8,["http-client"])):W.value?(e.openBlock(),e.createElementBlock("section",{key:2,class:"media-album-grid","data-testid":"media-album-grid","aria-label":Pe.value.albums},[e.createElementVNode("header",AP,[e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":Q[8]||(Q[8]=ne=>I.value=ne),type:"search",class:"media-album-grid__search",placeholder:Pe.value.findAlbum,"data-testid":"input-media-album-filter","aria-label":Pe.value.findAlbum},null,8,RP),[[e.vModelText,I.value]])]),e.createElementVNode("div",LP,[Ht.value?(e.openBlock(),e.createElementBlock("form",{key:1,class:"media-album-grid__new-tile media-album-grid__new-tile--form","data-testid":"media-album-new-tile-form",role:"listitem",novalidate:"",onSubmit:Q[11]||(Q[11]=e.withModifiers(ne=>void Et(),["prevent"])),onKeydown:Kt},[e.createElementVNode("label",UP,[e.createElementVNode("span",OP,e.toDisplayString(Pe.value.newAlbumNamePrompt),1),e.withDirectives(e.createElementVNode("input",{id:"media-album-grid-new-name",ref_key:"newAlbumInputRef",ref:Gt,"onUpdate:modelValue":Q[10]||(Q[10]=ne=>Zt.value=ne),type:"text",class:e.normalizeClass(["media-album-grid__new-tile-input",{"media-album-grid__new-tile-input--error":It.value!==""}]),maxlength:Ir+16,"aria-invalid":It.value!==""?"true":"false","aria-describedby":"media-album-grid-new-error",autocomplete:"off","data-testid":"input-media-album-new-tile-name",disabled:Ut.value,onInput:Yt},null,42,zP),[[e.vModelText,Zt.value]])]),It.value!==""?(e.openBlock(),e.createElementBlock("p",jP,e.toDisplayString(It.value),1)):e.createCommentVNode("",!0),e.createElementVNode("div",WP,[e.createElementVNode("button",{type:"button",class:"media-album-grid__new-tile-btn media-album-grid__new-tile-btn--ghost","data-testid":"btn-media-album-new-tile-cancel",disabled:Ut.value,onClick:yt},e.toDisplayString(Pe.value.newAlbumCancel),9,HP),e.createElementVNode("button",{type:"submit",class:"media-album-grid__new-tile-btn media-album-grid__new-tile-btn--primary","data-testid":"btn-media-album-new-tile-submit",disabled:!pe.value},[Ut.value?(e.openBlock(),e.createElementBlock("span",GP,"…")):(e.openBlock(),e.createElementBlock("span",XP,e.toDisplayString(Pe.value.newAlbumSubmit),1))],8,ZP)])],32)):(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-album-grid__new-tile","data-testid":"btn-media-album-new-tile",role:"listitem","aria-label":"Create new album",onClick:Q[9]||(Q[9]=ne=>void wt())},[Q[26]||(Q[26]=e.createElementVNode("span",{class:"media-album-grid__new-tile-glyph","aria-hidden":"true"},"+",-1)),e.createElementVNode("span",PP,e.toDisplayString(Pe.value.newAlbum),1)])),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(be.value,ne=>(e.openBlock(),e.createElementBlock("article",{key:ne.id,class:"media-album-grid__tile","data-testid":`media-album-tile-${ne.id}`,role:"listitem"},[e.createElementVNode("button",{type:"button",class:"media-album-grid__tile-button","data-testid":`btn-media-album-open-${ne.id}`,onClick:Qe=>$e(ne.id)},[e.createElementVNode("div",JP,[ye(ne)!==null?(e.openBlock(),e.createElementBlock("img",{key:0,class:"media-album-grid__cover-image",src:ye(ne),alt:"",loading:"lazy"},null,8,YP)):(e.openBlock(),e.createElementBlock("span",QP,e.toDisplayString(_e(ne)),1))]),e.createElementVNode("div",eU,[e.createElementVNode("span",tU,e.toDisplayString(ne.name),1),e.createElementVNode("span",aU,e.toDisplayString(Ne(ne)),1)])],8,qP),e.createElementVNode("div",nU,[e.createElementVNode("button",{type:"button",class:"media-album-grid__tile-action-trigger","data-testid":`btn-media-album-actions-${ne.id}`,"aria-label":Pe.value.albumActions(ne.name),"aria-haspopup":"menu","aria-controls":Se(ne.id),"aria-expanded":T.value===ne.id?"true":"false",onClick:e.withModifiers(Qe=>Oe(ne.id,Qe),["stop"])}," ⋯ ",8,oU),T.value===ne.id?(e.openBlock(),e.createElementBlock("div",{key:0,id:Se(ne.id),class:"media-album-grid__action-menu",role:"menu","data-testid":`media-album-action-menu-${ne.id}`,onKeydown:rt},[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`btn-media-album-edit-${ne.id}`,onClick:e.withModifiers(Qe=>bt(ne),["stop"])},e.toDisplayString(Pe.value.editAlbum),9,rU),e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`btn-media-album-delete-${ne.id}`,onClick:e.withModifiers(Qe=>Ct(ne),["stop"])},e.toDisplayString(Pe.value.deleteAlbum),9,lU)],40,iU)):e.createCommentVNode("",!0)])],8,KP))),128))]),be.value.length===0&&I.value!==""?(e.openBlock(),e.createElementBlock("p",sU,e.toDisplayString(Pe.value.noAlbumMatchesFound),1)):be.value.length===0?(e.openBlock(),e.createElementBlock("p",dU,e.toDisplayString(Pe.value.noAlbumsYet),1)):e.createCommentVNode("",!0)],8,DP)):(e.openBlock(),e.createBlock(Qf,{key:`workspace-${ht.value}`,"http-client":l.httpClient,filters:$t.value,"initial-view":Ot.value,capabilities:l.capabilities,labels:{scopeLabel:ke.value},onFiltersChange:qe,onCreatePost:Q[12]||(Q[12]=ne=>s("create-post",ne)),onCreateGallery:Q[13]||(Q[13]=ne=>s("create-gallery",ne)),onAddToAlbum:gt,onEdit:Q[14]||(Q[14]=ne=>s("edit",ne)),onDeleted:Q[15]||(Q[15]=ne=>s("deleted",ne)),onRestored:Q[16]||(Q[16]=ne=>s("restored",ne)),onRestoreConflict:Q[17]||(Q[17]=ne=>s("restore-conflict",ne)),onError:Q[18]||(Q[18]=ne=>s("error",ne))},{"bulk-actions":e.withCtx(ne=>[e.createVNode(qd,{"selected-count":ne.selectedCount,"cross-page-count":ne.crossPageCount,scope:Jt.value,"source-album":st.value,capabilities:l.capabilities,onClear:ne.clearSelection,onBulkMoveToTrash:ne.onBulkDelete,onBulkAddToAlbum:Qe=>{var Tt;return(Tt=ne.onAddToAlbum)==null?void 0:Tt.call(ne)},onBulkMoveBetweenAlbums:Qe=>Cn({mediaIds:ne.selectedItemIds,items:ne.selectedItems,source:"bulk"}),onBulkRemoveFromCurrentAlbum:Qe=>void Ta({mediaIds:ne.selectedItemIds,items:ne.selectedItems,source:"bulk"}),onBulkCreatePost:Qe=>{var Tt;return(Tt=ne.onCreatePost)==null?void 0:Tt.call(ne)},onBulkCreateGallery:Qe=>{var Tt;return(Tt=ne.onCreateGallery)==null?void 0:Tt.call(ne)},onInspect:Qe=>tn({mediaIds:ne.selectedItemIds,items:ne.selectedItems},ne.crossPageCount)},null,8,["selected-count","cross-page-count","scope","source-album","capabilities","onClear","onBulkMoveToTrash","onBulkAddToAlbum","onBulkMoveBetweenAlbums","onBulkRemoveFromCurrentAlbum","onBulkCreatePost","onBulkCreateGallery","onInspect"])]),"item-actions":e.withCtx(ne=>[e.createElementVNode("div",cU,[e.createElementVNode("div",uU,[e.createElementVNode("button",{type:"button",class:"media-library-shell__item-action-trigger","data-testid":`btn-media-shell-item-actions-${ne.media.uuid}`,"aria-label":Pe.value.itemActions(va(ne.media)),"aria-haspopup":"menu","aria-controls":Qa(ne.media.uuid),"aria-expanded":f.value===ne.media.uuid?"true":"false",onClick:Qe=>On(ne.media.uuid,Qe)}," ... ",8,mU),f.value===ne.media.uuid?(e.openBlock(),e.createElementBlock("div",{key:0,id:Qa(ne.media.uuid),class:"media-library-shell__item-action-panel",role:"menu","data-testid":`media-shell-item-actions-menu-${ne.media.uuid}`,onKeydown:zn},[e.createElementVNode("button",{type:"button",role:"menuitem","data-testid":`btn-media-shell-preview-${ne.media.uuid}`,onClick:Qe=>ga(ne.onPreview)},e.toDisplayString(ne.labels.previewButton),9,fU),ne.onEdit?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",role:"menuitem","data-testid":`btn-media-shell-edit-${ne.media.uuid}`,onClick:Qe=>ga(ne.onEdit)},e.toDisplayString(ne.labels.editButton),9,hU)):e.createCommentVNode("",!0),ne.onCreatePost?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",role:"menuitem","data-testid":`btn-media-shell-create-post-${ne.media.uuid}`,onClick:Qe=>ga(ne.onCreatePost)},e.toDisplayString(ne.labels.createPostButton),9,vU)):e.createCommentVNode("",!0),ne.onCreateGallery?(e.openBlock(),e.createElementBlock("button",{key:2,type:"button",role:"menuitem","data-testid":`btn-media-shell-create-gallery-${ne.media.uuid}`,onClick:Qe=>ga(ne.onCreateGallery)},e.toDisplayString(ne.labels.createGalleryButton),9,gU)):e.createCommentVNode("",!0),st.value!==null&&l.capabilities.allowAddToAlbum===!0?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button",role:"menuitem","data-testid":`btn-media-shell-move-album-${ne.media.uuid}`,onClick:Qe=>ga(()=>Ra(ne.media))},e.toDisplayString(Pe.value.moveToAnotherAlbum),9,bU)):ne.onAddToAlbum?(e.openBlock(),e.createElementBlock("button",{key:4,type:"button",role:"menuitem","data-testid":`btn-media-shell-add-album-${ne.media.uuid}`,onClick:Qe=>ga(ne.onAddToAlbum)},e.toDisplayString(ne.labels.addToAlbumButton),9,yU)):e.createCommentVNode("",!0),st.value!==null?(e.openBlock(),e.createElementBlock("button",{key:5,type:"button",role:"menuitem","data-testid":`btn-media-shell-remove-current-album-${ne.media.uuid}`,onClick:Qe=>ga(()=>Wo(ne.media))},e.toDisplayString(Pe.value.removeFromThisAlbum),9,wU)):e.createCommentVNode("",!0)],40,pU)):e.createCommentVNode("",!0)])])]),_:1},8,["http-client","filters","initial-view","capabilities","labels"]))]),e.createVNode(zf,{open:v.value,"selected-count":((Fe=p.value)==null?void 0:Fe.mediaIds.length)??0,onCancel:ot,onConfirm:Za,onError:Q[19]||(Q[19]=ne=>s("error",ne))},null,8,["open","selected-count"]),e.createVNode(qf,{class:"media-library-shell__inspector",target:m.value,"http-client":l.httpClient,capabilities:q.value,mode:k.value,"in-album-scope":c.value!==null&&c.value!=="unfiled",labels:{removeFromThisAlbum:Pe.value.removeFromThisAlbum,removeFromAlbums:st.value!==null?Pe.value.moveToAnotherAlbum:Pe.value.addToAlbum},onEdit:vi,onDownload:ba,onMoveToTrash:Wn,onSetAsAlbumCover:zt,onRemoveFromThisAlbum:lo,onRemoveFromAlbums:Ba,onBulkAddToAlbum:Xa,onBulkCreateAlbum:Xa,onBulkMoveToTrash:da,onMetadataUpdated:xn,onClose:F},null,8,["target","http-client","capabilities","mode","in-album-scope","labels"])],2),(e.openBlock(),e.createBlock(e.Teleport,{to:"body"},[me.value&&B.value?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-album-dialog","data-testid":"media-album-dialog",role:"presentation",onKeydown:pt},[e.createElementVNode("button",{type:"button",class:"media-album-dialog__backdrop","data-testid":"btn-media-album-dialog-backdrop","aria-label":Pe.value.closeAlbumDialog,tabindex:"-1",onClick:mt},null,8,kU),e.createElementVNode("section",{ref_key:"albumDialogPanelRef",ref:z,class:"media-album-dialog__panel",role:"dialog","aria-modal":"true","aria-labelledby":"media-album-dialog-title","aria-describedby":N.value==="delete"?"media-album-dialog-delete-description media-album-dialog-error":void 0},[N.value==="edit"?(e.openBlock(),e.createElementBlock("form",{key:0,class:"media-album-dialog__form","data-testid":"media-album-edit-form",onSubmit:Q[22]||(Q[22]=e.withModifiers(ne=>void Nt(),["prevent"]))},[e.createElementVNode("header",EU,[e.createElementVNode("h3",SU,e.toDisplayString(Pe.value.editAlbumTitle),1)]),e.createElementVNode("label",CU,[e.createElementVNode("span",null,e.toDisplayString(Pe.value.albumNameLabel),1),e.withDirectives(e.createElementVNode("input",{ref_key:"albumEditNameRef",ref:j,"onUpdate:modelValue":Q[20]||(Q[20]=ne=>P.value=ne),type:"text","data-testid":"input-media-album-edit-name",maxlength:Ir+16,"aria-invalid":M.value!==""?"true":"false",autocomplete:"off",disabled:E.value},null,8,xU),[[e.vModelText,P.value]])]),e.createElementVNode("label",NU,[e.createElementVNode("span",null,e.toDisplayString(Pe.value.albumDescriptionLabel),1),e.withDirectives(e.createElementVNode("textarea",{"onUpdate:modelValue":Q[21]||(Q[21]=ne=>x.value=ne),"data-testid":"textarea-media-album-edit-description",rows:"4",disabled:E.value},null,8,VU),[[e.vModelText,x.value]])]),M.value!==""?(e.openBlock(),e.createElementBlock("p",TU,e.toDisplayString(M.value),1)):e.createCommentVNode("",!0),e.createElementVNode("footer",BU,[e.createElementVNode("button",{type:"button",class:"media-album-dialog__button","data-testid":"btn-media-album-edit-cancel",disabled:E.value,onClick:mt},e.toDisplayString(Pe.value.cancelAlbumEdit),9,MU),e.createElementVNode("button",{type:"submit",class:"media-album-dialog__button media-album-dialog__button--primary","data-testid":"btn-media-album-edit-save",disabled:!Vt.value},e.toDisplayString(Pe.value.saveAlbum),9,IU)])],32)):(e.openBlock(),e.createElementBlock("div",$U,[e.createElementVNode("header",FU,[e.createElementVNode("h3",DU,e.toDisplayString(Pe.value.deleteAlbumTitle(B.value.name)),1)]),e.createElementVNode("p",AU,e.toDisplayString(Pe.value.deleteAlbumDescription),1),M.value!==""?(e.openBlock(),e.createElementBlock("p",RU,e.toDisplayString(M.value),1)):e.createCommentVNode("",!0),e.createElementVNode("footer",LU,[e.createElementVNode("button",{ref_key:"albumDeleteCancelRef",ref:L,type:"button",class:"media-album-dialog__button","data-testid":"btn-media-album-delete-cancel",disabled:D.value,onClick:mt},e.toDisplayString(Pe.value.cancelDeleteAlbum),9,PU),e.createElementVNode("button",{type:"button",class:"media-album-dialog__button media-album-dialog__button--danger","data-testid":"btn-media-album-delete-confirm",disabled:D.value,onClick:Q[23]||(Q[23]=ne=>void Ce())},e.toDisplayString(Pe.value.confirmDeleteAlbum),9,UU)])]))],8,_U)],32)):e.createCommentVNode("",!0)])),e.createVNode(Wf,{open:g.value,onClose:Q[24]||(Q[24]=ne=>g.value=!1)},null,8,["open"])],10,fP)}}}),zU=Ae(OU,[["__scopeId","data-v-ad1d5942"]]),jU={class:"album-nav-rail__search"},WU={class:"album-nav-rail__sr-only"},HU=["placeholder"],ZU={class:"album-nav-rail__primary","aria-label":"Media scopes"},GU={class:"album-nav-rail__count"},XU={class:"album-nav-rail__count"},KU={key:0,class:"album-nav-rail__recent","data-testid":"album-rail-recent","aria-label":"Recent albums"},qU={class:"album-nav-rail__section-label"},JU=["data-testid","onClick"],YU={class:"album-nav-rail__tree"},QU={class:"album-nav-rail__utility"},e9={class:"album-nav-rail__count"},t9=e.defineComponent({__name:"AlbumNavRail",props:{activeAlbumId:{},collapsed:{type:Boolean,default:!1},allowDragDropTarget:{type:Boolean,default:!1},mediaCounts:{default:()=>({})},labels:{default:()=>({})},recentAlbums:{default:()=>[]}},emits:["change-album","create-album","drop-media","open-trash"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.ref(""),l=e.ref([]),s=e.ref(null),d=e.computed(()=>{var w,_,b,g,I,T;return{allMedia:((w=t.labels)==null?void 0:w.allMedia)??"All media",unfiled:((_=t.labels)==null?void 0:_.unfiled)??"Unfiled",newAlbum:((b=t.labels)==null?void 0:b.newAlbum)??"New album",findAlbum:((g=t.labels)==null?void 0:g.findAlbum)??"Find album...",trash:((I=t.labels)==null?void 0:I.trash)??"Trash",recentSection:((T=t.labels)==null?void 0:T.recentSection)??"Recent"}});function c(w){return typeof w=="number"&&Number.isFinite(w)?String(w):""}function u(w){n("change-album",w.id)}function m(w,_){i.value=!1,n("create-album",_?{name:w,parentId:_}:{name:w})}function p(w){var b;const _=((b=w.dataTransfer)==null?void 0:b.getData("application/x-mediables-media-ids"))??"";if(_.trim()==="")return l.value;try{const g=JSON.parse(_);return Array.isArray(g)?g.filter(I=>typeof I=="string"&&I.trim()!==""):[]}catch{return _.split(",").map(g=>g.trim()).filter(g=>g!=="")}}function f(w,_){t.allowDragDropTarget&&(w.preventDefault(),s.value=_)}function h(){s.value=null}function v(w,_){if(!t.allowDragDropTarget)return;w.preventDefault();const b=p(w);s.value=null,b.length!==0&&n("drop-media",{albumId:_==="all"||_==="unfiled"?null:_,mediaIds:b})}const y=e.computed(()=>({"is-collapsed":t.collapsed}));return(w,_)=>(e.openBlock(),e.createElementBlock("aside",{class:e.normalizeClass(["album-nav-rail",y.value]),"data-testid":"album-rail"},[e.createElementVNode("label",jU,[e.createElementVNode("span",WU,e.toDisplayString(d.value.findAlbum),1),e.withDirectives(e.createElementVNode("input",{"onUpdate:modelValue":_[0]||(_[0]=b=>r.value=b),type:"search",placeholder:d.value.findAlbum,"data-testid":"input-album-rail-search"},null,8,HU),[[e.vModelText,r.value]])]),e.createElementVNode("nav",ZU,[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["album-nav-rail__row",{"is-active":t.activeAlbumId===null,"is-drop-target":s.value==="all"}]),"data-testid":"album-rail-row-all",onClick:_[1]||(_[1]=b=>n("change-album",null)),onDragover:_[2]||(_[2]=b=>f(b,"all")),onDragleave:h,onDrop:_[3]||(_[3]=b=>v(b,"all"))},[e.createElementVNode("span",null,e.toDisplayString(d.value.allMedia),1),e.createElementVNode("span",GU,e.toDisplayString(c(t.mediaCounts.all)),1)],34),e.createElementVNode("button",{type:"button",class:e.normalizeClass(["album-nav-rail__row",{"is-active":t.activeAlbumId==="unfiled","is-drop-target":s.value==="unfiled"}]),"data-testid":"album-rail-row-unfiled",onClick:_[4]||(_[4]=b=>n("change-album","unfiled")),onDragover:_[5]||(_[5]=b=>f(b,"unfiled")),onDragleave:h,onDrop:_[6]||(_[6]=b=>v(b,"unfiled"))},[e.createElementVNode("span",null,e.toDisplayString(d.value.unfiled),1),e.createElementVNode("span",XU,e.toDisplayString(c(t.mediaCounts.unfiled)),1)],34)]),t.recentAlbums.length>0?(e.openBlock(),e.createElementBlock("section",KU,[e.createElementVNode("p",qU,e.toDisplayString(d.value.recentSection),1),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.recentAlbums,b=>(e.openBlock(),e.createElementBlock("button",{key:`recent-${b.id}`,type:"button",class:e.normalizeClass(["album-nav-rail__row album-nav-rail__row--recent",{"is-active":t.activeAlbumId===b.id}]),"data-testid":`album-rail-recent-${b.id}`,onClick:g=>n("change-album",b.id)},[e.createElementVNode("span",null,e.toDisplayString(b.name),1)],10,JU))),128))])):e.createCommentVNode("",!0),e.createElementVNode("div",YU,[e.createVNode(zl,{"model-value":t.activeAlbumId==="unfiled"?null:t.activeAlbumId,mode:"rail",compact:!0,draggable:!1,onAlbumSelected:u},null,8,["model-value"])]),e.createElementVNode("button",{type:"button",class:"album-nav-rail__new","data-testid":"btn-album-rail-new",onClick:_[7]||(_[7]=b=>i.value=!0)}," + "+e.toDisplayString(d.value.newAlbum),1),e.createVNode(jd,{open:i.value,onCancel:_[8]||(_[8]=b=>i.value=!1),onCreate:m},null,8,["open"]),e.createElementVNode("div",QU,[e.createElementVNode("button",{type:"button",class:e.normalizeClass(["album-nav-rail__row album-nav-rail__row--utility",{"is-drop-target":s.value==="trash"}]),"data-testid":"album-rail-row-trash",onClick:_[9]||(_[9]=b=>n("open-trash")),onDragover:_[10]||(_[10]=b=>f(b,"trash")),onDragleave:h,onDrop:_[11]||(_[11]=b=>v(b,"trash"))},[e.createElementVNode("span",null,e.toDisplayString(d.value.trash),1),e.createElementVNode("span",e9,e.toDisplayString(c(t.mediaCounts.trash)),1)],34)])],2))}}),a9=Ae(t9,[["__scopeId","data-v-0913c5b6"]]),n9=o=>`/v1/media/${o}/hide`,o9=o=>`/v1/media/${o}/unhide`,i9="/v1/media/bulk-hide",r9="/v1/media/bulk-unhide";function l9(o){const a=e.ref(!1),t=o.hideEndpoint??n9,n=o.unhideEndpoint??o9,i=o.bulkHideEndpoint??i9,r=o.bulkUnhideEndpoint??r9;async function l(d){a.value=!0;try{await o.httpClient.post(d,{})}finally{a.value=!1}}async function s(d,c){if(c.length===0)throw new Error("media_uuids must not be empty");a.value=!0;try{const u=await o.httpClient.post(d,{media_uuids:c});return{updated_count:Number((u==null?void 0:u.updated_count)??0),skipped_count:Number((u==null?void 0:u.skipped_count)??0)}}finally{a.value=!1}}return{hide:d=>l(t(d)),unhide:d=>l(n(d)),bulkHide:d=>s(i,d),bulkUnhide:d=>s(r,d),isMutating:a}}const s9={key:0,class:"media-selection-tray","data-testid":"media-selection-tray"},d9={class:"media-selection-tray__header"},c9={class:"media-selection-tray__title"},u9={class:"media-selection-tray__items"},m9={class:"media-selection-tray__item-preview"},p9=["src","alt"],f9={key:1,class:"media-selection-tray__file-icon"},h9={class:"media-selection-tray__item-copy"},v9=["aria-label","onClick"],g9=e.defineComponent({__name:"MediaSelectionTray",props:{items:{},selectedCountLabel:{default:"Selected items"},dismissLabel:{default:"Remove"}},emits:["remove"],setup(o,{emit:a}){const t=a;function n(r){var l;return r?r.thumbnail_url??((l=r.conversion_urls)==null?void 0:l.thumb)??r.preview_url??r.original_url??r.url??null:null}function i(r){return r!=null&&r.mime_type?r.mime_type.startsWith("image/"):!1}return(r,l)=>r.items.length>0?(e.openBlock(),e.createElementBlock("section",s9,[e.createElementVNode("header",d9,[e.createElementVNode("h3",c9,e.toDisplayString(r.selectedCountLabel),1)]),e.createElementVNode("div",u9,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.items,s=>{var d,c,u,m;return e.openBlock(),e.createElementBlock("article",{key:s.id,class:"media-selection-tray__item"},[e.createElementVNode("div",m9,[i(s.media)&&n(s.media)?(e.openBlock(),e.createElementBlock("img",{key:0,src:n(s.media),alt:((d=s.media)==null?void 0:d.alt_text)??((c=s.media)==null?void 0:c.file_name)??"Selected media",class:"media-selection-tray__thumb"},null,8,p9)):(e.openBlock(),e.createElementBlock("div",f9,[...l[0]||(l[0]=[e.createElementVNode("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[e.createElementVNode("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.createElementVNode("polyline",{points:"14 2 14 8 20 8"})],-1)])]))]),e.createElementVNode("div",h9,[e.createElementVNode("strong",null,e.toDisplayString(((u=s.media)==null?void 0:u.file_name)??s.id),1),e.createElementVNode("span",null,e.toDisplayString(s.status),1)]),e.createElementVNode("button",{type:"button",class:"media-selection-tray__remove","aria-label":`${r.dismissLabel} ${((m=s.media)==null?void 0:m.file_name)??s.id}`,onClick:p=>t("remove",s.id)},e.toDisplayString(r.dismissLabel),9,v9)])}),128))])])):e.createCommentVNode("",!0)}}),b9=Ae(g9,[["__scopeId","data-v-f2a3d69d"]]);function Qd(o={}){const a=e.ref(!1),t=e.ref(!1),n=e.ref(null),i=e.ref(null),r=e.ref(0),l=e.ref(0),s=e.ref(null),d=e.ref(null),c=e.computed(()=>d.value!==null),u=_=>{if(r.value++,d.value=null,i.value=null,t.value=!1,_!=null&&typeof _=="object"&&!(_ instanceof Blob)&&("image"in _||"state"in _||"sessionKey"in _)){const b=_;n.value=b.image??null,s.value=b.state??null,l.value=b.sessionKey??r.value}else n.value=_??null,s.value=null,l.value=r.value;a.value=!0},m=()=>{a.value=!1,n.value=null,i.value=null,d.value=null,t.value=!1,s.value=null},p=async _=>{try{return t.value=!0,i.value=_,o.onSave&&await o.onSave(_),m(),_}catch(b){const g=b;throw d.value=g,o.onError&&o.onError(g),g}finally{t.value=!1}},f=()=>{o.onCancel&&o.onCancel(),m()},h=_=>{d.value=_,o.onError&&o.onError(_)},v=()=>{d.value=null},y=()=>i.value,w=e.computed(()=>a.value&&i.value!==null&&!t.value);return{isOpen:a,isProcessing:t,uploadedImage:n,editedImage:i,sessionKey:l,initialState:s,error:d,hasError:c,hasUnsavedChanges:w,open:u,close:m,handleSave:p,handleCancel:f,handleError:h,clearError:v,getEditedImage:y}}let _s=null;function y9(o){return _s||(_s=Qd(o)),_s}function w9(o){return a=>new Promise((t,n)=>{Qd({...o,onSave:async r=>{o!=null&&o.onSave&&await o.onSave(r),t(r)},onError:r=>{o!=null&&o.onError&&o.onError(r),n(r)},onCancel:()=>{o!=null&&o.onCancel&&o.onCancel(),n(new Error("User cancelled"))}}).open(a)})}function ec(o){return o.filter(a=>a.media&&!a.markedForRemoval).map((a,t)=>{const n={uuid:a.media.uuid,name:a.name,order:t};return a.customProperties&&(n.custom_properties=a.customProperties),n})}function ud(o){return o.map((a,t)=>{const n={media:a,clientId:a.uuid,name:a.name||a.file_name,order:t};return a.custom_properties&&(n.customProperties=a.custom_properties),n})}function tc(o){if(o){const t={};o.apiBaseUrl!==void 0&&(t.apiBaseUrl=o.apiBaseUrl),o.isAdmin!==void 0&&(t.isAdmin=o.isAdmin),ai(t)}return{name:"mediables",async upload(t,n){const r=await ja().uploadFile(t,{collection:(n==null?void 0:n.collection)||"default",customProperties:n==null?void 0:n.customProperties});if(!r)throw new Error("Upload failed: No media returned");return{media:r,uuid:r.uuid}},async attach(t,n){await ja().attachMedia(n.modelType,String(n.modelId),[t],n.collection||"images")},async attachMany(t,n){await ja().attachMedia(n.modelType,String(n.modelId),t,n.collection||"images")},async detach(t,n){await ja().detachMedia(n.modelType,String(n.modelId),t,n.collection||"images")},async reorder(t,n){await ja().reorderMedia(t.modelType,String(t.modelId),n,t.collection||"images")},async fetchModelMedia(t){return await ja().fetchModelMedia(t.modelType,String(t.modelId),t.collection||"images")},getUrl(t,n){return ja().getMediaUrl(t,n)},getThumbnailUrl(t){var n,i;return(n=t.conversion_urls)!=null&&n.thumb?t.conversion_urls.thumb:(i=t.conversion_urls)!=null&&i.thumbnail?t.conversion_urls.thumbnail:t.thumbnail_url?t.thumbnail_url:t.original_url||t.url||""},async delete(t){await ja().deleteMedia(t)},async update(t,n){const r=await ja().updateMedia(t,n);if(!r)throw new Error("Update failed: No media returned");return r},configure(t){const n={};t.apiBaseUrl!==void 0&&(n.apiBaseUrl=t.apiBaseUrl),t.isAdmin!==void 0&&(n.isAdmin=t.isAdmin),ai(n)}}}let Hr=null;function k9(){return Hr||(Hr=tc()),Hr}function _9(){Hr=null}const E9={apiBaseUrl:"/media-library-pro"};function $r(){var o;return typeof document>"u"?null:((o=document.querySelector('meta[name="csrf-token"]'))==null?void 0:o.getAttribute("content"))||null}function Es(o){const a={uuid:o.uuid,file_name:o.fileName||o.name,mime_type:`application/${o.extension}`,size:o.size,disk:"public",original_url:o.original_url||"",created_at:new Date().toISOString(),updated_at:new Date().toISOString()};return o.name&&(a.name=o.name),o.original_url&&(a.url=o.original_url),o.preview_url&&(a.thumbnail_url=o.preview_url,a.preview_url=o.preview_url),o.custom_properties&&(a.custom_properties=o.custom_properties),a}function ac(o){const a={...E9,...o};return{name:"spatie",async upload(n,i){const r=new FormData;r.append("file",n),i!=null&&i.collection&&r.append("collection",i.collection),i!=null&&i.customProperties&&r.append("custom_properties",JSON.stringify(i.customProperties));const l={Accept:"application/json",...a.headers},s=a.csrfToken||$r();s&&(l["X-CSRF-TOKEN"]=s);const d={method:"POST",headers:l,body:r,credentials:"include"};i!=null&&i.signal&&(d.signal=i.signal);const c=await fetch(`${a.apiBaseUrl}/uploads`,d);if(!c.ok){const p=await c.json().catch(()=>({message:"Upload failed"}));throw new Error(p.message||`HTTP ${c.status}`)}const u=await c.json(),m=Es(u);return i!=null&&i.onProgress&&i.onProgress(100),{media:m,uuid:u.uuid}},async attach(n,i){},async attachMany(n,i){},async detach(n,i){},async reorder(n,i){},async fetchModelMedia(n){const i={Accept:"application/json",...a.headers},r=a.csrfToken||$r();r&&(i["X-CSRF-TOKEN"]=r);const l=new URLSearchParams;l.append("model_type",n.modelType),l.append("model_id",String(n.modelId)),n.collection&&l.append("collection",n.collection);try{const s=await fetch(`${a.apiBaseUrl}/media?${l}`,{method:"GET",headers:i,credentials:"include"});if(!s.ok)throw new Error(`HTTP ${s.status}`);return(await s.json()).map(Es)}catch{return[]}},getUrl(n,i){var r;if(i){const l=(r=n.conversion_urls)==null?void 0:r[i];if(l)return l}return n.original_url||n.url||""},getThumbnailUrl(n){var i,r;return n.preview_url?n.preview_url:(i=n.conversion_urls)!=null&&i.preview?n.conversion_urls.preview:n.thumbnail_url?n.thumbnail_url:(r=n.conversion_urls)!=null&&r.thumb?n.conversion_urls.thumb:n.original_url||n.url||""},async delete(n){const i={Accept:"application/json",...a.headers},r=a.csrfToken||$r();r&&(i["X-CSRF-TOKEN"]=r);const l=await fetch(`${a.apiBaseUrl}/uploads/${n}`,{method:"DELETE",headers:i,credentials:"include"});if(!l.ok){const s=await l.json().catch(()=>({message:"Delete failed"}));throw new Error(s.message||`HTTP ${l.status}`)}},async update(n,i){const r={Accept:"application/json","Content-Type":"application/json",...a.headers},l=a.csrfToken||$r();l&&(r["X-CSRF-TOKEN"]=l);const s=await fetch(`${a.apiBaseUrl}/uploads/${n}`,{method:"PATCH",headers:r,body:JSON.stringify(i),credentials:"include"});if(!s.ok){const c=await s.json().catch(()=>({message:"Update failed"}));throw new Error(c.message||`HTTP ${s.status}`)}const d=await s.json();return Es(d)},configure(n){Object.assign(a,n)}}}let Zr=null;function S9(){return Zr||(Zr=ac()),Zr}function C9(){Zr=null}function ah(o,a){switch(o){case"mediables":return tc(a);case"spatie":return ac(a);default:throw new Error(`Unknown adapter: ${o}`)}}function nh(o={}){const{enabled:a=!0,onReorder:t,onDragStart:n,onDragEnd:i,draggingClass:r="is-dragging",dropTargetClass:l="is-drop-target"}=o,s=e.ref({isDragging:!1,dragIndex:null,dropIndex:null,draggedItem:null}),d=e.ref(!1);let c=null;function u(_,b,g){a&&("dataTransfer"in _&&_.dataTransfer&&(_.dataTransfer.effectAllowed="move",_.dataTransfer.setData("text/plain",String(g))),c=_.target,c&&c.classList.add(r),s.value={isDragging:!0,dragIndex:g,dropIndex:g,draggedItem:b},d.value=!0,n==null||n(b,g))}function m(_,b){var g;if(!(!a||!s.value.isDragging)&&(_.preventDefault(),s.value.dropIndex!==b)){const I=document.querySelector(`.${l}`);I==null||I.classList.remove(l);const T=(g=_.target)==null?void 0:g.closest("[data-index]");T==null||T.classList.add(l),s.value.dropIndex=b}}function p(){if(!s.value.isDragging)return;const{dragIndex:_,dropIndex:b,draggedItem:g}=s.value;c&&c.classList.remove(r);const I=document.querySelector(`.${l}`);I==null||I.classList.remove(l),_!==null&&b!==null&&_!==b&&g&&(t==null||t({fromIndex:_,toIndex:b,item:g})),h(),i==null||i()}function f(){c&&c.classList.remove(r);const _=document.querySelector(`.${l}`);_==null||_.classList.remove(l),h(),i==null||i()}function h(){s.value={isDragging:!1,dragIndex:null,dropIndex:null,draggedItem:null},d.value=!1,c=null}function v(_,b,g){const I=[..._],[T]=I.splice(b,1);return I.splice(g,0,T),I.map(($,N)=>({...$,order:N}))}function y(_,b){return{draggable:a,"data-index":b,onDragstart:g=>u(g,_,b),onDragover:g=>m(g,b),onDragend:()=>p(),onDrop:g=>{g.preventDefault(),p()}}}function w(_){_.key==="Escape"&&s.value.isDragging&&f()}return e.onMounted(()=>{document.addEventListener("keydown",w)}),e.onUnmounted(()=>{document.removeEventListener("keydown",w),f()}),{dragState:s,isDragging:d,startDrag:u,handleDragOver:m,endDrag:p,cancelDrag:f,reorderItems:v,getDragProps:y}}function Hl(o={}){const{initialItems:a=[],modelType:t,modelId:n,collection:i="images",maxItems:r,maxFileSize:l,acceptedMimeTypes:s,sortable:d=!0,disabled:c=!1,rules:u={},adapterType:m="mediables",adapter:p,maxConcurrentUploads:f=3,onChange:h,onUpload:v,onUploadComplete:y,onUploadError:w,onRemove:_,onReorder:b,onError:g,onReadyToSubmitChange:I}=o,T={maxItems:r,maxFileSize:l,acceptedMimeTypes:s,...u},$=p||ah(m),N=e.ref([]),B=e.ref(!1),P=e.ref([]);function x(ye){if(ye.length===0)return[];const Ne=ye[0];return"media"in Ne&&"clientId"in Ne?ye:ud(ye)}N.value=x(a);const{acceptString:M,canAddFiles:E}=Zd({rules:T}),D=Gd({adapter:$,maxConcurrent:f,rules:T,collection:i,onUploadStart:ye=>{v==null||v(ye)},onUploadComplete:(ye,Ne)=>{const Se=N.value.findIndex(Re=>Re.clientId===ye.id);Se!==-1&&(N.value[Se]={...N.value[Se],media:Ne,name:Ne.name||Ne.file_name,upload:{...ye,status:"completed"}}),y==null||y(Ne)},onUploadError:(ye,Ne)=>{const Se=N.value.findIndex(Re=>Re.clientId===ye.id);Se!==-1&&(N.value[Se]={...N.value[Se],upload:{...ye,status:"error",error:Ne.message},errors:[{field:"upload",message:Ne.message,code:"UPLOAD_ERROR"}]}),w==null||w({file:ye.file,message:Ne.message})},onQueueComplete:()=>{h==null||h(N.value)}}),{dragState:j,getDragProps:L,reorderItems:z}=nh({enabled:d&&!c,onReorder:ye=>{N.value=z(N.value,ye.fromIndex,ye.toIndex),b==null||b(N.value),h==null||h(N.value)}}),C=e.computed(()=>D.isUploading.value),A=e.computed(()=>!D.isUploading.value&&D.pendingCount.value===0),O=e.computed(()=>r?N.value.length>=r:!1),K=e.computed(()=>ec(N.value)),se=e.computed(()=>N.value.length),xe=e.computed(()=>r?Math.max(0,r-N.value.length):1/0);e.watch(A,ye=>{I==null||I(ye)});function ue(ye){N.value=x(ye),h==null||h(N.value)}async function le(ye){if(c)return;const Ne=Array.from(ye);if(!E(Ne.length,N.value.length)){const it={field:"count",message:`Maximum ${r} files allowed`,code:"MAX_ITEMS"};P.value=[it],g==null||g([it]);return}const Se=await D.addFiles(Ne),Re=N.value.length,Oe=Se.map((it,rt)=>({...it,order:Re+rt}));N.value=[...N.value,...Oe],h==null||h(N.value)}function Z(ye){c||(ye.upload&&(ye.upload.status==="uploading"||ye.upload.status==="pending")&&D.cancelUpload(ye.clientId),N.value=N.value.filter(Ne=>Ne.clientId!==ye.clientId),N.value=N.value.map((Ne,Se)=>({...Ne,order:Se})),_==null||_(ye),h==null||h(N.value))}function k(ye){const Ne=N.value.find(Se=>Se.clientId===ye);Ne&&Z(Ne)}function F(){c||(D.clearAll(),N.value=[],h==null||h(N.value))}function W(ye,Ne){c||!d||(N.value=z(N.value,ye,Ne),b==null||b(N.value),h==null||h(N.value))}function J(ye,Ne){if(c)return;const Se=N.value.findIndex(Re=>Re.clientId===ye);Se!==-1&&(N.value[Se]={...N.value[Se],...Ne},h==null||h(N.value))}function ce(ye){D.cancelUpload(ye),k(ye)}async function Ue(ye){await D.retryUpload(ye)}async function be(){if(!t||!n)throw new Error("modelType and modelId are required for save()");const ye={modelType:t,modelId:n,collection:i},Ne=N.value.filter(Se=>Se.media&&!Se.markedForRemoval).map(Se=>Se.media.uuid);B.value=!0;try{await $.attachMany(Ne,ye),await $.reorder(ye,Ne)}finally{B.value=!1}}async function _e(){if(!t||!n)throw new Error("modelType and modelId are required for load()");const ye={modelType:t,modelId:n,collection:i};B.value=!0;try{const Ne=await $.fetchModelMedia(ye);N.value=ud(Ne),h==null||h(N.value)}finally{B.value=!1}}return e.onMounted(()=>{t&&n&&a.length===0&&_e().catch(console.error)}),e.onUnmounted(()=>{D.clearAll()}),{items:N,setItems:ue,addFiles:le,removeItem:Z,removeItemById:k,clearAll:F,reorderItems:W,updateItem:J,cancelUpload:ce,retryUpload:Ue,save:be,load:_e,isLoading:B,isUploading:C,isReadyToSubmit:A,isAtMaxItems:O,errors:P,dragState:j,getDragProps:L,adapter:$,formValues:K,acceptString:M,count:se,remainingSlots:xe}}const x9=["aria-disabled"],N9=["accept","multiple","disabled"],V9={class:"media-dropzone__content"},T9={class:"media-dropzone__title"},B9={class:"media-dropzone__subtitle"},M9=["disabled"],I9={key:0,class:"media-dropzone__helper"},$9=e.defineComponent({__name:"MediaCollectionDropzone",props:{accept:{default:"*"},multiple:{type:Boolean,default:!0},disabled:{type:Boolean,default:!1},maxFileSize:{},maxItems:{},title:{default:"Drop files here"},subtitle:{default:"or click to browse"},buttonText:{default:"Select files"}},emits:["files"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.ref(null),l=e.computed(()=>({"media-dropzone":!0,"media-dropzone--drag-over":i.value,"media-dropzone--disabled":t.disabled})),s=e.computed(()=>{const v=[];return t.maxFileSize&&v.push(`Max size: ${ul(t.maxFileSize)}`),t.maxItems&&t.maxItems>1&&v.push(`Max files: ${t.maxItems}`),v.join(" • ")});function d(v){v.preventDefault(),!t.disabled&&(i.value=!0)}function c(v){v.preventDefault(),i.value=!1}function u(v){v.preventDefault()}function m(v){var w;if(v.preventDefault(),i.value=!1,t.disabled)return;const y=(w=v.dataTransfer)==null?void 0:w.files;y&&y.length>0&&n("files",y)}function p(){var v;t.disabled||(v=r.value)==null||v.click()}function f(v){const y=v.target,w=y.files;w&&w.length>0&&n("files",w),y.value=""}function h(v){(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),p())}return(v,y)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(l.value),role:"button",tabindex:"0","aria-disabled":v.disabled,"aria-label":"Upload files",onClick:p,onKeydown:h,onDragenter:d,onDragleave:c,onDragover:u,onDrop:m},[e.createElementVNode("input",{ref_key:"fileInput",ref:r,type:"file",accept:v.accept,multiple:v.multiple,disabled:v.disabled,class:"media-dropzone__input",onChange:f},null,40,N9),e.createElementVNode("div",V9,[e.renderSlot(v.$slots,"icon",{},()=>[y[0]||(y[0]=e.createElementVNode("svg",{class:"media-dropzone__icon",xmlns:"http://www.w3.org/2000/svg",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e.createElementVNode("polyline",{points:"17 8 12 3 7 8"}),e.createElementVNode("line",{x1:"12",y1:"3",x2:"12",y2:"15"})],-1))],!0),e.createElementVNode("p",T9,[e.renderSlot(v.$slots,"title",{},()=>[e.createTextVNode(e.toDisplayString(v.title),1)],!0)]),e.createElementVNode("p",B9,[e.renderSlot(v.$slots,"subtitle",{},()=>[e.createTextVNode(e.toDisplayString(v.subtitle),1)],!0)]),e.createElementVNode("button",{type:"button",class:"media-dropzone__button",disabled:v.disabled,onClick:e.withModifiers(p,["stop"])},[e.renderSlot(v.$slots,"button",{},()=>[e.createTextVNode(e.toDisplayString(v.buttonText),1)],!0)],8,M9),s.value?(e.openBlock(),e.createElementBlock("p",I9,e.toDisplayString(s.value),1)):e.createCommentVNode("",!0)])],42,x9))}}),nc=Ae($9,[["__scopeId","data-v-b1366c1e"]]),F9=["data-index"],D9={key:0,class:"media-item__drag-handle","aria-label":"Drag to reorder",role:"button",tabindex:"0"},A9={class:"media-item__thumbnail"},R9=["src","alt"],L9={key:1,class:"media-item__file-icon"},P9={key:2,class:"media-item__progress-overlay"},U9={class:"media-item__progress-text"},O9={key:3,class:"media-item__processing-overlay"},z9={key:4,class:"media-item__error-overlay"},j9={class:"media-item__info"},W9=["title"],H9={key:0,class:"media-item__size"},Z9={key:1,class:"media-item__error-message"},G9={class:"media-item__actions"},X9=["disabled"],K9=["disabled"],q9=["disabled"],J9=["disabled"],Y9=e.defineComponent({__name:"MediaCollectionItem",props:{item:{},adapter:{},disabled:{type:Boolean,default:!1},sortable:{type:Boolean,default:!1},showRemove:{type:Boolean,default:!0},showEdit:{type:Boolean,default:!1},index:{default:0}},emits:["remove","edit","retry","cancel"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(!1),r=e.computed(()=>{var b;return(b=t.item.upload)!=null&&b.previewUrl?t.item.upload.previewUrl:t.item.media?t.adapter.getThumbnailUrl(t.item.media):null}),l=e.computed(()=>{var b,g,I;return((b=t.item.upload)==null?void 0:b.status)==="uploading"||((g=t.item.upload)==null?void 0:g.status)==="pending"||((I=t.item.upload)==null?void 0:I.status)==="queued"}),s=e.computed(()=>{var b;return((b=t.item.upload)==null?void 0:b.status)==="processing"}),d=e.computed(()=>{var b;return((b=t.item.upload)==null?void 0:b.status)==="error"||t.item.errors&&t.item.errors.length>0}),c=e.computed(()=>{var b;return(b=t.item.upload)!=null&&b.error?t.item.upload.error:t.item.errors&&t.item.errors.length>0?t.item.errors[0].message:null}),u=e.computed(()=>{var b;return((b=t.item.upload)==null?void 0:b.progress)||0}),m=e.computed(()=>{var b;return t.item.name||((b=t.item.media)==null?void 0:b.file_name)||"Unknown file"}),p=e.computed(()=>{var $,N;const b=(($=t.item.media)==null?void 0:$.size)||((N=t.item.upload)==null?void 0:N.file.size);if(!b)return"";const g=1024,I=["Bytes","KB","MB","GB"],T=Math.floor(Math.log(b)/Math.log(g));return parseFloat((b/Math.pow(g,T)).toFixed(2))+" "+I[T]}),f=e.computed(()=>{var g,I;const b=((g=t.item.media)==null?void 0:g.mime_type)||((I=t.item.upload)==null?void 0:I.file.type);return b==null?void 0:b.startsWith("image/")}),h=e.computed(()=>({"media-item":!0,"media-item--uploading":l.value,"media-item--processing":s.value,"media-item--error":d.value,"media-item--disabled":t.disabled,"media-item--sortable":t.sortable}));function v(){t.disabled||n("remove",t.item)}function y(){t.disabled||n("edit",t.item)}function w(){t.disabled||n("retry",t.item)}function _(){t.disabled||n("cancel",t.item)}return(b,g)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(h.value),"data-index":b.index,onMouseenter:g[0]||(g[0]=I=>i.value=!0),onMouseleave:g[1]||(g[1]=I=>i.value=!1)},[b.sortable&&!b.disabled?(e.openBlock(),e.createElementBlock("div",D9,[...g[2]||(g[2]=[e.createStaticVNode('<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" data-v-ff81c9ec><circle cx="9" cy="5" r="1" data-v-ff81c9ec></circle><circle cx="9" cy="12" r="1" data-v-ff81c9ec></circle><circle cx="9" cy="19" r="1" data-v-ff81c9ec></circle><circle cx="15" cy="5" r="1" data-v-ff81c9ec></circle><circle cx="15" cy="12" r="1" data-v-ff81c9ec></circle><circle cx="15" cy="19" r="1" data-v-ff81c9ec></circle></svg>',1)])])):e.createCommentVNode("",!0),e.createElementVNode("div",A9,[r.value&&f.value?(e.openBlock(),e.createElementBlock("img",{key:0,src:r.value,alt:m.value,class:"media-item__image"},null,8,R9)):(e.openBlock(),e.createElementBlock("div",L9,[...g[3]||(g[3]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.createElementVNode("polyline",{points:"14 2 14 8 20 8"})],-1)])])),l.value?(e.openBlock(),e.createElementBlock("div",P9,[e.createElementVNode("div",{class:"media-item__progress-bar",style:e.normalizeStyle({width:`${u.value}%`})},null,4),e.createElementVNode("span",U9,e.toDisplayString(u.value)+"%",1)])):e.createCommentVNode("",!0),s.value?(e.openBlock(),e.createElementBlock("div",O9,[...g[4]||(g[4]=[e.createElementVNode("div",{class:"media-item__spinner","aria-label":"Processing"},null,-1)])])):e.createCommentVNode("",!0),d.value?(e.openBlock(),e.createElementBlock("div",z9,[...g[5]||(g[5]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("circle",{cx:"12",cy:"12",r:"10"}),e.createElementVNode("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),e.createElementVNode("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})],-1)])])):e.createCommentVNode("",!0)]),e.createElementVNode("div",j9,[e.createElementVNode("span",{class:"media-item__name",title:m.value},e.toDisplayString(m.value),9,W9),p.value?(e.openBlock(),e.createElementBlock("span",H9,e.toDisplayString(p.value),1)):e.createCommentVNode("",!0),c.value?(e.openBlock(),e.createElementBlock("span",Z9,e.toDisplayString(c.value),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",G9,[l.value?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-item__action media-item__action--cancel",disabled:b.disabled,"aria-label":"Cancel upload",onClick:_},[...g[6]||(g[6]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.createElementVNode("line",{x1:"6",y1:"6",x2:"18",y2:"18"})],-1)])],8,X9)):e.createCommentVNode("",!0),d.value?(e.openBlock(),e.createElementBlock("button",{key:1,type:"button",class:"media-item__action media-item__action--retry",disabled:b.disabled,"aria-label":"Retry upload",onClick:w},[...g[7]||(g[7]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("polyline",{points:"23 4 23 10 17 10"}),e.createElementVNode("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})],-1)])],8,K9)):e.createCommentVNode("",!0),b.showEdit&&b.item.media&&!l.value?(e.openBlock(),e.createElementBlock("button",{key:2,type:"button",class:"media-item__action media-item__action--edit",disabled:b.disabled,"aria-label":"Edit",onClick:y},[...g[8]||(g[8]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),e.createElementVNode("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})],-1)])],8,q9)):e.createCommentVNode("",!0),b.showRemove?(e.openBlock(),e.createElementBlock("button",{key:3,type:"button",class:"media-item__action media-item__action--remove",disabled:b.disabled,"aria-label":"Remove",onClick:v},[...g[9]||(g[9]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("polyline",{points:"3 6 5 6 21 6"}),e.createElementVNode("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})],-1)])],8,J9)):e.createCommentVNode("",!0)])],42,F9))}}),oc=Ae(Y9,[["__scopeId","data-v-ff81c9ec"]]),Q9=["aria-label"],eO=["draggable","data-index","onDragstart","onDragover","onDragend","onDrop"],tO={key:0,class:"media-collection__footer"},aO={class:"media-collection__count"},nO={key:0},oO={key:0,class:"media-collection__uploading"},iO=["name","value"],rO=["name","value"],lO=["name","value"],sO=["name","value"],dO={key:3,class:"media-collection__errors",role:"alert","aria-live":"polite"},cO=e.defineComponent({__name:"MediaCollection",props:{modelValue:{default:()=>[]},name:{default:"media"},modelType:{},modelId:{},collection:{default:"images"},maxItems:{},maxFileSize:{},acceptedMimeTypes:{},sortable:{type:Boolean,default:!0},disabled:{type:Boolean,default:!1},readonly:{type:Boolean,default:!1},rules:{},adapter:{default:"mediables"},labels:{},showUploadZone:{type:Boolean,default:!0},generateFormFields:{type:Boolean,default:!0}},emits:["update:modelValue","change","upload","upload-complete","upload-error","remove","reorder","is-ready-to-submit-change","validation-error"],setup(o,{emit:a}){const t=o,n=a,i={initialItems:t.modelValue,modelType:t.modelType,modelId:t.modelId,collection:t.collection,maxItems:t.maxItems,maxFileSize:t.maxFileSize,acceptedMimeTypes:t.acceptedMimeTypes,sortable:t.sortable,disabled:t.disabled,rules:t.rules,adapterType:t.adapter,onChange:C=>{n("update:modelValue",C),n("change",C)},onUpload:C=>{n("upload",C)},onUploadComplete:C=>{n("upload-complete",C)},onUploadError:C=>{n("upload-error",C)},onRemove:C=>{n("remove",C)},onReorder:C=>{n("reorder",C)},onError:C=>{n("validation-error",C)},onReadyToSubmitChange:C=>{n("is-ready-to-submit-change",C)}},{items:r,setItems:l,addFiles:s,removeItem:d,reorderItems:c,cancelUpload:u,retryUpload:m,isLoading:p,isUploading:f,isAtMaxItems:h,errors:v,dragState:y,getDragProps:w,adapter:_,formValues:b,acceptString:g,count:I,remainingSlots:T}=Hl(i);e.provide("mediaAdapter",_),e.provide("mediaCollection",{items:r,addFiles:s,removeItem:d,reorderItems:c}),e.watch(()=>t.modelValue,C=>{C!==r.value&&l(C)},{deep:!0});const $=e.computed(()=>t.showUploadZone&&!t.disabled&&!t.readonly&&!h.value),N=e.computed(()=>({"media-collection":!0,"media-collection--disabled":t.disabled,"media-collection--readonly":t.readonly,"media-collection--loading":p.value,"media-collection--has-items":r.value.length>0,"media-collection--dragging":y.value.isDragging}));function B(C){s(C)}function P(C){d(C)}function x(C){m(C.clientId)}function M(C){u(C.clientId)}function E(C){}function D(C,A,O){if(!t.sortable||t.disabled)return;const K=w(A,O);K.onDragstart&&K.onDragstart(C)}function j(C,A){if(!t.sortable||t.disabled)return;C.preventDefault();const O=r.value[A],K=w(O,A);K.onDragover&&K.onDragover(C)}function L(C,A){const O=w(C,A);O.onDragend&&O.onDragend()}function z(C,A){C.preventDefault();const O=r.value[A],K=w(O,A);K.onDrop&&K.onDrop(C)}return(C,A)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(N.value)},[e.renderSlot(C.$slots,"dropzone",{addFiles:e.unref(s)},()=>[$.value?(e.openBlock(),e.createBlock(nc,{key:0,accept:e.unref(g),multiple:C.maxItems!==1,disabled:C.disabled,"max-file-size":C.maxFileSize,"max-items":e.unref(T),onFiles:B},null,8,["accept","multiple","disabled","max-file-size","max-items"])):e.createCommentVNode("",!0)],!0),e.unref(r).length>0?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-collection__list",role:"list","aria-label":`${e.unref(I)} media items`},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(r),(O,K)=>e.renderSlot(C.$slots,"item",{key:O.clientId,item:O,index:K,remove:()=>P(O)},()=>[e.createElementVNode("div",{class:e.normalizeClass(["media-collection__item-wrapper",{"media-collection__item-wrapper--drag-over":e.unref(y).dropIndex===K}]),draggable:C.sortable&&!C.disabled,"data-index":K,onDragstart:se=>D(se,O,K),onDragover:se=>j(se,K),onDragend:se=>L(O,K),onDrop:se=>z(se,K)},[e.createVNode(oc,{item:O,adapter:e.unref(_),disabled:C.disabled,sortable:C.sortable,"show-remove":!C.readonly,"show-edit":!1,index:K,onRemove:P,onRetry:x,onCancel:M,onEdit:E},null,8,["item","adapter","disabled","sortable","show-remove","index"])],42,eO)],!0)),128))],8,Q9)):$.value?e.createCommentVNode("",!0):e.renderSlot(C.$slots,"empty",{key:1},()=>[A[0]||(A[0]=e.createElementVNode("div",{class:"media-collection__empty"},[e.createElementVNode("p",null,"No files uploaded")],-1))],!0),e.renderSlot(C.$slots,"footer",{count:e.unref(I),isUploading:e.unref(f)},()=>[e.unref(r).length>0?(e.openBlock(),e.createElementBlock("div",tO,[e.createElementVNode("span",aO,[e.createTextVNode(e.toDisplayString(e.unref(I))+" "+e.toDisplayString(e.unref(I)===1?"file":"files")+" ",1),C.maxItems?(e.openBlock(),e.createElementBlock("span",nO," / "+e.toDisplayString(C.maxItems)+" max",1)):e.createCommentVNode("",!0)]),e.unref(f)?(e.openBlock(),e.createElementBlock("span",oO," Uploading... ")):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)],!0),C.generateFormFields?(e.openBlock(),e.createElementBlock(e.Fragment,{key:2},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(b),(O,K)=>(e.openBlock(),e.createElementBlock("input",{key:`${C.name}-${O.uuid}`,type:"hidden",name:`${C.name}[${K}][uuid]`,value:O.uuid},null,8,iO))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(b),(O,K)=>(e.openBlock(),e.createElementBlock("input",{key:`${C.name}-${O.uuid}-name`,type:"hidden",name:`${C.name}[${K}][name]`,value:O.name},null,8,rO))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(b),(O,K)=>(e.openBlock(),e.createElementBlock("input",{key:`${C.name}-${O.uuid}-order`,type:"hidden",name:`${C.name}[${K}][order]`,value:O.order},null,8,lO))),128)),(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(b),(O,K)=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:`${C.name}-${O.uuid}-props`},[O.custom_properties?(e.openBlock(),e.createElementBlock("input",{key:0,type:"hidden",name:`${C.name}[${K}][custom_properties]`,value:JSON.stringify(O.custom_properties)},null,8,sO)):e.createCommentVNode("",!0)],64))),128))],64)):e.createCommentVNode("",!0),e.unref(v).length>0?(e.openBlock(),e.createElementBlock("div",dO,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(v),O=>(e.openBlock(),e.createElementBlock("p",{key:O.code||O.message,class:"media-collection__error"},e.toDisplayString(O.message),1))),128))])):e.createCommentVNode("",!0)],2))}}),uO=Ae(cO,[["__scopeId","data-v-10a5bfff"]]);function ic(o={}){const{initialItem:a,onChange:t,onReplace:n,onUpload:i,onUploadComplete:r,onUploadError:l,onRemove:s,onError:d,onReadyToSubmitChange:c,...u}=o,p={...u,initialItems:a?[a]:[],maxItems:1,sortable:!1,onChange:$=>{t==null||t($[0]||null)},onUpload:i,onUploadComplete:r,onUploadError:l,onRemove:s,onError:d,onReadyToSubmitChange:c},f=Hl(p),h=e.computed(()=>f.items.value[0]||null),v=e.computed(()=>h.value!==null),y=e.computed(()=>f.formValues.value[0]||null);function w($){$===null?f.clearAll():f.setItems([$])}async function _($){const N=h.value;N&&f.removeItem(N),await f.addFiles([$])}function b(){h.value&&f.removeItem(h.value)}async function g($){const N=h.value;N&&f.removeItem(N),await f.addFiles([$]);const B=f.items.value[0];B&&(n==null||n(N,B))}function I(){var $;($=h.value)!=null&&$.upload&&f.cancelUpload(h.value.clientId)}async function T(){var $,N;((N=($=h.value)==null?void 0:$.upload)==null?void 0:N.status)==="error"&&await f.retryUpload(h.value.clientId)}return{item:h,setItem:w,addFile:_,removeItem:b,replaceItem:g,cancelUpload:I,retryUpload:T,save:f.save,load:f.load,isLoading:f.isLoading,isUploading:f.isUploading,isReadyToSubmit:f.isReadyToSubmit,hasItem:v,errors:f.errors,adapter:f.adapter,formValue:y,acceptString:f.acceptString}}const mO=["accept","disabled"],pO={class:"media-attachment__preview"},fO=["name","value"],hO=["name","value"],vO=["name","value"],gO=["name","value"],bO={key:4,class:"media-attachment__errors",role:"alert","aria-live":"polite"},yO=e.defineComponent({__name:"MediaAttachment",props:{modelValue:{default:null},name:{default:"media"},modelType:{},modelId:{},collection:{default:"images"},maxFileSize:{},acceptedMimeTypes:{},disabled:{type:Boolean,default:!1},readonly:{type:Boolean,default:!1},rules:{},adapter:{default:"mediables"},labels:{},showUploadZone:{type:Boolean,default:!0},generateFormFields:{type:Boolean,default:!0},showReplaceButton:{type:Boolean,default:!0}},emits:["update:modelValue","change","upload","upload-complete","upload-error","remove","replace","is-ready-to-submit-change","validation-error"],setup(o,{emit:a}){const t=o,n=a,i=e.ref(null),r={initialItem:t.modelValue,modelType:t.modelType,modelId:t.modelId,collection:t.collection,maxFileSize:t.maxFileSize,acceptedMimeTypes:t.acceptedMimeTypes,disabled:t.disabled,rules:t.rules,adapterType:t.adapter,onChange:x=>{n("update:modelValue",x),n("change",x)},onUpload:x=>{n("upload",x)},onUploadComplete:x=>{n("upload-complete",x)},onUploadError:x=>{n("upload-error",x)},onRemove:x=>{n("remove",x)},onReplace:(x,M)=>{n("replace",M)},onError:x=>{n("validation-error",x)},onReadyToSubmitChange:x=>{n("is-ready-to-submit-change",x)}},{item:l,setItem:s,addFile:d,removeItem:c,replaceItem:u,cancelUpload:m,retryUpload:p,isLoading:f,hasItem:h,errors:v,adapter:y,formValue:w,acceptString:_}=ic(r);e.provide("mediaAdapter",y),e.watch(()=>t.modelValue,x=>{x!==l.value&&s(x)},{deep:!0});const b=e.computed(()=>t.showUploadZone&&!t.disabled&&!t.readonly&&!h.value),g=e.computed(()=>({"media-attachment":!0,"media-attachment--disabled":t.disabled,"media-attachment--readonly":t.readonly,"media-attachment--loading":f.value,"media-attachment--has-item":h.value}));function I(x){x.length>0&&d(x[0])}function T(){var x;(x=i.value)==null||x.click()}function $(x){const M=x.target,E=M.files;E&&E.length>0&&u(E[0]),M.value=""}function N(x){c()}function B(x){p()}function P(x){m()}return(x,M)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(g.value)},[e.createElementVNode("input",{ref_key:"fileInputRef",ref:i,type:"file",accept:e.unref(_),disabled:x.disabled,class:"media-attachment__hidden-input",onChange:$},null,40,mO),b.value?e.renderSlot(x.$slots,"dropzone",{key:0,addFile:e.unref(d)},()=>[e.createVNode(nc,{accept:e.unref(_),multiple:!1,disabled:x.disabled,"max-file-size":x.maxFileSize,onFiles:I},null,8,["accept","disabled","max-file-size"])],!0):e.unref(h)&&e.unref(l)?e.renderSlot(x.$slots,"preview",{key:1,item:e.unref(l),remove:e.unref(c),replace:T},()=>[e.createElementVNode("div",pO,[e.createVNode(oc,{item:e.unref(l),adapter:e.unref(y),disabled:x.disabled,sortable:!1,"show-remove":!x.readonly,"show-edit":!1,onRemove:N,onRetry:B,onCancel:P},null,8,["item","adapter","disabled","show-remove"]),x.showReplaceButton&&!x.readonly&&!x.disabled&&e.unref(l).media?(e.openBlock(),e.createElementBlock("button",{key:0,type:"button",class:"media-attachment__replace-button",onClick:T},[...M[0]||(M[0]=[e.createElementVNode("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[e.createElementVNode("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e.createElementVNode("polyline",{points:"17 8 12 3 7 8"}),e.createElementVNode("line",{x1:"12",y1:"3",x2:"12",y2:"15"})],-1),e.createTextVNode(" Replace ",-1)])])):e.createCommentVNode("",!0)])],!0):e.renderSlot(x.$slots,"empty",{key:2},()=>[M[1]||(M[1]=e.createElementVNode("div",{class:"media-attachment__empty"},[e.createElementVNode("p",null,"No file selected")],-1))],!0),x.generateFormFields&&e.unref(w)?(e.openBlock(),e.createElementBlock(e.Fragment,{key:3},[e.createElementVNode("input",{type:"hidden",name:`${x.name}[uuid]`,value:e.unref(w).uuid},null,8,fO),e.createElementVNode("input",{type:"hidden",name:`${x.name}[name]`,value:e.unref(w).name},null,8,hO),e.createElementVNode("input",{type:"hidden",name:`${x.name}[order]`,value:e.unref(w).order},null,8,vO),e.unref(w).custom_properties?(e.openBlock(),e.createElementBlock("input",{key:0,type:"hidden",name:`${x.name}[custom_properties]`,value:JSON.stringify(e.unref(w).custom_properties)},null,8,gO)):e.createCommentVNode("",!0)],64)):e.createCommentVNode("",!0),e.unref(v).length>0?(e.openBlock(),e.createElementBlock("div",bO,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(e.unref(v),E=>(e.openBlock(),e.createElementBlock("p",{key:E.code||E.message,class:"media-attachment__error"},e.toDisplayString(E.message),1))),128))])):e.createCommentVNode("",!0)],2))}}),wO=Ae(yO,[["__scopeId","data-v-26911174"]]),oh={dropzone:{title:"Drop files here",subtitle:"or click to browse",button:"Select files"},item:{remove:"Remove",replace:"Replace",edit:"Edit",download:"Download"},errors:{maxItems:"Maximum {max} files allowed",maxFileSize:"File exceeds maximum size of {max}",invalidType:"File type not allowed",uploadFailed:"Upload failed"},status:{uploading:"Uploading...",processing:"Processing...",completed:"Complete",error:"Error"}},kO=e.defineComponent({__name:"MediaCollectionProvider",props:{modelValue:{default:()=>[]},name:{default:"media"},modelType:{},modelId:{},collection:{default:"images"},maxItems:{},maxFileSize:{},acceptedMimeTypes:{},sortable:{type:Boolean,default:!0},disabled:{type:Boolean,default:!1},readonly:{type:Boolean,default:!1},rules:{},adapter:{default:"mediables"},labels:{},showUploadZone:{type:Boolean,default:!0},generateFormFields:{type:Boolean,default:!0}},emits:["update:modelValue","change","upload","upload-complete","upload-error","remove","reorder","is-ready-to-submit-change","validation-error"],setup(o,{expose:a,emit:t}){const n=o,i=t,r={initialItems:n.modelValue,modelType:n.modelType,modelId:n.modelId,collection:n.collection,maxItems:n.maxItems,maxFileSize:n.maxFileSize,acceptedMimeTypes:n.acceptedMimeTypes,sortable:n.sortable,disabled:n.disabled,rules:n.rules,adapterType:n.adapter,onChange:x=>{i("update:modelValue",x),i("change",x)},onUpload:x=>{i("upload",x)},onUploadComplete:x=>{i("upload-complete",x)},onUploadError:x=>{i("upload-error",x)},onRemove:x=>{i("remove",x)},onReorder:x=>{i("reorder",x)},onError:x=>{i("validation-error",x)},onReadyToSubmitChange:x=>{i("is-ready-to-submit-change",x)}},{items:l,setItems:s,addFiles:d,removeItem:c,reorderItems:u,updateItem:m,cancelUpload:p,retryUpload:f,isLoading:h,isUploading:v,isReadyToSubmit:y,isAtMaxItems:w,errors:_,dragState:b,getDragProps:g,adapter:I,formValues:T,acceptString:$}=Hl(r);e.provide("mediaAdapter",I),e.provide("mediaCollection",{items:l,addFiles:d,removeItem:c,reorderItems:u}),e.watch(()=>n.modelValue,x=>{x!==l.value&&s(x)},{deep:!0});const N=e.computed(()=>({...oh,...n.labels})),B=e.computed(()=>({accept:$.value,multiple:n.maxItems!==1,disabled:n.disabled||n.readonly||w.value})),P=e.computed(()=>({items:l.value,isLoading:h.value,isUploading:v.value,isReadyToSubmit:y.value,isAtMaxItems:w.value,errors:_.value,addFiles:d,removeItem:c,reorderItems:u,clearAll:()=>{l.value.forEach(x=>c(x))},cancelUpload:p,retryUpload:f,labels:N.value,dropzoneProps:B.value}));return a({items:l,addFiles:d,removeItem:c,reorderItems:u,updateItem:m,cancelUpload:p,retryUpload:f,isLoading:h,isUploading:v,isReadyToSubmit:y,isAtMaxItems:w,errors:_,dragState:b,getDragProps:g,adapter:I,formValues:T,acceptString:$}),(x,M)=>e.renderSlot(x.$slots,"default",e.normalizeProps(e.guardReactiveProps(P.value)))}}),_O=e.defineComponent({__name:"MediaAttachmentProvider",props:{modelValue:{default:null},name:{default:"media"},modelType:{},modelId:{},collection:{default:"images"},maxFileSize:{},acceptedMimeTypes:{},disabled:{type:Boolean,default:!1},readonly:{type:Boolean,default:!1},rules:{},adapter:{default:"mediables"},labels:{},showUploadZone:{type:Boolean,default:!0},generateFormFields:{type:Boolean,default:!0},showReplaceButton:{type:Boolean,default:!0}},emits:["update:modelValue","change","upload","upload-complete","upload-error","remove","replace","is-ready-to-submit-change","validation-error"],setup(o,{expose:a,emit:t}){const n=o,i=t,r={initialItem:n.modelValue,modelType:n.modelType,modelId:n.modelId,collection:n.collection,maxFileSize:n.maxFileSize,acceptedMimeTypes:n.acceptedMimeTypes,disabled:n.disabled,rules:n.rules,adapterType:n.adapter,onChange:N=>{i("update:modelValue",N),i("change",N)},onUpload:N=>{i("upload",N)},onUploadComplete:N=>{i("upload-complete",N)},onUploadError:N=>{i("upload-error",N)},onRemove:N=>{i("remove",N)},onReplace:(N,B)=>{i("replace",B)},onError:N=>{i("validation-error",N)},onReadyToSubmitChange:N=>{i("is-ready-to-submit-change",N)}},{item:l,setItem:s,addFile:d,removeItem:c,replaceItem:u,cancelUpload:m,retryUpload:p,isLoading:f,isUploading:h,isReadyToSubmit:v,hasItem:y,errors:w,adapter:_,formValue:b,acceptString:g}=ic(r);e.provide("mediaAdapter",_),e.watch(()=>n.modelValue,N=>{N!==l.value&&s(N)},{deep:!0});const I=e.computed(()=>({...oh,...n.labels})),T=e.computed(()=>({accept:g.value,multiple:!1,disabled:n.disabled||n.readonly||y.value})),$=e.computed(()=>({item:l.value,hasItem:y.value,isLoading:f.value,isUploading:h.value,isReadyToSubmit:v.value,errors:w.value,addFile:d,removeItem:c,replaceItem:u,cancelUpload:m,retryUpload:p,labels:I.value,dropzoneProps:T.value}));return a({item:l,setItem:s,addFile:d,removeItem:c,replaceItem:u,cancelUpload:m,retryUpload:p,isLoading:f,isUploading:h,isReadyToSubmit:v,hasItem:y,errors:w,adapter:_,formValue:b,acceptString:g}),(N,B)=>e.renderSlot(N.$slots,"default",e.normalizeProps(e.guardReactiveProps($.value)))}}),EO=["name","value"],SO=["name","value"],CO=["name","value"],xO=["name","value"],NO=e.defineComponent({__name:"MediaHiddenFields",props:{items:{default:()=>[]},item:{default:null},name:{default:"media"},format:{default:"mediables"}},setup(o){const a=o,t=e.computed(()=>a.item?[a.item]:a.items),n=e.computed(()=>ec(t.value));function i(s,d){var u;const c=((u=n.value[s])==null?void 0:u.uuid)||"";return`${a.name}[${c}][${d}]`}function r(s,d){return`${a.name}[${s}][${d}]`}function l(s,d){return a.format==="spatie"?i(s,d):r(s,d)}return(s,d)=>(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(n.value,(c,u)=>(e.openBlock(),e.createElementBlock(e.Fragment,{key:c.uuid},[e.createElementVNode("input",{type:"hidden",name:l(u,"uuid"),value:c.uuid},null,8,EO),e.createElementVNode("input",{type:"hidden",name:l(u,"name"),value:c.name},null,8,SO),e.createElementVNode("input",{type:"hidden",name:l(u,"order"),value:c.order},null,8,CO),c.custom_properties&&Object.keys(c.custom_properties).length>0?(e.openBlock(),e.createElementBlock("input",{key:0,type:"hidden",name:l(u,"custom_properties"),value:JSON.stringify(c.custom_properties)},null,8,xO)):e.createCommentVNode("",!0)],64))),128))}}),VO=["data-testid"],TO=["data-testid"],BO=["id"],MO=["value","maxlength","disabled","aria-labelledby","placeholder","data-testid","onInput"],IO=e.defineComponent({__name:"MediaAttachmentMetadataFields",props:{items:{},disabled:{type:Boolean,default:!1},label:{default:"Caption"},placeholder:{default:"Add an optional caption"},maxLength:{default:500},testIdPrefix:{default:"media-attachment-metadata"},getItemLabel:{type:Function,default:(o,a)=>`${o.type==="video"?"video":"photo"} ${a+1}`}},emits:["update:items"],setup(o,{emit:a}){const t=o,n=a;function i(r,l){const s=l.target;s instanceof HTMLInputElement&&n("update:items",t.items.map((d,c)=>c!==r?d:{...d,caption:s.value===""?null:s.value}))}return(r,l)=>r.items.length>0?(e.openBlock(),e.createElementBlock("div",{key:0,class:"media-attachment-metadata-fields","data-testid":r.testIdPrefix},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(r.items,(s,d)=>(e.openBlock(),e.createElementBlock("div",{key:s._key??s.id??`${s.url}:${d}`,class:"media-attachment-metadata-fields__row","data-testid":`${r.testIdPrefix}-${d}`},[e.createElementVNode("p",{id:`${r.testIdPrefix}-label-${d}`,class:"media-attachment-metadata-fields__label"},e.toDisplayString(r.label)+" for "+e.toDisplayString(r.getItemLabel(s,d)),9,BO),e.createElementVNode("input",{value:s.caption??"",type:"text",class:"media-attachment-metadata-fields__input",maxlength:r.maxLength,disabled:r.disabled,"aria-labelledby":`${r.testIdPrefix}-label-${d}`,placeholder:r.placeholder,"data-testid":`input-${r.testIdPrefix}-${d}`,onInput:c=>i(d,c)},null,40,MO)],8,TO))),128))],8,VO)):e.createCommentVNode("",!0)}}),$O=Ae(IO,[["__scopeId","data-v-a153768a"]]);exports.AlbumBrowser=wf;exports.AlbumManager=nF;exports.AlbumMediaGrid=hF;exports.AlbumNavRail=a9;exports.AlbumTree=zl;exports.ArrayBufferTarget=yd;exports.ExistingMediaSelector=Tb;exports.ImageEditor=hm;exports.ImageEditorModal=vm;exports.LiveStreamManager=v5;exports.ManagedMediaGallery=rv;exports.MediaAlbumInlineCreate=jd;exports.MediaAlbumPickerModal=zf;exports.MediaAlbumUnavailableState=kf;exports.MediaAttachment=wO;exports.MediaAttachmentMetadataFields=$O;exports.MediaBulkActionBar=qd;exports.MediaCollection=uO;exports.MediaCollectionDropzone=nc;exports.MediaCollectionItem=oc;exports.MediaEmptyState=eh;exports.MediaFilterChips=Jf;exports.MediaInspectorPanel=qf;exports.MediaLibraryPicker=Of;exports.MediaLibraryPickerModal=HD;exports.MediaLibraryShell=zU;exports.MediaLibraryToolbar=jf;exports.MediaLibraryWorkspace=Qf;exports.MediaManagementView=Yf;exports.MediaPreviewSheet=Wd;exports.MediaSelectionTray=b9;exports.MediaShortcutHelp=Wf;exports.MediaSourceSheet=Vf;exports.MediaThumbnailCell=Bf;exports.MediaTrashWorkspace=th;exports.MediaUploadSheet=Tf;exports.MediaUsageList=Zf;exports.MediaVariantStrip=Gf;exports.MediaWorkspace=av;exports.ModelMediaManager=Jg;exports.Muxer=Pm;exports.RequiresConfirmationError=Wl;exports.VideoEditor=mf;exports.VideoEditorDialog=Q4;exports.VideoEditorSimple=EM;exports.VideoExportPanel=a3;exports.VideoJobClient=Ll;exports.VideoPlayer=vf;exports.VideoTimeline=GM;exports.VideoToolsPanel=AI;exports.VideoUploader=j3;exports.VirtualMediaGrid=Mf;exports._sfc_main=kO;exports._sfc_main$1=_O;exports._sfc_main$2=NO;exports.applyTemporaryMediaStoreConfig=lm;exports.configureAlbumStore=gf;exports.configureMediaStore=ai;exports.createAdapter=ah;exports.createImageEditor=w9;exports.createMediablesAdapter=tc;exports.createSpatieAdapter=ac;exports.formatFileSize=ul;exports.fromMediaArray=ud;exports.getFileExtension=If;exports.getImageDimensions=$f;exports.getMediablesAdapter=k9;exports.getSpatieAdapter=S9;exports.isImageFile=Hd;exports.normalizeRecipeForServerRender=F4;exports.recipeHasServerRenderableEdits=$4;exports.recipeHasUnsupportedServerEdits=hf;exports.resetMediablesAdapter=_9;exports.resetSpatieAdapter=C9;exports.restoreAlbumStoreConfig=x5;exports.restoreMediaStoreConfig=rm;exports.snapshotAlbumStoreConfig=C5;exports.snapshotMediaStoreConfig=im;exports.toFormValues=ec;exports.useAdminMediaStore=sm;exports.useAlbumDragDrop=yf;exports.useAlbumStore=Ul;exports.useAlbums=Ol;exports.useGlobalImageEditor=y9;exports.useImageEditorModal=Qd;exports.useMediaAttachment=ic;exports.useMediaCollection=Hl;exports.useMediaDeletion=Jd;exports.useMediaDragSort=nh;exports.useMediaLibraryPickerController=Uf;exports.useMediaLibraryQuery=Xd;exports.useMediaLibrarySession=Af;exports.useMediaLibraryStateMachine=Rf;exports.useMediaLibraryTelemetry=Lf;exports.useMediaLibraryUploads=Hf;exports.useMediaLibraryVisibility=l9;exports.useMediaMetadata=Kf;exports.useMediaSelection=fl;exports.useMediaStore=ja;exports.useMediaTrash=Yd;exports.useMediaUploadQueue=Gd;exports.useMediaValidation=Zd;exports.validateFile=Ff;
357
+ //# sourceMappingURL=index-DutUeSES.cjs.map